Compare commits

...
10 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 23e033d7d7 1.11.0
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00
Radosław SmolińskiandClaude Opus 5.5 f809526f1d Page-filled form fields, links to entries, entry JSON-LD, R2-optional dev
Forms: `values` on RenderForm / BuilderForm / useBuilderForm fills fields the
page knows (chosen product variant, category) — read-only <output>, in the
SSR HTML, sent and validated like any field. prepareBuilderForm (/rsc) is the
server half of RenderForm for client components whose values change in the
browser; publicForm is exported so projects stop copying it.

Links: buildLinkField({ relationTo: ['pages', 'categories', …] }) — a
polymorphic relation; resolveLinkHref builds /{locale}/{archive}/{entry} from
`archives`, which getLinkOptions in createContentHelpers fills from Site
Settings.

SEO: pageJsonLd.entries — the main JSON-LD node per content collection
instead of BlogPosting; buildProductJsonLd emits an Offer only for a real
price from the panel.

Pages: createPageRoute / createNotFoundPage pass isFirst to blocks, so the
first section carries the page's only h1.

Fixes: ipalEnvRules({ storage: true }) requires R2_* in production only
(development: optional, all or none); buildImagesConfig allows the app's own
media on localhost outside production.

Docs, CHANGELOG, PROGRAMISTA §6 (34–37), ipal-form and ipal-upgrade skills.
Tests: builderForm, links, drafts (entries + archives), seo, media, env.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00
Radosław Smoliński 46d30d4ecd 1.10.1
CI / check (push) Canceled after 0s
2026-10-19 00:07:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 a6eda2e3a3 Pass siteDescription to page metadata; document media cache rule
createPageMetadata read Site Settings → siteDescription but never passed it to
buildMetadata, so pages without their own meta description had no
<meta name="description"> or og:description. Regression test in seo.test.ts.

storage.md: Cloudflare Cache Rule for the media domain (R2 objects carry no
Cache-Control; storage-s3 cannot set it, Cloudflare defaults to 4 h).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 00:07:28 +02:00
radoslaw.smolinski d28cbe2570 1.10.0
CI / check (push) Canceled after 0s
2026-10-17 03:20:12 +02:00
radoslaw.smolinskiandClaude Opus 5.5 2bd9d60822 Cookie banner layout options; keep admin UI out of /client
CookieBanner: order, settings="modal", controls="switch",
settingsActions, icon and a class slot for every element. Cookie
Settings gains eyebrow, title, settingsDescription, alwaysActiveLabel
and buttons.close.

MaskedField, TestEmailButton and IntegrationStatusBanner import
@payloadcms/ui and moved from /client to /admin; with sideEffects in
package.json the site bundle no longer ships ~235 KB gz of admin code.
A test walks the /client import graph to keep it that way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 03:20:11 +02:00
radoslaw.smolinski 0f6a43ad12 1.9.9
CI / check (push) Canceled after 0s
2026-10-17 01:29:01 +02:00
radoslaw.smolinskiandClaude Opus 5.5 14d71bcc3a Readable form emails (forms.emailLayout)
{{*:table}} renders a readable submission summary (questions, option labels,
grouped by step, empty fields skipped) inside an email template with logo,
accent colour and footer from Site Settings → Emails. submitForm stores the
submission in the page language, so emails follow the visitor's locale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 01:29:00 +02:00
radoslaw.smolinski 78e4e0f8e6 1.9.8
CI / check (push) Canceled after 0s
2026-10-16 22:15:57 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8f8b79d003 Under construction mode (developer tool)
Site Settings -> Under construction: a switch, 'Pages still available' and
notice texts. When on, only the homepage and the chosen pages open (every
language); other addresses redirect to the homepage with the notice
(createPageRoute redirect option), and <ConstructionNotice> cancels clicks
on links to blocked pages and shows the notice. getConstructionMode(locale).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:15:57 +02:00
61 changed files with 1819 additions and 157 deletions
+89
View File
@@ -8,6 +8,95 @@ 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
dopiero powyżej 20.
## 1.11.0
### Nowe
- **Pola formularza wypełniane przez stronę** — `values` w `RenderForm`, `BuilderForm` i `useBuilderForm`
(`{ subject: 'Pierścionek · białe złoto · 0,70 ct' }`): pole tylko do odczytu (`classNames.fixed`), w SSR,
wysyłane i walidowane jak każde inne. `prepareBuilderForm` (`/rsc`) — serwerowa połowa `RenderForm` dla
komponentu klienckiego ze zmiennymi wartościami (konfigurator); `publicForm` eksportowany. Koniec kopii `publicForm` w projektach.
- **Linki do wpisów kolekcji** — `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })`;
`resolveLinkHref` / `resolveLink` / `resolveNav` budują `/{locale}/{archiwum}/{wpis}`, `getLinkOptions` podaje archiwa z Site Settings.
- **JSON-LD wpisów, które nie są artykułami** — `pageJsonLd.entries` (węzeł per kolekcja) i `buildProductJsonLd`
(`Offer` tylko z prawdziwą ceną).
- **`isFirst`** dla bloków z `createPageRoute` / `createNotFoundPage` — pierwsza sekcja niesie jedyny `h1`.
### Poprawki
- `ipalEnvRules({ storage: true })`: `R2_*` wymagane na produkcji; w dev opcjonalne (media na dysku), ale wszystkie albo żadne.
Wcześniej dev bez R2 nie startował, więc projekty warunkowały `storage` same.
- `buildImagesConfig()`: poza produkcją dopuszcza media serwowane przez aplikację (`/api/media/file/**` na
`NEXT_PUBLIC_SERVER_URL`) i localhost (`dangerouslyAllowLocalIP`) — bez R2 obrazy w dev nie dawały 500.
### Wymaga zmian w projekcie
- Usuń obejścia z PROGRAMISTA §6 poz. 34–37 (kopie `publicForm`, ręczne remotePatterns dla localhost,
warunkowe `storage`, własny graf JSON-LD wpisów).
- Zmiana `relationTo` linku na tablicę zmienia kształt danych istniejących linków — migracja (ipal-migrate-fields).
## 1.10.1
### Poprawki
- **Zapasowy metaopis działa.** `createPageMetadata` (a więc `createPageRoute` / `generatePageMetadata`) czytał
Site Settings → `siteDescription`, ale nie przekazywał go do `buildMetadata` — strona bez własnego
`meta.description` nie miała `<meta name="description">` ani `og:description` (Lighthouse SEO: „Dokument nie
ma metaopisu”). Test regresyjny w `test/seo.test.ts`.
### Dokumentacja
- storage.md → „Pamięć podręczna mediów”: reguła Cache Rules w Cloudflare dla domeny mediów (1 rok). Pliki w R2
nie mają `Cache-Control` (adapter S3 nie pozwala go ustawić), a Cloudflare daje domyślnie 4 h.
### Wymaga zmian w projekcie
- Obejście metaopisu w projekcie (własne uzupełnianie `description` w `generateMetadata`) można usunąć —
wystarczy `export const generateMetadata = route.generateMetadata`.
- Cloudflare: dodaj regułę Cache Rules dla domeny mediów (storage.md).
## 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
+1
View File
@@ -16,6 +16,7 @@ Szczegóły API — jeden plik na moduł:
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.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) |
| Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) |
+3
View File
@@ -780,6 +780,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md |
| Link do kategorii / produktu / wpisu | `buildLinkField({ relationTo: ['pages', 'categories'] })` — adres z archiwum | links.md |
| Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md |
| Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md |
| Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md |
@@ -804,6 +805,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
| Formularz z panelu w bloku (kroki, radio, listy, daty) | `<RenderForm form action locale texts classNames>` (`/rsc`) | forms.md |
| Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md |
| Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| Pole wypełniane przez stronę (wariant produktu, kategoria) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md |
| Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.md |
| Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md |
@@ -817,6 +819,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
| Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md |
| sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md |
| JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `<JsonLdGraph>` | seo.md |
| JSON-LD produktu / kategorii (wpis, który nie jest artykułem) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md |
| llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md |
| IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Wyszukiwarka | `createSearchRoute` | content.md |
+3
View File
@@ -68,6 +68,9 @@ własny typ pola, suwak): nie kopiuj silnika — w kolejności:
2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`.
**Pole wypełniane przez stronę** (wybrany wariant produktu, kategoria, oferta): w panelu zwykłe pole tekstowe
(np. `subject`), w kodzie `RenderForm values={{ subject }}`; wartość zmieniana w przeglądarce →
`prepareBuilderForm` (serwer) + `<BuilderForm values>` (klient). Nigdy kopia `publicForm` w projekcie (forms.md).
Własny typ pola w panelu: `forms.fields: { mojTyp: { slug, fields } }` (blok form-buildera)
+ `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**.
+5
View File
@@ -38,6 +38,11 @@ własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) →
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
(nowe typy pól formularza i teksty w Notifications).
**→ 1.11.0 (PROGRAMISTA §6, poz. 34–37):** usuń obejścia — kopię `publicForm` (→ `RenderForm values` /
`prepareBuilderForm`), ręczne `remotePatterns`/`dangerouslyAllowLocalIP` (→ `buildImagesConfig()`), warunkowe
`storage` w `ipalEnvRules`, własny graf JSON-LD produktów (→ `pageJsonLd.entries` + `buildProductJsonLd`),
własny RenderBlocks dla `h1` (→ `isFirst`). Linki do wpisów: `buildLinkField({ relationTo: [...] })` z migracją danych.
## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
+44 -4
View File
@@ -168,15 +168,55 @@ zmienna po zmiennej. Na większe zmiany są `classNames`:
<CookieButton className="fixed bottom-6 right-6 ..." />
```
Sloty: `root`, `primaryButton`, `secondaryButton`. Podany className zastępuje
domyślny (nie dokleja się).
Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swój slot (1.10.0):
| 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
`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 →
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)
+50
View File
@@ -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`).
+4
View File
@@ -545,6 +545,10 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 30 | **1.9.2** — layout składany ręcznie (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `<SiteProviders shell={await getSiteShell(locale)} …>` — te same opcje (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 |
| 31 | **1.9.2** — strona catch-all i `not-found.tsx` pisane ręcznie | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` z `/rsc`; `revalidate` zostaje literałem | pages.md |
| 32 | **1.9.2** — trasy llms/md/mcp/health/indexnow/manifest z konfiguracją w każdym pliku | re-eksport z `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` raz w `createContentHelpers` | PROGRAMISTA §2.7 |
| 34 | **1.11.0** — kopia `publicForm`, własny renderer pola z wariantem / kontekstem | `RenderForm values` albo `prepareBuilderForm` + `<BuilderForm values>`; usuń kopię | forms.md |
| 35 | **1.11.0** — dodatkowe relacje „kategorie” obok linków, linki do wpisów jako URL | `buildLinkField({ relationTo: ['pages', 'categories'] })` (migracja danych linków) | links.md |
| 36 | **1.11.0** — JSON-LD produktu / kategorii składany w projekcie, `jsonLd: false` | `pageJsonLd.entries` + `buildProductJsonLd`, z powrotem `jsonLd` w `createPageRoute` | seo.md |
| 37 | **1.11.0** — własny RenderBlocks w trasie strony tylko dla `h1` pierwszej sekcji; `storage` w `ipalEnvRules` warunkowany NODE_ENV; ręczne `remotePatterns` / `dangerouslyAllowLocalIP` dla localhost | `isFirst` z `createPageRoute`; `ipalEnvRules({ storage: true })`; `buildImagesConfig()` | pages.md, env.md, storage.md |
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, ręczne `resolveLinkHref` w `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (ten sam kształt danych — bez migracji), `resolveNav`, `resolveLink` z `lib/content` | blocks.md, links.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
+1 -1
View File
@@ -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).
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
`payload generate:importmap`, żeby panel rozpoznał komponent.
+1
View File
@@ -49,6 +49,7 @@ używasz).
```ts
ipalEnvRules({
storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL)
// produkcja: wymagane; dev: opcjonalne (media na dysku), ale wszystkie albo żadne (1.11.0)
emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER)
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string },
serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL'
+44 -1
View File
@@ -117,6 +117,32 @@ po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `fiel
- Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy →
po aktualizacji wygeneruj migrację (`payload migrate:create`).
### Wartości pól ze strony (`values`, 1.11.0)
Strona zna wartość pola, której nie wpisuje odwiedzający — wybrany wariant produktu, kategorię, ofertę.
Redaktor dodaje w formularzu zwykłe pole tekstowe (np. `subject`, „Dotyczy”), a strona je wypełnia:
```tsx
// wartość znana na serwerze (kategoria „wkrótce”)
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} values={{ subject: category.title }} />
```
Pole z `values` jest pokazane tylko do odczytu (`<output>`, klasa `classNames.fixed`, `data-ipal="form-fixed"`),
wysyłane jak każde inne i walidowane przez serwer według definicji z panelu. Nazwy spoza formularza są pomijane.
Wartość jest w pierwszym HTML (SSR), nie dopiero po hydracji.
Wartość zmieniana w przeglądarce (konfigurator): serwer przygotowuje formularz `prepareBuilderForm` (`/rsc`) —
publiczną część (`publicForm`, bez zakładki Emails), wyrenderowane bloki message i potwierdzenie, akcję przypiętą
do formularza i języka, cel przekierowania — a komponent kliencki renderuje `BuilderForm` z aktualnym `values`:
```tsx
// serwer
const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale })
<Configurator form={form} texts={formTexts} />
// klient ('use client')
<BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
```
`publicForm(form)` (`/rsc`) — sama publiczna część dokumentu, gdy budujesz własny przekaz do klienta. Nigdy nie
przekazuj do przeglądarki surowego dokumentu formularza.
### Formularz nietypowy — bez kopiowania silnika
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
@@ -208,7 +234,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
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
+9
View File
@@ -55,6 +55,15 @@ Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`,
Plik do pobrania to link typu `file` — **nie** osobne pole `pdfUrl`.
## Linki do wpisów kolekcji (1.11.0)
Strona, kategoria, produkt — jedno pole: `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })`
(polimorficzna relacja; jedna kolekcja = jak dotąd). Wpis kolekcji z `content` rozwiązuje się do
`/{locale}/{strona-archiwum}/{wpis}` — `resolveLink` / `resolveNav` / `getLinkOptions` z `lib/content`
same biorą archiwa z Site Settings (`archives: { categories: 'kategorie' }`). Bez lib/content:
`resolveLinkHref(link, { config, locale, archives, pagesSlug })`. Wpis bez przypisanego archiwum → `null`
(link się nie renderuje). Zmiana `relationTo` na tablicę zmienia kształt danych (`page` → `{ relationTo, value }`):
istniejące linki trzeba przenieść (ipal-migrate-fields).
## href
```ts
+4
View File
@@ -77,9 +77,13 @@ export default createNotFoundPage(content, {
```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`).
Każdy blok strony dostaje `locale`, wynik `blockProps` i **`isFirst`** (1.11.0) — `true` dla pierwszej sekcji:
jej nagłówek jest jedynym `h1` strony (`<SectionHeader as={isFirst ? 'h1' : 'h2'}>`), pozostałe dają `h2`.
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
(`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):
+12
View File
@@ -1177,6 +1177,18 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
WebPage / CollectionPage / BlogPosting (język, `dateModified`, obraz), BreadcrumbList z prawdziwej
trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`:
`<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />`.
- **Wpisy, które nie są artykułami** (1.11.0): `pageJsonLd.entries` — główny węzeł per kolekcja zamiast
`BlogPosting`; okruszki i FAQ zostają z pluginu. Kontekst: `{ doc, url, image, description, siteName, archive, locale }`.
```ts
createContentHelpers({ pageJsonLd: { entries: {
products: ({ doc, url, image, siteName }) => buildProductJsonLd({ name: String(doc.title), sku: String(doc.sku), url, image, brand: siteName,
price: doc.price?.amount ? { amount: doc.price.amount, currency: doc.price.currency, kind: 'from' } : null }),
categories: ({ doc, url, description }) => buildWebPageJsonLd({ type: 'CollectionPage', name: String(doc.title), url, description }),
} } })
```
**`buildProductJsonLd({ name, url, sku, description, image, category, brand, price, availability })`** — Product;
`Offer` tylko z prawdziwą ceną z panelu (`kind: 'exact'` → `price`, `'from'` → `minPrice`); produkt „na zapytanie”
(bez ceny) nie dostaje `Offer` — szacowana cena w danych strukturalnych wprowadza w błąd.
- **`buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config, homeSlug })`** — nawigacja z
globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala:
`getLink` / `getChildren`.
+25 -1
View File
@@ -132,6 +132,27 @@ ustawiona). Bez niej Payload zwróci URL wskazujący na prywatny endpoint S3 →
Bez tego media wgrają się do R2, ale front pokaże 403. Konfiguracja domeny jest
po stronie Cloudflare, publiczny URL po stronie projektu (.env).
### Pamięć podręczna mediów (Cache Rule — obowiązkowo)
Pliki w R2 nie mają nagłówka `Cache-Control`: `@payloadcms/storage-s3` przy wysyłce ustawia tylko
`ContentType` i `ACL`, bez opcji na nagłówki. Cloudflare daje wtedy przeglądarce domyślne **4 h** —
Lighthouse: „Używaj efektywnego czasu przechowywania w pamięci podręcznej” (wideo, logo, tła pobierane od
nowa przy każdej wizycie po 4 h). Nazwy plików są stałe (nowa wersja = nowy plik z `normalizeFilename`),
więc długi czas jest bezpieczny.
Cloudflare → strefa domeny → **Caching → Cache Rules → Create rule**:
- *When incoming requests match*: `Hostname` equals `media.klient.pl` (domena z `R2_PUBLIC_URL`);
- *Cache eligibility*: Eligible for cache;
- *Edge TTL*: Ignore cache-control header and use this TTL → **1 year**;
- *Browser TTL*: Override origin and use this TTL → **1 year**.
Sprawdzenie (po kilku minutach):
```bash
curl -sI https://media.klient.pl/<plik> | grep -iE 'cache-control|cf-cache-status'
# cache-control: max-age=31536000 cf-cache-status: HIT (przy drugim zapytaniu)
```
Podmiana pliku pod TĄ SAMĄ nazwą (rzadkie — panel nadaje nową) wymaga Caching → Purge → Custom (URL).
## Migracja istniejących mediów
Jeśli projekt miał media lokalnie i przełączasz na R2 — nowe uploady idą do R2,
@@ -318,6 +339,9 @@ env, komponent podąża automatycznie.
- `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`.
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
uploadzie przez `sharp` z configu. Postgres: `migrate:create`.
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`).
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`). Poza produkcją
(1.11.0) także media serwowane przez aplikację — `/api/media/file/**` na `NEXT_PUBLIC_SERVER_URL` (dysk lokalny,
bez R2) — i `dangerouslyAllowLocalIP` dla localhost (Next 16 inaczej odrzuca prywatne IP). Opcje: `serverUrl`,
`production`, `publicUrl`, `extraHosts`.
- `<YouTubeEmbed videoId title playLabel note poster>` z `/client` — iframe po kliknięciu.
- `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów).
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.9.7",
"version": "1.11.0",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -57,6 +57,9 @@
"docs",
"bin"
],
"sideEffects": [
"**/*.css"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
+7 -4
View File
@@ -1,10 +1,13 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
* Admin-panel UI components (white-label branding, array row labels, integration fields and
* banners). Separate export so Payload's importMap can resolve them by a stable path, and so
* 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 { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
+4 -4
View File
@@ -1,6 +1,4 @@
'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 type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
@@ -23,7 +21,10 @@ export {
useConsent,
useConsentContext,
} 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 type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
@@ -74,7 +75,6 @@ export {
useSetAlternateLinks,
} 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 { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { Turnstile } from '../modules/turnstile/client.js'
+2 -2
View File
@@ -14,8 +14,8 @@ export type {
} from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderForm } from '../modules/forms/RenderForm.js'
export type { RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js'
export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js'
+38
View File
@@ -22,6 +22,22 @@ export const cookieSettingsFields: Field[] = [
min: 1,
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',
type: 'textarea',
@@ -38,6 +54,22 @@ export const cookieSettingsFields: Field[] = [
},
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',
type: 'text',
@@ -59,6 +91,12 @@ export const cookieSettingsFields: Field[] = [
{ name: 'settings', type: 'text', localized: true },
{ name: 'save', 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,
},
],
},
{
+2 -2
View File
@@ -64,7 +64,7 @@ export const smtpFields: Field[] = [
description: 'SMTP account password.',
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
components: {
Field: '@intecion/ipal-kit/client#MaskedField',
Field: '@intecion/ipal-kit/admin#MaskedField',
},
},
},
@@ -87,7 +87,7 @@ export const smtpFields: Field[] = [
type: 'ui',
admin: {
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.',
// Masked in the UI (••••) — stored plaintext, readable for verification.
components: {
Field: '@intecion/ipal-kit/client#MaskedField',
Field: '@intecion/ipal-kit/admin#MaskedField',
},
},
},
+8
View File
@@ -6,6 +6,10 @@ import { themeFields } from './fields/theme.js'
type BuildSiteSettingsArgs = {
/** Extra fields injected by the client project */
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,
* privacy policy, collection archives). Assembled by the caller, which is the
@@ -30,6 +34,8 @@ type BuildSiteSettingsArgs = {
*/
export function buildSiteSettings({
additionalFields,
constructionFields,
emailFields,
systemPageFields,
}: BuildSiteSettingsArgs = {}): GlobalConfig {
return {
@@ -55,6 +61,8 @@ export function buildSiteSettings({
...(systemPageFields?.length
? [{ fields: systemPageFields, label: 'System Pages' }]
: []),
...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []),
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
],
},
+5 -2
View File
@@ -42,6 +42,9 @@ export {
updateConsent,
} 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 {
archiveFieldName,
@@ -105,7 +108,7 @@ export {
required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { ContentHelpers, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
@@ -215,7 +218,7 @@ export { buildSummaryField } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
+273 -80
View File
@@ -1,19 +1,76 @@
'use client'
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 { useConsentContext } from './ConsentContext.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
* 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 = {
/** 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
/** Button "Reject" — falls back to primaryButton with equalChoice, else secondaryButton. */
rejectButton?: string
root?: string
/** Settings view: button "Save preferences" — falls back to primaryButton. */
saveButton?: 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
* 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 border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
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 = {
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)]`,
const defaults: Required<CookieBannerClassNames> = {
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}`,
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)]`,
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)]'
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)]'
/** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
const SWITCH_TRACK =
'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)]'
type CookieBannerProps = {
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,
* EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true.
*/
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 { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
const closeRef = useRef<HTMLButtonElement>(null)
const modal = settings === 'modal'
useEffect(() => {
setChoices(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
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now.
if (!isMounted) {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) => {
if (cat === 'necessary') {return}
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
}
const rootClass = classNames?.root ?? defaults.root
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton
const control = (cat: ConsentCategory) => {
const checked = cat === 'necessary' ? true : choices[cat]
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 (
<div aria-label={texts.settingsTitle} className={rootClass} data-ipal="banner" role="dialog">
<div className="mx-auto max-w-4xl">
{!showSettings ? (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-start gap-3">
<Cookie aria-hidden="true" className={`h-6 w-6 shrink-0 ${accent}`} />
<p className={`text-justify text-sm ${bodyText}`}>
{texts.message}
{texts.privacyLink && (
<>
{' '}
<a
className={`${accent} underline hover:no-underline`}
href={texts.privacyLink.href}
>
{texts.privacyLink.label}
</a>
</>
)}
const settingsView = (
<div className="flex flex-col gap-4">
<div className="flex items-start justify-between gap-4">
<h2 className={cn('settingsTitle')} id="ipal-consent-title">
{icon && !modal && <Cookie aria-hidden="true" className={cn('icon')} />}
{texts.settingsTitle}
</h2>
{modal && (
<button aria-label={texts.buttons.close} className={cn('closeButton')} data-ipal="close" onClick={() => setShowSettings(false)} ref={closeRef} type="button">
<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>
</button>
)}
</div>
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
<ul className={cn('categories')}>
{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>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings}
</button>
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject}
</button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
{texts.buttons.acceptAll}
</button>
{control(cat)}
</li>
))}
</ul>
<div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
</div>
)
if (modal && showSettings) {
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 className={cn('actions')}>{order.map(button)}</div>
</div>
) : (
<div className="flex flex-col gap-4">
<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>
settingsView
)}
</div>
</div>
+1 -1
View File
@@ -2,7 +2,7 @@
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.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'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
+11
View File
@@ -13,6 +13,7 @@ const FALLBACK: ConsentTexts = {
buttons: {
acceptAll: 'Accept all',
back: 'Back',
close: 'Close',
reject: 'Reject',
save: 'Save preferences',
settings: 'Settings',
@@ -37,13 +38,17 @@ const FALLBACK: ConsentTexts = {
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = {
alwaysActiveLabel?: null | string
buttons?: null | Partial<ConsentTexts['buttons']>
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
eyebrow?: null | string
message?: null | string
policyVersion?: null | number
privacyLinkLabel?: null | string
settingsDescription?: null | string
settingsTitle?: null | string
title?: null | string
}
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
@@ -135,6 +140,7 @@ export async function getConsentTexts({
buttons: {
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
back: g.buttons?.back || FALLBACK.buttons.back,
close: g.buttons?.close || FALLBACK.buttons.close,
reject: g.buttons?.reject || FALLBACK.buttons.reject,
save: g.buttons?.save || FALLBACK.buttons.save,
settings: g.buttons?.settings || FALLBACK.buttons.settings,
@@ -143,6 +149,11 @@ export async function getConsentTexts({
message: g.message || FALLBACK.message,
privacyLink,
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) } : {}),
}
}
+10
View File
@@ -1,18 +1,28 @@
import type { ConsentCategory } from './categories.js'
export type ConsentTexts = {
/** Badge next to the necessary category (e.g. "Always active"). Empty = no badge. */
alwaysActiveLabel?: string
buttons: {
acceptAll: string
back: string
/** Accessible label of the ✕ button closing the settings dialog. */
close: string
reject: string
save: string
settings: 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
/** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null
/** Intro under the settings title. Empty = not shown. */
settingsDescription?: 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. */
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>
)
}
+44
View File
@@ -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,
},
]
}
+17
View File
@@ -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}`
+17
View File
@@ -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'
+14 -5
View File
@@ -16,7 +16,12 @@ export type IpalEnvFeatures = {
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
serverUrlVar?: string
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
/**
* R2 object storage (buildR2Storage). Adds the R2_* vars — required in
* production (media on a container disk vanish on redeploy). Outside
* production they're optional (media go to the local disk), but a partial
* set is an error: buildR2Storage needs all of them.
*/
storage?: boolean
/**
* Cloudflare Turnstile. true uses the common var names
@@ -69,14 +74,18 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
]
if (storage) {
const r2Vars = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT', 'R2_PUBLIC_URL']
// Production: always. Development: only once any R2_* is set (all or nothing).
const r2Required = process.env.NODE_ENV === 'production' || r2Vars.some((name) => Boolean(process.env[name]))
rules.push(
{ name: 'R2_BUCKET', description: 'R2 bucket name' },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },
{ name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
{
name: 'R2_PUBLIC_URL',
description: 'Public base URL media is served from (custom domain of the bucket)',
required: r2Required,
// Production: absolute URL (https://media.example.com). Outside production a
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
+16 -1
View File
@@ -18,7 +18,7 @@ import { useBuilderForm } from './useBuilderForm.js'
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
@@ -51,6 +51,9 @@ export type BuilderFormProps = {
turnstileTheme?: 'auto' | 'dark' | 'light'
} & UseBuilderFormOptions
/** A page-supplied value (always a string from `values`) as text. */
const fixedText = (value: unknown) => (typeof value === 'string' ? value : '')
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/**
@@ -108,6 +111,18 @@ export function BuilderForm({
const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
if (f.isFixed(field)) {
// Filled by the page (`values`): visible, not editable, sent with the form.
const id = f.fieldId(field)
return (
<>
<span className={cn.label} id={`${id}-label`}>{field.label}</span>
<output aria-labelledby={`${id}-label`} className={cn.fixed} data-ipal="form-fixed" id={id}>
{fixedText(f.values[field.name ?? ''])}
</output>
</>
)
}
switch (field.blockType) {
case 'checkbox': {
const props = f.getInputProps(field)
+68 -17
View File
@@ -38,11 +38,13 @@ export type RenderFormProps = {
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light'
/** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */
values?: Record<string, string>
}
/** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return {
id: form.id,
analytics: form.analytics,
@@ -54,27 +56,42 @@ function publicForm(form: BuilderFormDoc): BuilderFormDoc {
}
}
export type PrepareBuilderFormArgs = Pick<
RenderFormProps,
'action' | 'converters' | 'form' | 'linkOptions' | 'locale' | 'richTextClassName'
>
/** What the browser gets for a panel form — spread it into <BuilderForm> (plus texts, classNames, values). */
export type PreparedBuilderForm = {
action: (values: Record<string, unknown>, turnstileToken?: string) => Promise<SubmitActionResult>
confirmation: ReactNode
form: BuilderFormDoc
messages: Record<number, ReactNode>
redirectHref: null | string
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
* The server half of RenderForm without the markup: the public part of the form,
* rendered message blocks and confirmation, the action bound to form + locale,
* the redirect target. For a client component that renders <BuilderForm> itself —
* e.g. with `values` that change in the browser (a product configurator):
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
* // server
* const prepared = prepareBuilderForm({ form, action: sendForm, locale })
* <ProductConfigurator form={prepared} texts={formTexts} />
* // client
* <BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
* Returns null for an unpopulated form (an id or nothing).
*/
export function RenderForm({
export function prepareBuilderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
}: RenderFormProps) {
}: PrepareBuilderFormArgs): null | PreparedBuilderForm {
if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) =>
@@ -93,17 +110,51 @@ export function RenderForm({
: safeHref(form.redirect?.url)
: null
return {
action: action.bind(null, String(form.id), locale),
confirmation: rich(form.confirmationMessage),
form: publicForm(form),
messages,
redirectHref,
}
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
*
* `values` fill fields the page already knows (`{ subject: 'Brooches' }`): shown
* read-only and sent with the submission. Values that change in the browser:
* prepareBuilderForm + <BuilderForm values>.
*/
export function RenderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
values,
}: RenderFormProps) {
const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName })
if (!prepared) {return null}
return (
<BuilderForm
action={action.bind(null, String(form.id), locale)}
{...prepared}
classNames={classNames}
confirmation={rich(form.confirmationMessage)}
form={publicForm(form)}
messages={messages}
redirectHref={redirectHref}
requiredMark={requiredMark}
texts={texts}
turnstileTheme={turnstileTheme}
values={values}
/>
)
}
+1
View File
@@ -75,6 +75,7 @@ export function createSubmitAction({
data: fields,
formId: String(formId),
ip,
locale,
maxPerMinute,
payload,
turnstileOnConfigError,
+188
View File
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
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
}
}
}
+11
View File
@@ -1,3 +1,4 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { Block, Field, Plugin } from 'payload'
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
@@ -6,6 +7,7 @@ import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
@@ -56,7 +58,16 @@ function hideEmails(fields: Field[]): Field[] {
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.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({
...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
+4
View File
@@ -19,6 +19,8 @@ export type SubmitFormArgs = {
formId: string
/** Client IP — used for Turnstile and rate limiting. */
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.
* Set to 0 to disable (e.g. when a real limiter sits in front).
@@ -96,6 +98,7 @@ export async function submitForm({
data,
formId,
ip,
locale,
maxPerMinute = 5,
payload,
turnstileOnConfigError = 'allow',
@@ -143,6 +146,7 @@ export async function submitForm({
try {
const submission = await payload.create({
collection: 'form-submissions',
...(locale ? { locale: locale as never } : {}),
data: {
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
+12
View File
@@ -1,3 +1,4 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { CollectionConfig, Field } from 'payload'
/**
@@ -25,12 +26,23 @@ export type FormsOption = {
* formOverrides / formSubmissionOverrides still wins.
*/
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
* with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'.
*/
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. */
fields?: {
checkbox?: boolean
+26 -3
View File
@@ -23,6 +23,12 @@ export type UseBuilderFormOptions = {
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string
texts: BuilderFormTexts
/**
* Fields the page fills, by name (e.g. `{ subject: 'Ring · white gold · 0.70 ct' }`):
* kept in sync when the prop changes, read-only in BuilderForm, sent like any
* field. Names not in the form are ignored (the server rejects unknown fields).
*/
values?: Record<string, string>
}
/**
@@ -40,7 +46,7 @@ export type UseBuilderFormOptions = {
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
@@ -65,7 +71,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
const f = useForm<Record<string, unknown>>({
errorFallback: texts.error,
initialValues: initialBuilderValues(fields),
// Page values are in the first render too — server HTML shows them before hydration.
initialValues: {
...initialBuilderValues(fields),
...Object.fromEntries(Object.entries(pageValues ?? {}).filter(([name]) => fields.some((field) => field.name === name))),
},
onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values)
@@ -78,7 +88,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
submitAction,
validate,
})
const { setErrors, setTurnstileToken } = f
const { setErrors, setField, setTurnstileToken } = f
// Page-supplied values follow the prop (a configurator changes them in the browser).
const fixedNames = useMemo(
() => new Set(Object.keys(pageValues ?? {}).filter((name) => fields.some((field) => field.name === name))),
[pageValues, fields],
)
const fixedKey = JSON.stringify(pageValues ?? {})
useEffect(() => {
for (const name of fixedNames) {setField(name, pageValues?.[name] ?? '')}
}, [fixedKey, fixedNames, setField])
/** True for a field whose value comes from the page (`values`) — show it, don't let the visitor edit it. */
const isFixed = useCallback((field: BuilderField) => Boolean(field.name && fixedNames.has(field.name)), [fixedNames])
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
const steps = useMemo(() => {
const shown = new Set(visibleFields(fields, f.values))
@@ -258,6 +280,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
getTextareaProps,
goTo,
isFirst,
isFixed,
isLast,
next,
/** Message the server returned on success (Notifications → success). */
+79 -3
View File
@@ -5,6 +5,7 @@ import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.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 { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
@@ -18,6 +19,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { archiveFieldName } from '../content/types.js'
import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
import { createMcpRoute } from '../mcp/createMcpRoute.js'
@@ -93,9 +95,30 @@ type CreateContentHelpersArgs = {
summaryField?: string
}
/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */
export type EntryJsonLdContext = {
/** Archive page of the entry (title, slug). */
archive: Record<string, unknown>
/** Meta description (SEO tab or the site's description). */
description?: string
doc: Record<string, unknown>
/** Absolute share-image URL. */
image?: string
locale: string
siteName?: string
/** Absolute canonical URL of the entry. */
url: string
}
export type PageJsonLdOptions = {
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
breadcrumbs?: boolean
/**
* The main node per content collection, instead of the article (`entryType`):
* `{ products: (ctx) => buildProductJsonLd({…}), categories: (ctx) => buildWebPageJsonLd({ type: 'CollectionPage', … }) }`.
* Return null to emit no main node. Breadcrumbs and FAQ still follow.
*/
entries?: Record<string, (ctx: EntryJsonLdContext) => null | Record<string, unknown>>
/** schema.org type of archive entries. Default 'BlogPosting'. */
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
/**
@@ -269,7 +292,10 @@ export function createContentHelpers({
const image = meta.openGraph?.images?.[0]?.url
const nodes: (null | Record<string, unknown>)[] = []
if (route.type === 'entry') {
const entryNode = route.type === 'entry' ? opts.entries?.[route.collection] : undefined
if (route.type === 'entry' && entryNode) {
nodes.push(entryNode({ archive: route.archive, description: meta.description, doc, image, locale, siteName, url }))
} else if (route.type === 'entry') {
nodes.push(
buildArticleJsonLd({
type: opts.entryType ?? 'BlogPosting',
@@ -571,8 +597,23 @@ export function createContentHelpers({
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
const homeSlug = await getHomeSlug(locale)
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
const settings = await getSettings(locale)
const homeSlug = homeSlugFrom(settings)
// Archive page per content collection → links to entries (categories, products…) resolve too.
const archives = Object.fromEntries(
(content?.collections ?? []).flatMap(({ slug }) => {
const archive = (settings as Record<string, unknown>)[archiveFieldName(slug)]
const archiveSlug = archive && typeof archive === 'object' ? (archive as { slug?: unknown }).slug : undefined
return typeof archiveSlug === 'string' && archiveSlug ? [[slug, archiveSlug]] : []
}),
)
return {
config: needI18n('getLinkOptions'),
locale,
pagesSlug,
...(homeSlug ? { homeSlug } : {}),
...(Object.keys(archives).length ? { archives } : {}),
}
}
/**
@@ -604,6 +645,40 @@ export function createContentHelpers({
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 ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -682,6 +757,7 @@ export function createContentHelpers({
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
getConstructionMode,
getEntries,
getFormTexts,
getHomeSlug,
+22 -5
View File
@@ -5,10 +5,11 @@ import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Pick<
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
@@ -16,7 +17,11 @@ type Helpers = Pick<
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
export type PageRouteOptions = {
/** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */
/**
* Props for every block on top of `locale` and `isFirst` (true for the first
* section — its heading is the page's only h1), computed once per page —
* e.g. `{ formTexts, sendForm }` for form blocks.
*/
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
/** blockType → component (the project's registry). */
blocks: BlockComponentMap
@@ -28,6 +33,11 @@ export type PageRouteOptions = {
notFound: () => never
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
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.
* Return undefined to keep the default (the document's blocks).
@@ -57,7 +67,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
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 l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
@@ -73,6 +83,13 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { slug, locale: param } = await params
const locale = localeOf(param)
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)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
@@ -84,7 +101,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
<RenderBlocks
blocks={doc[layoutField] as BlockData[] | undefined}
components={blocks}
enhanceProps={() => ({ locale, ...extra })}
enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })}
/>
)
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
@@ -129,7 +146,7 @@ export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOption
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
if (!doc || !layout?.length) {return [locale, fb] as const}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const
}),
),
)
+1 -1
View File
@@ -54,7 +54,7 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
components: {
Field: {
clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
},
},
},
+6 -8
View File
@@ -20,7 +20,7 @@ export type BuildLinkFieldOptions = {
/** Field name. Default 'link'. */
name?: string
/** Collection the "Page" option points at. Default 'pages'. */
relationTo?: string
relationTo?: readonly string[] | string
required?: boolean
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
uploadTo?: string
@@ -50,6 +50,7 @@ export function buildLinkField({
required = false,
uploadTo = 'media',
}: BuildLinkFieldOptions = {}): GroupField {
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
const fields: Field[] = [
{
type: 'row',
@@ -73,13 +74,10 @@ export function buildLinkField({
},
],
},
{
name: 'page',
type: 'relationship',
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },
relationTo,
required,
},
// One collection → plain relation; several (pages + content entries) → polymorphic.
typeof relationTo === 'string'
? { name: 'page', type: 'relationship', admin: pageAdmin, relationTo, required }
: { name: 'page', type: 'relationship', admin: pageAdmin, relationTo: [...relationTo], required },
{
name: 'url',
type: 'text',
+22 -3
View File
@@ -1,5 +1,6 @@
import type { I18nConfig } from '../i18n/index.js'
import { buildEntryPath } from '../content/paths.js'
import { buildLocalizedPath } from '../i18n/index.js'
/**
@@ -32,6 +33,12 @@ export type LinkValue = {
}
export type ResolveLinkHrefOptions = {
/**
* Archive page slug per content collection in this locale (`{ categories: 'kategorie' }`) —
* links to entries (buildLinkField({ relationTo: ['pages', 'categories'] })) become
* /{locale}/{archive}/{entry}. getLinkOptions in lib/content fills it from Site Settings.
*/
archives?: Record<string, string>
config: I18nConfig
/**
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
@@ -39,6 +46,8 @@ export type ResolveLinkHrefOptions = {
*/
homeSlug?: Record<string, string> | string
locale: string
/** The pages collection — links to it are page paths, other collections are entries. Default 'pages'. */
pagesSlug?: string
}
/**
@@ -54,7 +63,7 @@ export type ResolveLinkHrefOptions = {
*/
export function resolveLinkHref(
link: LinkValue | null | undefined,
{ config, homeSlug, locale }: ResolveLinkHrefOptions,
{ archives, config, homeSlug, locale, pagesSlug = 'pages' }: ResolveLinkHrefOptions,
): null | string {
if (!link) {return null}
@@ -69,12 +78,22 @@ export function resolveLinkHref(
return null
}
// internal (default)
const page = link.page
// internal (default) — a page, or (polymorphic relation) an entry of a content collection
let page = link.page
let collection = pagesSlug
if (page && typeof page === 'object' && 'relationTo' in page && 'value' in page) {
collection = String((page as { relationTo: unknown }).relationTo)
page = (page as { value: unknown }).value
}
if (!page || typeof page !== 'object') {return null}
const slug = (page as { slug?: unknown }).slug
if (typeof slug !== 'string' || !slug) {return null}
if (collection !== pagesSlug) {
const archiveSlug = archives?.[collection]
return archiveSlug ? buildEntryPath({ archiveSlug, entrySlug: slug, locale }) : null
}
return (
buildLocalizedPath({
config,
+69
View File
@@ -0,0 +1,69 @@
type ProductPrice = {
amount: number
currency: string
/** 'exact' → Offer.price; 'from' → minPrice (a starting price, not a promise). */
kind?: 'exact' | 'from'
}
type ProductJsonLdArgs = {
/** schema.org availability, e.g. 'MadeToOrder', 'InStock'. Default 'InStock' when a price is given. */
availability?: string
brand?: string
category?: string
description?: string
/** Absolute image URL. */
image?: string
name: string
/** Only a real price from the panel — no price (on request) → no Offer at all. */
price?: null | ProductPrice
sku?: string
/** Absolute URL of the product page (also its @id). */
url: string
}
/**
* schema.org Product for a catalog entry: name, SKU, image, category, brand and —
* only when the panel has one — an Offer. A product "on request" gets no Offer:
* an invented or estimated price in structured data misleads search results.
*
* createContentHelpers({ pageJsonLd: { entries: {
* products: ({ doc, url, image }) => buildProductJsonLd({ name: doc.title, sku: doc.sku, url, image, … }),
* } } })
*/
export function buildProductJsonLd({
name,
availability,
brand,
category,
description,
image,
price,
sku,
url,
}: ProductJsonLdArgs): Record<string, unknown> {
const offer =
price && Number.isFinite(price.amount) && price.currency
? {
'@type': 'Offer',
availability: `https://schema.org/${availability ?? 'InStock'}`,
priceCurrency: price.currency,
url,
...(price.kind === 'from'
? { priceSpecification: { '@type': 'PriceSpecification', minPrice: price.amount, priceCurrency: price.currency } }
: { price: price.amount }),
}
: undefined
return {
name,
'@context': 'https://schema.org',
'@id': url,
'@type': 'Product',
url,
...(sku ? { sku } : {}),
...(description ? { description } : {}),
...(image ? { image } : {}),
...(category ? { category } : {}),
...(brand ? { brand: { name: brand, '@type': 'Brand' } } : {}),
...(offer ? { offers: offer } : {}),
}
}
+2
View File
@@ -142,6 +142,8 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
locale,
order: site.order,
separator: site.separator,
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
siteDescription: site.siteDescription,
siteName: site.siteName,
}
+1
View File
@@ -11,6 +11,7 @@ export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
export { buildProductJsonLd } from './buildProductJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
+26 -3
View File
@@ -1,6 +1,8 @@
type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
export type ImagesConfig = {
/** Development only: lets next/image optimize files served by the app itself on localhost. */
dangerouslyAllowLocalIP?: boolean
formats: ('image/avif' | 'image/webp')[]
minimumCacheTTL: number
remotePatterns: RemotePattern[]
@@ -11,15 +13,20 @@ export type ImagesConfig = {
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality;
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
* optimize R2 files — otherwise it refuses them;
* - optimized images cached for 31 days (uploads get new names when replaced).
* - optimized images cached for 31 days (uploads get new names when replaced);
* - outside production, media served by the app itself (`/api/media/file/**` on
* NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which
* Next 16 otherwise refuses as a private IP.
*
* import { buildImagesConfig } from '@intecion/ipal-kit'
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
*/
export function buildImagesConfig({
extraHosts = [],
production = process.env.NODE_ENV === 'production',
publicUrl = process.env.R2_PUBLIC_URL,
}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig {
serverUrl = process.env.NEXT_PUBLIC_SERVER_URL,
}: { extraHosts?: string[]; production?: boolean; publicUrl?: string; serverUrl?: string } = {}): ImagesConfig {
const remotePatterns: RemotePattern[] = []
if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
const u = new URL(publicUrl)
@@ -31,5 +38,21 @@ export function buildImagesConfig({
})
}
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns }
let localMedia = false
if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) {
const u = new URL(serverUrl)
remotePatterns.push({
hostname: u.hostname,
protocol: u.protocol.replace(':', '') as 'http' | 'https',
...(u.port ? { port: u.port } : {}),
pathname: '/api/media/file/**',
})
localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
}
return {
formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 60 * 60 * 24 * 31,
remotePatterns,
...(localMedia ? { dangerouslyAllowLocalIP: true } : {}),
}
}
+4
View File
@@ -8,8 +8,10 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { emailSettingsFields } from './modules/forms/emailLayout.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
@@ -212,6 +214,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.globals ?? []),
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
+49 -1
View File
@@ -6,7 +6,7 @@ import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderT
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { RenderForm } from '../src/modules/forms/RenderForm.js'
import { prepareBuilderForm, publicForm, RenderForm } from '../src/modules/forms/RenderForm.js'
vi.mock('server-only', () => ({}))
@@ -131,3 +131,51 @@ describe('RenderForm', () => {
expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull()
})
})
describe('page values (values prop) and prepareBuilderForm', () => {
const withSubject: BuilderFormDoc = {
id: 9,
fields: [
{ name: 'subject', blockType: 'text', label: 'Dotyczy' },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
],
submitButtonLabel: 'Wyślij',
}
test('a field filled by the page is read-only output in the first HTML, others stay inputs', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action: async () => ({ message: 'ok', success: true }),
classNames: { fixed: 'fx' },
form: withSubject,
texts,
values: { subject: 'Pierścionek · białe złoto', unknown: 'x' },
}),
)
expect(html).toContain('<output')
expect(html).toContain('class="fx"')
expect(html).toContain('Pierścionek · białe złoto')
expect(html).not.toMatch(/<input[^>]*name="subject"/)
expect(html).toMatch(/<input[^>]*name="email"/)
expect(html).not.toContain('unknown')
})
test('RenderForm passes values through', () => {
const action = async () => ({ message: 'ok', success: true })
const html = renderToStaticMarkup(
createElement(RenderForm, { action, form: withSubject, locale: 'pl', texts, values: { subject: 'Broszki' } }),
)
expect(html).toContain('Broszki')
})
test('prepareBuilderForm: public part only, bound action, null for an id', () => {
const doc = { ...withSubject, emails: [{ emailTo: '[email protected]' }] } as BuilderFormDoc
const action = vi.fn(async () => ({ message: 'ok', success: true }))
const prepared = prepareBuilderForm({ action, form: doc, locale: 'pl' })
expect(JSON.stringify(prepared?.form)).not.toContain('[email protected]')
expect(prepared?.form).toEqual(publicForm(doc))
void prepared?.action({ email: '[email protected]' })
expect(action).toHaveBeenCalledWith('9', 'pl', { email: '[email protected]' })
expect(prepareBuilderForm({ action, form: '9', locale: 'pl' })).toBeNull()
})
})
+90
View File
@@ -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')
})
})
+26
View File
@@ -87,3 +87,29 @@ describe('noindex protection', () => {
expect(updated.noindex).toBe(true)
})
})
describe('content entries: own JSON-LD and links', () => {
test('pageJsonLd.entries replaces the article node; link options know the archives', async () => {
const { createContentHelpers } = await import('../src/modules/frontend/createContentHelpers.js')
const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js')
const archive = await payload.create({ collection: 'pages' as never, data: { slug: 'wyroby', _status: 'published', title: 'Wyroby' } as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { postsArchive: archive.id, siteName: 'Acme' } as never })
await payload.create({ collection: 'posts' as never, data: { slug: 'pierscionek', _status: 'published', title: 'Pierścionek' } as never })
const h = createContentHelpers({
baseUrl: 'https://acme.pl',
config: payload.config,
content: { collections: [{ slug: 'posts' }] },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
pageJsonLd: {
entries: { posts: ({ doc, siteName, url }) => buildProductJsonLd({ name: String(doc.title), brand: siteName, url }) },
},
})
const nodes = await h.getPageJsonLd('pl', ['wyroby', 'pierscionek'])
expect(nodes.map((n) => n['@type'])).toEqual(['Product', 'BreadcrumbList'])
expect(nodes[0]).toMatchObject({ name: 'Pierścionek', brand: { name: 'Acme' } })
expect(nodes[0]).not.toHaveProperty('offers')
const options = await h.getLinkOptions('pl')
expect(options.archives).toEqual({ posts: 'wyroby' })
expect(await h.resolveLink({ type: 'internal', label: 'x', page: { relationTo: 'posts', value: { slug: 'pierscionek' } } }, 'pl')).toMatchObject({ href: '/pl/wyroby/pierscionek' })
})
})
+89
View File
@@ -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 &lt;script&gt;')
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' }))
})
})
+36
View File
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { assertEnv } from '../src/modules/env/assertEnv.js'
import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js'
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 's' }
const r2 = {
R2_ACCESS_KEY_ID: 'k',
R2_BUCKET: 'b',
R2_ENDPOINT: 'https://acc.r2.cloudflarestorage.com',
R2_PUBLIC_URL: 'https://media.acme.pl',
R2_SECRET_ACCESS_KEY: 's',
}
function check(env: Record<string, string>) {
vi.unstubAllEnvs()
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
return () => assertEnv(ipalEnvRules({ storage: true }), { env })
}
afterEach(() => vi.unstubAllEnvs())
describe('ipalEnvRules({ storage })', () => {
test('production: every R2_* is required', () => {
expect(check({ ...base, NODE_ENV: 'production' })).toThrow(/R2_BUCKET is required/)
expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow()
})
test('development: no R2 at all is fine (local disk)', () => {
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
})
test('development: a partial R2 set is an error (all or nothing)', () => {
expect(check({ ...base, NODE_ENV: 'development', R2_BUCKET: 'b' })).toThrow(/R2_ACCESS_KEY_ID is required/)
})
})
+26
View File
@@ -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([])
})
})
+38 -1
View File
@@ -13,7 +13,7 @@ import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
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 { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
@@ -239,6 +239,10 @@ describe('one-call helpers — layout, page, GEO routes', () => {
const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect })
const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } }
expect(JSON.stringify(el.props.children[0])).toContain('Usługi')
// Blocks get the locale and whether they are the first section (the page's h1).
const blocksEl = el.props.children[1] as { props: { enhanceProps: (a: { allBlocks: never[]; block: never; index: number }) => Record<string, unknown> } }
expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 0 })).toMatchObject({ isFirst: true, locale: 'pl' })
expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 1 }).isFirst).toBe(false)
await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND')
expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi')
})
@@ -304,6 +308,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', () => {
test('rows from Cookie Settings in the requested language', async () => {
await payload.updateGlobal({
+18
View File
@@ -1,6 +1,8 @@
import { describe, expect, test } from 'vitest'
import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js'
import { buildLinkField } from '../src/modules/links/buildLinkField.js'
import { resolveLinkHref } from '../src/modules/links/resolveLinkHref.js'
import { homeSlugFrom, resolveLink, resolveNav } from '../src/modules/links/resolveNav.js'
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const
@@ -104,3 +106,19 @@ describe('resolveSystemLinks', () => {
expect(resolveSystemLinks(null, opts)).toEqual([])
})
})
describe('links to content entries (polymorphic page relation)', () => {
test('buildLinkField with several collections makes a polymorphic relation', () => {
const field = buildLinkField({ relationTo: ['pages', 'categories'] })
const page = JSON.stringify(field.fields)
expect(page).toContain('"relationTo":["pages","categories"]')
})
test('an entry resolves under its archive page; a page stays a page; no archive → null', () => {
const entry = { type: 'internal' as const, page: { relationTo: 'categories', value: { slug: 'pierscionki' } } }
const archives = { categories: 'kategorie' }
expect(resolveLinkHref(entry, { archives, config, locale: 'pl' })).toBe('/pl/kategorie/pierscionki')
expect(resolveLinkHref({ type: 'internal', page: { relationTo: 'pages', value: { slug: 'kontakt' } } }, { archives, config, locale: 'pl' })).toBe('/pl/kontakt')
expect(resolveLinkHref(entry, { config, locale: 'pl' })).toBeNull()
})
})
+9 -2
View File
@@ -57,12 +57,19 @@ describe('videoProps', () => {
describe('buildImagesConfig', () => {
test('AVIF/WebP and the R2 domain', () => {
expect(buildImagesConfig({ publicUrl: 'https://media.acme.pl/' })).toEqual({
expect(buildImagesConfig({ production: true, publicUrl: 'https://media.acme.pl/', serverUrl: 'https://acme.pl' })).toEqual({
formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 2678400,
remotePatterns: [{ hostname: 'media.acme.pl', pathname: '/**', protocol: 'https' }],
})
expect(buildImagesConfig({ publicUrl: '/media' }).remotePatterns).toEqual([])
expect(buildImagesConfig({ production: true, publicUrl: '/media' }).remotePatterns).toEqual([])
})
test('development without R2: the app\'s own media on localhost (private IP allowed)', () => {
const config = buildImagesConfig({ production: false, publicUrl: undefined, serverUrl: 'http://localhost:3000' })
expect(config.remotePatterns).toEqual([{ hostname: 'localhost', pathname: '/api/media/file/**', port: '3000', protocol: 'http' }])
expect(config.dangerouslyAllowLocalIP).toBe(true)
expect(buildImagesConfig({ production: false, serverUrl: 'https://staging.acme.pl' }).dangerouslyAllowLocalIP).toBeUndefined()
})
})
+42
View File
@@ -9,6 +9,7 @@ import { buildCsp } from '../src/modules/security/buildCsp.js'
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
const config: I18nConfig = {
@@ -259,3 +260,44 @@ describe('site-wide noindex (IPAL_NOINDEX) and Markdown headers', () => {
expect(res.headers.get('link')).toBe('<https://acme.pl/pl/o-nas>; rel="canonical"')
})
})
describe('createPageMetadata — siteDescription fallback', () => {
// Regresja 1.10.0: readSiteMetaConfig czytał siteDescription, ale nie trafiał do buildMetadata —
// strona bez meta.description nie miała <meta name="description"> (Lighthouse SEO).
const settings = { homepage: null, siteDescription: 'Opis firmy z Site Settings', siteName: 'Acme' }
const payload = {} as never
test('page without its own description gets Site Settings → siteDescription', async () => {
const pageMetadata = createPageMetadata({
baseUrl: 'https://acme.pl',
config,
loaders: { getSettings: async () => settings, resolveRoute: async () => null },
})
const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload })
expect(metadata.description).toBe('Opis firmy z Site Settings')
expect(metadata.openGraph?.description).toBe('Opis firmy z Site Settings')
})
test('no siteDescription → no description (field omitted, not invented)', async () => {
const pageMetadata = createPageMetadata({
baseUrl: 'https://acme.pl',
config,
loaders: { getSettings: async () => ({ ...settings, siteDescription: null }), resolveRoute: async () => null },
})
const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload })
expect(metadata.description).toBeUndefined()
})
})
describe('buildProductJsonLd', () => {
test('an Offer only for a real price; "from" is a minimum, not a price', async () => {
const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js')
const base = { name: 'Pierścionek', url: 'https://acme.pl/pl/wyroby/p' }
expect(buildProductJsonLd(base)).not.toHaveProperty('offers')
expect(buildProductJsonLd({ ...base, price: { amount: 6900, currency: 'PLN', kind: 'exact' } }).offers).toMatchObject({ price: 6900, priceCurrency: 'PLN' })
expect(buildProductJsonLd({ ...base, availability: 'MadeToOrder', price: { amount: 6900, currency: 'PLN', kind: 'from' } }).offers).toMatchObject({
availability: 'https://schema.org/MadeToOrder',
priceSpecification: { minPrice: 6900 },
})
})
})