Merge main (security-perf + SEO) into docs; finish English docs and agent guide
- Resolve conflicts in analytics, consent, content, i18n, mcp and stats, keeping the docs fixes and the new code behaviour, verified against src - Translate the remaining 14 module pages, ipal-seo-check skill and script - Integrate the security-perf and SEO agent-guide text: getRobots, isPathVisible, Search & AI (DNS verification first, meta fields optional), sitemap index/cache/503, consentMode basic/advanced, policyVersion, globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess, firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale claims fixed across AGENT.md, skills, frontend, developer guide, vibe - docsConsistency: pending list removed (all docs English); relative links now also check #anchors Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+366
-295
@@ -1,172 +1,190 @@
|
||||
# forms
|
||||
|
||||
Wpina `@payloadcms/plugin-form-builder` (kolekcje forms + form-submissions) i
|
||||
dostarcza `submitForm` — funkcję serwerową (wołaną z Server Action), która spina:
|
||||
rate limit → Turnstile → walidację względem definicji z panelu → zapis zgłoszenia.
|
||||
Maile wysyła form-builder (Forms → Emails) przez `mailAdapter()`.
|
||||
Wires `@payloadcms/plugin-form-builder` (forms + form-submissions collections) and
|
||||
provides `submitForm` — a server function (called from a Server Action) that chains:
|
||||
rate limit → Turnstile → validation against the form definition from the panel → storing the submission.
|
||||
Emails are sent by the form-builder (Forms → Emails) through `mailAdapter()`.
|
||||
|
||||
## ⚠️ ZASADA: formularz POCHODZI z buildera w panelu (obowiązkowe)
|
||||
## ⚠️ RULE: the form COMES FROM the builder in the panel (mandatory)
|
||||
|
||||
**Formularze buduje redaktor w panelu** (kolekcja Forms), NIE deweloper w kodzie.
|
||||
To jest CMS — klient sam definiuje pola, etykiety, komunikaty, odbiorcę. Front
|
||||
tylko RENDERUJE formularz z panelu i wysyła przez `submitForm`.
|
||||
**Forms are built by the editor in the panel** (Forms collection), NOT by the developer in code.
|
||||
This is a CMS — the client defines fields, labels, messages and the recipient. The front end
|
||||
only RENDERS the form from the panel and submits it through `submitForm`.
|
||||
|
||||
**NIGDY nie twórz własnego, hardkodowanego formularza** — z ręcznie wpisanymi
|
||||
polami, etykietami w JSX, własną walidacją. To łamie „nic na sztywno" (klient nie
|
||||
zmieni pól ani tekstów) i omija cały mechanizm pluginu (Turnstile, rate-limit,
|
||||
consent RODO, powiadomienia).
|
||||
**NEVER build your own hard-coded form** — with hand-written
|
||||
fields, labels in JSX, your own validation. It breaks "nothing hard-coded" (the client cannot
|
||||
change fields or texts) and skips the plugin's whole mechanism (Turnstile, rate limit,
|
||||
GDPR consent, notifications).
|
||||
|
||||
| ŹLE (własny formularz) | DOBRZE (builder pluginu) |
|
||||
| WRONG (your own form) | RIGHT (the plugin's builder) |
|
||||
|---|---|
|
||||
| `<input name="email" placeholder="Email" />` w JSX | pola z kolekcji Forms (panel) |
|
||||
| etykiety/komunikaty w kodzie | etykiety per język w panelu |
|
||||
| własna walidacja/wysyłka | `submitForm` (Turnstile+consent+mail) |
|
||||
| klient nie zmieni formularza | klient edytuje pola w panelu |
|
||||
| `<input name="email" placeholder="Email" />` in JSX | fields from the Forms collection (panel) |
|
||||
| labels/messages in code | labels per language in the panel |
|
||||
| your own validation/submit | `submitForm` (Turnstile+consent+mail) |
|
||||
| the client cannot change the form | the client edits fields in the panel |
|
||||
|
||||
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → blok renderuje go
|
||||
przez `<RenderForm>` → wysyłka przez `sendForm` (`createSubmitAction` → `submitForm`). Pola,
|
||||
etykiety, komunikaty, odbiorca — wszystko z panelu.
|
||||
**How to do it right:** the editor creates a form in the Forms collection → a block renders it
|
||||
with `<RenderForm>` → it is submitted through `sendForm` (`createSubmitAction` → `submitForm`). Fields,
|
||||
labels, messages, recipient — all from the panel.
|
||||
|
||||
Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigurację
|
||||
`fields` (patrz niżej) albo rozbuduj plugin. NIE hardkoduj własnego formularza.
|
||||
If a form needs a field the builder does not have — add it through the `fields`
|
||||
configuration (see below) or extend the plugin. Do NOT hard-code your own form.
|
||||
|
||||
## Zależność
|
||||
## Dependency
|
||||
|
||||
```json
|
||||
"dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // ta sama wersja co payload
|
||||
"dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // same version as payload
|
||||
```
|
||||
(the plugin's peer dependency: `^3.90.2`)
|
||||
|
||||
## Config (payload.config.ts)
|
||||
|
||||
```ts
|
||||
ipalKit({
|
||||
forms: {
|
||||
redirectRelationships: ['pages'], // formularz może przekierować na Page
|
||||
// fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
|
||||
// // time, select, radio, checkbox, checkboxGroup, message, step
|
||||
redirectRelationships: ['pages'], // a form can redirect to a Page
|
||||
// fields: { date: false, … }, // default: text, textarea, email, number, date,
|
||||
// // time, select, radio, checkbox, checkboxGroup, message, step
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions**
|
||||
(zgłoszenia) — w panelu w grupie **Forms** z etykietami „Form/Forms” i
|
||||
„Submission/Submissions” (bez nadpisań w projekcie). Inna grupa:
|
||||
`forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
|
||||
formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej).
|
||||
`forms` options (`FormsOption`):
|
||||
|
||||
## Front — RenderForm (zalecane, jedna linia)
|
||||
| Option | Default | Description |
|
||||
|---|---|---|
|
||||
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
|
||||
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default ipal block |
|
||||
| `redirectRelationships` | — | collections a form can redirect to |
|
||||
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
|
||||
| `emailLayout` | `false` | nice emails + the Site Settings → Emails tab |
|
||||
| `beforeEmail` | — | the form-builder's `beforeEmail` (after the layout, when `emailLayout`) |
|
||||
| `consentFieldName` | `'consent'` | name of the GDPR consent field for `submitForm` / `createSubmitAction` (the call's argument wins) |
|
||||
|
||||
Cały front formularza z panelu jest w pluginie. Projekt ma blok i klasy:
|
||||
`payment` is always off — `fields: { payment: true }` does **not** turn it on (the value `true`
|
||||
is skipped); it can only be turned on by passing a block object. `country` / `state` keep the form-builder's
|
||||
default settings.
|
||||
|
||||
Adds the **Forms** (the editor builds forms) and **Form Submissions**
|
||||
(submissions) collections — in the panel in the **Forms** group with the labels "Form/Forms" and
|
||||
"Submission/Submissions" (no overrides needed in the project). A different group:
|
||||
`forms: { adminGroup: 'Content' }`; Payload's default: `adminGroup: false`. Emails after a submission are sent by the form-builder according to the form's **Emails**
|
||||
tab — through the adapter from `email:` in the config (the "Emails" section below).
|
||||
|
||||
## Front end — RenderForm (recommended, one line)
|
||||
|
||||
The whole front end of a panel form lives in the plugin. The project has the block and the classes:
|
||||
|
||||
```tsx
|
||||
// src/blocks/FormBlock/Component.tsx
|
||||
import { RenderForm } from '@intecion/ipal-kit/rsc'
|
||||
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||||
```
|
||||
- `form` — relacja z bloku (depth ≥ 1; ID albo null → nic się nie renderuje),
|
||||
- `action` — `sendForm` z `createSubmitAction` (niżej), `texts` — `getFormTexts(locale)` z `lib/content`
|
||||
- `form` — the relation from the block (depth ≥ 1; an ID or null → nothing renders),
|
||||
- `action` — `sendForm` from `createSubmitAction` (below), `texts` — `getFormTexts(locale)` from `lib/content`
|
||||
(Notifications → Form messages),
|
||||
- `classNames` — **jedyne** miejsce wyglądu (`src/components/forms/formClasses.ts`, szablon w ipal-form);
|
||||
plugin nie ma żadnych stylów. Klucze: `form, progress, step, stepTitle, stepDescription, fields,
|
||||
- `classNames` — the **only** place for looks (`src/components/forms/formClasses.ts`, template in ipal-form);
|
||||
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
|
||||
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
|
||||
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
|
||||
next, submit, success, required`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
|
||||
- opcje: `requiredMark` (np. `" *"`), `converters` / `richTextClassName` (wygląd rich text),
|
||||
`linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme`.
|
||||
next, submit, success, required, fixed`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
|
||||
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
|
||||
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
|
||||
(default `'page'`), `values` (below).
|
||||
|
||||
`RenderForm` (serwer) renderuje bloki **message** i potwierdzenie przez `RenderRichText`, wiąże
|
||||
akcję z formularzem i językiem, rozwiązuje redirect i podaje przeglądarce **tylko publiczną część
|
||||
formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładkę Emails (adresy firmy);
|
||||
ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient).
|
||||
`RenderForm` (server) renders **message** blocks and the confirmation through `RenderRichText`, binds
|
||||
the action to the form and the language, resolves the redirect and gives the browser **only the public part of the
|
||||
form** — the Local API reads with `overrideAccess`, so the document has the Emails tab (company addresses);
|
||||
a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Underneath it is `BuilderForm` (client).
|
||||
|
||||
### Typy pól w panelu
|
||||
### Field types in the panel
|
||||
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
|
||||
message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`.
|
||||
message, **Step** (+ country/state as text). Turning a type off: `forms.fields: { date: false }`.
|
||||
|
||||
**Placeholder** (1.11.1): text, email, textarea i number mają lokalizowane pole „Placeholder” — podpowiedź
|
||||
w pustym polu („np. 10:00–12:00”). `BuilderForm` i `useBuilderForm` (`getInputProps`, `getTextareaProps`)
|
||||
przekazują je same. Własny blok z tym polem: `withPlaceholder(block)` / `placeholderField` z roota;
|
||||
blok godziny: `timeBlock`. Nowe pola w blokach formularzy = migracja (`pnpm payload migrate:create`).
|
||||
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
|
||||
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
|
||||
pass it on by themselves. Your own block with this field: `withPlaceholder(block)` / `placeholderField` from the root;
|
||||
the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payload migrate:create`).
|
||||
|
||||
| Typ | Wartość | Serwer sprawdza |
|
||||
| Type | Value | The server checks |
|
||||
|---|---|---|
|
||||
| radio, select | jedna wartość | tylko wartości z panelu |
|
||||
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
|
||||
| date | `YYYY-MM-DD` | prawdziwa data |
|
||||
| time | `HH:MM` (`<input type="time">`) | godzina 00:00–23:59 |
|
||||
| Step | — (podział) | nie jest polem |
|
||||
| radio, select | one value | only values from the panel |
|
||||
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
|
||||
| date | `YYYY-MM-DD` | a real date |
|
||||
| time | `HH:MM` (`<input type="time">`) | a time 00:00–23:59 |
|
||||
| Step | — (split) | not a field |
|
||||
|
||||
### Formularz krokowy
|
||||
Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym Step to ekran 1.
|
||||
`BuilderForm`: „Krok 1 z 3” (`stepOf`), Dalej waliduje tylko bieżący krok, Wstecz zachowuje
|
||||
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
|
||||
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
|
||||
### Multi-step form
|
||||
A **Step** block (title, description, per language) starts a new screen; fields above the first Step are screen 1.
|
||||
`BuilderForm`: "Step 1 of 3" (`stepOf`), Next validates only the current step, Back keeps the
|
||||
values, focus moves to the new step, Turnstile is on the last step, a field error from the server goes back
|
||||
to the step with that field. Button texts: Notifications → Form messages → `next`, `back`, `stepOf`.
|
||||
|
||||
### Pola i kroki warunkowe („Show only when”)
|
||||
Każdy blok formularza (wbudowane, **Checkbox group**, **Step**, message) ma w panelu grupę
|
||||
**Show only when** (`showWhen`): `field` — nazwa techniczna innego pola, `values` — wartości opcji
|
||||
po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `field` = zawsze widoczne.
|
||||
### Conditional fields and steps ("Show only when")
|
||||
Every form block (built-in, **Checkbox group**, **Step**, message) has a
|
||||
**Show only when** group in the panel (`showWhen`): `field` — the technical name of another field, `values` — option values,
|
||||
comma-separated (empty = when that field is filled in / checked). An empty `field` = always visible.
|
||||
|
||||
- Na polu: pole pokazuje się dopiero przy pasującej odpowiedzi (np. „Z czego wynika termin?”
|
||||
tylko przy `deadline = fixed`).
|
||||
- Na **Step**: cały krok (z polami) wypada, gdy warunek nie pasuje — kolejne kroki się przenumerowują
|
||||
(„Krok 2 z 3”). Tak buduje się brief: ekran 1 wybiera obszary (Checkbox group), każdy następny
|
||||
Step ma `showWhen: { field: 'areas', values: 'web' }`.
|
||||
- Pole w ukrytym kroku jest ukryte, nawet gdy jego warunek pasuje; warunek wskazujący ukryte pole też
|
||||
nie pasuje. Nazwa nieistniejącego pola (literówka) albo cykl ukrywa pole — widać to w podglądzie.
|
||||
- Wspólna reguła `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — przeglądarka
|
||||
(`useBuilderForm`/`BuilderForm`: co pokazać, walidować i wysłać) i serwer (`validateSubmission`):
|
||||
ukryte pole **nie jest wymagane i nie jest zapisywane**, nawet gdy ktoś je dośle ręcznie.
|
||||
Wyjątek: pole zgody RODO (`consent`) jest egzekwowane zawsze — warunkiem nie da się go wyłączyć.
|
||||
- Typ `FieldCondition` (`{ field, values }`) dla własnego markupu na `useBuilderForm`; `splitSteps(fields, isShown)`
|
||||
pomija ukryte pola i kroki, zachowując oryginalny `index` (bloki message renderują się po nim).
|
||||
- Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy →
|
||||
po aktualizacji wygeneruj migrację (`payload migrate:create`).
|
||||
- On a field: the field shows up only for a matching answer (e.g. "What sets the deadline?"
|
||||
only when `deadline = fixed`).
|
||||
- On a **Step**: the whole step (with its fields) drops out when the condition does not match — the following steps are renumbered
|
||||
("Step 2 of 3"). This is how a brief is built: screen 1 picks areas (Checkbox group), each following
|
||||
Step has `showWhen: { field: 'areas', values: 'web' }`.
|
||||
- A field in a hidden step is hidden, even when its own condition matches; a condition that points at a hidden field
|
||||
does not match either. The name of a field that does not exist (a typo) or a cycle hides the field — you can see it in the preview.
|
||||
- One shared rule `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — the browser
|
||||
(`useBuilderForm`/`BuilderForm`: what to show, validate and send) and the server (`validateSubmission`):
|
||||
a hidden field **is not required and is not stored**, even when someone sends it by hand.
|
||||
Exception: the GDPR consent field (`consent`) is always enforced — a condition cannot turn it off.
|
||||
- The `FieldCondition` type (`{ field, values }`) for your own markup on `useBuilderForm`; `splitSteps(fields, isShown)`
|
||||
skips hidden fields and steps, keeping the original `index` (message blocks render by it).
|
||||
- The new group = columns `show_when_field` / `show_when_values` in the form block tables →
|
||||
after updating, generate a migration (`payload migrate:create`).
|
||||
|
||||
### Wartości pól ze strony (`values`, 1.11.0)
|
||||
Strona zna wartość pola, której nie wpisuje odwiedzający — wybrany wariant produktu, kategorię, ofertę.
|
||||
Redaktor dodaje w formularzu zwykłe pole tekstowe (np. `subject`, „Dotyczy”), a strona je wypełnia:
|
||||
### Field values from the page (`values`, 1.11.0)
|
||||
The page knows a field value the visitor does not type — the chosen product variant, category, offer.
|
||||
The editor adds a plain text field to the form (e.g. `subject`, "Regarding"), and the page fills it:
|
||||
|
||||
```tsx
|
||||
// wartość znana na serwerze (kategoria „wkrótce”)
|
||||
// a value known on the server (the "coming soon" category)
|
||||
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} values={{ subject: category.title }} />
|
||||
```
|
||||
Pole z `values` jest pokazane tylko do odczytu (`<output>`, klasa `classNames.fixed`, `data-ipal="form-fixed"`),
|
||||
wysyłane jak każde inne i walidowane przez serwer według definicji z panelu. Nazwy spoza formularza są pomijane.
|
||||
Wartość jest w pierwszym HTML (SSR), nie dopiero po hydracji.
|
||||
A field with `values` is shown read-only (`<output>`, class `classNames.fixed`, `data-ipal="form-fixed"`),
|
||||
sent like any other field and validated by the server against the definition from the panel. Names not in the form are skipped.
|
||||
The value is in the first HTML (SSR), not only after hydration.
|
||||
|
||||
Wartość zmieniana w przeglądarce (konfigurator): serwer przygotowuje formularz `prepareBuilderForm` (`/rsc`) —
|
||||
publiczną część (`publicForm`, bez zakładki Emails), wyrenderowane bloki message i potwierdzenie, akcję przypiętą
|
||||
do formularza i języka, cel przekierowania — a komponent kliencki renderuje `BuilderForm` z aktualnym `values`:
|
||||
A value that changes in the browser (a configurator): the server prepares the form with `prepareBuilderForm` (`/rsc`) —
|
||||
the public part (`publicForm`, without the Emails tab), the rendered message blocks and confirmation, the action bound
|
||||
to the form and the language, the redirect target — and a client component renders `BuilderForm` with the current `values`:
|
||||
|
||||
```tsx
|
||||
// serwer
|
||||
// server
|
||||
const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale })
|
||||
<Configurator form={form} texts={formTexts} />
|
||||
// klient ('use client')
|
||||
// client ('use client')
|
||||
<BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
|
||||
```
|
||||
`publicForm(form)` (`/rsc`) — sama publiczna część dokumentu, gdy budujesz własny przekaz do klienta. Nigdy nie
|
||||
przekazuj do przeglądarki surowego dokumentu formularza.
|
||||
`publicForm(form)` (`/rsc`) — just the public part of the document, when you build your own hand-off to the client. Never
|
||||
pass the raw form document to the browser.
|
||||
|
||||
### Formularz nietypowy — bez kopiowania silnika
|
||||
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
|
||||
### An unusual form — without copying the engine
|
||||
1. `renderField` (BuilderForm in a `'use client'` file) — replaces selected fields:
|
||||
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
|
||||
2. `useBuilderForm({ form, action, texts })` — cała logika, markup Twój: `steps`, `step`,
|
||||
2. `useBuilderForm({ form, action, texts })` — all the logic, the markup is yours: `steps`, `step`,
|
||||
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
|
||||
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `getFieldProps`,
|
||||
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`,
|
||||
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
|
||||
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
|
||||
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
|
||||
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
|
||||
`TurnstileWidget`. Example: `ipal-form/resources/CustomForm.example.tsx`.
|
||||
3. Pure logic (also on the server / in tests): `splitSteps`, `initialBuilderValues`,
|
||||
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name).
|
||||
|
||||
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
|
||||
`useOptionalTurnstile()` — like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing.
|
||||
|
||||
## Front — submitForm (server)
|
||||
## Front end — submitForm (server)
|
||||
|
||||
Wołasz w Server Action. Kształt pasuje 1:1 do `useForm` / `useContactForm`
|
||||
(`(values, turnstileToken) → { success, message }`) — `formId` i `locale`
|
||||
doklejasz przez `.bind`, kod błędu zamieniasz na tekst z panelu:
|
||||
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
|
||||
(`(values, turnstileToken) → { success, message }`) — you attach `formId` and `locale`
|
||||
with `.bind`, and turn the error code into text from the panel:
|
||||
|
||||
```ts
|
||||
// src/app/(frontend)/[locale]/actions.ts
|
||||
@@ -184,85 +202,105 @@ export async function sendForm(
|
||||
) {
|
||||
const payload = await getCachedPayload()
|
||||
const texts = (await getNotificationTexts({ payload, locale })).form
|
||||
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: udawany sukces
|
||||
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success
|
||||
const { [HONEYPOT_FIELD]: _hp, ...data } = values
|
||||
const ip = clientIp(await headers()) || undefined // headers(): OK w server action — NIE w drzewie strony (SSG)
|
||||
const ip = clientIp(await headers()) || undefined // headers(): OK in a server action — NOT in the page tree (SSG)
|
||||
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
|
||||
return { success: result.success, message: resolveFormMessage(result, texts) }
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// w komponencie klienckim:
|
||||
// in a client component:
|
||||
const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, form.id, locale) })
|
||||
```
|
||||
|
||||
Wynik `submitForm`: `{ success: true, submissionId }` albo `{ success: false, reason, … }`
|
||||
(kody niżej). Opcje: `maxPerMinute` (domyślnie 5, `0` wyłącza), `consentFieldName`.
|
||||
`submitForm` result: `{ success: true, submissionId }` or `{ success: false, reason, … }`
|
||||
(codes below). Options: `payload`, `formId`, `data` (required), `ip`, `locale`, `turnstileToken`,
|
||||
`maxPerMinute` (default 5, `0` turns it off; without `ip` — the shared `unknown-ip` bucket, below),
|
||||
`consentFieldName` (default from `ipalKit({ forms })`, then `'consent'`), `turnstileOnConfigError`
|
||||
(`'allow'` | `'reject'`, default `'allow'`), `turnstileHostnames` (see [turnstile.md](./turnstile.md)).
|
||||
|
||||
### IP klienta i rate limit
|
||||
Simpler: `createSubmitAction({ getCachedPayload, headers })` from `/server` (section 1.9.1 below) —
|
||||
extra options: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute`,
|
||||
`turnstileOnConfigError`, `turnstileHostnames`.
|
||||
|
||||
`clientIp(req | headers, { header?, trustedProxies? })` czyta kolejno
|
||||
`cf-connecting-ip`, `x-real-ip`, a z `X-Forwarded-For` bierze wpis **od prawej**
|
||||
(lewy wpisuje sam klient, więc mógłby podawać nowe IP przy każdym żądaniu i omijać
|
||||
limit). Na produkcji przypnij nagłówek, któremu ufasz, np. `IPAL_IP_HEADER=cf-connecting-ip`
|
||||
za Cloudflare. Bez tego klient, który trafi do aplikacji z pominięciem proxy, może
|
||||
podstawić dowolny z tych nagłówków. Ta sama opcja `clientIp` jest w `createSearchRoute`
|
||||
i `createMcpRoute`.
|
||||
### Client IP and rate limit
|
||||
|
||||
Limity domyślnie trzymane są w pamięci, osobno dla każdej instancji. Kilka instancji
|
||||
→ wspólny store (np. Redis) raz przy starcie: `setRateLimitStore({ hit })`
|
||||
(przykład w JSDoc `RateLimitStore`). Gdy store padnie, żądanie przechodzi (log ostrzeżenia).
|
||||
`clientIp(req | headers, { header?, trustedProxies? })` (from `@intecion/ipal-kit`):
|
||||
|
||||
## Flow i gwarancje
|
||||
- **Pinned header** — `header` or the env **`IPAL_IP_HEADER`**: only that header is read (missing → empty
|
||||
string). For `x-forwarded-for` it takes the `trustedProxies`-th entry (default 1) from the right.
|
||||
- **Not pinned** (default): it trusts **any** of the headers, in this order: `cf-connecting-ip`,
|
||||
`x-real-ip`, then `X-Forwarded-For` counted **from the right** (the client writes the left part itself). A client
|
||||
that reaches the app bypassing the proxy can therefore inject `cf-connecting-ip` /
|
||||
`x-real-ip` and dodge the limit. In production without `IPAL_IP_HEADER` there is a one-time warning in the log.
|
||||
Set e.g. `IPAL_IP_HEADER=cf-connecting-ip` behind Cloudflare, `x-forwarded-for` only behind Traefik/nginx.
|
||||
- No recognised IP → the shared bucket (below). The same `clientIp` option exists in `createSearchRoute`
|
||||
and `createMcpRoute`.
|
||||
|
||||
A missing IP (the proxy strips the header, a wrong `IPAL_IP_HEADER`) does **not** bypass the limit: such requests
|
||||
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
|
||||
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
|
||||
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
|
||||
Without a pinned header the order
|
||||
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
|
||||
behind Cloudflare into the bucket of the edge node) — that is why `IPAL_IP_HEADER` is mandatory in production
|
||||
(`ipalEnvRules({ ipHeader: true })`).
|
||||
|
||||
Limits are kept in memory by default, separately for each instance. Several instances
|
||||
→ a shared store (e.g. Redis) once at startup: `setRateLimitStore({ hit })`
|
||||
(example in the `RateLimitStore` JSDoc). When the store fails, the request goes through (a warning in the log).
|
||||
|
||||
## Flow and guarantees
|
||||
|
||||
1. **Rate limit** per IP → `rate_limited`.
|
||||
2. **Turnstile** — decyduje konfiguracja **serwera**, nie to, czy front wysłał token.
|
||||
Oba klucze ustawione (panel albo env) → token **wymagany**: brak lub nieudany →
|
||||
`turnstile`, odrzucone **przed** zapisem. Klucze nieustawione → widget się nie
|
||||
pokazuje, a sprawdzenie jest pomijane. Szczegóły: [turnstile.md](./turnstile.md).
|
||||
3. **Walidacja** względem definicji formularza z panelu (+ wymuszona zgoda RODO).
|
||||
4. **Zapis** submission (form-submissions) → form-builder wysyła maile z zakładki Emails.
|
||||
2. **Turnstile** — the **server** configuration decides, not whether the front end sent a token.
|
||||
Both keys set (panel or env) → the token is **required**: missing or failed →
|
||||
`turnstile`, rejected **before** storing. Keys not set → the widget does not
|
||||
show, and the check is skipped. Details: [turnstile.md](./turnstile.md).
|
||||
3. **Validation** against the form definition from the panel (+ enforced GDPR consent).
|
||||
4. **Storing** the submission (form-submissions) → the form-builder sends the emails from the Emails tab.
|
||||
|
||||
**Zapisane zgłoszenie = sukces, nawet gdy mail padnie** — błąd wysyłki loguje
|
||||
Payload, dane zgłoszenia nie giną (są w Form Submissions).
|
||||
**A stored submission = success, even when the email fails** — Payload logs the sending error,
|
||||
the submission data is not lost (it is in Form Submissions).
|
||||
|
||||
## Maile
|
||||
## Emails
|
||||
|
||||
Plugin nie składa maili formularzy. Po zapisie submission form-builder wysyła
|
||||
wiadomości skonfigurowane przez edytora (Forms → formularz → Emails), przez
|
||||
`payload.sendEmail`. Żeby wyszły, config musi mieć adapter:
|
||||
The plugin does not compose form emails. After storing a submission, the form-builder sends the
|
||||
messages the editor configured (Forms → form → Emails), through
|
||||
`payload.sendEmail`. For them to go out, the config needs an adapter:
|
||||
|
||||
```ts
|
||||
email: mailAdapter(), // z '@intecion/ipal-kit' — SMTP albo Graph wg panelu (email.md)
|
||||
email: mailAdapter(), // from '@intecion/ipal-kit' — SMTP or Graph according to the panel (email.md)
|
||||
```
|
||||
|
||||
Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i
|
||||
treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu.
|
||||
Then they go through the transport chosen in Site Integrations (SMTP or Graph). The editor sets recipients, subject and
|
||||
body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the code.
|
||||
|
||||
`submitForm` odpowiada tylko za weryfikację Turnstile i zapis. Zgłoszenie zapisuje w języku strony
|
||||
(`locale` z `createSubmitAction`), więc form-builder bierze teksty maili i etykiety w tym języku.
|
||||
`submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language
|
||||
(`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language.
|
||||
|
||||
### Ładne maile (`emailLayout`)
|
||||
### Nice emails (`emailLayout`)
|
||||
|
||||
```ts
|
||||
forms: { emailLayout: true } // opcjonalnie: beforeEmail: (emails, args) => emails (po layoucie)
|
||||
forms: { emailLayout: true } // optional: beforeEmail: (emails, args) => emails (after the layout)
|
||||
```
|
||||
|
||||
- `{{*:table}}` zamienia się w **czytelne podsumowanie**: treść pytania zamiast nazwy pola, etykiety opcji
|
||||
zamiast wartości (także Checkbox group), zaznaczony checkbox = ✓, puste odpowiedzi pominięte, grupy według
|
||||
kroków (tytuły Step). Tylko pola, które odwiedzający widział (ukrytych warunkiem serwer nie zapisuje).
|
||||
- Każdy mail dostaje **szablon** (tabele + inline CSS — Gmail, Outlook, Apple Mail): nagłówek z logo,
|
||||
treść z panelu, stopka. Ustawienia: **Site Settings → Emails** — logo (**PNG/JPG**, SVG nie działa w
|
||||
Gmailu/Outlooku; puste = nazwa strony), kolor akcentu (hex), stopka (per język). Link do strony i
|
||||
absolutny adres logo z `serverURL` w `buildConfig` (ustaw go z `NEXT_PUBLIC_SERVER_URL`).
|
||||
- Błąd przy składaniu szablonu nigdy nie blokuje wysyłki — idzie oryginalny mail, błąd w logu.
|
||||
- Nowa zakładka = migracja w projekcie (`payload migrate:create`).
|
||||
- `{{*:table}}` turns into a **readable summary**: the question text instead of the field name, option labels
|
||||
instead of values (Checkbox group too), a checked checkbox = ✓, empty answers skipped, groups by
|
||||
step (Step titles). Only fields the visitor saw (the server does not store fields hidden by a condition).
|
||||
- Every email gets a **template** (tables + inline CSS — Gmail, Outlook, Apple Mail): a header with the logo,
|
||||
the body from the panel, a footer. Settings: **Site Settings → Emails** — logo (**PNG/JPG**, SVG does not work in
|
||||
Gmail/Outlook; empty = the site name), accent colour (hex), footer (per language). The link to the site and the
|
||||
absolute logo address come from `serverURL` in `buildConfig` (set it from `NEXT_PUBLIC_SERVER_URL`).
|
||||
- An error while building the template never blocks sending — the original email goes out, the error goes to the log.
|
||||
- New tab = a migration in the project (`payload migrate:create`).
|
||||
|
||||
## Własne pola w kolekcji formularzy
|
||||
## Your own fields in the forms collection
|
||||
|
||||
`formOverrides` przechodzi prosto do form-buildera — plugin nie ma opinii, czego
|
||||
formularz potrzebuje poza swoimi polami:
|
||||
`formOverrides` goes straight to the form-builder — the plugin has no opinion about what
|
||||
a form needs beyond its own fields:
|
||||
|
||||
```ts
|
||||
ipalKit({
|
||||
@@ -275,185 +313,198 @@ ipalKit({
|
||||
],
|
||||
admin: { group: 'Content' },
|
||||
},
|
||||
// formSubmissionOverrides: { ... } // to samo dla zgłoszeń
|
||||
// formSubmissionOverrides: { ... } // the same for submissions
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
`fields` dostaje domyślne pola kolekcji i zwraca finalną listę — możesz dodawać,
|
||||
usuwać, zmieniać kolejność. Poza `fields` przyjmuje dowolne ustawienia kolekcji
|
||||
`fields` gets the collection's default fields and returns the final list — you can add,
|
||||
remove and reorder. Besides `fields` it accepts any collection settings
|
||||
(admin, access, hooks).
|
||||
|
||||
## Bezpieczeństwo i wynik zgłoszenia
|
||||
## Security and the submission result
|
||||
|
||||
`submitForm` przechodzi trzy bramki w kolejności rosnącej po koszcie: rate limit
|
||||
(in-memory, per IP), Turnstile, walidacja względem schematu formularza. Dopiero
|
||||
potem zapis. Flood ginie, zanim dotknie sieci czy bazy.
|
||||
`submitForm` passes three gates in order of increasing cost: rate limit
|
||||
(in-memory, per IP), Turnstile, validation against the form schema. Only
|
||||
then does it store. A flood dies before it touches the network or the database.
|
||||
|
||||
**REST zamknięty.** Form-builder domyślnie pozwala każdemu tworzyć zgłoszenia przez
|
||||
`POST /api/form-submissions` — z pominięciem wszystkich bramek poniżej. ipal-kit
|
||||
ustawia `access.create` kolekcji `form-submissions` na „tylko zalogowani”; front
|
||||
wysyła przez `submitForm` (server action → Local API), więc to go nie dotyczy.
|
||||
Świadomie publiczny REST (np. zewnętrzna aplikacja) →
|
||||
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — wtedy
|
||||
zabezpieczenia `submitForm` na tej drodze nie działają.
|
||||
**REST is closed.** By default the form-builder lets anyone create submissions through
|
||||
`POST /api/form-submissions` — skipping all the gates below. ipal-kit
|
||||
sets `access.create` of the `form-submissions` collection to "logged-in users only"; the front end
|
||||
submits through `submitForm` (server action → Local API), so this does not affect it.
|
||||
A deliberately public REST (e.g. an external app) →
|
||||
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — then
|
||||
the `submitForm` safeguards do not apply on that path.
|
||||
|
||||
Walidacja jest istotna, bo server action to publiczny endpoint — da się go wołać
|
||||
z pominięciem formularza. Plugin ładuje definicję formularza i: odrzuca nieznane
|
||||
klucze, wymusza pola `required`, tnie długość (5000 znaków). Do bazy trafia tylko
|
||||
to, co formularz definiuje.
|
||||
**Only `editor+` edits forms.** The `forms` collection is publicly readable (the fields render the
|
||||
form), but `create`/`update`/`delete` and reading the Emails tab (recipients, BCC) require the role
|
||||
`editor` or `admin` — a `user` account cannot add itself as BCC to every submission. Override:
|
||||
`forms: { formOverrides: { access: { … } } }`.
|
||||
|
||||
Rate limit: 5/min/IP domyślnie, `maxPerMinute` zmienia, `0` wyłącza (gdy limiter
|
||||
jest z przodu). In-memory — przy wielu instancjach licznik jest per-proces, więc
|
||||
efektywny limit to per-instancja. Do formularza kontaktowego wystarcza.
|
||||
Validation matters, because a server action is a public endpoint — it can be called
|
||||
without the form. The plugin loads the form definition and: rejects unknown
|
||||
keys, enforces `required` fields, truncates length (5000 characters). Only what the
|
||||
form defines reaches the database.
|
||||
|
||||
### Honeypot — darmowa druga warstwa antyspam
|
||||
Rate limit: 5/min/IP by default (60 s window, the `form` counter is separate from search and MCP),
|
||||
`maxPerMinute` changes it, `0` turns it off (when a limiter sits in front). In-memory — with several
|
||||
instances the counter is per process (unless `setRateLimitStore`).
|
||||
|
||||
Ukryte pole, którego realny użytkownik nie widzi ani nie wypełni, a naiwny bot
|
||||
tak. Zero tarcia (bez sieci, bez interakcji), obok Turnstile. Czyste funkcje —
|
||||
klient renderuje input, serwer sprawdza:
|
||||
Unknown keys in `data` (other than form fields and `cf-turnstile-response` /
|
||||
`g-recaptcha-response`) reject the **whole** submission (`kind: 'unknown_fields'`).
|
||||
|
||||
### Honeypot — a free second anti-spam layer
|
||||
|
||||
A hidden field that a real user neither sees nor fills in, but a naive bot
|
||||
does. Zero friction (no network, no interaction), alongside Turnstile. Pure functions —
|
||||
the client renders the input, the server checks it:
|
||||
|
||||
```tsx
|
||||
// front — w formularzu:
|
||||
// front end — in the form:
|
||||
import { honeypotInputProps } from '@intecion/ipal-kit/client'
|
||||
<input {...honeypotInputProps()} /> // off-screen, aria-hidden, tabIndex -1
|
||||
```
|
||||
|
||||
```ts
|
||||
// server action — SPRAWDŹ PIERWSZE, przed submitForm:
|
||||
// server action — CHECK FIRST, before submitForm:
|
||||
import { isHoneypotTripped, HONEYPOT_FIELD } from '@intecion/ipal-kit'
|
||||
if (isHoneypotTripped(values)) return { success: true } // udawaj sukces (bot bez sygnału)
|
||||
const { [HONEYPOT_FIELD]: _hp, ...clean } = values // usuń, by submitForm nie widział nieznanego pola
|
||||
if (isHoneypotTripped(values)) return { success: true } // fake success (no signal to the bot)
|
||||
const { [HONEYPOT_FIELD]: _hp, ...clean } = values // remove it so submitForm does not see an unknown field
|
||||
return submitForm({ /* … */ data: clean })
|
||||
```
|
||||
|
||||
Nazwa pola domyślnie `company_url` (wygląda realnie dla bota); własna:
|
||||
The field name defaults to `company_url` (looks real to a bot); your own:
|
||||
`honeypotInputProps('website_2')` + `isHoneypotTripped(values, 'website_2')`.
|
||||
|
||||
### Wynik to KOD, nie tekst
|
||||
### The result is a CODE, not text
|
||||
|
||||
`submitForm` zwraca ustrukturyzowany błąd — plugin mówi CO się stało, projekt
|
||||
decyduje JAK to pokazać (język, brzmienie, obsługa per pole):
|
||||
`submitForm` returns a structured error — the plugin says WHAT happened, the project
|
||||
decides HOW to show it (language, wording, per-field handling):
|
||||
|
||||
```ts
|
||||
type SubmitFormResult =
|
||||
| { success: true; submissionId: string | number }
|
||||
| { success: false; reason: 'rate_limited' }
|
||||
| { success: false; reason: 'turnstile' }
|
||||
| { success: false; reason: 'validation'; field?: string; kind?: 'required' | 'too_long' | 'unknown_fields' }
|
||||
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' }
|
||||
| { success: false; reason: 'not_found' }
|
||||
| { success: false; reason: 'consent'; field?: string }
|
||||
| { success: false; reason: 'error' }
|
||||
```
|
||||
|
||||
Front mapuje kody na własne komunikaty:
|
||||
The front end maps codes to its own messages:
|
||||
|
||||
```tsx
|
||||
function errorMessage(r) {
|
||||
switch (r.reason) {
|
||||
case 'rate_limited': return 'Zbyt wiele zgłoszeń...'
|
||||
case 'rate_limited': return 'Too many submissions...'
|
||||
case 'validation':
|
||||
if (r.kind === 'required') return 'Uzupełnij wymagane pola.'
|
||||
// r.field → podświetl konkretne pole
|
||||
if (r.kind === 'required') return 'Fill in the required fields.'
|
||||
// r.field → highlight the specific field
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ten sam wzorzec co consent: plugin nie zaszywa języka, oddaje dane.
|
||||
The same pattern as consent: the plugin does not hard-code a language, it hands over data.
|
||||
|
||||
|
||||
## Zgoda RODO (consent field)
|
||||
## GDPR consent (consent field)
|
||||
|
||||
Pole zgody RODO to checkbox o nazwie `consent` (konfigurowalna przez
|
||||
`FormsOption.consentFieldName`). Plugin WYMUSZA jego zaznaczenie SERVER-SIDE —
|
||||
niezależnie od tego, jak redaktor ustawił pole w panelu.
|
||||
The GDPR consent field is the field named `consent` (the name is changed by the `consentFieldName` argument
|
||||
of `submitForm` / `createSubmitAction`). The plugin ENFORCES it being checked SERVER-SIDE
|
||||
(the value must be exactly `true`) — regardless of how the editor set up the field
|
||||
in the panel and of the "Show only when" condition.
|
||||
|
||||
### Dlaczego server-side
|
||||
### Why server-side
|
||||
|
||||
Zgoda egzekwowana jest w `validateSubmission`, nie flagą w panelu. To jedyne
|
||||
miejsce, którego redaktor nie osłabi (zapominając `required`) ani nie naruszy
|
||||
(ustawiając `defaultValue: true` — pre-zaznaczenie, którego RODO zabrania), a
|
||||
front nie obejdzie. Jeśli formularz ma pole `consent`, MUSI być zaznaczone,
|
||||
inaczej `submitForm` zwraca `reason: 'consent'`.
|
||||
Consent is enforced in `validateSubmission`, not by a flag in the panel. It is the only
|
||||
place the editor cannot weaken (by forgetting `required`) or break
|
||||
(by setting `defaultValue: true` — a pre-checked box, which GDPR forbids), and the
|
||||
front end cannot bypass. If the form has a `consent` field, it MUST be checked,
|
||||
otherwise `submitForm` returns `reason: 'consent'`.
|
||||
|
||||
### Jak użyć
|
||||
### How to use
|
||||
|
||||
1. Redaktor dodaje w panelu checkbox o nazwie `consent`, label „Akceptuję
|
||||
politykę prywatności [link]" (link do polityki wpisuje w label — treść zgody
|
||||
należy do panelu).
|
||||
2. Plugin wymusza zaznaczenie. Niezaznaczony → `reason: 'consent'`.
|
||||
3. Komunikat z modułu notifications (`notifications.form.consent`, per język).
|
||||
1. The editor adds a checkbox named `consent` in the panel, with a label like "I accept the
|
||||
privacy policy [link]" (the policy link goes into the label — the consent text
|
||||
belongs to the panel).
|
||||
2. The plugin enforces it being checked. Unchecked → `reason: 'consent'`.
|
||||
3. The message comes from the notifications module (`notifications.form.consent`, per language).
|
||||
|
||||
Zmiana nazwy pola:
|
||||
Renaming the field:
|
||||
|
||||
```ts
|
||||
ipalKit({ forms: { consentFieldName: 'zgoda' } })
|
||||
export const sendForm = createSubmitAction({ getCachedPayload, headers, consentFieldName: 'zgoda' })
|
||||
// or: submitForm({ …, consentFieldName: 'zgoda' })
|
||||
```
|
||||
|
||||
## Komunikaty — resolveFormMessage (zalecane)
|
||||
Or once for the whole site: `ipalKit({ forms: { consentFieldName: 'zgoda' } })` — `submitForm`
|
||||
reads it from `payload.config.custom.ipal` when the call does not pass one.
|
||||
|
||||
Zamiast ręcznego switcha po `reason`, użyj `resolveFormMessage` z modułu
|
||||
notifications — mapuje kod na tekst z panelu, per język, z interpolacją `{field}`:
|
||||
## Messages — resolveFormMessage (recommended)
|
||||
|
||||
Instead of a hand-written switch on `reason`, use `resolveFormMessage` from the
|
||||
notifications module — it maps the code to text from the panel, per language, with `{field}` interpolation:
|
||||
|
||||
```tsx
|
||||
import { resolveFormMessage, getNotificationTexts } from '@intecion/ipal-kit'
|
||||
|
||||
const notifications = await getNotificationTexts({ payload, locale })
|
||||
// w FormRenderer:
|
||||
// in FormRenderer:
|
||||
if (!result.success) {
|
||||
setError(resolveFormMessage(result, notifications.form))
|
||||
}
|
||||
```
|
||||
|
||||
To obsługuje WSZYSTKIE kody (w tym `consent`, `rate_limited`, `validation` z
|
||||
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
|
||||
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
|
||||
It handles ALL codes (including `consent`, `rate_limited`, `validation` with
|
||||
`{field}`) with texts from the panel. Keep the hand-written switch (above) only if you do not
|
||||
use the notifications module. Details: [notifications.md](./notifications.md).
|
||||
|
||||
## Logika klienta — useForm / useContactForm (niższy poziom)
|
||||
## Client logic — useForm / useContactForm (lower level)
|
||||
|
||||
Dla formularzy z panelu używaj `RenderForm` / `useBuilderForm` (wyżej) — mają kroki, listy
|
||||
wyboru i walidację z definicji pola. `useForm` to silnik pod spodem: dla formularza **spoza
|
||||
buildera** (np. wyszukiwarka z filtrami), nie dla formularzy kontaktowych.
|
||||
For panel forms use `RenderForm` / `useBuilderForm` (above) — they have steps, choice
|
||||
lists and validation from the field definition. `useForm` is the engine underneath: for a form **outside
|
||||
the builder** (e.g. a search with filters), not for contact forms.
|
||||
|
||||
`submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w
|
||||
każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit,
|
||||
stan sukcesu/błędu — ~150 linii identycznego kodu na projekt. To wyniesione do
|
||||
hooka. **Hook nie renderuje ŻADNEGO markupu** — projekt zachowuje 100% kontroli
|
||||
nad wyglądem (zasada „nie pozbawiamy projektów kontroli nad wyglądem").
|
||||
`submitForm` is the server. On the client side the same plumbing was repeated in
|
||||
every project: `useState` for fields, an email regex, the Turnstile token, submit,
|
||||
success/error state — ~150 lines of identical code per project. It was moved into a
|
||||
hook. **The hook renders NO markup at all** — the project keeps 100% control
|
||||
over the looks (the rule "we do not take control over the looks away from projects").
|
||||
|
||||
To warstwa LOGIKI, nie zamiennik buildera. Zasada „pola z buildera" obowiązuje
|
||||
dalej: dla formularzy edytowalnych przez redaktora budujesz `initialValues` i
|
||||
reguły z definicji z panelu i podajesz do `useForm` (wariant dynamiczny niżej).
|
||||
`useContactForm` to preset dla klasycznego formularza kontaktowego o stałych
|
||||
polach — gdy to świadomie właściwy wybór.
|
||||
This is a LOGIC layer, not a replacement for the builder. The rule "fields from the builder" still
|
||||
applies: for forms the editor can edit, you build `initialValues` and
|
||||
rules from the definition in the panel and pass them to `useForm` (dynamic variant below).
|
||||
`useContactForm` is a preset for a classic contact form with fixed
|
||||
fields — when that is deliberately the right choice.
|
||||
|
||||
Antywzorzec, który hook eliminuje, to **duplikacja logiki** (walidacja/submit/
|
||||
Turnstile ręcznie w każdym projekcie), a nie „użycie hooka".
|
||||
The anti-pattern the hook removes is **duplicated logic** (validation/submit/
|
||||
Turnstile by hand in every project), not "using a hook".
|
||||
|
||||
### Preset — formularz kontaktowy (zero walidatorów)
|
||||
### Preset — contact form (zero validators)
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
import { useContactForm } from '@intecion/ipal-kit/client'
|
||||
|
||||
const f = useContactForm({
|
||||
submitAction, // Twój server action wołający submitForm
|
||||
submitAction, // your server action that calls submitForm
|
||||
requireTurnstile: Boolean(siteKey),
|
||||
requireTopic: topics.length > 0,
|
||||
requireConsent: Boolean(consentText),
|
||||
})
|
||||
// JSX i klasy Twoje — z hooka tylko wiring:
|
||||
// JSX and classes are yours — only the wiring comes from the hook:
|
||||
<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>
|
||||
{f.isSuccess && <PanelSukcesu onReset={f.reset} />}
|
||||
{f.isSuccess && <SuccessPanel onReset={f.reset} />}
|
||||
```
|
||||
|
||||
Pola presetu: `name, email, phone, topic, message, consent`. Zwraca:
|
||||
Preset fields: `name, email, phone, topic, message, consent`. Returns:
|
||||
`values, errors, isSubmitting, isSuccess, errorMessage, turnstileToken,
|
||||
setField, setValues, setTurnstileToken, handleSubmit, reset`.
|
||||
|
||||
### Generyczny engine — dowolne / dynamiczne pola
|
||||
### Generic engine — any / dynamic fields
|
||||
|
||||
```tsx
|
||||
import { useForm, buildValidator, required, email, minLength, pattern } from '@intecion/ipal-kit/client'
|
||||
@@ -463,14 +514,14 @@ const f = useForm({
|
||||
submitAction,
|
||||
validate: buildValidator({
|
||||
company: [required()],
|
||||
nip: [required(), pattern(/^\d{10}$/, 'NIP = 10 cyfr')],
|
||||
nip: [required(), pattern(/^\d{10}$/, 'NIP = 10 digits')],
|
||||
email: [required(), email()],
|
||||
message: [required(), minLength(10)],
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
Pola dynamiczne z buildera — schemat budowany w runtime z definicji z panelu:
|
||||
Dynamic fields from the builder — the schema is built at runtime from the definition in the panel:
|
||||
|
||||
```tsx
|
||||
const initialValues = Object.fromEntries(fields.map((fl) => [fl.name, fl.type === 'checkbox' ? false : '']))
|
||||
@@ -478,44 +529,44 @@ const validate = buildValidator(Object.fromEntries(fields.map((fl) => [fl.name,
|
||||
const f = useForm({ initialValues, submitAction, validate })
|
||||
```
|
||||
|
||||
### Walidatory (czyste — też po stronie serwera)
|
||||
### Validators (pure — also server-side)
|
||||
|
||||
`required`, `email`, `minLength`, `maxLength`, `checked`, `pattern`, `custom`,
|
||||
`isEmail`, `buildValidator`. Każdy przyjmuje własny komunikat. Są czyste (bez
|
||||
`'use client'`), więc tych samych reguł użyjesz do re-walidacji w server action.
|
||||
`isEmail`, `buildValidator`. Each takes its own message. They are pure (no
|
||||
`'use client'`), so you can use the same rules to re-validate in a server action.
|
||||
|
||||
### errors to STRING, nie boolean
|
||||
### errors are a STRING, not a boolean
|
||||
|
||||
`errors.<pole>` to komunikat (truthy, gdy błąd). Działa jako warunek `className`
|
||||
jak dawny boolean, a dodatkowo masz tekst do wyświetlenia. `setField` czyści błąd
|
||||
pola przy edycji (domyślnie).
|
||||
`errors.<field>` is a message (truthy when there is an error). It works as a `className` condition
|
||||
like the old boolean, and you also get text to display. `setField` clears the field's error
|
||||
on edit (by default).
|
||||
|
||||
### Event GTM/analytics po wysłaniu (Lead/Pixel)
|
||||
### GTM/analytics event after submitting (Lead/Pixel)
|
||||
|
||||
Tag „Lead" (Meta Pixel / GA) w GTM zwykle odpala się na zdarzeniu `form_submit`
|
||||
w `dataLayer`. Hook ma `onSuccess` (odpala się RAZ po udanej wysyłce), a plugin
|
||||
daje helper `pushDataLayer` — więc event leci automatycznie, bez ręcznego pushu
|
||||
w każdym projekcie:
|
||||
A "Lead" tag (Meta Pixel / GA) in GTM usually fires on a `form_submit` event
|
||||
in `dataLayer`. The hook has `onSuccess` (fires ONCE after a successful submit), and the plugin
|
||||
provides the `pushDataLayer` helper — so the event goes out automatically, without a manual push
|
||||
in every project:
|
||||
|
||||
```tsx
|
||||
import { useContactForm, pushDataLayer } from '@intecion/ipal-kit/client'
|
||||
|
||||
const f = useContactForm({
|
||||
submitAction,
|
||||
onSuccess: (_result, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
|
||||
onSuccess: (_result, v) => pushDataLayer('form_submit', { form_name: v.topic || 'contact' }),
|
||||
})
|
||||
```
|
||||
|
||||
W GTM: Data Layer Variable `DLV – form_name` (klucz `form_name`) + custom event
|
||||
trigger `form_submit`. **Zgodę nadal gatuje GTM** (`ad_storage`) — `pushDataLayer`
|
||||
tylko emituje zdarzenie, nie omija consentu. `onSuccess` jest owinięty w
|
||||
try/catch — zepsuty analytics nie zablokuje udanej wysyłki. `pushDataLayer` jest
|
||||
SSR-safe i buforuje event, gdy GTM jeszcze się nie załadował.
|
||||
In GTM: Data Layer Variable `DLV – form_name` (key `form_name`) + a custom event
|
||||
trigger `form_submit`. **Consent is still gated by GTM** (`ad_storage`) — `pushDataLayer`
|
||||
only emits the event, it does not bypass consent. `onSuccess` is wrapped in
|
||||
try/catch — broken analytics will not block a successful submit. `pushDataLayer` is
|
||||
SSR-safe and buffers the event when GTM has not loaded yet.
|
||||
|
||||
#### Zarządzanie z PANELU (bez kodu per formularz)
|
||||
#### Managing from the PANEL (no code per form)
|
||||
|
||||
Zamiast wpisywać nazwę eventu/parametry w kodzie, przenieś to do panelu. Dodaj
|
||||
pola analityki do kolekcji Forms:
|
||||
Instead of writing the event name/parameters in code, move them to the panel. Add
|
||||
the analytics fields to the Forms collection:
|
||||
|
||||
```ts
|
||||
// payload.config.ts
|
||||
@@ -529,54 +580,74 @@ ipalKit({
|
||||
})
|
||||
```
|
||||
|
||||
Redaktor ustawia per formularz (etykiety panelu po angielsku): **Event name**
|
||||
(domyślnie `form_submit`) i **Event parameters** (klucz/wartość; wartość `$pole`
|
||||
bierze się z pola formularza, np. `form_name = $topic`). Grupa pól nazywa się
|
||||
**Analytics (GTM / dataLayer)**. Front czyta to i emituje automatycznie — jedna, generyczna
|
||||
linia w współdzielonym rendererze, działa dla WSZYSTKICH formularzy:
|
||||
The editor sets per form (panel labels are in English): **Event name**
|
||||
(default `form_submit`) and **Event parameters** (key/value; a `$field` value
|
||||
is taken from the form field, e.g. `form_name = $topic`). The field group is called
|
||||
**Analytics (GTM / dataLayer)**. The front end reads it and emits automatically — one generic
|
||||
line in the shared renderer works for ALL forms:
|
||||
|
||||
```tsx
|
||||
import { useContactForm, formAnalyticsOnSuccess } from '@intecion/ipal-kit/client'
|
||||
|
||||
const f = useContactForm({
|
||||
submitAction,
|
||||
onSuccess: formAnalyticsOnSuccess(form.analytics), // form.analytics z panelu
|
||||
onSuccess: formAnalyticsOnSuccess(form.analytics), // form.analytics from the panel
|
||||
})
|
||||
```
|
||||
|
||||
Efekt: dodanie śledzonego formularza albo zmiana nazwy eventu/parametrów = **tylko
|
||||
panel, zero deployu**. Pusta nazwa zdarzenia → nic się nie wypycha.
|
||||
Result: adding a tracked form or changing the event name/parameters = **panel only,
|
||||
zero deploys**. An empty event name → nothing is pushed.
|
||||
|
||||
Co zostaje w GTM (świadomie — to też panel, tylko Google): sam tag (Lead/Pixel),
|
||||
jego trigger na nazwę zdarzenia i warunek zgody `ad_storage`. Plugin dostarcza
|
||||
event + sygnał consentu; GTM decyduje, co i kiedy odpalić.
|
||||
What stays in GTM (deliberately — it is also a panel, just Google's): the tag itself (Lead/Pixel),
|
||||
its trigger on the event name and the `ad_storage` consent condition. The plugin provides the
|
||||
event + the consent signal; GTM decides what to fire and when.
|
||||
|
||||
### resolveLocalized — koniec z getSafeString
|
||||
### resolveLocalized — no more getSafeString
|
||||
|
||||
Rozwiązywanie wartości lokalizowanej (topics, etykiety) to jeden import, nie
|
||||
kopiowany `(v as any)[locale]`:
|
||||
Resolving a localized value (topics, labels) is one import, not a
|
||||
copied `(v as any)[locale]`:
|
||||
|
||||
```ts
|
||||
import { resolveLocalized } from '@intecion/ipal-kit' // lub /client
|
||||
import { resolveLocalized } from '@intecion/ipal-kit' // root only (not in /client)
|
||||
const label = resolveLocalized(topic.label, locale)
|
||||
```
|
||||
|
||||
## PUŁAPKA — pola captchy
|
||||
## TRAP — captcha fields
|
||||
|
||||
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
|
||||
(nie odrzuca jako `unknown_fields`) — bo sam obsługuje Turnstile. Nie musisz go
|
||||
filtrować w kliencie.
|
||||
Turnstile injects a hidden `cf-turnstile-response` field. The plugin tolerates it
|
||||
(does not reject it as `unknown_fields`) — because it handles Turnstile itself. You do not need to
|
||||
filter it out on the client.
|
||||
|
||||
## 1.9.1 — gotowa akcja, seed formularza, walidacja typów
|
||||
## 1.9.1 — ready action, form seed, type validation
|
||||
|
||||
- **`createSubmitAction({ getCachedPayload, headers })`** z `/server` zastępuje ręczny `actions.ts`:
|
||||
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` z
|
||||
`next/headers`, wstrzyknięty). Honeypot → `clientIp` → `submitForm` → tekst z Notifications;
|
||||
wynik `{ success, message, reason?, field? }`.
|
||||
- **Seed formularza** (`ipal-form/resources/seed-form.template.ts`): pola, potwierdzenie, mail do firmy
|
||||
(adres z panelu) i potwierdzenie do klienta (`{{email}}`), każdy język, idempotentny. Obowiązkowy.
|
||||
- **Walidacja po typie pola z panelu:** email = jeden adres (bez `a@x, b@y`, bez CR/LF), select/radio
|
||||
tylko wartości z panelu, liczby, checkbox `true/false`, obiekty i tablice odrzucane, znaki
|
||||
sterujące i bidi usuwane. Błąd: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
|
||||
- **Dostęp:** zgłoszenia czytają tylko `editor`/`admin` (wcześniej każde konto), usuwa `admin`;
|
||||
zakładka Emails formularza (adresy odbiorców) ukryta w publicznym `GET /api/forms`.
|
||||
- **`createSubmitAction({ getCachedPayload, headers })`** from `/server` replaces a hand-written `actions.ts`:
|
||||
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` from
|
||||
`next/headers`, injected). Honeypot → `clientIp` → `submitForm` → text from Notifications;
|
||||
result `{ success, message, reason?, field? }`.
|
||||
- **Form seed** (`ipal-form/resources/seed-form.template.ts`): fields, confirmation, an email to the company
|
||||
(address from the panel) and a confirmation to the customer (`{{email}}`), every language, idempotent. Mandatory.
|
||||
- **Validation by the field type from the panel:** email = one address (no `a@x, b@y`, no CR/LF), select/radio
|
||||
only values from the panel, numbers, checkbox `true/false`, objects and arrays rejected, control
|
||||
and bidi characters removed. Error: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
|
||||
- **Access:** submissions are read only by `editor`/`admin` (before: any account), deleted by `admin`;
|
||||
the form's Emails tab (recipient addresses) is hidden in the public `GET /api/forms`.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
|
||||
Single field types: `forms.fields.<type>: false`.
|
||||
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
|
||||
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
|
||||
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
|
||||
editor+, `read`: public) — in `formOverrides.access`. The Emails tab protection (`read`: editor+) is
|
||||
applied to the default fields **before** `formOverrides.fields`, so you change it there.
|
||||
- **Override a field type:** `forms.fields.<type>: <Block>` replaces the block; your own blocks with "Placeholder" /
|
||||
time: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root).
|
||||
- **Submit gates:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = no limit),
|
||||
`turnstileOnConfigError`, `turnstileHostnames`, `consentFieldName`, `clientIp`, `honeypotField`;
|
||||
site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`.
|
||||
- **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/<id>` = 403;
|
||||
submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`.
|
||||
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template.
|
||||
- **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`,
|
||||
`visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root).
|
||||
|
||||
Reference in New Issue
Block a user