Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d28cbe2570 | ||
|
|
2bd9d60822 | ||
|
|
0f6a43ad12 | ||
|
|
14d71bcc3a | ||
|
|
78e4e0f8e6 | ||
|
|
8f8b79d003 | ||
|
|
91d5e986c5 | ||
|
|
080086adfe | ||
|
|
8c1a8b0e8e | ||
|
|
002eef56d1 | ||
|
|
924b5cf8be |
@@ -8,6 +8,78 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
|
|||||||
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
||||||
dopiero powyżej 20.
|
dopiero powyżej 20.
|
||||||
|
|
||||||
|
## 1.10.0
|
||||||
|
|
||||||
|
### Nowe
|
||||||
|
- **Baner cookies pod projekt** — `CookieBanner`: `order` (kolejność przycisków), `settings="modal"` (ustawienia
|
||||||
|
w oknie na środku: ✕, Escape, klik w tło), `controls="switch"` (przełączniki `role="switch"`),
|
||||||
|
`settingsActions` (np. Zapisz / Tylko niezbędne / Akceptuj), `icon={false}`; `classNames` ma slot dla każdego
|
||||||
|
elementu (tekst, każdy przycisk, modal, karta kategorii, przełącznik, znacznik). Cookie Settings: `eyebrow`,
|
||||||
|
`title`, `settingsDescription`, `alwaysActiveLabel`, `buttons.close`. Opis: consent.md → „Układ”.
|
||||||
|
|
||||||
|
### Poprawki
|
||||||
|
- **`/client` nie wciąga panelu admina do strony.** `MaskedField`, `TestEmailButton`, `IntegrationStatusBanner`
|
||||||
|
(importują `@payloadcms/ui`) są teraz w `/admin`; `sideEffects` w package.json. Każda strona importująca
|
||||||
|
cokolwiek z `/client` (CookieBanner, LanguageSwitcher…) ładowała ~235 KB gz kodu panelu. Test pilnuje regresji.
|
||||||
|
|
||||||
|
### Wymaga zmian w projekcie
|
||||||
|
- `pnpm payload generate:importmap` (ścieżki komponentów panelu: `/client#…` → `/admin#…`), `rm -rf .next`.
|
||||||
|
- Import `MaskedField` / `TestEmailButton` / `IntegrationStatusBanner` z `@intecion/ipal-kit/client` →
|
||||||
|
`@intecion/ipal-kit/admin`.
|
||||||
|
- Nowe pola Cookie Settings: Postgres/SQLite → `pnpm payload migrate:create`; MongoDB bez zmian.
|
||||||
|
|
||||||
|
## 1.9.9
|
||||||
|
|
||||||
|
### Nowe
|
||||||
|
- **Ładne maile z formularzy** (`forms: { emailLayout: true }`): `{{*:table}}` → czytelne podsumowanie (pytania,
|
||||||
|
etykiety odpowiedzi, grupy według kroków, bez pustych pól) + szablon maila (logo, kolor akcentu, stopka z
|
||||||
|
Site Settings → Emails; tabele + inline CSS). Przepustka `forms.beforeEmail`. Opis: forms.md → „Ładne maile”.
|
||||||
|
|
||||||
|
### Poprawki
|
||||||
|
- `submitForm` zapisuje zgłoszenie w języku strony — maile (temat, treść, potwierdzenie) wychodziły zawsze w
|
||||||
|
języku domyślnym, także dla odwiedzających wersję angielską.
|
||||||
|
|
||||||
|
### Wymaga zmian w projekcie
|
||||||
|
- `emailLayout: true` dodaje pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`).
|
||||||
|
Ustaw `serverURL` w `buildConfig` (absolutny adres logo i link w mailu).
|
||||||
|
|
||||||
|
## 1.9.8
|
||||||
|
|
||||||
|
### Nowe
|
||||||
|
- **Strona w budowie** (narzędzie deweloperskie): Site Settings → Under construction — przełącznik, lista
|
||||||
|
„Pages still available” i teksty popupu. Gdy włączone, otwiera się tylko strona główna i wybrane strony
|
||||||
|
(w każdym języku); inne adresy → strona główna z popupem, kliknięcie linku do zablokowanej strony →
|
||||||
|
popup zamiast przejścia. `createPageRoute(…, { redirect })`, `getConstructionMode(locale)`,
|
||||||
|
`<ConstructionNotice>` (`/client`). Opis: construction.md.
|
||||||
|
|
||||||
|
### Wymaga zmian w projekcie
|
||||||
|
- Nowe pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`, jeśli projekt ich używa).
|
||||||
|
Bez `redirect` w `createPageRoute` i bez `<ConstructionNotice>` tryb nie działa (nic się nie zmienia).
|
||||||
|
|
||||||
|
## 1.9.7
|
||||||
|
|
||||||
|
### Nowe
|
||||||
|
- **Pola i kroki warunkowe w formularzach z panelu** („Show only when”, `showWhen`): każde pole,
|
||||||
|
Checkbox group, message i **Step** może pokazywać się tylko przy wybranej odpowiedzi innego pola
|
||||||
|
(`field` + `values` po przecinku). Ukryty Step wypada z formularza razem z polami, kolejne kroki
|
||||||
|
się przenumerowują. Przeglądarka i serwer stosują tę samą regułę (`visibleFields`): ukryte pole nie
|
||||||
|
jest wymagane ani zapisywane; zgoda RODO (`consent`) jest egzekwowana zawsze. Opis: forms.md →
|
||||||
|
„Pola i kroki warunkowe”.
|
||||||
|
|
||||||
|
### Wymaga zmian w projekcie
|
||||||
|
- Nowa grupa w blokach formularzy = nowe kolumny w bazie. Po aktualizacji: `pnpm payload migrate:create`
|
||||||
|
(z kompletem `R2_*`, jeśli projekt ich używa) i `pnpm payload migrate`. Istniejące formularze działają
|
||||||
|
bez zmian (puste „Show only when” = pole zawsze widoczne).
|
||||||
|
|
||||||
|
## 1.9.6
|
||||||
|
|
||||||
|
### Poprawki
|
||||||
|
- Trasa Markdown: bezpieczny typ przy odczycie kodów języków z configu (bez zmian w działaniu).
|
||||||
|
Wydanie zbiorcze — zawiera wszystko z 1.9.2–1.9.5 (formularze krokowe, `SiteProviders`,
|
||||||
|
`createPageRoute`, trasy z jednej linii, własne style linków, `getSystemLinks`, Markdown na
|
||||||
|
stronie jednojęzycznej, nowe reguły audytu). Przy aktualizacji ze starszej wersji przejdź sekcje
|
||||||
|
„Wymaga zmian w projekcie” od swojej wersji w górę.
|
||||||
|
|
||||||
## 1.9.5
|
## 1.9.5
|
||||||
|
|
||||||
### Poprawki
|
### Poprawki
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ Szczegóły API — jeden plik na moduł:
|
|||||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||||
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||||
| Zgoda cookies, baner | [consent.md](./consent.md) |
|
| Zgoda cookies, baner | [consent.md](./consent.md) |
|
||||||
|
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
|
||||||
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
|
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
|
||||||
| Email SMTP / Graph | [email.md](./email.md) |
|
| Email SMTP / Graph | [email.md](./email.md) |
|
||||||
| Walidacja env | [env.md](./env.md) |
|
| Walidacja env | [env.md](./env.md) |
|
||||||
|
|||||||
+44
-4
@@ -168,15 +168,55 @@ zmienna po zmiennej. Na większe zmiany są `classNames`:
|
|||||||
<CookieButton className="fixed bottom-6 right-6 ..." />
|
<CookieButton className="fixed bottom-6 right-6 ..." />
|
||||||
```
|
```
|
||||||
|
|
||||||
Sloty: `root`, `primaryButton`, `secondaryButton`. Podany className zastępuje
|
Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swój slot (1.10.0):
|
||||||
domyślny (nie dokleja się).
|
|
||||||
|
| Slot | Element |
|
||||||
|
|---|---|
|
||||||
|
| `root`, `body`, `content` | pasek, wewnętrzna szerokość, rząd tekst + przyciski |
|
||||||
|
| `text`, `icon`, `eyebrow`, `title`, `message`, `link` | blok tekstu banera |
|
||||||
|
| `actions` | rząd przycisków banera |
|
||||||
|
| `primaryButton`, `secondaryButton` | dwa style przycisków (domyślne dla wszystkich) |
|
||||||
|
| `acceptButton`, `rejectButton`, `settingsButton`, `saveButton`, `backButton` | pojedyncze przyciski — puste → `primaryButton` / `secondaryButton` |
|
||||||
|
| `overlay`, `dialog`, `closeButton` | modal ustawień (`settings="modal"`) |
|
||||||
|
| `settingsTitle`, `settingsDescription`, `categories`, `category`, `categoryTitle`, `categoryDescription` | widok ustawień |
|
||||||
|
| `control`, `controlThumb`, `badge` | checkbox / przełącznik, kciuk przełącznika, znacznik „Zawsze aktywne” |
|
||||||
|
| `settingsActions` | rząd przycisków pod kategoriami |
|
||||||
|
|
||||||
|
### Układ: kolejność przycisków, modal, przełączniki (1.10.0)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<CookieBanner
|
||||||
|
equalChoice
|
||||||
|
icon={false} // bez ikony ciasteczka
|
||||||
|
order={['accept', 'reject', 'settings']} // przyciski banera w tej kolejności
|
||||||
|
settings="modal" // ustawienia w oknie na środku (✕, Escape, klik w tło)
|
||||||
|
controls="switch" // przełączniki role="switch" zamiast checkboxów
|
||||||
|
settingsActions={['save', 'reject', 'accept']} // przyciski pod kategoriami
|
||||||
|
classNames={{ … }}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Domyślnie (bez tych propsów) baner wygląda i działa jak przed 1.10.0.
|
||||||
|
|
||||||
|
Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się nie pokazuje:
|
||||||
|
|
||||||
|
| Pole | Gdzie |
|
||||||
|
|---|---|
|
||||||
|
| `eyebrow` | mały napis nad tytułem banera („Prywatność i cookies”) |
|
||||||
|
| `title` | tytuł banera („Szanujemy Twoją prywatność”) |
|
||||||
|
| `settingsDescription` | opis pod tytułem ustawień |
|
||||||
|
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
|
||||||
|
| `buttons.close` | etykieta przycisku ✕ dla czytników ekranu (puste → „Close”) |
|
||||||
|
|
||||||
|
Nowe pola w globalu = migracja w projektach na Postgres/SQLite (`payload migrate:create`); MongoDB bez zmian.
|
||||||
|
|
||||||
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
|
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
|
||||||
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
|
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
|
||||||
`accept`, `back`, `save`.
|
`accept`, `back`, `save`; w trybie modal także `consent-overlay`, `consent-dialog`, `close`.
|
||||||
|
|
||||||
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
|
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
|
||||||
settingsTitle** (per język) — bez tekstów na sztywno w komponentach.
|
title** albo **settingsTitle** (per język) — bez tekstów na sztywno w komponentach. Modal ma
|
||||||
|
`aria-modal`, fokus na ✕ po otwarciu i zamyka się Escape; przełączniki mają `role="switch"` i `aria-checked`.
|
||||||
|
|
||||||
## Locale jako cookie functional (wbudowane)
|
## Locale jako cookie functional (wbudowane)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Strona w budowie (narzędzie deweloperskie)
|
||||||
|
|
||||||
|
Tryb dla strony, która nie jest jeszcze gotowa: odwiedzający widzą tylko stronę główną i wybrane
|
||||||
|
podstrony (np. brief), a cała reszta jest zablokowana — bez zmian w kodzie, jednym przełącznikiem w panelu.
|
||||||
|
|
||||||
|
## Panel
|
||||||
|
|
||||||
|
**Site Settings → Under construction** (zakładka jest, gdy włączony moduł `pages`):
|
||||||
|
|
||||||
|
| Pole | Znaczenie |
|
||||||
|
|---|---|
|
||||||
|
| Site under construction | włącza tryb |
|
||||||
|
| Pages still available | strony, które dalej się otwierają; **strona główna jest dostępna zawsze** |
|
||||||
|
| Notice title / text / Close button label | treść popupu (per język) |
|
||||||
|
|
||||||
|
Lista stron i teksty pokazują się dopiero po zaznaczeniu przełącznika. Wyłączenie trybu przywraca
|
||||||
|
normalne działanie strony.
|
||||||
|
|
||||||
|
## Jak działa
|
||||||
|
|
||||||
|
- **Adres spoza listy** (także nieistniejący) → przekierowanie na stronę główną w tym języku z
|
||||||
|
`?notice=construction` (`createPageRoute` z opcją `redirect`). Strony dozwolone liczone są w
|
||||||
|
**każdym języku** (`/pl/brief` i `/en/project-brief`), więc przełącznik języka działa.
|
||||||
|
- **Kliknięcie linku** do strony spoza listy → `<ConstructionNotice>` anuluje przejście (przed
|
||||||
|
`next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"`
|
||||||
|
i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie.
|
||||||
|
- Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu.
|
||||||
|
- **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania
|
||||||
|
sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings).
|
||||||
|
|
||||||
|
## Wpięcie w projekcie
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/(frontend)/[locale]/[[...slug]]/page.tsx — redirect włącza blokadę adresów
|
||||||
|
import { notFound, permanentRedirect, redirect } from 'next/navigation'
|
||||||
|
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect })
|
||||||
|
|
||||||
|
// app/(frontend)/[locale]/layout.tsx — popup + przechwytywanie linków (bez stylów, classNames)
|
||||||
|
import { ConstructionNotice } from '@intecion/ipal-kit/client'
|
||||||
|
<ConstructionNotice
|
||||||
|
mode={await getConstructionMode(locale)} // z lib/content (createContentHelpers)
|
||||||
|
classNames={{ overlay: '…', dialog: '…', title: '…', message: '…', button: '…' }}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
`getConstructionMode(locale)` zwraca `{ enabled, allowedPaths, homePath, texts }` (typ
|
||||||
|
`ConstructionMode`). Czysta logika: `isPathAllowed(pathname, allowedPaths)`,
|
||||||
|
`constructionNoticeHref(homePath)`, stała `CONSTRUCTION_NOTICE_PARAM` (`@intecion/ipal-kit`).
|
||||||
|
|
||||||
|
Nowe pola w Site Settings = migracja w projekcie (`payload migrate:create`).
|
||||||
+1
-1
@@ -88,7 +88,7 @@ przyciskiem Reveal/Hide. To maskowanie UI, NIE hashowanie ani szyfrowanie:
|
|||||||
wartość w bazie jest plaintext (musi być odzyskiwalna do autentykacji SMTP/R2).
|
wartość w bazie jest plaintext (musi być odzyskiwalna do autentykacji SMTP/R2).
|
||||||
Chroni przed patrzeniem przez ramię i przypadkowym pokazaniem panelu.
|
Chroni przed patrzeniem przez ramię i przypadkowym pokazaniem panelu.
|
||||||
|
|
||||||
Podpięte przez `admin.components.Field: '@intecion/ipal-kit/client#MaskedField'`.
|
Podpięte przez `admin.components.Field: '@intecion/ipal-kit/admin#MaskedField'`.
|
||||||
Działa na dowolnym polu `text`. Po wpięciu w projekcie może być konieczne
|
Działa na dowolnym polu `text`. Po wpięciu w projekcie może być konieczne
|
||||||
`payload generate:importmap`, żeby panel rozpoznał komponent.
|
`payload generate:importmap`, żeby panel rozpoznał komponent.
|
||||||
|
|
||||||
|
|||||||
+40
-2
@@ -96,6 +96,27 @@ Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym
|
|||||||
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
|
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`.
|
na krok z tym polem. Teksty przycisków: 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.
|
||||||
|
|
||||||
|
- 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`).
|
||||||
|
|
||||||
### Formularz nietypowy — bez kopiowania silnika
|
### Formularz nietypowy — bez kopiowania silnika
|
||||||
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
|
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
|
||||||
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
|
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
|
||||||
@@ -105,7 +126,7 @@ na krok z tym polem. Teksty przycisków: Notifications → Form messages → `ne
|
|||||||
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
|
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
|
||||||
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
|
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
|
||||||
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
|
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
|
||||||
`validateBuilderFields`, `stepOfField`, `inputFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
|
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
|
||||||
|
|
||||||
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
|
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
|
||||||
|
|
||||||
@@ -187,7 +208,24 @@ email: mailAdapter(), // z '@intecion/ipal-kit' — SMTP albo Graph wg panelu
|
|||||||
Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i
|
Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i
|
||||||
treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu.
|
treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu.
|
||||||
|
|
||||||
`submitForm` odpowiada tylko za weryfikację Turnstile i zapis.
|
`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.
|
||||||
|
|
||||||
|
### Ładne maile (`emailLayout`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
forms: { emailLayout: true } // opcjonalnie: beforeEmail: (emails, args) => emails (po layoucie)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `{{*: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`).
|
||||||
|
|
||||||
## Własne pola w kolekcji formularzy
|
## Własne pola w kolekcji formularzy
|
||||||
|
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `Local
|
|||||||
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
|
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
|
||||||
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
|
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
|
||||||
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
|
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
|
||||||
|
Opcja `redirect` (z `next/navigation`) włącza tryb „strona w budowie” — [construction.md](./construction.md).
|
||||||
|
|
||||||
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
|
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@intecion/ipal-kit",
|
"name": "@intecion/ipal-kit",
|
||||||
"version": "1.9.5",
|
"version": "1.10.0",
|
||||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -57,6 +57,9 @@
|
|||||||
"docs",
|
"docs",
|
||||||
"bin"
|
"bin"
|
||||||
],
|
],
|
||||||
|
"sideEffects": [
|
||||||
|
"**/*.css"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
||||||
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
|
||||||
/**
|
/**
|
||||||
* Entry point: @intecion/ipal-kit/admin
|
* Entry point: @intecion/ipal-kit/admin
|
||||||
*
|
*
|
||||||
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
|
* Admin-panel UI components (white-label branding, array row labels, integration fields and
|
||||||
* importMap can resolve them by a stable path when ipalKit injects
|
* banners). Separate export so Payload's importMap can resolve them by a stable path, and so
|
||||||
* admin.components.graphics.Logo/Icon.
|
* nothing importing @payloadcms/ui ends up in /client — that entry ships to every site visitor.
|
||||||
*/
|
*/
|
||||||
|
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
|
||||||
|
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
||||||
|
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
|
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
|
||||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
||||||
|
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
'use client'
|
'use client'
|
||||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
|
|
||||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
|
||||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
|
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
|
||||||
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
|
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
|
||||||
export { Analytics } from '../modules/analytics/client.js'
|
export { Analytics } from '../modules/analytics/client.js'
|
||||||
@@ -23,10 +21,13 @@ export {
|
|||||||
useConsent,
|
useConsent,
|
||||||
useConsentContext,
|
useConsentContext,
|
||||||
} from '../modules/consent/client.js'
|
} from '../modules/consent/client.js'
|
||||||
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from '../modules/consent/client.js'
|
||||||
|
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
|
||||||
|
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
|
||||||
|
export type { ConstructionMode } from '../modules/construction/types.js'
|
||||||
export { BuilderForm } from '../modules/forms/BuilderForm.js'
|
export { BuilderForm } from '../modules/forms/BuilderForm.js'
|
||||||
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
|
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
|
||||||
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js'
|
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
|
||||||
export type {
|
export type {
|
||||||
BuilderField,
|
BuilderField,
|
||||||
BuilderFormAction,
|
BuilderFormAction,
|
||||||
@@ -34,6 +35,7 @@ export type {
|
|||||||
BuilderFormTexts,
|
BuilderFormTexts,
|
||||||
BuilderOption,
|
BuilderOption,
|
||||||
BuilderStep,
|
BuilderStep,
|
||||||
|
FieldCondition,
|
||||||
} from '../modules/forms/builderTypes.js'
|
} from '../modules/forms/builderTypes.js'
|
||||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
|
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
|
||||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
|
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
|
||||||
@@ -73,7 +75,6 @@ export {
|
|||||||
useSetAlternateLinks,
|
useSetAlternateLinks,
|
||||||
} from '../modules/i18n/index.js'
|
} from '../modules/i18n/index.js'
|
||||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
|
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
|
||||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
|
||||||
export { LocaleView } from '../modules/pages/LocaleView.js'
|
export { LocaleView } from '../modules/pages/LocaleView.js'
|
||||||
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
|
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
|
||||||
export { Turnstile } from '../modules/turnstile/client.js'
|
export { Turnstile } from '../modules/turnstile/client.js'
|
||||||
|
|||||||
@@ -22,6 +22,22 @@ export const cookieSettingsFields: Field[] = [
|
|||||||
min: 1,
|
min: 1,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'eyebrow',
|
||||||
|
type: 'text',
|
||||||
|
admin: {
|
||||||
|
description: 'Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.',
|
||||||
|
},
|
||||||
|
localized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'title',
|
||||||
|
type: 'text',
|
||||||
|
admin: {
|
||||||
|
description: 'Banner heading, e.g. "We respect your privacy". Empty → not shown.',
|
||||||
|
},
|
||||||
|
localized: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'message',
|
name: 'message',
|
||||||
type: 'textarea',
|
type: 'textarea',
|
||||||
@@ -38,6 +54,22 @@ export const cookieSettingsFields: Field[] = [
|
|||||||
},
|
},
|
||||||
localized: true,
|
localized: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'settingsDescription',
|
||||||
|
type: 'textarea',
|
||||||
|
admin: {
|
||||||
|
description: 'Intro under the settings heading — what cookies are for and that the choice can be changed later.',
|
||||||
|
},
|
||||||
|
localized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'alwaysActiveLabel',
|
||||||
|
type: 'text',
|
||||||
|
admin: {
|
||||||
|
description: 'Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.',
|
||||||
|
},
|
||||||
|
localized: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'privacyLinkLabel',
|
name: 'privacyLinkLabel',
|
||||||
type: 'text',
|
type: 'text',
|
||||||
@@ -59,6 +91,12 @@ export const cookieSettingsFields: Field[] = [
|
|||||||
{ name: 'settings', type: 'text', localized: true },
|
{ name: 'settings', type: 'text', localized: true },
|
||||||
{ name: 'save', type: 'text', localized: true },
|
{ name: 'save', type: 'text', localized: true },
|
||||||
{ name: 'back', type: 'text', localized: true },
|
{ name: 'back', type: 'text', localized: true },
|
||||||
|
{
|
||||||
|
name: 'close',
|
||||||
|
type: 'text',
|
||||||
|
admin: { description: 'Screen-reader label of the ✕ button in the settings dialog.' },
|
||||||
|
localized: true,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ export const smtpFields: Field[] = [
|
|||||||
description: 'SMTP account password.',
|
description: 'SMTP account password.',
|
||||||
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
|
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
|
||||||
components: {
|
components: {
|
||||||
Field: '@intecion/ipal-kit/client#MaskedField',
|
Field: '@intecion/ipal-kit/admin#MaskedField',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -87,7 +87,7 @@ export const smtpFields: Field[] = [
|
|||||||
type: 'ui',
|
type: 'ui',
|
||||||
admin: {
|
admin: {
|
||||||
components: {
|
components: {
|
||||||
Field: '@intecion/ipal-kit/client#TestEmailButton',
|
Field: '@intecion/ipal-kit/admin#TestEmailButton',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export const turnstileFields: Field[] = [
|
|||||||
description: 'Secret key used for server-side verification.',
|
description: 'Secret key used for server-side verification.',
|
||||||
// Masked in the UI (••••) — stored plaintext, readable for verification.
|
// Masked in the UI (••••) — stored plaintext, readable for verification.
|
||||||
components: {
|
components: {
|
||||||
Field: '@intecion/ipal-kit/client#MaskedField',
|
Field: '@intecion/ipal-kit/admin#MaskedField',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,6 +6,10 @@ import { themeFields } from './fields/theme.js'
|
|||||||
type BuildSiteSettingsArgs = {
|
type BuildSiteSettingsArgs = {
|
||||||
/** Extra fields injected by the client project */
|
/** Extra fields injected by the client project */
|
||||||
additionalFields?: Field[]
|
additionalFields?: Field[]
|
||||||
|
/** "Under construction" tab (developer tool) — given when the pages module is on. */
|
||||||
|
constructionFields?: Field[]
|
||||||
|
/** "Emails" tab — given with `forms: { emailLayout: true }`. */
|
||||||
|
emailFields?: Field[]
|
||||||
/**
|
/**
|
||||||
* Fields for the "System Pages" tab — page assignments by role (homepage,
|
* Fields for the "System Pages" tab — page assignments by role (homepage,
|
||||||
* privacy policy, collection archives). Assembled by the caller, which is the
|
* privacy policy, collection archives). Assembled by the caller, which is the
|
||||||
@@ -30,6 +34,8 @@ type BuildSiteSettingsArgs = {
|
|||||||
*/
|
*/
|
||||||
export function buildSiteSettings({
|
export function buildSiteSettings({
|
||||||
additionalFields,
|
additionalFields,
|
||||||
|
constructionFields,
|
||||||
|
emailFields,
|
||||||
systemPageFields,
|
systemPageFields,
|
||||||
}: BuildSiteSettingsArgs = {}): GlobalConfig {
|
}: BuildSiteSettingsArgs = {}): GlobalConfig {
|
||||||
return {
|
return {
|
||||||
@@ -55,6 +61,8 @@ export function buildSiteSettings({
|
|||||||
...(systemPageFields?.length
|
...(systemPageFields?.length
|
||||||
? [{ fields: systemPageFields, label: 'System Pages' }]
|
? [{ fields: systemPageFields, label: 'System Pages' }]
|
||||||
: []),
|
: []),
|
||||||
|
...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []),
|
||||||
|
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
|
||||||
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
|
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
+5
-2
@@ -42,6 +42,9 @@ export {
|
|||||||
updateConsent,
|
updateConsent,
|
||||||
} from './modules/consent/index.js'
|
} from './modules/consent/index.js'
|
||||||
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
||||||
|
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
|
||||||
|
export type { ConstructionMode } from './modules/construction/types.js'
|
||||||
|
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
|
||||||
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
|
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
|
||||||
export {
|
export {
|
||||||
archiveFieldName,
|
archiveFieldName,
|
||||||
@@ -78,8 +81,8 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
|||||||
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
|
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
|
||||||
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
|
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
|
||||||
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js'
|
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js'
|
||||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js'
|
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js'
|
||||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.js'
|
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
|
||||||
// Panel-managed form analytics (config-time field builder).
|
// Panel-managed form analytics (config-time field builder).
|
||||||
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
|
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
|
||||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||||
|
|||||||
@@ -1,19 +1,76 @@
|
|||||||
'use client'
|
'use client'
|
||||||
import { Cookie } from 'lucide-react'
|
import { Cookie } from 'lucide-react'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
|
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
|
||||||
import { useConsentContext } from './ConsentContext.js'
|
import { useConsentContext } from './ConsentContext.js'
|
||||||
import { useIsMounted } from './useIsMounted.js'
|
import { useIsMounted } from './useIsMounted.js'
|
||||||
|
|
||||||
|
/** A button on the banner (first level). */
|
||||||
|
export type CookieBannerAction = 'accept' | 'reject' | 'settings'
|
||||||
|
/** A button under the category list (settings view). */
|
||||||
|
export type CookieSettingsAction = 'accept' | 'back' | 'reject' | 'save'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Optional class overrides — for when tokens aren't enough, e.g. turning the
|
* Optional class overrides — for when tokens aren't enough, e.g. turning the
|
||||||
* bottom bar into a centred modal. Replaces the slot's classes outright.
|
* bottom bar into a centred modal. Each slot replaces its default classes
|
||||||
|
* outright. Per-button slots (acceptButton, rejectButton…) fall back to
|
||||||
|
* primaryButton / secondaryButton, so styling those two still restyles all.
|
||||||
*/
|
*/
|
||||||
export type CookieBannerClassNames = {
|
export type CookieBannerClassNames = {
|
||||||
|
/** Button "Accept all" — falls back to primaryButton. */
|
||||||
|
acceptButton?: string
|
||||||
|
/** Button row on the banner. */
|
||||||
|
actions?: string
|
||||||
|
/** Settings view: button "Back" (closes the dialog in modal mode) — falls back to secondaryButton. */
|
||||||
|
backButton?: string
|
||||||
|
/** Settings view: badge next to Necessary (CookieSettings → alwaysActiveLabel). */
|
||||||
|
badge?: string
|
||||||
|
/** Banner inner wrapper (width / centring). */
|
||||||
|
body?: string
|
||||||
|
/** Settings view: list of categories. */
|
||||||
|
categories?: string
|
||||||
|
/** Settings view: one category row/card. */
|
||||||
|
category?: string
|
||||||
|
categoryDescription?: string
|
||||||
|
categoryTitle?: string
|
||||||
|
/** Settings dialog (modal mode): the ✕ button. */
|
||||||
|
closeButton?: string
|
||||||
|
/** Banner: text + buttons row. */
|
||||||
|
content?: string
|
||||||
|
/** Settings view: the switch track or the checkbox. */
|
||||||
|
control?: string
|
||||||
|
/** Settings view: the switch knob (controls="switch"). */
|
||||||
|
controlThumb?: string
|
||||||
|
/** Settings dialog box (modal mode). */
|
||||||
|
dialog?: string
|
||||||
|
/** Small label above the banner title (CookieSettings → eyebrow). */
|
||||||
|
eyebrow?: string
|
||||||
|
/** Cookie icon next to the banner text and the settings title. */
|
||||||
|
icon?: string
|
||||||
|
/** Privacy-policy link inside the message. */
|
||||||
|
link?: string
|
||||||
|
message?: string
|
||||||
|
/** Backdrop behind the settings dialog (modal mode). */
|
||||||
|
overlay?: string
|
||||||
primaryButton?: string
|
primaryButton?: string
|
||||||
|
/** Button "Reject" — falls back to primaryButton with equalChoice, else secondaryButton. */
|
||||||
|
rejectButton?: string
|
||||||
root?: string
|
root?: string
|
||||||
|
/** Settings view: button "Save preferences" — falls back to primaryButton. */
|
||||||
|
saveButton?: string
|
||||||
secondaryButton?: string
|
secondaryButton?: string
|
||||||
|
/** Settings view: button row under the categories. */
|
||||||
|
settingsActions?: string
|
||||||
|
/** Button "Settings" on the banner — falls back to secondaryButton. */
|
||||||
|
settingsButton?: string
|
||||||
|
/** Settings view: intro under the title (CookieSettings → settingsDescription). */
|
||||||
|
settingsDescription?: string
|
||||||
|
settingsTitle?: string
|
||||||
|
/** Banner: block with eyebrow, title and message. */
|
||||||
|
text?: string
|
||||||
|
/** Banner heading (CookieSettings → title). */
|
||||||
|
title?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -35,131 +92,267 @@ export type CookieBannerClassNames = {
|
|||||||
*
|
*
|
||||||
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
|
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
|
||||||
* exposing them as tokens would mean re-inventing CSS one variable at a time.
|
* exposing them as tokens would mean re-inventing CSS one variable at a time.
|
||||||
|
* For a different layout use classNames (every element has a slot).
|
||||||
*/
|
*/
|
||||||
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
|
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
|
||||||
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
|
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
|
||||||
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
|
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
|
||||||
const accent = 'text-[var(--ipal-primary,#2563eb)]'
|
const accent = 'text-[var(--ipal-primary,#2563eb)]'
|
||||||
|
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
|
||||||
|
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
|
||||||
|
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
|
||||||
|
const primaryBg = 'bg-[var(--ipal-primary,#2563eb)]'
|
||||||
|
|
||||||
const defaults = {
|
const defaults: Required<CookieBannerClassNames> = {
|
||||||
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
|
acceptButton: '',
|
||||||
|
actions: 'flex shrink-0 gap-2',
|
||||||
|
backButton: '',
|
||||||
|
badge: `shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${border} ${accent}`,
|
||||||
|
body: 'mx-auto max-w-4xl',
|
||||||
|
categories: 'flex flex-col gap-3',
|
||||||
|
category: 'flex items-start justify-between gap-4',
|
||||||
|
categoryDescription: `text-xs ${mutedText}`,
|
||||||
|
categoryTitle: `text-sm font-medium ${strongText}`,
|
||||||
|
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,#f5f5f5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
|
||||||
|
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
|
||||||
|
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
|
||||||
|
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
|
||||||
|
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
|
||||||
|
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
|
||||||
|
icon: `h-6 w-6 shrink-0 ${accent}`,
|
||||||
|
link: `${accent} underline hover:no-underline`,
|
||||||
|
message: `text-justify text-sm ${bodyText}`,
|
||||||
|
overlay: 'fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4',
|
||||||
|
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium ${primaryBg} text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
|
||||||
|
rejectButton: '',
|
||||||
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
|
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
|
||||||
|
saveButton: '',
|
||||||
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
|
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
|
||||||
|
settingsActions: 'flex justify-end gap-2',
|
||||||
|
settingsButton: '',
|
||||||
|
settingsDescription: `text-sm ${bodyText}`,
|
||||||
|
settingsTitle: `flex items-center gap-2 text-base font-semibold ${strongText}`,
|
||||||
|
text: 'flex items-start gap-3',
|
||||||
|
title: `mb-1 text-base font-semibold ${strongText}`,
|
||||||
}
|
}
|
||||||
|
|
||||||
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
|
/** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
|
||||||
const strongText =
|
const SWITCH_TRACK =
|
||||||
'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
|
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
|
||||||
const mutedText =
|
|
||||||
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
|
|
||||||
|
|
||||||
type CookieBannerProps = {
|
type CookieBannerProps = {
|
||||||
classNames?: CookieBannerClassNames
|
classNames?: CookieBannerClassNames
|
||||||
|
/** Category controls: native checkboxes (default) or accessible switches (role="switch"). */
|
||||||
|
controls?: 'checkbox' | 'switch'
|
||||||
/**
|
/**
|
||||||
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
|
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
|
||||||
* EDPB) expect refusing to be as easy and visible as accepting. Default false
|
* EDPB) expect refusing to be as easy and visible as accepting. Default false
|
||||||
* keeps the existing look; recommended true.
|
* keeps the existing look; recommended true.
|
||||||
*/
|
*/
|
||||||
equalChoice?: boolean
|
equalChoice?: boolean
|
||||||
|
/** Cookie icon next to the banner text and the settings title. Default true. */
|
||||||
|
icon?: boolean
|
||||||
|
/** Banner buttons, in this order. Default ['settings', 'reject', 'accept']. */
|
||||||
|
order?: CookieBannerAction[]
|
||||||
|
/**
|
||||||
|
* Where category settings open: in the banner itself (default) or in a centred
|
||||||
|
* dialog over a dimmed page ('modal' — closes with ✕, Escape or a click outside).
|
||||||
|
*/
|
||||||
|
settings?: 'inline' | 'modal'
|
||||||
|
/** Buttons under the categories, in this order. Default ['back', 'save']. */
|
||||||
|
settingsActions?: CookieSettingsAction[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) {
|
const DEFAULT_ORDER: CookieBannerAction[] = ['settings', 'reject', 'accept']
|
||||||
|
const DEFAULT_SETTINGS_ACTIONS: CookieSettingsAction[] = ['back', 'save']
|
||||||
|
|
||||||
|
export function CookieBanner({
|
||||||
|
classNames,
|
||||||
|
controls = 'checkbox',
|
||||||
|
equalChoice = false,
|
||||||
|
icon = true,
|
||||||
|
order = DEFAULT_ORDER,
|
||||||
|
settings = 'inline',
|
||||||
|
settingsActions = DEFAULT_SETTINGS_ACTIONS,
|
||||||
|
}: CookieBannerProps = {}) {
|
||||||
const isMounted = useIsMounted()
|
const isMounted = useIsMounted()
|
||||||
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
|
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
|
||||||
const [showSettings, setShowSettings] = useState(false)
|
const [showSettings, setShowSettings] = useState(false)
|
||||||
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
|
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
|
||||||
|
const closeRef = useRef<HTMLButtonElement>(null)
|
||||||
|
const modal = settings === 'modal'
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setChoices(state)
|
setChoices(state)
|
||||||
}, [state])
|
}, [state])
|
||||||
|
|
||||||
|
// Modal: focus the ✕ on open, Escape closes (back to the banner)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!modal || !showSettings) {return}
|
||||||
|
closeRef.current?.focus()
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === 'Escape') {setShowSettings(false)}
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKey)
|
||||||
|
return () => document.removeEventListener('keydown', onKey)
|
||||||
|
}, [modal, showSettings])
|
||||||
|
|
||||||
// Render nothing until mounted — avoids the React 19 hydration mismatch that
|
// Render nothing until mounted — avoids the React 19 hydration mismatch that
|
||||||
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
|
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
|
||||||
// needed now.
|
// needed now.
|
||||||
if (!isMounted) {return null}
|
if (!isMounted) {return null}
|
||||||
if (decided) {return null}
|
if (decided) {return null}
|
||||||
|
|
||||||
|
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
|
||||||
|
const primary = cn('primaryButton')
|
||||||
|
const secondary = cn('secondaryButton')
|
||||||
|
const buttonClass: Record<CookieBannerAction | CookieSettingsAction, string> = {
|
||||||
|
accept: classNames?.acceptButton ?? primary,
|
||||||
|
back: classNames?.backButton ?? secondary,
|
||||||
|
reject: classNames?.rejectButton ?? (equalChoice ? primary : secondary),
|
||||||
|
save: classNames?.saveButton ?? primary,
|
||||||
|
settings: classNames?.settingsButton ?? secondary,
|
||||||
|
}
|
||||||
|
const run: Record<CookieBannerAction | CookieSettingsAction, () => void> = {
|
||||||
|
accept: acceptAll,
|
||||||
|
back: () => setShowSettings(false),
|
||||||
|
reject: rejectAll,
|
||||||
|
save: () => savePreferences(choices),
|
||||||
|
settings: () => setShowSettings(true),
|
||||||
|
}
|
||||||
|
const label: Record<CookieBannerAction | CookieSettingsAction, string> = {
|
||||||
|
accept: texts.buttons.acceptAll,
|
||||||
|
back: texts.buttons.back,
|
||||||
|
reject: texts.buttons.reject,
|
||||||
|
save: texts.buttons.save,
|
||||||
|
settings: texts.buttons.settings,
|
||||||
|
}
|
||||||
|
const button = (action: CookieBannerAction | CookieSettingsAction) => (
|
||||||
|
<button className={buttonClass[action]} data-ipal={action} key={action} onClick={run[action]} type="button">
|
||||||
|
{label[action]}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
|
||||||
const toggle = (cat: ConsentCategory) => {
|
const toggle = (cat: ConsentCategory) => {
|
||||||
if (cat === 'necessary') {return}
|
if (cat === 'necessary') {return}
|
||||||
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
|
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootClass = classNames?.root ?? defaults.root
|
const control = (cat: ConsentCategory) => {
|
||||||
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton
|
const checked = cat === 'necessary' ? true : choices[cat]
|
||||||
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton
|
if (cat === 'necessary' && texts.alwaysActiveLabel) {
|
||||||
|
return <span className={cn('badge')}>{texts.alwaysActiveLabel}</span>
|
||||||
|
}
|
||||||
|
if (controls === 'switch') {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
aria-checked={checked}
|
||||||
|
aria-describedby={`ipal-consent-${cat}-desc`}
|
||||||
|
aria-labelledby={`ipal-consent-${cat}`}
|
||||||
|
className={classNames?.control ?? SWITCH_TRACK}
|
||||||
|
data-checked={checked}
|
||||||
|
disabled={cat === 'necessary'}
|
||||||
|
onClick={() => toggle(cat)}
|
||||||
|
role="switch"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<span aria-hidden="true" className={cn('controlThumb')} data-checked={checked} />
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
aria-describedby={`ipal-consent-${cat}-desc`}
|
||||||
|
aria-labelledby={`ipal-consent-${cat}`}
|
||||||
|
checked={checked}
|
||||||
|
className={cn('control')}
|
||||||
|
disabled={cat === 'necessary'}
|
||||||
|
onChange={() => toggle(cat)}
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
const settingsView = (
|
||||||
<div aria-label={texts.settingsTitle} className={rootClass} data-ipal="banner" role="dialog">
|
<div className="flex flex-col gap-4">
|
||||||
<div className="mx-auto max-w-4xl">
|
<div className="flex items-start justify-between gap-4">
|
||||||
{!showSettings ? (
|
<h2 className={cn('settingsTitle')} id="ipal-consent-title">
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
{icon && !modal && <Cookie aria-hidden="true" className={cn('icon')} />}
|
||||||
<div className="flex items-start gap-3">
|
{texts.settingsTitle}
|
||||||
<Cookie aria-hidden="true" className={`h-6 w-6 shrink-0 ${accent}`} />
|
</h2>
|
||||||
<p className={`text-justify text-sm ${bodyText}`}>
|
{modal && (
|
||||||
{texts.message}
|
<button aria-label={texts.buttons.close} className={cn('closeButton')} data-ipal="close" onClick={() => setShowSettings(false)} ref={closeRef} type="button">
|
||||||
{texts.privacyLink && (
|
<svg aria-hidden="true" fill="none" height="20" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="20">
|
||||||
<>
|
<path d="M18 6 6 18M6 6l12 12" />
|
||||||
{' '}
|
</svg>
|
||||||
<a
|
</button>
|
||||||
className={`${accent} underline hover:no-underline`}
|
)}
|
||||||
href={texts.privacyLink.href}
|
</div>
|
||||||
>
|
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
|
||||||
{texts.privacyLink.label}
|
<ul className={cn('categories')}>
|
||||||
</a>
|
{CONSENT_CATEGORIES.map((cat) => (
|
||||||
</>
|
<li className={cn('category')} key={cat}>
|
||||||
)}
|
<div>
|
||||||
|
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
|
||||||
|
{texts.categories[cat].title}
|
||||||
|
</p>
|
||||||
|
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
|
||||||
|
{texts.categories[cat].description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex shrink-0 gap-2">
|
{control(cat)}
|
||||||
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
|
</li>
|
||||||
{texts.buttons.settings}
|
))}
|
||||||
</button>
|
</ul>
|
||||||
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
|
<div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
|
||||||
{texts.buttons.reject}
|
</div>
|
||||||
</button>
|
)
|
||||||
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
|
|
||||||
{texts.buttons.acceptAll}
|
if (modal && showSettings) {
|
||||||
</button>
|
return (
|
||||||
|
<div
|
||||||
|
className={cn('overlay')}
|
||||||
|
data-ipal="consent-overlay"
|
||||||
|
onClick={(event) => {
|
||||||
|
if (event.target === event.currentTarget) {setShowSettings(false)}
|
||||||
|
}}
|
||||||
|
// klik w tło zamyka dialog; klawiatura: Escape (listener wyżej) i przycisk ✕
|
||||||
|
role="presentation"
|
||||||
|
>
|
||||||
|
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={cn('dialog')} data-ipal="consent-dialog" role="dialog">
|
||||||
|
{settingsView}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" role="dialog">
|
||||||
|
<div className={cn('body')}>
|
||||||
|
{!showSettings ? (
|
||||||
|
<div className={cn('content')}>
|
||||||
|
<div className={cn('text')}>
|
||||||
|
{icon && <Cookie aria-hidden="true" className={cn('icon')} />}
|
||||||
|
<div>
|
||||||
|
{texts.eyebrow && <p className={cn('eyebrow')}>{texts.eyebrow}</p>}
|
||||||
|
{texts.title && <h2 className={cn('title')}>{texts.title}</h2>}
|
||||||
|
<p className={cn('message')}>
|
||||||
|
{texts.message}
|
||||||
|
{texts.privacyLink && (
|
||||||
|
<>
|
||||||
|
{' '}
|
||||||
|
<a className={cn('link')} href={texts.privacyLink.href}>
|
||||||
|
{texts.privacyLink.label}
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className={cn('actions')}>{order.map(button)}</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-4">
|
settingsView
|
||||||
<h2 className={`flex items-center gap-2 text-base font-semibold ${strongText}`}>
|
|
||||||
<Cookie aria-hidden="true" className={`h-5 w-5 ${accent}`} />
|
|
||||||
{texts.settingsTitle}
|
|
||||||
</h2>
|
|
||||||
<ul className="flex flex-col gap-3">
|
|
||||||
{CONSENT_CATEGORIES.map((cat) => (
|
|
||||||
<li className="flex items-start justify-between gap-4" key={cat}>
|
|
||||||
<div>
|
|
||||||
<p className={`text-sm font-medium ${strongText}`} id={`ipal-consent-${cat}`}>
|
|
||||||
{texts.categories[cat].title}
|
|
||||||
</p>
|
|
||||||
<p className={`text-xs ${mutedText}`} id={`ipal-consent-${cat}-desc`}>
|
|
||||||
{texts.categories[cat].description}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
aria-describedby={`ipal-consent-${cat}-desc`}
|
|
||||||
aria-labelledby={`ipal-consent-${cat}`}
|
|
||||||
checked={cat === 'necessary' ? true : choices[cat]}
|
|
||||||
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
|
|
||||||
disabled={cat === 'necessary'}
|
|
||||||
onChange={() => toggle(cat)}
|
|
||||||
type="checkbox"
|
|
||||||
/>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
<div className="flex justify-end gap-2">
|
|
||||||
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)} type="button">
|
|
||||||
{texts.buttons.back}
|
|
||||||
</button>
|
|
||||||
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)} type="button">
|
|
||||||
{texts.buttons.save}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
|
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
|
||||||
export { ConsentScript } from './ConsentScript.js'
|
export { ConsentScript } from './ConsentScript.js'
|
||||||
export { CookieBanner } from './CookieBanner.js'
|
export { CookieBanner } from './CookieBanner.js'
|
||||||
export type { CookieBannerClassNames } from './CookieBanner.js'
|
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
|
||||||
export { CookieButton } from './CookieButton.js'
|
export { CookieButton } from './CookieButton.js'
|
||||||
// Client-only consent exports — hook, provider, and UI components.
|
// Client-only consent exports — hook, provider, and UI components.
|
||||||
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
|
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ const FALLBACK: ConsentTexts = {
|
|||||||
buttons: {
|
buttons: {
|
||||||
acceptAll: 'Accept all',
|
acceptAll: 'Accept all',
|
||||||
back: 'Back',
|
back: 'Back',
|
||||||
|
close: 'Close',
|
||||||
reject: 'Reject',
|
reject: 'Reject',
|
||||||
save: 'Save preferences',
|
save: 'Save preferences',
|
||||||
settings: 'Settings',
|
settings: 'Settings',
|
||||||
@@ -37,13 +38,17 @@ const FALLBACK: ConsentTexts = {
|
|||||||
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||||
|
|
||||||
type CookieSettingsData = {
|
type CookieSettingsData = {
|
||||||
|
alwaysActiveLabel?: null | string
|
||||||
buttons?: null | Partial<ConsentTexts['buttons']>
|
buttons?: null | Partial<ConsentTexts['buttons']>
|
||||||
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
|
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
|
||||||
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
|
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
|
||||||
|
eyebrow?: null | string
|
||||||
message?: null | string
|
message?: null | string
|
||||||
policyVersion?: null | number
|
policyVersion?: null | number
|
||||||
privacyLinkLabel?: null | string
|
privacyLinkLabel?: null | string
|
||||||
|
settingsDescription?: null | string
|
||||||
settingsTitle?: null | string
|
settingsTitle?: null | string
|
||||||
|
title?: null | string
|
||||||
}
|
}
|
||||||
|
|
||||||
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
|
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
|
||||||
@@ -135,6 +140,7 @@ export async function getConsentTexts({
|
|||||||
buttons: {
|
buttons: {
|
||||||
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
|
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
|
||||||
back: g.buttons?.back || FALLBACK.buttons.back,
|
back: g.buttons?.back || FALLBACK.buttons.back,
|
||||||
|
close: g.buttons?.close || FALLBACK.buttons.close,
|
||||||
reject: g.buttons?.reject || FALLBACK.buttons.reject,
|
reject: g.buttons?.reject || FALLBACK.buttons.reject,
|
||||||
save: g.buttons?.save || FALLBACK.buttons.save,
|
save: g.buttons?.save || FALLBACK.buttons.save,
|
||||||
settings: g.buttons?.settings || FALLBACK.buttons.settings,
|
settings: g.buttons?.settings || FALLBACK.buttons.settings,
|
||||||
@@ -143,6 +149,11 @@ export async function getConsentTexts({
|
|||||||
message: g.message || FALLBACK.message,
|
message: g.message || FALLBACK.message,
|
||||||
privacyLink,
|
privacyLink,
|
||||||
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
|
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
|
||||||
|
// optional copy — no English fallback: empty in the panel = element not rendered
|
||||||
|
...(g.eyebrow?.trim() ? { eyebrow: g.eyebrow.trim() } : {}),
|
||||||
|
...(g.title?.trim() ? { title: g.title.trim() } : {}),
|
||||||
|
...(g.settingsDescription?.trim() ? { settingsDescription: g.settingsDescription.trim() } : {}),
|
||||||
|
...(g.alwaysActiveLabel?.trim() ? { alwaysActiveLabel: g.alwaysActiveLabel.trim() } : {}),
|
||||||
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
|
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,28 @@
|
|||||||
import type { ConsentCategory } from './categories.js'
|
import type { ConsentCategory } from './categories.js'
|
||||||
|
|
||||||
export type ConsentTexts = {
|
export type ConsentTexts = {
|
||||||
|
/** Badge next to the necessary category (e.g. "Always active"). Empty = no badge. */
|
||||||
|
alwaysActiveLabel?: string
|
||||||
buttons: {
|
buttons: {
|
||||||
acceptAll: string
|
acceptAll: string
|
||||||
back: string
|
back: string
|
||||||
|
/** Accessible label of the ✕ button closing the settings dialog. */
|
||||||
|
close: string
|
||||||
reject: string
|
reject: string
|
||||||
save: string
|
save: string
|
||||||
settings: string
|
settings: string
|
||||||
}
|
}
|
||||||
categories: Record<ConsentCategory, { description: string; title: string }>
|
categories: Record<ConsentCategory, { description: string; title: string }>
|
||||||
|
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
|
||||||
|
eyebrow?: string
|
||||||
message: string
|
message: string
|
||||||
/** null = no privacy-policy link shown */
|
/** null = no privacy-policy link shown */
|
||||||
privacyLink: { href: string; label: string } | null
|
privacyLink: { href: string; label: string } | null
|
||||||
|
/** Intro under the settings title. Empty = not shown. */
|
||||||
|
settingsDescription?: string
|
||||||
settingsTitle: string
|
settingsTitle: string
|
||||||
|
/** Banner heading (e.g. "We respect your privacy"). Empty = not shown. */
|
||||||
|
title?: string
|
||||||
/** Policy version from the panel — a stored consent from another version asks again. */
|
/** Policy version from the panel — a stored consent from another version asks again. */
|
||||||
version?: number
|
version?: number
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useId, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import type { ConstructionMode } from './types.js'
|
||||||
|
|
||||||
|
import { isPathAllowed } from './logic.js'
|
||||||
|
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
|
||||||
|
|
||||||
|
export type ConstructionNoticeClassNames = {
|
||||||
|
button?: string
|
||||||
|
dialog?: string
|
||||||
|
message?: string
|
||||||
|
overlay?: string
|
||||||
|
title?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The "site under construction" notice (Site Settings → Under construction).
|
||||||
|
* Opens after a redirect from a blocked address (?notice=construction, then
|
||||||
|
* removed from the URL) and when a visitor clicks a link to a page that isn't
|
||||||
|
* available — the click is cancelled. Closes with its button or Escape.
|
||||||
|
* Renders nothing while the mode is off.
|
||||||
|
*
|
||||||
|
* Unstyled (classNames, like CookieBanner); texts come from the panel.
|
||||||
|
*
|
||||||
|
* // [locale]/layout.tsx
|
||||||
|
* <ConstructionNotice mode={await getConstructionMode(locale)} classNames={{ overlay: '…', dialog: '…' }} />
|
||||||
|
*/
|
||||||
|
export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const buttonRef = useRef<HTMLButtonElement>(null)
|
||||||
|
const titleId = useId()
|
||||||
|
const close = useCallback(() => setOpen(false), [])
|
||||||
|
const { allowedPaths, enabled } = mode
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) {return}
|
||||||
|
// After a redirect: show the notice once and clean the address bar
|
||||||
|
const url = new URL(window.location.href)
|
||||||
|
if (url.searchParams.get(CONSTRUCTION_NOTICE_PARAM) === CONSTRUCTION_NOTICE_VALUE) {
|
||||||
|
setOpen(true)
|
||||||
|
url.searchParams.delete(CONSTRUCTION_NOTICE_PARAM)
|
||||||
|
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture phase, before Next's <Link> — a cancelled click doesn't navigate
|
||||||
|
const onClick = (event: MouseEvent) => {
|
||||||
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {return}
|
||||||
|
const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null
|
||||||
|
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute('download')) {return}
|
||||||
|
if (anchor.target && anchor.target !== '_self') {return}
|
||||||
|
const target = new URL(anchor.href, window.location.href)
|
||||||
|
if (target.origin !== window.location.origin || isPathAllowed(target.pathname, allowedPaths)) {return}
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
setOpen(true)
|
||||||
|
}
|
||||||
|
document.addEventListener('click', onClick, true)
|
||||||
|
return () => document.removeEventListener('click', onClick, true)
|
||||||
|
}, [enabled, allowedPaths])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) {return}
|
||||||
|
buttonRef.current?.focus()
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === 'Escape') {close()}
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKey)
|
||||||
|
return () => document.removeEventListener('keydown', onKey)
|
||||||
|
}, [open, close])
|
||||||
|
|
||||||
|
if (!enabled || !open) {return null}
|
||||||
|
return (
|
||||||
|
<div className={cn.overlay} data-ipal="construction-notice">
|
||||||
|
<div aria-labelledby={mode.texts.title ? titleId : undefined} aria-modal="true" className={cn.dialog} role="dialog">
|
||||||
|
{mode.texts.title ? <p className={cn.title} id={titleId}>{mode.texts.title}</p> : null}
|
||||||
|
{mode.texts.message ? <p className={cn.message}>{mode.texts.message}</p> : null}
|
||||||
|
<button className={cn.button} onClick={close} ref={buttonRef} type="button">
|
||||||
|
{mode.texts.button ?? '×'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import type { Field } from 'payload'
|
||||||
|
|
||||||
|
const whenEnabled = (_: unknown, siblingData: { enabled?: boolean } | undefined) => Boolean(siblingData?.enabled)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Site Settings → "Under construction" tab: a developer tool for a site that
|
||||||
|
* isn't finished. When enabled, only the homepage and the chosen pages are
|
||||||
|
* reachable — any other address redirects to the homepage with a notice, and a
|
||||||
|
* link to another page shows the notice instead of navigating. One rule for
|
||||||
|
* every visitor (pages stay static, there is no per-user check).
|
||||||
|
*/
|
||||||
|
export function buildConstructionFields(pagesSlug: string): Field[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: 'construction',
|
||||||
|
type: 'group',
|
||||||
|
admin: { hideGutter: true },
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: 'enabled',
|
||||||
|
type: 'checkbox',
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
'Only the homepage and the pages below can be opened. Other addresses redirect to the homepage with the notice; links to other pages show it instead of navigating.',
|
||||||
|
},
|
||||||
|
defaultValue: false,
|
||||||
|
label: 'Site under construction',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'allowedPages',
|
||||||
|
type: 'relationship',
|
||||||
|
admin: { condition: whenEnabled, description: 'The homepage is always available.' },
|
||||||
|
hasMany: true,
|
||||||
|
label: 'Pages still available',
|
||||||
|
relationTo: pagesSlug as never,
|
||||||
|
},
|
||||||
|
{ name: 'title', type: 'text', admin: { condition: whenEnabled }, label: 'Notice title', localized: true },
|
||||||
|
{ name: 'message', type: 'textarea', admin: { condition: whenEnabled }, label: 'Notice text', localized: true },
|
||||||
|
{ name: 'buttonLabel', type: 'text', admin: { condition: whenEnabled }, label: 'Close button label', localized: true },
|
||||||
|
],
|
||||||
|
label: false,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
|
||||||
|
|
||||||
|
/** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */
|
||||||
|
export const normalizePath = (path: string): string => {
|
||||||
|
const trimmed = path.replace(/\/+$/, '')
|
||||||
|
return trimmed === '' ? '/' : trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is this pathname one of the allowed ones? Exact match, trailing slash ignored. */
|
||||||
|
export function isPathAllowed(pathname: string, allowedPaths: readonly string[]): boolean {
|
||||||
|
const path = normalizePath(pathname)
|
||||||
|
return allowedPaths.some((allowed) => normalizePath(allowed) === path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a blocked address goes: the homepage with the notice parameter. */
|
||||||
|
export const constructionNoticeHref = (homePath: string): string =>
|
||||||
|
`${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}`
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* "Site under construction" (Site Settings → Under construction) as the
|
||||||
|
* frontend needs it: getConstructionMode(locale) in createContentHelpers.
|
||||||
|
*/
|
||||||
|
export type ConstructionMode = {
|
||||||
|
/** Paths a visitor may open, in every language: the homepage and "Pages still available". */
|
||||||
|
allowedPaths: string[]
|
||||||
|
enabled: boolean
|
||||||
|
/** Homepage in the current language — blocked addresses redirect here (with the notice). */
|
||||||
|
homePath: string
|
||||||
|
/** Notice texts from the panel, in the current language. Empty = not set. */
|
||||||
|
texts: { button?: string; message?: string; title?: string }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Query parameter that opens the notice after a redirect: /pl?notice=construction */
|
||||||
|
export const CONSTRUCTION_NOTICE_PARAM = 'notice'
|
||||||
|
export const CONSTRUCTION_NOTICE_VALUE = 'construction'
|
||||||
@@ -161,7 +161,7 @@ function routeOf(
|
|||||||
params: { locale?: string; slug?: string[] },
|
params: { locale?: string; slug?: string[] },
|
||||||
config: CreateMarkdownRendererArgs['config'],
|
config: CreateMarkdownRendererArgs['config'],
|
||||||
): { locale: string; slug?: string[] } {
|
): { locale: string; slug?: string[] } {
|
||||||
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? String((l as { code?: unknown }).code ?? '') : String(l)))
|
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? (l as { code?: string }).code ?? '' : typeof l === 'string' ? l : ''))
|
||||||
const fallback = config?.defaultLocale ?? codes[0] ?? ''
|
const fallback = config?.defaultLocale ?? codes[0] ?? ''
|
||||||
if (!params.locale) {return { slug: params.slug, locale: fallback }}
|
if (!params.locale) {return { slug: params.slug, locale: fallback }}
|
||||||
if (codes.length === 1 && !codes.includes(params.locale)) {
|
if (codes.length === 1 && !codes.includes(params.locale)) {
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ import type { Block, Field } from 'payload'
|
|||||||
*
|
*
|
||||||
* Plain English labels (the panel is EN). Rendered by BuilderForm /
|
* Plain English labels (the panel is EN). Rendered by BuilderForm /
|
||||||
* useBuilderForm, validated by submitForm like every other field.
|
* useBuilderForm, validated by submitForm like every other field.
|
||||||
|
*
|
||||||
|
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
|
||||||
|
* (`showWhen`) — conditional visibility, evaluated by visibleFields.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const name: Field = {
|
const name: Field = {
|
||||||
@@ -24,7 +27,41 @@ const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, lab
|
|||||||
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
|
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 required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
|
||||||
|
|
||||||
export const stepBlock: Block = {
|
/**
|
||||||
|
* "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).
|
||||||
|
*/
|
||||||
|
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".',
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
type: 'row',
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: 'Show only when',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds "Show only when" at the end of a block's fields. */
|
||||||
|
export function withShowWhen<B extends Block>(block: B): B {
|
||||||
|
return { ...block, fields: [...block.fields, showWhenField] }
|
||||||
|
}
|
||||||
|
|
||||||
|
const stepBase: Block = {
|
||||||
slug: 'step',
|
slug: 'step',
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
@@ -42,7 +79,7 @@ export const stepBlock: Block = {
|
|||||||
labels: { plural: 'Steps', singular: 'Step' },
|
labels: { plural: 'Steps', singular: 'Step' },
|
||||||
}
|
}
|
||||||
|
|
||||||
export const checkboxGroupBlock: Block = {
|
const checkboxGroupBase: Block = {
|
||||||
slug: 'checkboxGroup',
|
slug: 'checkboxGroup',
|
||||||
fields: [
|
fields: [
|
||||||
{ type: 'row', fields: [name, label] },
|
{ type: 'row', fields: [name, label] },
|
||||||
@@ -72,3 +109,6 @@ export const checkboxGroupBlock: Block = {
|
|||||||
],
|
],
|
||||||
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
|
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const stepBlock: Block = withShowWhen(stepBase)
|
||||||
|
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||||
|
|
||||||
import { NON_INPUT_TYPES } from './builderTypes.js'
|
import { NON_INPUT_TYPES } from './builderTypes.js'
|
||||||
import { isEmail } from './validators.js'
|
import { isEmail } from './validators.js'
|
||||||
@@ -19,16 +19,24 @@ export function inputFields(fields: BuilderField[] | null | undefined): ({ name:
|
|||||||
/**
|
/**
|
||||||
* Splits the field list at `step` blocks. Fields before the first Step form
|
* Splits the field list at `step` blocks. Fields before the first Step form
|
||||||
* the first screen; a form without Steps is one screen.
|
* the first screen; a form without Steps is one screen.
|
||||||
|
*
|
||||||
|
* `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a
|
||||||
|
* hidden Step with everything under it — out, while `index` stays the field's
|
||||||
|
* position in the full list (RenderForm renders `message` blocks by it).
|
||||||
*/
|
*/
|
||||||
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
|
export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] {
|
||||||
const steps: BuilderStep[] = []
|
const steps: BuilderStep[] = []
|
||||||
let current: BuilderStep | null = null
|
let current: BuilderStep | null = null
|
||||||
|
let skipping = false
|
||||||
;(fields ?? []).forEach((field, index) => {
|
;(fields ?? []).forEach((field, index) => {
|
||||||
if (field.blockType === 'step') {
|
if (field.blockType === 'step') {
|
||||||
|
skipping = isShown ? !isShown(field) : false
|
||||||
|
if (skipping) {return}
|
||||||
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
|
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
|
||||||
steps.push(current)
|
steps.push(current)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (skipping || (isShown && !isShown(field))) {return}
|
||||||
if (!current) {
|
if (!current) {
|
||||||
current = { fields: [], index: 0 }
|
current = { fields: [], index: 0 }
|
||||||
steps.push(current)
|
steps.push(current)
|
||||||
@@ -40,6 +48,60 @@ export function splitSteps(fields: BuilderField[] | null | undefined): BuilderSt
|
|||||||
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
|
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isBlankValue = (v: unknown) =>
|
||||||
|
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
||||||
|
|
||||||
|
/** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */
|
||||||
|
type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null }
|
||||||
|
|
||||||
|
const conditionValues = (condition: FieldCondition | null | undefined) =>
|
||||||
|
(condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fields (Steps and messages included) a visitor sees for the given values,
|
||||||
|
* in panel order. A field is hidden when its own "Show only when" fails, when
|
||||||
|
* its Step's condition fails (the whole step goes), or when the field its
|
||||||
|
* condition points at is itself hidden. A condition naming a field that doesn't
|
||||||
|
* exist hides the field — a typo shows up in the preview instead of passing silently.
|
||||||
|
*
|
||||||
|
* Shared by the browser (useBuilderForm: which steps and fields to show and
|
||||||
|
* validate) and the server (validateSubmission: hidden fields are neither
|
||||||
|
* required nor stored), so both agree on what was on screen.
|
||||||
|
*/
|
||||||
|
export function visibleFields<F extends ConditionalField>(fields: F[] | null | undefined, values: Record<string, unknown>): F[] {
|
||||||
|
const list = fields ?? []
|
||||||
|
const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f]))
|
||||||
|
const stepOf = new Map<F, F | undefined>()
|
||||||
|
let currentStep: F | undefined
|
||||||
|
for (const field of list) {
|
||||||
|
if (field.blockType === 'step') {currentStep = field}
|
||||||
|
stepOf.set(field, field.blockType === 'step' ? undefined : currentStep)
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = new Map<F, boolean>()
|
||||||
|
const met = (condition: FieldCondition | null | undefined, seen: Set<F>): boolean => {
|
||||||
|
const ref = condition?.field?.trim()
|
||||||
|
if (!ref) {return true}
|
||||||
|
const target = byName.get(ref)
|
||||||
|
if (!target || seen.has(target) || !visible(target, seen)) {return false}
|
||||||
|
const value = values[ref]
|
||||||
|
const wanted = conditionValues(condition)
|
||||||
|
if (wanted.length === 0) {return !isBlankValue(value)}
|
||||||
|
if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))}
|
||||||
|
return value != null && value !== '' && wanted.includes(String(value as boolean | number | string))
|
||||||
|
}
|
||||||
|
const visible = (field: F, seen: Set<F> = new Set()): boolean => {
|
||||||
|
const cached = cache.get(field)
|
||||||
|
if (cached !== undefined) {return cached}
|
||||||
|
const nextSeen = new Set(seen).add(field)
|
||||||
|
const step = stepOf.get(field)
|
||||||
|
const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen)
|
||||||
|
cache.set(field, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
return list.filter((field) => visible(field))
|
||||||
|
}
|
||||||
|
|
||||||
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
|
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
|
||||||
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
|
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
@@ -52,8 +114,7 @@ export function initialBuilderValues(fields: BuilderField[] | null | undefined):
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const isBlank = (v: unknown) =>
|
const isBlank = isBlankValue
|
||||||
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
|
||||||
|
|
||||||
/** Errors for the given fields (one message per field), empty object = valid. */
|
/** Errors for the given fields (one message per field), empty object = valid. */
|
||||||
export function validateBuilderFields(
|
export function validateBuilderFields(
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ import type { FormAnalyticsConfig } from './formAnalytics.js'
|
|||||||
*/
|
*/
|
||||||
export type BuilderOption = { label?: null | string; value: string }
|
export type BuilderOption = { label?: null | string; value: string }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Show only when" of a field or a Step (panel group `showWhen`): visible only
|
||||||
|
* when the field named `field` has one of `values` (comma-separated). Empty
|
||||||
|
* `values` = when that field is filled in / ticked. Empty `field` = always.
|
||||||
|
*/
|
||||||
|
export type FieldCondition = { field?: null | string; values?: null | string }
|
||||||
|
|
||||||
export type BuilderField = {
|
export type BuilderField = {
|
||||||
blockName?: null | string
|
blockName?: null | string
|
||||||
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
||||||
@@ -23,6 +30,8 @@ export type BuilderField = {
|
|||||||
options?: BuilderOption[] | null
|
options?: BuilderOption[] | null
|
||||||
placeholder?: null | string
|
placeholder?: null | string
|
||||||
required?: boolean | null
|
required?: boolean | null
|
||||||
|
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
|
||||||
|
showWhen?: FieldCondition | null
|
||||||
/** step */
|
/** step */
|
||||||
title?: null | string
|
title?: null | string
|
||||||
width?: null | number
|
width?: null | number
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ export function createSubmitAction({
|
|||||||
data: fields,
|
data: fields,
|
||||||
formId: String(formId),
|
formId: String(formId),
|
||||||
ip,
|
ip,
|
||||||
|
locale,
|
||||||
maxPerMinute,
|
maxPerMinute,
|
||||||
payload,
|
payload,
|
||||||
turnstileOnConfigError,
|
turnstileOnConfigError,
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import type { FormattedEmail } from '@payloadcms/plugin-form-builder/types'
|
||||||
|
import type { Field, PayloadRequest } from 'payload'
|
||||||
|
|
||||||
|
import type { BuilderField } from './builderTypes.js'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Branded e-mails for panel forms (`forms: { emailLayout: true }`).
|
||||||
|
*
|
||||||
|
* The form-builder sends what the editor wrote in Forms → Emails, with
|
||||||
|
* `{{*:table}}` rendered as a bare `field : value` table — technical names
|
||||||
|
* (`web_type`) and raw option values (`redesign_site`). This module swaps that
|
||||||
|
* table for a readable summary (the question as the visitor saw it, option
|
||||||
|
* labels, grouped by step, blanks left out) and wraps the message in an
|
||||||
|
* e-mail-safe layout (tables + inline CSS) with the logo, accent colour and
|
||||||
|
* footer from Site Settings → Emails. Pure functions + one beforeEmail hook.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type SummaryRow = { label: string; value: string }
|
||||||
|
export type SummaryGroup = { rows: SummaryRow[]; title?: string }
|
||||||
|
type SubmissionValue = { field?: null | string; value?: unknown }
|
||||||
|
|
||||||
|
const NON_INPUT = new Set(['message', 'step'])
|
||||||
|
|
||||||
|
const escapeHtml = (text: string): string =>
|
||||||
|
text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
|
||||||
|
|
||||||
|
const asText = (value: unknown): string =>
|
||||||
|
value == null ? '' : typeof value === 'string' ? value : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stored submission as readable rows: one group per Step (titled), the
|
||||||
|
* field label as the question, option labels instead of values (a checkbox
|
||||||
|
* group's "a, b" too), a ticked checkbox as ✓. Empty answers are skipped.
|
||||||
|
*/
|
||||||
|
export function buildSubmissionSummary(fields: BuilderField[] | null | undefined, submissionData: readonly SubmissionValue[]): SummaryGroup[] {
|
||||||
|
const stored = new Map(submissionData.filter((d) => d.field).map((d) => [d.field as string, asText(d.value).trim()]))
|
||||||
|
const groups: SummaryGroup[] = [{ rows: [] }]
|
||||||
|
for (const field of fields ?? []) {
|
||||||
|
if (field.blockType === 'step') {
|
||||||
|
groups.push({ rows: [], ...(field.title ? { title: field.title } : {}) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!field.name || NON_INPUT.has(field.blockType)) {continue}
|
||||||
|
const raw = stored.get(field.name)
|
||||||
|
if (!raw || raw === 'false') {continue}
|
||||||
|
const optionLabel = (value: string) => field.options?.find((o) => o.value === value)?.label || value
|
||||||
|
const value =
|
||||||
|
field.blockType === 'checkbox' ? '✓'
|
||||||
|
: field.blockType === 'checkboxGroup' ? raw.split(', ').map(optionLabel).join(', ')
|
||||||
|
: field.options?.length ? optionLabel(raw)
|
||||||
|
: raw
|
||||||
|
groups[groups.length - 1].rows.push({ label: field.label || field.name, value })
|
||||||
|
}
|
||||||
|
return groups.filter((g) => g.rows.length > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
|
||||||
|
|
||||||
|
/** The summary as an e-mail-safe table (inline CSS only). */
|
||||||
|
export function renderSummaryHtml(groups: SummaryGroup[], { accent }: { accent: string }): string {
|
||||||
|
const rows = groups
|
||||||
|
.map((group) => {
|
||||||
|
const title = group.title
|
||||||
|
? `<tr><td colspan="2" class="ipal-group" style="padding:22px 0 8px;font-family:${FONT};font-size:13px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;color:${accent};border-bottom:2px solid ${accent};">${escapeHtml(group.title)}</td></tr>`
|
||||||
|
: ''
|
||||||
|
const items = group.rows
|
||||||
|
.map(
|
||||||
|
(row) =>
|
||||||
|
`<tr class="ipal-row"><td valign="top" class="ipal-label" style="padding:10px 16px 10px 0;width:42%;font-family:${FONT};font-size:13px;line-height:1.5;color:#6b7280;border-bottom:1px solid #eceef1;">${escapeHtml(row.label)}</td>` +
|
||||||
|
`<td valign="top" class="ipal-value" style="padding:10px 0;font-family:${FONT};font-size:14px;line-height:1.5;color:#111827;border-bottom:1px solid #eceef1;white-space:pre-line;">${escapeHtml(row.value)}</td></tr>`,
|
||||||
|
)
|
||||||
|
.join('')
|
||||||
|
return title + items
|
||||||
|
})
|
||||||
|
.join('')
|
||||||
|
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin:8px 0 4px;">${rows}</table>`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** form-builder's `{{*:table}}` output (optionally inside a paragraph) → the readable summary. */
|
||||||
|
export const replaceSubmissionTable = (html: string, summaryHtml: string): string =>
|
||||||
|
html.replace(/(<p[^>]*>\s*)?<table>[\s\S]*?<\/table>(\s*<\/p>)?/g, summaryHtml)
|
||||||
|
|
||||||
|
export type EmailLayoutArgs = {
|
||||||
|
/** Accent colour (hex), Site Settings → Emails. */
|
||||||
|
accent: string
|
||||||
|
/** The message body (HTML from the panel, summary already in). */
|
||||||
|
content: string
|
||||||
|
/** Footer line, Site Settings → Emails. */
|
||||||
|
footer?: string
|
||||||
|
/** Absolute URL of a PNG/JPG logo — without it the site name is shown. */
|
||||||
|
logoUrl?: string
|
||||||
|
siteName?: string
|
||||||
|
siteUrl?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A complete HTML e-mail: header (logo or name), the message, footer. Tables + inline CSS. */
|
||||||
|
export function wrapEmailHtml({ accent, content, footer, logoUrl, siteName, siteUrl }: EmailLayoutArgs): string {
|
||||||
|
const name = siteName ? escapeHtml(siteName) : ''
|
||||||
|
const brand = logoUrl
|
||||||
|
? `<img src="${escapeHtml(logoUrl)}" alt="${name}" height="36" style="display:block;height:36px;width:auto;border:0;">`
|
||||||
|
: `<span style="font-family:${FONT};font-size:20px;font-weight:700;color:#111827;">${name}</span>`
|
||||||
|
const linkedBrand = siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="text-decoration:none;">${brand}</a>` : brand
|
||||||
|
const footerLines = [footer ? escapeHtml(footer).replace(/\n/g, '<br>') : '', siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="color:#6b7280;">${escapeHtml(siteUrl.replace(/^https?:\/\//, ''))}</a>` : '']
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('<br>')
|
||||||
|
return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light">
|
||||||
|
<style>@media (max-width:520px){.ipal-pad{padding-left:20px!important;padding-right:20px!important}.ipal-row td{display:block!important;width:auto!important}.ipal-label{padding:12px 0 2px!important;border-bottom:0!important}.ipal-value{padding:0 0 12px!important}}</style></head>
|
||||||
|
<body style="margin:0;padding:0;background:#f3f4f6;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f3f4f6;"><tr><td align="center" style="padding:32px 12px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:#ffffff;border-radius:12px;overflow:hidden;border-top:4px solid ${accent};">
|
||||||
|
<tr><td class="ipal-pad" style="padding:28px 36px 20px;border-bottom:1px solid #eceef1;">${linkedBrand}</td></tr>
|
||||||
|
<tr><td class="ipal-pad" style="padding:28px 36px 32px;font-family:${FONT};font-size:15px;line-height:1.65;color:#1f2937;">${content}</td></tr>
|
||||||
|
${footerLines ? `<tr><td class="ipal-pad" style="padding:20px 36px 28px;background:#f9fafb;font-family:${FONT};font-size:12px;line-height:1.6;color:#6b7280;">${footerLines}</td></tr>` : ''}
|
||||||
|
</table></td></tr></table></body></html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Site Settings → "Emails" tab (shown with `forms: { emailLayout: true }`). */
|
||||||
|
export const emailSettingsFields: Field[] = [
|
||||||
|
{
|
||||||
|
name: 'email',
|
||||||
|
type: 'group',
|
||||||
|
admin: { hideGutter: true },
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
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',
|
||||||
|
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.',
|
||||||
|
},
|
||||||
|
{ name: 'footer', type: 'textarea', admin: { description: 'E.g. company name and address.' }, label: 'Footer', localized: true },
|
||||||
|
],
|
||||||
|
label: false,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Neutral accent when the panel has none (plugin default, not a brand colour). */
|
||||||
|
const DEFAULT_ACCENT = '#111827'
|
||||||
|
|
||||||
|
type HookArgs = { data?: { form?: unknown; submissionData?: SubmissionValue[] }; req: PayloadRequest }
|
||||||
|
|
||||||
|
const mediaUrl = (media: unknown): string | undefined =>
|
||||||
|
media && typeof media === 'object' && 'url' in media && typeof media.url === 'string' ? media.url : undefined
|
||||||
|
|
||||||
|
/**
|
||||||
|
* form-builder `beforeEmail`: summary instead of the raw table + the layout.
|
||||||
|
* Never blocks sending — on any error the original e-mails go out (logged).
|
||||||
|
*/
|
||||||
|
export function buildEmailLayoutHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}) {
|
||||||
|
return async (emails: FormattedEmail[], { data, req }: HookArgs): Promise<FormattedEmail[]> => {
|
||||||
|
const { locale, payload } = req
|
||||||
|
try {
|
||||||
|
const formRef = data?.form
|
||||||
|
const formId = formRef && typeof formRef === 'object' && 'id' in formRef ? formRef.id : formRef
|
||||||
|
const [form, settings] = await Promise.all([
|
||||||
|
payload.findByID({ id: formId as number | string, collection: formsSlug as never, depth: 0, locale: locale as never, overrideAccess: true, req }),
|
||||||
|
payload.findGlobal({ slug: 'site-settings' as never, depth: 1, locale: locale as never, req }),
|
||||||
|
])
|
||||||
|
const s = settings as { email?: { accentColor?: string; footer?: string; logo?: unknown }; siteName?: string }
|
||||||
|
const accent = s.email?.accentColor || DEFAULT_ACCENT
|
||||||
|
const summary = renderSummaryHtml(buildSubmissionSummary((form as { fields?: BuilderField[] }).fields, data?.submissionData ?? []), { accent })
|
||||||
|
const serverURL = payload.config.serverURL?.replace(/\/$/, '')
|
||||||
|
const logo = mediaUrl(s.email?.logo)
|
||||||
|
const logoUrl = logo && /^https?:\/\//.test(logo) ? logo : logo && serverURL ? `${serverURL}${logo}` : undefined
|
||||||
|
return emails.map((email) => ({
|
||||||
|
...email,
|
||||||
|
html: wrapEmailHtml({
|
||||||
|
accent,
|
||||||
|
content: replaceSubmissionTable(email.html ?? '', summary),
|
||||||
|
...(s.email?.footer ? { footer: s.email.footer } : {}),
|
||||||
|
...(logoUrl ? { logoUrl } : {}),
|
||||||
|
...(s.siteName ? { siteName: s.siteName } : {}),
|
||||||
|
...(serverURL ? { siteUrl: serverURL } : {}),
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
} catch (err) {
|
||||||
|
payload.logger.error(`[ipal] E-mail layout skipped: ${(err as Error).message}`)
|
||||||
|
return emails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,20 @@
|
|||||||
import type { Field, Plugin } from 'payload'
|
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
|
||||||
|
import type { Block, Field, Plugin } from 'payload'
|
||||||
|
|
||||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||||
|
|
||||||
import type { FormsOption } from './types.js'
|
import type { FormsOption } from './types.js'
|
||||||
|
|
||||||
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
||||||
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
|
||||||
|
import { buildEmailLayoutHook } from './emailLayout.js'
|
||||||
|
|
||||||
type AccessArgs = { req: { user?: unknown } }
|
type AccessArgs = { req: { user?: unknown } }
|
||||||
|
|
||||||
|
/** 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)
|
||||||
|
|
||||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||||
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
||||||
/**
|
/**
|
||||||
@@ -52,25 +58,36 @@ function hideEmails(fields: Field[]): Field[] {
|
|||||||
export function buildFormsPlugin(forms: FormsOption): Plugin {
|
export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||||
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
|
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
|
||||||
const group = adminGroup ? { group: adminGroup } : {}
|
const group = adminGroup ? { group: adminGroup } : {}
|
||||||
|
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
|
||||||
|
const beforeEmail: BeforeEmail | undefined =
|
||||||
|
layout || forms.beforeEmail
|
||||||
|
? async (emails, args) => {
|
||||||
|
const laidOut = layout ? await layout(emails, args) : emails
|
||||||
|
return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
return formBuilderPlugin({
|
return formBuilderPlugin({
|
||||||
|
...(beforeEmail ? { beforeEmail } : {}),
|
||||||
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
|
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
|
||||||
// panel choices only — a form uses what the editor adds, nothing changes on
|
// panel choices only — a form uses what the editor adds, nothing changes on
|
||||||
// existing forms. Switch any off with forms.fields.<type>: false.
|
// existing forms. Switch any off with forms.fields.<type>: false.
|
||||||
fields: {
|
fields: {
|
||||||
checkbox: true,
|
// every block carries "Show only when" (showWhen) — conditional fields and steps
|
||||||
|
checkbox: builtin('checkbox'),
|
||||||
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
||||||
date: true,
|
date: builtin('date'),
|
||||||
email: true,
|
email: builtin('email'),
|
||||||
message: true,
|
message: builtin('message'),
|
||||||
number: true,
|
number: builtin('number'),
|
||||||
payment: false,
|
payment: false,
|
||||||
radio: true,
|
radio: builtin('radio'),
|
||||||
select: true,
|
select: builtin('select'),
|
||||||
step: forms.fields?.step === false ? false : stepBlock,
|
step: forms.fields?.step === false ? false : stepBlock,
|
||||||
text: true,
|
text: builtin('text'),
|
||||||
textarea: true,
|
textarea: builtin('textarea'),
|
||||||
...Object.fromEntries(
|
...Object.fromEntries(
|
||||||
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
|
// `true` keeps ipal's block (with "Show only when"); false / an object override it
|
||||||
|
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
...(forms.redirectRelationships
|
...(forms.redirectRelationships
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// Panel field types: step-by-step forms + multiple choice (enabled by default).
|
// Panel field types: step-by-step forms + multiple choice (enabled by default).
|
||||||
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||||
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
|
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
|
||||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||||
export { formAnalyticsOnSuccess } from './formAnalytics.js'
|
export { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||||
export type { FormAnalyticsConfig } from './formAnalytics.js'
|
export type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||||
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ export type SubmitFormArgs = {
|
|||||||
formId: string
|
formId: string
|
||||||
/** Client IP — used for Turnstile and rate limiting. */
|
/** Client IP — used for Turnstile and rate limiting. */
|
||||||
ip?: string
|
ip?: string
|
||||||
|
/** Page language — the form-builder reads the form (e-mail texts, labels) in it. */
|
||||||
|
locale?: string
|
||||||
/**
|
/**
|
||||||
* Rate limit: max submissions per IP per minute. Defaults to 5.
|
* Rate limit: max submissions per IP per minute. Defaults to 5.
|
||||||
* Set to 0 to disable (e.g. when a real limiter sits in front).
|
* Set to 0 to disable (e.g. when a real limiter sits in front).
|
||||||
@@ -96,6 +98,7 @@ export async function submitForm({
|
|||||||
data,
|
data,
|
||||||
formId,
|
formId,
|
||||||
ip,
|
ip,
|
||||||
|
locale,
|
||||||
maxPerMinute = 5,
|
maxPerMinute = 5,
|
||||||
payload,
|
payload,
|
||||||
turnstileOnConfigError = 'allow',
|
turnstileOnConfigError = 'allow',
|
||||||
@@ -143,6 +146,7 @@ export async function submitForm({
|
|||||||
try {
|
try {
|
||||||
const submission = await payload.create({
|
const submission = await payload.create({
|
||||||
collection: 'form-submissions',
|
collection: 'form-submissions',
|
||||||
|
...(locale ? { locale: locale as never } : {}),
|
||||||
data: {
|
data: {
|
||||||
form: formId,
|
form: formId,
|
||||||
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
|
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
|
||||||
import type { CollectionConfig, Field } from 'payload'
|
import type { CollectionConfig, Field } from 'payload'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,12 +26,23 @@ export type FormsOption = {
|
|||||||
* formOverrides / formSubmissionOverrides still wins.
|
* formOverrides / formSubmissionOverrides still wins.
|
||||||
*/
|
*/
|
||||||
adminGroup?: false | string
|
adminGroup?: false | string
|
||||||
|
/**
|
||||||
|
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
|
||||||
|
* the ipal layout when `emailLayout` is on.
|
||||||
|
*/
|
||||||
|
beforeEmail?: BeforeEmail
|
||||||
/**
|
/**
|
||||||
* Name of the checkbox field treated as a GDPR consent gate. A form field
|
* Name of the checkbox field treated as a GDPR consent gate. A form field
|
||||||
* with this name must be checked for submission to succeed — enforced
|
* with this name must be checked for submission to succeed — enforced
|
||||||
* server-side in submitForm. Defaults to 'consent'.
|
* server-side in submitForm. Defaults to 'consent'.
|
||||||
*/
|
*/
|
||||||
consentFieldName?: string
|
consentFieldName?: string
|
||||||
|
/**
|
||||||
|
* Branded e-mails (emailLayout.ts): `{{*:table}}` becomes a readable summary
|
||||||
|
* (questions, option labels, grouped by step) and every e-mail gets a layout
|
||||||
|
* with the logo, accent colour and footer from Site Settings → Emails. Default false.
|
||||||
|
*/
|
||||||
|
emailLayout?: boolean
|
||||||
/** Field types available in the form builder. Sensible defaults applied. */
|
/** Field types available in the form builder. Sensible defaults applied. */
|
||||||
fields?: {
|
fields?: {
|
||||||
checkbox?: boolean
|
checkbox?: boolean
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
|
|||||||
|
|
||||||
import { safeHref } from '../links/resolveLinkHref.js'
|
import { safeHref } from '../links/resolveLinkHref.js'
|
||||||
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
|
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
|
||||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||||
import { formAnalyticsOnSuccess } from './formAnalytics.js'
|
import { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||||
import { useForm } from './useForm.js'
|
import { useForm } from './useForm.js'
|
||||||
|
|
||||||
@@ -42,8 +42,8 @@ export type UseBuilderFormOptions = {
|
|||||||
*/
|
*/
|
||||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
||||||
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
||||||
const steps = useMemo(() => splitSteps(fields), [fields])
|
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
|
||||||
const inputs = useMemo(() => inputFields(fields), [fields])
|
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
|
||||||
const [stepIndex, setStepIndex] = useState(0)
|
const [stepIndex, setStepIndex] = useState(0)
|
||||||
const [resultMessage, setResultMessage] = useState<null | string>(null)
|
const [resultMessage, setResultMessage] = useState<null | string>(null)
|
||||||
const ts = useOptionalTurnstile()
|
const ts = useOptionalTurnstile()
|
||||||
@@ -52,15 +52,16 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
|||||||
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
|
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
|
||||||
const submitAction = useCallback(
|
const submitAction = useCallback(
|
||||||
async (values: Record<string, unknown>, token?: string) => {
|
async (values: Record<string, unknown>, token?: string) => {
|
||||||
const result = await action(values, token)
|
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)}
|
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) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
|
||||||
return result
|
return result
|
||||||
},
|
},
|
||||||
[action, texts.validation],
|
[action, texts.validation, visibleInputs],
|
||||||
)
|
)
|
||||||
|
|
||||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
|
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
|
||||||
|
|
||||||
const f = useForm<Record<string, unknown>>({
|
const f = useForm<Record<string, unknown>>({
|
||||||
errorFallback: texts.error,
|
errorFallback: texts.error,
|
||||||
@@ -78,6 +79,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
|||||||
validate,
|
validate,
|
||||||
})
|
})
|
||||||
const { setErrors, setTurnstileToken } = f
|
const { setErrors, setTurnstileToken } = f
|
||||||
|
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
|
||||||
|
const steps = useMemo(() => {
|
||||||
|
const shown = new Set(visibleFields(fields, f.values))
|
||||||
|
return splitSteps(fields, (field) => shown.has(field))
|
||||||
|
}, [fields, f.values])
|
||||||
|
|
||||||
// Turnstile token lives in the provider; the engine needs it at submit.
|
// Turnstile token lives in the provider; the engine needs it at submit.
|
||||||
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
|
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import type { BasePayload } from 'payload'
|
import type { BasePayload } from 'payload'
|
||||||
|
|
||||||
|
import type { FieldCondition } from './builderTypes.js'
|
||||||
|
|
||||||
|
import { visibleFields } from './builderLogic.js'
|
||||||
|
|
||||||
/** A form-builder field, trimmed to what validation needs. */
|
/** A form-builder field, trimmed to what validation needs. */
|
||||||
type FormField = {
|
type FormField = {
|
||||||
blockType?: string
|
blockType?: string
|
||||||
@@ -11,6 +15,8 @@ type FormField = {
|
|||||||
/** select / radio / checkboxGroup choices defined in the panel. */
|
/** select / radio / checkboxGroup choices defined in the panel. */
|
||||||
options?: { value?: unknown }[] | null
|
options?: { value?: unknown }[] | null
|
||||||
required?: boolean | null
|
required?: boolean | null
|
||||||
|
/** "Show only when" — hidden fields are neither required nor stored. */
|
||||||
|
showWhen?: FieldCondition | null
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormDoc = {
|
type FormDoc = {
|
||||||
@@ -171,10 +177,15 @@ export async function validateSubmission(
|
|||||||
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
|
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
|
||||||
)
|
)
|
||||||
const known = new Map(fields.map((f) => [f.name, f]))
|
const known = new Map(fields.map((f) => [f.name, f]))
|
||||||
|
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
|
||||||
|
const shown = new Set(visibleFields(form.fields, data))
|
||||||
|
|
||||||
const cleaned: Record<string, unknown> = {}
|
const cleaned: Record<string, unknown> = {}
|
||||||
|
|
||||||
for (const field of fields) {
|
for (const field of fields) {
|
||||||
|
// Hidden by a condition: not required, not stored. The consent gate never hides —
|
||||||
|
// an editor can't switch GDPR consent off with a condition.
|
||||||
|
if (!shown.has(field) && field.name !== consentFieldName) {continue}
|
||||||
const value = data[field.name]
|
const value = data[field.name]
|
||||||
const isBlank =
|
const isBlank =
|
||||||
value == null ||
|
value == null ||
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { cache } from 'react'
|
|||||||
|
|
||||||
import type { AnalyticsConfig } from '../analytics/types.js'
|
import type { AnalyticsConfig } from '../analytics/types.js'
|
||||||
import type { ConsentTexts } from '../consent/texts.js'
|
import type { ConsentTexts } from '../consent/texts.js'
|
||||||
|
import type { ConstructionMode } from '../construction/types.js'
|
||||||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
||||||
import type { I18nConfig } from '../i18n/index.js'
|
import type { I18nConfig } from '../i18n/index.js'
|
||||||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
|
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
|
||||||
@@ -604,6 +605,40 @@ export function createContentHelpers({
|
|||||||
segments,
|
segments,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Site Settings → Under construction, for this locale: whether it's on, the
|
||||||
|
* paths still reachable (homepage + chosen pages, in every language), the
|
||||||
|
* homepage to redirect to and the notice texts. createPageRoute (with
|
||||||
|
* `redirect`) and <ConstructionNotice> (/client) use it.
|
||||||
|
*/
|
||||||
|
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
|
||||||
|
const settings = (await getSettings(locale)) as null | Record<string, unknown>
|
||||||
|
const options = await getLinkOptions(locale)
|
||||||
|
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
|
||||||
|
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
|
||||||
|
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
|
||||||
|
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }}
|
||||||
|
|
||||||
|
const configured = await getConfiguredLocales()
|
||||||
|
const paths = await Promise.all(
|
||||||
|
(configured.length ? configured : [locale]).map(async (code) => {
|
||||||
|
const localized = (await getSettings(code)) as null | Record<string, unknown>
|
||||||
|
const linkOptions = await getLinkOptions(code)
|
||||||
|
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
|
||||||
|
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
|
||||||
|
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
|
||||||
|
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
|
||||||
|
return {
|
||||||
|
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
|
||||||
|
enabled: true,
|
||||||
|
homePath,
|
||||||
|
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// ── Layout ────────────────────────────────────────────────────────────────
|
// ── Layout ────────────────────────────────────────────────────────────────
|
||||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||||
@@ -682,6 +717,7 @@ export function createContentHelpers({
|
|||||||
generateStaticParams,
|
generateStaticParams,
|
||||||
getCachedPayload,
|
getCachedPayload,
|
||||||
getConfiguredLocales,
|
getConfiguredLocales,
|
||||||
|
getConstructionMode,
|
||||||
getEntries,
|
getEntries,
|
||||||
getFormTexts,
|
getFormTexts,
|
||||||
getHomeSlug,
|
getHomeSlug,
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ import type { ResolvedRoute } from '../content/index.js'
|
|||||||
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
|
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
|
||||||
|
|
||||||
import { RenderBlocks } from '../blocks/RenderBlocks.js'
|
import { RenderBlocks } from '../blocks/RenderBlocks.js'
|
||||||
|
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
|
||||||
import { LocaleView } from '../pages/LocaleView.js'
|
import { LocaleView } from '../pages/LocaleView.js'
|
||||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||||
|
|
||||||
type Helpers = Pick<
|
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||||
ContentHelpers,
|
ContentHelpers,
|
||||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||||
>
|
>
|
||||||
@@ -28,6 +29,11 @@ export type PageRouteOptions = {
|
|||||||
notFound: () => never
|
notFound: () => never
|
||||||
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
|
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
|
||||||
permanentRedirect: (url: string) => never
|
permanentRedirect: (url: string) => never
|
||||||
|
/**
|
||||||
|
* `redirect` from 'next/navigation' — enables Site Settings → Under construction:
|
||||||
|
* pages that aren't available (and unknown addresses) go to the homepage with the notice.
|
||||||
|
*/
|
||||||
|
redirect?: (url: string) => never
|
||||||
/**
|
/**
|
||||||
* Render a route yourself — an archive listing, a blog entry template.
|
* Render a route yourself — an archive listing, a blog entry template.
|
||||||
* Return undefined to keep the default (the document's blocks).
|
* Return undefined to keep the default (the document's blocks).
|
||||||
@@ -57,7 +63,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
|||||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||||
*/
|
*/
|
||||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
|
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, render } = options
|
||||||
const localeOf = (locale: string | undefined) => {
|
const localeOf = (locale: string | undefined) => {
|
||||||
const l = locale ?? helpers.i18n?.defaultLocale
|
const l = locale ?? helpers.i18n?.defaultLocale
|
||||||
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||||
@@ -73,6 +79,13 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
|||||||
const { slug, locale: param } = await params
|
const { slug, locale: param } = await params
|
||||||
const locale = localeOf(param)
|
const locale = localeOf(param)
|
||||||
const segments = slug ?? []
|
const segments = slug ?? []
|
||||||
|
// Under construction: anything but the homepage and the chosen pages → homepage + notice
|
||||||
|
if (redirect && helpers.getConstructionMode) {
|
||||||
|
const construction = await helpers.getConstructionMode(locale)
|
||||||
|
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
|
||||||
|
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
|
||||||
|
if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))}
|
||||||
|
}
|
||||||
const route = await helpers.resolveRoute(locale, segments, 1)
|
const route = await helpers.resolveRoute(locale, segments, 1)
|
||||||
if (!route) {
|
if (!route) {
|
||||||
const target = await helpers.resolvePageRedirect(locale, segments)
|
const target = await helpers.resolvePageRedirect(locale, segments)
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
|
|||||||
components: {
|
components: {
|
||||||
Field: {
|
Field: {
|
||||||
clientProps: { label, statusField },
|
clientProps: { label, statusField },
|
||||||
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
|
path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
|||||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||||
import { injectRoles } from './modules/access/index.js'
|
import { injectRoles } from './modules/access/index.js'
|
||||||
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
||||||
|
import { buildConstructionFields } from './modules/construction/fields.js'
|
||||||
import { buildArchiveFields } from './modules/content/index.js'
|
import { buildArchiveFields } from './modules/content/index.js'
|
||||||
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
||||||
|
import { emailSettingsFields } from './modules/forms/emailLayout.js'
|
||||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||||
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
|
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
|
||||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||||
@@ -212,6 +214,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
|||||||
...(config.globals ?? []),
|
...(config.globals ?? []),
|
||||||
buildSiteSettings({
|
buildSiteSettings({
|
||||||
additionalFields: options.siteSettingsFields,
|
additionalFields: options.siteSettingsFields,
|
||||||
|
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
|
||||||
|
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
|
||||||
systemPageFields,
|
systemPageFields,
|
||||||
}),
|
}),
|
||||||
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { describe, expect, test } from 'vitest'
|
||||||
|
|
||||||
|
import type { BuilderField } from '../src/modules/forms/builderTypes.js'
|
||||||
|
|
||||||
|
import { inputFields, splitSteps, validateBuilderFields, visibleFields } from '../src/modules/forms/builderLogic.js'
|
||||||
|
import { validateSubmission } from '../src/modules/forms/validateSubmission.js'
|
||||||
|
import { fakePayload } from './helpers.js'
|
||||||
|
|
||||||
|
// A brief: screen 1 picks the areas, each later Step shows only for its area.
|
||||||
|
const fields: BuilderField[] = [
|
||||||
|
{ name: 'company', blockType: 'text', required: true },
|
||||||
|
{ name: 'areas', blockType: 'checkboxGroup', options: [{ value: 'web' }, { value: 'mkt' }, { value: 'it' }], required: true },
|
||||||
|
{ name: 'deadline', blockType: 'radio', options: [{ value: 'fixed' }, { value: 'flexible' }] },
|
||||||
|
{ name: 'deadline_reason', blockType: 'text', showWhen: { field: 'deadline', values: 'fixed' } },
|
||||||
|
{ name: 'consent', blockType: 'checkbox', required: true },
|
||||||
|
{ blockType: 'step', showWhen: { field: 'areas', values: 'web' }, title: 'Website' },
|
||||||
|
{ name: 'site_type', blockType: 'radio', options: [{ value: 'new' }, { value: 'redesign' }], required: true },
|
||||||
|
{ name: 'site_problems', blockType: 'textarea', showWhen: { field: 'site_type', values: 'redesign' } },
|
||||||
|
{ blockType: 'step', showWhen: { field: 'areas', values: 'mkt' }, title: 'Marketing' },
|
||||||
|
{ name: 'ads_budget', blockType: 'text', required: true },
|
||||||
|
{ blockType: 'step', showWhen: { field: 'areas', values: 'it, web' }, title: 'IT' },
|
||||||
|
{ name: 'it_scope', blockType: 'text' },
|
||||||
|
]
|
||||||
|
const names = (list: BuilderField[]) => inputFields(list).map((f) => f.name)
|
||||||
|
const texts = { validation: 'Check {field}' }
|
||||||
|
|
||||||
|
describe('conditional fields and steps (showWhen)', () => {
|
||||||
|
test('nothing picked → only the first screen; a field shows when its value matches', () => {
|
||||||
|
expect(names(visibleFields(fields, {}))).toEqual(['company', 'areas', 'deadline', 'consent'])
|
||||||
|
expect(names(visibleFields(fields, { deadline: 'fixed' }))).toContain('deadline_reason')
|
||||||
|
expect(names(visibleFields(fields, { deadline: 'flexible' }))).not.toContain('deadline_reason')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a Step with a failed condition drops out with all its fields; any of the listed values matches', () => {
|
||||||
|
const steps = splitSteps(visibleFields(fields, { areas: ['mkt'] }))
|
||||||
|
expect(steps.map((s) => s.title)).toEqual([undefined, 'Marketing'])
|
||||||
|
expect(splitSteps(visibleFields(fields, { areas: ['web'] })).map((s) => s.title)).toEqual([undefined, 'Website', 'IT'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('hidden fields and Steps leave the rest with their original index (message blocks render by it)', () => {
|
||||||
|
const list: BuilderField[] = [
|
||||||
|
{ name: 'pick', blockType: 'radio', options: [{ value: 'a' }, { value: 'b' }] },
|
||||||
|
{ blockType: 'step', showWhen: { field: 'pick', values: 'a' }, title: 'A' },
|
||||||
|
{ blockType: 'message' },
|
||||||
|
{ blockType: 'step', showWhen: { field: 'pick', values: 'b' }, title: 'B' },
|
||||||
|
{ blockType: 'message' },
|
||||||
|
]
|
||||||
|
const shown = new Set(visibleFields(list, { pick: 'b' }))
|
||||||
|
const steps = splitSteps(list, (field) => shown.has(field))
|
||||||
|
expect(steps.map((s) => ({ indexes: s.fields.map(({ index }) => index), title: s.title }))).toEqual([
|
||||||
|
{ indexes: [0], title: undefined },
|
||||||
|
{ indexes: [4], title: 'B' },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a field inside a hidden Step stays hidden even when its own condition matches', () => {
|
||||||
|
expect(names(visibleFields(fields, { areas: ['mkt'], site_type: 'redesign' }))).not.toContain('site_problems')
|
||||||
|
expect(names(visibleFields(fields, { areas: ['web'], site_type: 'redesign' }))).toContain('site_problems')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('empty values = when the field is filled in or ticked; unknown field or a cycle hides', () => {
|
||||||
|
const list: BuilderField[] = [
|
||||||
|
{ name: 'a', blockType: 'checkbox' },
|
||||||
|
{ name: 'b', blockType: 'text', showWhen: { field: 'a' } },
|
||||||
|
{ name: 'c', blockType: 'text', showWhen: { field: 'typo' } },
|
||||||
|
{ name: 'd', blockType: 'text', showWhen: { field: 'e' } },
|
||||||
|
{ name: 'e', blockType: 'text', showWhen: { field: 'd' } },
|
||||||
|
]
|
||||||
|
expect(names(visibleFields(list, { a: false }))).toEqual(['a'])
|
||||||
|
expect(names(visibleFields(list, { a: true }))).toEqual(['a', 'b'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validation of visible fields only: a hidden required field does not block', () => {
|
||||||
|
const values = { areas: ['mkt'], company: 'X', consent: true }
|
||||||
|
expect(validateBuilderFields(inputFields(visibleFields(fields, values)), values, texts)).toEqual({ ads_budget: 'Check ads_budget' })
|
||||||
|
expect(validateBuilderFields(inputFields(visibleFields(fields, { ...values, areas: ['it'] })), values, texts)).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('server: validateSubmission follows the same conditions', () => {
|
||||||
|
const { payload } = fakePayload({ forms: { brief: { fields } } })
|
||||||
|
const check = (data: Record<string, unknown>) => validateSubmission(payload, 'brief', data)
|
||||||
|
|
||||||
|
test('a required field in a hidden Step is not required — and its value is not stored', async () => {
|
||||||
|
const result = await check({ ads_budget: 'smuggled', areas: ['it'], company: 'X', consent: true, it_scope: 'servers' })
|
||||||
|
expect(result).toMatchObject({ cleaned: { areas: ['it'], company: 'X', consent: true, it_scope: 'servers' }, ok: true })
|
||||||
|
expect(result.ok && 'ads_budget' in result.cleaned).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a required field in a visible Step is still enforced', async () => {
|
||||||
|
expect(await check({ areas: ['mkt'], company: 'X', consent: true })).toMatchObject({ field: 'ads_budget', kind: 'required', ok: false })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('GDPR consent is enforced even if an editor hides it with a condition', async () => {
|
||||||
|
const { payload: p } = fakePayload({
|
||||||
|
forms: { f: { fields: [{ name: 'company', blockType: 'text' }, { name: 'consent', blockType: 'checkbox', showWhen: { field: 'company', values: 'never' } }] } },
|
||||||
|
})
|
||||||
|
expect(await validateSubmission(p, 'f', { company: 'X' })).toMatchObject({ field: 'consent', ok: false, reason: 'consent' })
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||||
|
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { buildConfig, getPayload } from 'payload'
|
||||||
|
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js'
|
||||||
|
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||||
|
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||||
|
import { ipalKit } from '../src/plugin.js'
|
||||||
|
|
||||||
|
vi.mock('server-only', () => ({}))
|
||||||
|
|
||||||
|
describe('under construction — path logic', () => {
|
||||||
|
test('paths compare without a trailing slash; the notice link carries the parameter', () => {
|
||||||
|
expect(normalizePath('/pl/')).toBe('/pl')
|
||||||
|
expect(normalizePath('')).toBe('/')
|
||||||
|
expect(isPathAllowed('/pl/brief/', ['/pl', '/pl/brief'])).toBe(true)
|
||||||
|
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
|
||||||
|
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('under construction — Site Settings → createPageRoute', () => {
|
||||||
|
let payload: Payload
|
||||||
|
let configPromise: Parameters<typeof getPayload>[0]['config']
|
||||||
|
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
configPromise = buildConfig({
|
||||||
|
collections: [
|
||||||
|
{ slug: 'users', auth: true, fields: [] },
|
||||||
|
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }] },
|
||||||
|
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-construction') } },
|
||||||
|
],
|
||||||
|
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||||
|
editor: lexicalEditor(),
|
||||||
|
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
|
||||||
|
secret: 'construction-test-secret',
|
||||||
|
telemetry: false,
|
||||||
|
})
|
||||||
|
payload = await getPayload({ config: configPromise })
|
||||||
|
}, 60_000)
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await payload?.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
const redirectError = (url: string): never => {
|
||||||
|
throw new Error(`REDIRECT ${url}`)
|
||||||
|
}
|
||||||
|
const route = () =>
|
||||||
|
createPageRoute(createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }), {
|
||||||
|
blocks: {},
|
||||||
|
notFound: () => {
|
||||||
|
throw new Error('NEXT_NOT_FOUND')
|
||||||
|
},
|
||||||
|
permanentRedirect: vi.fn() as unknown as (url: string) => never,
|
||||||
|
redirect: redirectError,
|
||||||
|
})
|
||||||
|
const open = (locale: string, slug?: string[]) => route().Page({ params: Promise.resolve({ slug, locale }) })
|
||||||
|
|
||||||
|
test('off: pages open normally; on: only the homepage and the chosen pages, everything else → homepage + notice', async () => {
|
||||||
|
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', title: 'Start' } as never, locale: 'pl' as never })
|
||||||
|
const brief = await payload.create({ collection: 'pages' as never, data: { slug: 'brief', title: 'Brief' } as never, locale: 'pl' as never })
|
||||||
|
await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never, locale: 'pl' as never })
|
||||||
|
await payload.update({ id: brief.id, collection: 'pages' as never, data: { slug: 'project-brief' } as never, locale: 'en' as never })
|
||||||
|
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
|
||||||
|
|
||||||
|
await expect(open('pl', ['o-nas'])).resolves.toBeTruthy()
|
||||||
|
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: 'site-settings' as never,
|
||||||
|
data: { construction: { allowedPages: [brief.id], enabled: true, message: 'Strona w budowie', title: 'Pracujemy nad stroną' } } as never,
|
||||||
|
locale: 'pl' as never,
|
||||||
|
})
|
||||||
|
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
|
||||||
|
const mode = await helpers.getConstructionMode('pl')
|
||||||
|
expect(mode).toMatchObject({ enabled: true, homePath: '/pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } })
|
||||||
|
expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief']))
|
||||||
|
|
||||||
|
await expect(open('pl')).resolves.toBeTruthy()
|
||||||
|
await expect(open('pl', ['brief'])).resolves.toBeTruthy()
|
||||||
|
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||||
|
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import type { PayloadRequest } from 'payload'
|
||||||
|
|
||||||
|
import { describe, expect, test, vi } from 'vitest'
|
||||||
|
|
||||||
|
import type { BuilderField } from '../src/modules/forms/builderTypes.js'
|
||||||
|
|
||||||
|
import { buildEmailLayoutHook, buildSubmissionSummary, renderSummaryHtml, replaceSubmissionTable, wrapEmailHtml } from '../src/modules/forms/emailLayout.js'
|
||||||
|
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||||
|
import { fakePayload } from './helpers.js'
|
||||||
|
|
||||||
|
vi.mock('server-only', () => ({}))
|
||||||
|
|
||||||
|
const fields: BuilderField[] = [
|
||||||
|
{ blockType: 'step', title: 'O firmie' },
|
||||||
|
{ blockType: 'message' },
|
||||||
|
{ name: 'company', blockType: 'text', label: 'Nazwa firmy' },
|
||||||
|
{ name: 'website', blockType: 'text', label: 'Strona' },
|
||||||
|
{ name: 'areas', blockType: 'checkboxGroup', label: 'Obszary', options: [{ label: 'Strony internetowe', value: 'web' }, { label: 'IT', value: 'it' }] },
|
||||||
|
{ name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Do 10', value: '1-9' }] },
|
||||||
|
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda RODO' },
|
||||||
|
{ blockType: 'step', title: 'IT' },
|
||||||
|
{ name: 'it_scope', blockType: 'textarea', label: 'Zakres' },
|
||||||
|
]
|
||||||
|
const stored = [
|
||||||
|
{ field: 'company', value: 'Acme <script>' },
|
||||||
|
{ field: 'website', value: '' },
|
||||||
|
{ field: 'areas', value: 'web, it' },
|
||||||
|
{ field: 'size', value: '1-9' },
|
||||||
|
{ field: 'consent', value: 'true' },
|
||||||
|
{ field: 'formSubmissionID', value: '42' },
|
||||||
|
]
|
||||||
|
|
||||||
|
describe('e-mail layout', () => {
|
||||||
|
test('summary: questions + option labels, grouped by step, blanks and empty steps left out', () => {
|
||||||
|
expect(buildSubmissionSummary(fields, stored)).toEqual([
|
||||||
|
{
|
||||||
|
rows: [
|
||||||
|
{ label: 'Nazwa firmy', value: 'Acme <script>' },
|
||||||
|
{ label: 'Obszary', value: 'Strony internetowe, IT' },
|
||||||
|
{ label: 'Wielkość', value: 'Do 10' },
|
||||||
|
{ label: 'Zgoda RODO', value: '✓' },
|
||||||
|
],
|
||||||
|
title: 'O firmie',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('summary HTML is escaped; the form-builder table (also inside <p>) is replaced', () => {
|
||||||
|
const html = renderSummaryHtml(buildSubmissionSummary(fields, stored), { accent: '#017BD0' })
|
||||||
|
expect(html).toContain('Acme <script>')
|
||||||
|
expect(html).not.toContain('<script>')
|
||||||
|
expect(replaceSubmissionTable('<p>Nowe:</p><p><table><tr><td>company</td><td>x</td></tr></table></p>', '[S]')).toBe('<p>Nowe:</p>[S]')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('layout: logo or site name, accent colour, footer', () => {
|
||||||
|
const withLogo = wrapEmailHtml({ accent: '#017BD0', content: '<p>Hi</p>', footer: 'Acme sp. z o.o.\nWrocław', logoUrl: 'https://cdn.acme.pl/logo.png', siteName: 'Acme', siteUrl: 'https://acme.pl' })
|
||||||
|
expect(withLogo).toContain('src="https://cdn.acme.pl/logo.png"')
|
||||||
|
expect(withLogo).toContain('border-top:4px solid #017BD0')
|
||||||
|
expect(withLogo).toContain('Acme sp. z o.o.<br>Wrocław')
|
||||||
|
expect(wrapEmailHtml({ accent: '#111827', content: '', siteName: 'Acme' })).toContain('>Acme</span>')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('hook: summary + layout from Site Settings → Emails; on an error the original e-mails go out', async () => {
|
||||||
|
const payload = {
|
||||||
|
config: { serverURL: 'https://acme.pl/' },
|
||||||
|
findByID: vi.fn(async () => ({ fields })),
|
||||||
|
findGlobal: vi.fn(async () => ({ email: { accentColor: '#017BD0', footer: 'Acme', logo: { url: '/api/media/file/logo.png' } }, siteName: 'Acme' })),
|
||||||
|
logger: { error: vi.fn() },
|
||||||
|
}
|
||||||
|
const hook = buildEmailLayoutHook()
|
||||||
|
const email = { from: '[email protected]', html: '<div><p><table><tr><td>company</td><td>Acme</td></tr></table></p></div>', replyTo: '[email protected]', subject: 'Nowy brief', to: '[email protected]' }
|
||||||
|
const req = { locale: 'en', payload } as unknown as PayloadRequest
|
||||||
|
const [out] = await hook([email], { data: { form: 5, submissionData: stored }, req })
|
||||||
|
expect(payload.findByID).toHaveBeenCalledWith(expect.objectContaining({ id: 5, locale: 'en' }))
|
||||||
|
expect(out.html).toContain('Strony internetowe, IT')
|
||||||
|
expect(out.html).toContain('src="https://acme.pl/api/media/file/logo.png"')
|
||||||
|
expect(out.html).not.toContain('<td>company</td>')
|
||||||
|
|
||||||
|
payload.findByID.mockRejectedValueOnce(new Error('db down'))
|
||||||
|
expect(await hook([email], { data: { form: 5, submissionData: stored }, req })).toEqual([email])
|
||||||
|
expect(payload.logger.error).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('submitForm stores the submission in the page language (e-mail texts per language)', async () => {
|
||||||
|
const { create, payload } = fakePayload({ forms: { f: { fields: [{ name: 'company', blockType: 'text' }] } } })
|
||||||
|
await submitForm({ data: { company: 'Acme' }, formId: 'f', locale: 'en', maxPerMinute: 0, payload })
|
||||||
|
expect(create).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' }))
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -35,3 +35,29 @@ describe('package exports', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('client entry', () => {
|
||||||
|
// Wszystko, co importuje /client, trafia do bundla strony publicznej — panel (@payloadcms/ui) to ~235 KB gz
|
||||||
|
test('does not pull admin UI (@payloadcms/ui, @payloadcms/next) into the site bundle', () => {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const offenders: string[] = []
|
||||||
|
const resolve = (from: string, spec: string) => {
|
||||||
|
const base = path.resolve(path.dirname(from), spec).replace(/\.js$/, '')
|
||||||
|
return ['.ts', '.tsx', '/index.ts', '/index.tsx'].map((ext) => base + ext).find((f) => existsSync(f))
|
||||||
|
}
|
||||||
|
const walk = (file: string) => {
|
||||||
|
if (seen.has(file)) {return}
|
||||||
|
seen.add(file)
|
||||||
|
for (const m of readFileSync(file, 'utf8').matchAll(/(?:import|export)\s[^'"]*?from\s+['"](?<spec>[^'"]+)['"]/g)) {
|
||||||
|
const spec = m.groups!.spec
|
||||||
|
if (/^@payloadcms\/(?:ui|next)(?:\/|$)/.test(spec)) {offenders.push(`${path.relative(root, file)} → ${spec}`)}
|
||||||
|
if (spec.startsWith('.')) {
|
||||||
|
const next = resolve(file, spec)
|
||||||
|
if (next) {walk(next)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(path.join(root, 'src/exports/client.ts'))
|
||||||
|
expect(offenders).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { buildConfig, getPayload } from 'payload'
|
|||||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||||
|
|
||||||
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
|
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
|
||||||
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js'
|
import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConsentTexts.js'
|
||||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||||
@@ -304,6 +304,39 @@ describe('consent log', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('consent texts', () => {
|
||||||
|
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
|
||||||
|
|
||||||
|
test('optional banner copy is omitted when empty and passed through when set', async () => {
|
||||||
|
const empty = await getConsentTexts({ config, locale: 'pl', payload, privacyPolicy: false })
|
||||||
|
expect(empty.eyebrow).toBeUndefined()
|
||||||
|
expect(empty.title).toBeUndefined()
|
||||||
|
expect(empty.settingsDescription).toBeUndefined()
|
||||||
|
expect(empty.alwaysActiveLabel).toBeUndefined()
|
||||||
|
expect(empty.buttons.close).toBe('Close')
|
||||||
|
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: 'cookie-settings' as never,
|
||||||
|
data: {
|
||||||
|
alwaysActiveLabel: 'Zawsze aktywne',
|
||||||
|
buttons: { close: 'Zamknij' },
|
||||||
|
eyebrow: 'Prywatność i cookies',
|
||||||
|
settingsDescription: 'Możesz zmienić wybór w dowolnym momencie.',
|
||||||
|
title: 'Szanujemy Twoją prywatność',
|
||||||
|
} as never,
|
||||||
|
locale: 'pl' as never,
|
||||||
|
})
|
||||||
|
const texts = await getConsentTexts({ config, locale: 'pl', payload, privacyPolicy: false })
|
||||||
|
expect(texts).toMatchObject({
|
||||||
|
alwaysActiveLabel: 'Zawsze aktywne',
|
||||||
|
buttons: { close: 'Zamknij' },
|
||||||
|
eyebrow: 'Prywatność i cookies',
|
||||||
|
settingsDescription: 'Możesz zmienić wybór w dowolnym momencie.',
|
||||||
|
title: 'Szanujemy Twoją prywatność',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('cookie table', () => {
|
describe('cookie table', () => {
|
||||||
test('rows from Cookie Settings in the requested language', async () => {
|
test('rows from Cookie Settings in the requested language', async () => {
|
||||||
await payload.updateGlobal({
|
await payload.updateGlobal({
|
||||||
|
|||||||
Reference in New Issue
Block a user