Compare commits

...
22 Commits
Author SHA1 Message Date
Radosław Smoliński 305c564d13 1.12.0
CI / check (push) Canceled after 0s
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 166bf51e53 Lazy 404: createNotFoundPage({ load }) + renderNotFoundView, NotFoundLoader
Next puts a layout's not-found tree into the RSC payload of every page under it. The eager
createNotFoundPage({ blocks }) rendered the panel's 404 page there in every locale, so with
404 = homepage each page shipped the homepage twice (homepage HTML 195 -> 146 KB gzip).
With { load } only <NotFoundLoader> is in the payload; the content comes from the project's
server action (renderNotFoundView, locale checked against configured locales) when a 404 shows.
The eager variant is unchanged. Docs: pages.md, i18n.md, AGENT.md, PROGRAMISTA, ipal-setup, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 8b35986635 1.11.1
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 faa4ad679c Theme switcher, table of contents, missing-page redirect, form placeholders and time field; audit and revalidate fixes
- buildRevalidateHook skips outside Next (no NEXT_RUNTIME) and with context.disableRevalidate
- BuilderForm focuses only on a real step change (no scroll to the form on remount)
- mediaImageProps: placeholder colour only for JPEG (placeholderColor); hook stores no colour for transparent images
- buildLinkField: interface name per shape (CmsLink, CmsLinkPlain, CmsLinkNoLabel) + interfaceName option
- Cookie Settings: buttons.save -> buttons.savePreferences (Mongoose reserved name)
- ThemeScript, ThemeSwitcher, useTheme; Site Settings defaultTheme 'system' + themeToggleLabel; Turnstile follows page theme
- extractHeadings, RenderRichText headingIds, TableOfContents, buildTableOfContentsField
- createPageRoute onMissing: 'redirectHome'
- Form builder: localized placeholder on text/email/textarea/number, new time field
- ipal-audit: no false positive for object keys between JSX elements; /md route not reported as dynamic

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
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
radoslaw.smolinski 91d5e986c5 1.9.7
CI / check (push) Canceled after 0s
2026-10-16 20:53:26 +02:00
radoslaw.smolinskiandClaude Opus 5.5 080086adfe Forms: conditional fields and steps (Show only when)
Every form block (built-in, Checkbox group, Step, message) gets a showWhen
group: visible only when another field has one of the given values. A hidden
Step drops out with its fields; browser and server share visibleFields, so a
hidden field is neither required nor stored. GDPR consent is always enforced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 20:53:25 +02:00
radoslaw.smolinski 8c1a8b0e8e 1.9.6
CI / check (push) Canceled after 0s
2026-10-16 13:51:33 +02:00
radoslaw.smolinskiandClaude Opus 5.5 002eef56d1 Changelog 1.9.6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:51:31 +02:00
radoslaw.smolinskiandClaude Opus 5.5 924b5cf8be Markdown route: type-safe locale code read
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:42:17 +02:00
radoslaw.smolinski 3e17f92af1 1.9.5
CI / check (push) Canceled after 0s
2026-10-16 13:32:34 +02:00
radoslaw.smolinskiandClaude Opus 5.5 c83d2dec0c Merge 1.9.5: single-language Markdown route
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:32:31 +02:00
radoslaw.smolinskiandClaude Opus 5.5 df0f5e03c3 Single-language sites: Markdown route without the locale param; i18n docs corrected
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:32:31 +02:00
103 changed files with 3789 additions and 325 deletions
+304 -4
View File
@@ -213,6 +213,19 @@ export interface Form {
width?: number | null; width?: number | null;
required?: boolean | null; required?: boolean | null;
defaultValue?: boolean | null; defaultValue?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'checkbox'; blockType: 'checkbox';
@@ -231,6 +244,23 @@ export interface Form {
label?: string | null; label?: string | null;
width?: number | null; width?: number | null;
required?: boolean | null; required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'email'; blockType: 'email';
@@ -251,6 +281,19 @@ export interface Form {
}; };
[k: string]: unknown; [k: string]: unknown;
} | null; } | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'message'; blockType: 'message';
@@ -261,6 +304,23 @@ export interface Form {
width?: number | null; width?: number | null;
defaultValue?: number | null; defaultValue?: number | null;
required?: boolean | null; required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'number'; blockType: 'number';
@@ -279,6 +339,19 @@ export interface Form {
}[] }[]
| null; | null;
required?: boolean | null; required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'select'; blockType: 'select';
@@ -298,6 +371,23 @@ export interface Form {
width?: number | null; width?: number | null;
defaultValue?: string | null; defaultValue?: string | null;
required?: boolean | null; required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'text'; blockType: 'text';
@@ -308,6 +398,23 @@ export interface Form {
width?: number | null; width?: number | null;
defaultValue?: string | null; defaultValue?: string | null;
required?: boolean | null; required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'textarea'; blockType: 'textarea';
@@ -335,6 +442,19 @@ export interface Form {
* Empty = no limit. * Empty = no limit.
*/ */
maxSelected?: number | null; maxSelected?: number | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'checkboxGroup'; blockType: 'checkboxGroup';
@@ -345,6 +465,19 @@ export interface Form {
width?: number | null; width?: number | null;
required?: boolean | null; required?: boolean | null;
defaultValue?: string | null; defaultValue?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'date'; blockType: 'date';
@@ -362,6 +495,19 @@ export interface Form {
}[] }[]
| null; | null;
required?: boolean | null; required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'radio'; blockType: 'radio';
@@ -372,10 +518,48 @@ export interface Form {
*/ */
title?: string | null; title?: string | null;
description?: string | null; description?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null; id?: string | null;
blockName?: string | null; blockName?: string | null;
blockType: 'step'; blockType: 'step';
} }
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'time';
}
)[] )[]
| null; | null;
submitButtonLabel?: string | null; submitButtonLabel?: string | null;
@@ -701,6 +885,12 @@ export interface FormsSelect<T extends boolean = true> {
width?: T; width?: T;
required?: T; required?: T;
defaultValue?: T; defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -721,6 +911,13 @@ export interface FormsSelect<T extends boolean = true> {
label?: T; label?: T;
width?: T; width?: T;
required?: T; required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -728,6 +925,12 @@ export interface FormsSelect<T extends boolean = true> {
| T | T
| { | {
message?: T; message?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -739,6 +942,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T; width?: T;
defaultValue?: T; defaultValue?: T;
required?: T; required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -758,6 +968,12 @@ export interface FormsSelect<T extends boolean = true> {
id?: T; id?: T;
}; };
required?: T; required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -779,6 +995,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T; width?: T;
defaultValue?: T; defaultValue?: T;
required?: T; required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -790,6 +1013,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T; width?: T;
defaultValue?: T; defaultValue?: T;
required?: T; required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -809,6 +1039,12 @@ export interface FormsSelect<T extends boolean = true> {
}; };
minSelected?: T; minSelected?: T;
maxSelected?: T; maxSelected?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -820,6 +1056,12 @@ export interface FormsSelect<T extends boolean = true> {
width?: T; width?: T;
required?: T; required?: T;
defaultValue?: T; defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -838,6 +1080,12 @@ export interface FormsSelect<T extends boolean = true> {
id?: T; id?: T;
}; };
required?: T; required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -846,6 +1094,28 @@ export interface FormsSelect<T extends boolean = true> {
| { | {
title?: T; title?: T;
description?: T; description?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
time?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T; id?: T;
blockName?: T; blockName?: T;
}; };
@@ -991,13 +1261,17 @@ export interface SiteSetting {
*/ */
favicon?: (number | null) | Media; favicon?: (number | null) | Media;
/** /**
* Theme applied on a visitor’s first visit. * Theme applied on a visitor’s first visit. System = the visitor’s device setting.
*/ */
defaultTheme: 'light' | 'dark'; defaultTheme: 'light' | 'dark' | 'system';
/** /**
* Show a light/dark switch on the site. * Show a light/dark switch on the site.
*/ */
allowThemeToggle?: boolean | null; allowThemeToggle?: boolean | null;
/**
* Name of the switch read by screen readers, e.g. "Dark mode".
*/
themeToggleLabel?: string | null;
updatedAt?: string | null; updatedAt?: string | null;
createdAt?: string | null; createdAt?: string | null;
} }
@@ -1092,6 +1366,14 @@ export interface CookieSetting {
* Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again. * Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.
*/ */
policyVersion: number; policyVersion: number;
/**
* Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.
*/
eyebrow?: string | null;
/**
* Banner heading, e.g. "We respect your privacy". Empty → not shown.
*/
title?: string | null;
/** /**
* Main consent message shown in the banner. * Main consent message shown in the banner.
*/ */
@@ -1100,6 +1382,14 @@ export interface CookieSetting {
* Heading for the detailed settings panel. * Heading for the detailed settings panel.
*/ */
settingsTitle?: string | null; settingsTitle?: string | null;
/**
* Intro under the settings heading — what cookies are for and that the choice can be changed later.
*/
settingsDescription?: string | null;
/**
* Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.
*/
alwaysActiveLabel?: string | null;
/** /**
* Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used. * Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.
*/ */
@@ -1111,8 +1401,12 @@ export interface CookieSetting {
acceptAll?: string | null; acceptAll?: string | null;
reject?: string | null; reject?: string | null;
settings?: string | null; settings?: string | null;
save?: string | null; savePreferences?: string | null;
back?: string | null; back?: string | null;
/**
* Screen-reader label of the ✕ button in the settings dialog.
*/
close?: string | null;
}; };
/** /**
* Per-category titles and descriptions. * Per-category titles and descriptions.
@@ -1206,6 +1500,7 @@ export interface SiteSettingsSelect<T extends boolean = true> {
favicon?: T; favicon?: T;
defaultTheme?: T; defaultTheme?: T;
allowThemeToggle?: T; allowThemeToggle?: T;
themeToggleLabel?: T;
updatedAt?: T; updatedAt?: T;
createdAt?: T; createdAt?: T;
globalType?: T; globalType?: T;
@@ -1259,8 +1554,12 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
*/ */
export interface CookieSettingsSelect<T extends boolean = true> { export interface CookieSettingsSelect<T extends boolean = true> {
policyVersion?: T; policyVersion?: T;
eyebrow?: T;
title?: T;
message?: T; message?: T;
settingsTitle?: T; settingsTitle?: T;
settingsDescription?: T;
alwaysActiveLabel?: T;
privacyLinkLabel?: T; privacyLinkLabel?: T;
buttons?: buttons?:
| T | T
@@ -1268,8 +1567,9 @@ export interface CookieSettingsSelect<T extends boolean = true> {
acceptAll?: T; acceptAll?: T;
reject?: T; reject?: T;
settings?: T; settings?: T;
save?: T; savePreferences?: T;
back?: T; back?: T;
close?: T;
}; };
categories?: categories?:
| T | T
+188
View File
@@ -8,6 +8,194 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20. dopiero powyżej 20.
## 1.12.0
### Nowe
- **Leniwa strona 404** — `createNotFoundPage(content, { load })` + `renderNotFoundView(content, { blocks, blockProps,
fallback }, locale)` (`/rsc`) w server action projektu; `<NotFoundLoader>` (`/client`). Next wkłada drzewo
`not-found` layoutu do danych RSC KAŻDEJ strony; wariant `{ blocks }` renderował tam stronę 404 z panelu w każdym
języku (404 = strona główna, 2 języki: HTML strony głównej 195 → 146 KB gzip, dane RSC −42%). Teraz w danych jest
tylko loader, treść przychodzi przy wyświetleniu 404. `renderNotFoundView` przyjmuje tylko skonfigurowane języki.
Opis: pages.md → „Strona 404”.
### Wymaga zmian w projekcie
Nic obowiązkowego — `createNotFoundPage(content, { blocks })` działa jak dotąd. Zalecane (każdy projekt z 404
z panelu, zwłaszcza 404 = strona główna albo kilka języków):
1. `src/app/(frontend)/[locale]/notFoundView.ts` (`.tsx`, gdy `fallback` to JSX):
`'use server'` + `export async function loadNotFoundView(locale: string) { return renderNotFoundView(content,
{ blocks: blockRegistry, blockProps, fallback }, locale) }` — opcje przenieś z `not-found.tsx`.
2. `not-found.tsx`: `export default createNotFoundPage(content, { load: loadNotFoundView })`.
3. Sprawdzenie: w HTML dowolnej strony brak treści strony 404 (`self.__next_f`), a nieznany adres
(np. `/xx/test`) nadal daje 404 z treścią z panelu.
## 1.11.1
### Nowe
- **Motyw jasny / ciemny** — `<ThemeScript>` (`/rsc`, albo `<SiteProviders theme>`) ustawia `data-theme` i
`color-scheme` na `<html>` przed malowaniem; `<ThemeSwitcher>` bez stylów (`role="switch"`), `useTheme()`,
`applyTheme` (`/client`). Wybór w `localStorage` (`ipal-theme`), synchronizacja kart. Site Settings → Theme:
`defaultTheme: 'system'`, `themeToggleLabel`; `getSiteShell(locale).theme`. Opis: theme.md.
- **Turnstile w motywie strony** — `turnstileTheme` domyślnie `'page'` (bez motywu strony = `'auto'` jak dotąd).
- **Spis treści** — `extractHeadings`, `RenderRichText headingIds` (te same id), `<TableOfContents>` (`/client`,
`aria-current="location"`), `buildTableOfContentsField()`. Opis: richtext.md.
- **Brak strony → strona główna** — `createPageRoute(…, { redirect, onMissing: 'redirectHome' })` albo własna funkcja.
- **Formularze** — pole „Placeholder” (localized) w blokach text, email, textarea, number; nowy typ **Time**
(`HH:MM`, walidowany na serwerze).
- `buildLinkField({ interfaceName })`.
### Poprawki
- **`buildRevalidateHook` poza Next** — bez `NEXT_RUNTIME` (`payload run`, seed, migracje) albo z
`context.disableRevalidate` hook nic nie robi. Wcześniej: `Invariant: static generation store missing`.
- **`BuilderForm` nie przewija strony do formularza** — fokus tylko przy zmianie kroku. Wcześniej React
uruchamiał efekt ponownie (Next przywracający odwiedzoną stronę, StrictMode) i fokus skakał na pierwsze pole.
- **Kolor placeholdera pod przezroczystymi obrazami** — `mediaImageProps` daje `backgroundColor` tylko dla JPEG
(`placeholderColor`), hook nie liczy koloru dla obrazów z alfą. Koniec czarnych prostokątów pod logotypami.
- **Typ linku nie zależy od kolejności pól** — każdy kształt ma własną nazwę: `CmsLink`, `CmsLinkPlain`
(`appearances: false`), `CmsLinkNoLabel`, `CmsLinkPlainNoLabel`. Wszystkie pasują do `CmsLink`.
- **Ostrzeżenie Mongoose przy każdym starcie** — pole Cookie Settings `buttons.save` → `buttons.savePreferences`
(`save` to nazwa zarezerwowana). API frontu bez zmian (`texts.buttons.save`).
- **ipal-audit** — klucze obiektu między elementami JSX (`narrow: <A />, wide: <B />`) nie są już zgłaszane jako
tekst na sztywno; reguła „page routes rendered dynamically” pomija trasę `/md/[locale]` (route handlery są `force-dynamic` z założenia).
### Wymaga zmian w projekcie
- Migracja (Postgres/SQLite): `pnpm payload migrate:create` — nowe pola (placeholder, time, `themeToggleLabel`,
wartość `system`), zmiana nazwy `buttons_save` → `buttons_save_preferences`: gdy drizzle zapyta o kolumnę,
wybierz **rename**; inaczej tekst przycisku wróci do domyślnego „Save preferences” i trzeba go wpisać w panelu.
MongoDB: bez migracji; plugin próbuje odczytać starą wartość, ale sprawdź przycisk „Zapisz” w banerze i w razie
potrzeby wpisz tekst w Cookie Settings → Buttons → Save.
- `pnpm payload generate:types` — linki bez stylu / bez etykiety mają nowe nazwy typów; kod z `CmsLink` działa dalej.
- Usuń obejścia z PROGRAMISTA §6 poz. 38–45 (komentarze `WORKAROUND ipal-kit` w projekcie). `pnpm ipal:skills` (nowy audyt).
## 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
- **Pola i kroki warunkowe w formularzach z panelu** („Show only when”, `showWhen`): każde pole,
Checkbox group, message i **Step** może pokazywać się tylko przy wybranej odpowiedzi innego pola
(`field` + `values` po przecinku). Ukryty Step wypada z formularza razem z polami, kolejne kroki
się przenumerowują. Przeglądarka i serwer stosują tę samą regułę (`visibleFields`): ukryte pole nie
jest wymagane ani zapisywane; zgoda RODO (`consent`) jest egzekwowana zawsze. Opis: forms.md →
„Pola i kroki warunkowe”.
### Wymaga zmian w projekcie
- Nowa grupa w blokach formularzy = nowe kolumny w bazie. Po aktualizacji: `pnpm payload migrate:create`
(z kompletem `R2_*`, jeśli projekt ich używa) i `pnpm payload migrate`. Istniejące formularze działają
bez zmian (puste „Show only when” = pole zawsze widoczne).
## 1.9.6
### Poprawki
- Trasa Markdown: bezpieczny typ przy odczycie kodów języków z configu (bez zmian w działaniu).
Wydanie zbiorcze — zawiera wszystko z 1.9.2–1.9.5 (formularze krokowe, `SiteProviders`,
`createPageRoute`, trasy z jednej linii, własne style linków, `getSystemLinks`, Markdown na
stronie jednojęzycznej, nowe reguły audytu). Przy aktualizacji ze starszej wersji przejdź sekcje
„Wymaga zmian w projekcie” od swojej wersji w górę.
## 1.9.5
### Poprawki
- **Markdown (GEO) na stronie jednojęzycznej:** `/md/kontakt` szło do trasy `md/[locale]/[[...slug]]`
jako język „kontakt” → 404, a `/md` (strona główna) nie miało trasy. `markdownRoute` /
`createMarkdownRoute` działa teraz bez parametru `locale` (`app/md/[[...slug]]/route.ts`, język z config),
a trasa z `[locale]` na stronie jednojęzycznej czyta ten segment jako slug.
### Dokumentacja
- i18n.md: strona jednojęzyczna na `SiteProviders`, `createPageRoute`, `createNotFoundPage` i
`app/md/[[...slug]]`. Usunięta błędna rada „załóż `[locale]` na zapas przy jednym języku” (linki byłyby
bez `/pl`, strony z `/pl`); opisane przejście na kilka języków (proxy przekieruje stare adresy).
### Wymaga zmian w projekcie
- Strona jednojęzyczna z `app/md/[locale]/[[...slug]]/route.ts` → przenieś plik do `app/md/[[...slug]]/route.ts`
(bez zmian treści), żeby działało `/md` dla strony głównej.
## 1.9.4 ## 1.9.4
### Nowe ### Nowe
+3 -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) | | GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) | | Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Zgoda cookies, baner | [consent.md](./consent.md) | | Zgoda cookies, baner | [consent.md](./consent.md) |
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) | | Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
| Email SMTP / Graph | [email.md](./email.md) | | Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) | | Walidacja env | [env.md](./env.md) |
@@ -27,10 +28,11 @@ Szczegóły API — jeden plik na moduł:
| Komunikaty formularzy | [notifications.md](./notifications.md) | | Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) | | Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
| Helpery Payload | [payload-helpers.md](./payload-helpers.md) | | Helpery Payload | [payload-helpers.md](./payload-helpers.md) |
| Rich text | [richtext.md](./richtext.md) | | Rich text, spis treści | [richtext.md](./richtext.md) |
| Nagłówki, CSP, 2FA | [security.md](./security.md) | | Nagłówki, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) | | SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Auto-slug | [slug.md](./slug.md) | | Auto-slug | [slug.md](./slug.md) |
| Motyw jasny / ciemny, przełącznik | [theme.md](./theme.md) |
| Media, R2 | [storage.md](./storage.md) | | Media, R2 | [storage.md](./storage.md) |
| Turnstile | [turnstile.md](./turnstile.md) | | Turnstile | [turnstile.md](./turnstile.md) |
| White-label panelu | [white-label.md](./white-label.md) | | White-label panelu | [white-label.md](./white-label.md) |
+10 -5
View File
@@ -52,12 +52,12 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| # | Obszar | Co musi być (plik) | API pluginu | Kontrola | | # | Obszar | Co musi być (plik) | API pluginu | Kontrola |
|---|---|---|---|---| |---|---|---|---|---|
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S | | 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, { load })` + `notFoundView.ts` (`renderNotFoundView`) | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S | | 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S | | 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S | | 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S | | 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S | | 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (jednojęzyczna: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S | | 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S |
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S | | 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S |
| 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S | | 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
@@ -285,7 +285,8 @@ src/
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md) [locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy) actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy)
not-found.tsx # createNotFoundPage(content, { blocks }) — 404 z panelu not-found.tsx # createNotFoundPage(content, { load: loadNotFoundView }) — 404 z panelu
notFoundView.ts # 'use server' → renderNotFoundView(content, { blocks }, locale)
[[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate [[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate
(payload)/ # panel (generowany) (payload)/ # panel (generowany)
manifest.ts # export { manifest as default } from lib/content + force-dynamic manifest.ts # export { manifest as default } from lib/content + force-dynamic
@@ -350,7 +351,8 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
statycznych — w blokach, komponentach, layoucie `[locale]` ani w statycznych — w blokach, komponentach, layoucie `[locale]` ani w
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`). `not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) → Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
wersja na każdy język + `<LocaleView>` (pages.md). `createNotFoundPage(content, { load })` — język z adresu, treść z server action dopiero przy 404
(wariant `{ blocks }` wkłada 404 w każdym języku do danych RSC KAŻDEJ strony — pages.md).
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę: 7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
`manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery `manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy. pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
@@ -769,7 +771,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|---|---|---| |---|---|---|
| Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md | | Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md |
| Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md | | Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { blocks, fallback })` (`/rsc`) | pages.md | | 404 z panelu w każdym języku | `createNotFoundPage(content, { load })` + server action `renderNotFoundView(content, { blocks, fallback }, locale)` (`/rsc`) | pages.md |
| Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md | | Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md |
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md | | Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md | | Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
@@ -780,6 +782,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
| Potrzeba | Użyj | Doc | | Potrzeba | Użyj | Doc |
|---|---|---| |---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md | | 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 | | Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md |
| Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md | | Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md |
| Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md | | Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md |
@@ -804,6 +807,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 | | 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 | | Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md |
| Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | 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 | | Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.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 | | Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md |
@@ -817,6 +821,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
| Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md | | Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md |
| sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md | | sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md |
| JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `<JsonLdGraph>` | 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 | | 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 | | IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Wyszukiwarka | `createSearchRoute` | content.md | | Wyszukiwarka | `createSearchRoute` | content.md |
@@ -248,7 +248,7 @@ if [ -n "$APP" ]; then
# GEO # GEO
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts (one language: src/app/md/[[...slug]]/route.ts) → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts
need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src
@@ -320,7 +320,8 @@ if [ "$QUICK" -eq 0 ]; then
echo "== pnpm build ==" echo "== pnpm build =="
BUILD_LOG=$(mktemp) BUILD_LOG=$(mktemp)
if pnpm -s build >"$BUILD_LOG" 2>&1; then if pnpm -s build >"$BUILD_LOG" 2>&1; then
DYN=$(grep -E '^[│├└ ]*ƒ .*\[locale\]' "$BUILD_LOG" || true) # Only page routes under /[locale]: route handlers (/md/[locale]/…, sitemap, llms) are force-dynamic by design.
DYN=$(grep -E '^[│├└ ]*ƒ /\[locale\]' "$BUILD_LOG" || true)
report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN" report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN"
else else
ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /' ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /'
@@ -21,6 +21,9 @@ const WORD = /\p{L}{2,}/u
// Text right after a closing/self-closing tag may be the JS that follows the JSX // Text right after a closing/self-closing tag may be the JS that follows the JSX
// expression (`<X /> : null`, `</div>) }`, `</p>\n const id = …`) — not visible text. // expression (`<X /> : null`, `</div>) }`, `</p>\n const id = …`) — not visible text.
const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/ const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/
// JSX elements as values in an object literal: `narrow: <A />,\n wide: <B />` leaves
// ", wide:" between the two elements — a property key, not visible text.
const OBJECT_KEY = /^\s*,\s*(?:[A-Za-z_$][\w$]*|'[^']*'|"[^"]*")\s*:\s*$/
const files = [] const files = []
const walk = (p) => { const walk = (p) => {
@@ -44,7 +47,7 @@ for (const file of files) {
const src = stripComments(readFileSync(file, 'utf8')) const src = stripComments(readFileSync(file, 'utf8'))
for (const m of src.matchAll(OPEN_OR_CLOSE)) { for (const m of src.matchAll(OPEN_OR_CLOSE)) {
const text = m[1].replace(/\s+/g, ' ').trim() const text = m[1].replace(/\s+/g, ' ').trim()
if (!text || !WORD.test(text) || JS_CODE.test(text)) continue if (!text || !WORD.test(text) || JS_CODE.test(text) || OBJECT_KEY.test(text)) continue
if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue
console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`) console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`)
} }
@@ -21,7 +21,8 @@ buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała k
Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor / Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor /
`file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts` `file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts`
powstaje typ `CmsLink`. Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo` powstaje typ `CmsLink` (bez stylu: `CmsLinkPlain`, bez etykiety: `CmsLinkNoLabel`; wszystkie
pasują do `CmsLink`; własna nazwa: `interfaceName`). Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
(domyślnie `'media'`), `required`. (domyślnie `'media'`), `required`.
+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 2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`, (`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`. `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) 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**. + `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**.
@@ -223,7 +223,7 @@ if (!skipped('markdown') && checkedPaths.length) {
const path = checkedPaths[0] const path = checkedPaths[0]
const md = await ok(`/md${path === '/' ? '' : path}`) const md = await ok(`/md${path === '/' ? '' : path}`)
const type = md?.res.headers.get('content-type') ?? '' const type = md?.res.headers.get('content-type') ?? ''
if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts (content.md)') if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts; one language: src/app/md/[[...slug]]/route.ts (i18n.md)')
} }
if (!skipped('mcp')) { if (!skipped('mcp')) {
let mcpOk = false let mcpOk = false
+2 -1
View File
@@ -41,7 +41,8 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7), (`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`, layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`, catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
`not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md). `not-found.tsx`: `createNotFoundPage(content, { load: loadNotFoundView })` + `notFoundView.ts` z
`renderNotFoundView` (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content` 7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content`
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`, (`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
`images: buildImagesConfig()`, `images: buildImagesConfig()`,
+12
View File
@@ -38,6 +38,18 @@ własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) →
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create` przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
(nowe typy pól formularza i teksty w Notifications). (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.
**→ 1.11.1 (PROGRAMISTA §6, poz. 38–45):** usuń obejścia (komentarze `WORKAROUND ipal-kit`) — warunek
`NEXT_RUNTIME` wokół `revalidatePath`, strażnik fokusu formularza, własny motyw (→ `ThemeScript`/`ThemeSwitcher`),
własny spis treści (→ `extractHeadings` + `TableOfContents` + `headingIds`), łapanie `notFound` dla przekierowania
(→ `onMissing: 'redirectHome'`), kolor tła tylko dla JPEG w `<Media>`, typowanie przez `ButtonAppearance` zamiast
`CmsLink['appearance']` (typy linków bez stylu to teraz `CmsLinkPlain`). Cookie Settings: `buttons.save` →
`buttons.savePreferences` — w `migrate:create` wybierz **rename** kolumny, żeby zachować teksty.
## 2. Inwentaryzacja (bez zmian w kodzie) ## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik. dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
+45 -4
View File
@@ -168,15 +168,56 @@ zmienna po zmiennej. Na większe zmiany są `classNames`:
<CookieButton className="fixed bottom-6 right-6 ..." /> <CookieButton className="fixed bottom-6 right-6 ..." />
``` ```
Sloty: `root`, `primaryButton`, `secondaryButton`. Podany className zastępuje Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swój slot (1.10.0):
domyślny (nie dokleja się).
| Slot | Element |
|---|---|
| `root`, `body`, `content` | pasek, wewnętrzna szerokość, rząd tekst + przyciski |
| `text`, `icon`, `eyebrow`, `title`, `message`, `link` | blok tekstu banera |
| `actions` | rząd przycisków banera |
| `primaryButton`, `secondaryButton` | dwa style przycisków (domyślne dla wszystkich) |
| `acceptButton`, `rejectButton`, `settingsButton`, `saveButton`, `backButton` | pojedyncze przyciski — puste → `primaryButton` / `secondaryButton` |
| `overlay`, `dialog`, `closeButton` | modal ustawień (`settings="modal"`) |
| `settingsTitle`, `settingsDescription`, `categories`, `category`, `categoryTitle`, `categoryDescription` | widok ustawień |
| `control`, `controlThumb`, `badge` | checkbox / przełącznik, kciuk przełącznika, znacznik „Zawsze aktywne” |
| `settingsActions` | rząd przycisków pod kategoriami |
### Układ: kolejność przycisków, modal, przełączniki (1.10.0)
```tsx
<CookieBanner
equalChoice
icon={false} // bez ikony ciasteczka
order={['accept', 'reject', 'settings']} // przyciski banera w tej kolejności
settings="modal" // ustawienia w oknie na środku (✕, Escape, klik w tło)
controls="switch" // przełączniki role="switch" zamiast checkboxów
settingsActions={['save', 'reject', 'accept']} // przyciski pod kategoriami
classNames={{ … }}
/>
```
Domyślnie (bez tych propsów) baner wygląda i działa jak przed 1.10.0.
Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się nie pokazuje:
| Pole | Gdzie |
|---|---|
| `eyebrow` | mały napis nad tytułem banera („Prywatność i cookies”) |
| `title` | tytuł banera („Szanujemy Twoją prywatność”) |
| `settingsDescription` | opis pod tytułem ustawień |
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
| `buttons.close` | etykieta przycisku ✕ dla czytników ekranu (puste → „Close”) |
| `buttons.savePreferences` | „Zapisz” w ustawieniach (do 1.11.0 pole `save` — nazwa zarezerwowana w Mongoose; w kodzie dalej `texts.buttons.save`) |
Nowe pola w globalu = migracja w projektach na Postgres/SQLite (`payload migrate:create`); MongoDB bez zmian.
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`, `ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
`accept`, `back`, `save`. `accept`, `back`, `save`; w trybie modal także `consent-overlay`, `consent-dialog`, `close`.
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings → Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
settingsTitle** (per język) — bez tekstów na sztywno w komponentach. title** albo **settingsTitle** (per język) — bez tekstów na sztywno w komponentach. Modal ma
`aria-modal`, fokus na ✕ po otwarciu i zamyka się Escape; przełączniki mają `role="switch"` i `aria-checked`.
## Locale jako cookie functional (wbudowane) ## Locale jako cookie functional (wbudowane)
+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`).
+29 -4
View File
@@ -106,7 +106,9 @@ export const i18nConfig = {
], ],
} as const satisfies I18nConfig } as const satisfies I18nConfig
``` ```
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` (i18n.md). Strona jednojęzyczna: jeden locale, bez folderu `[locale]` — layout z `i18nConfig.defaultLocale`,
`createPageRoute` / `createNotFoundPage` bez zmian, Markdown w `app/md/[[...slug]]/route.ts` (i18n.md).
Nie zakładaj `[locale]` „na zapas” przy jednym języku — linki byłyby bez `/pl`, strony z `/pl`.
### 2.3 payload.config.ts ### 2.3 payload.config.ts
```ts ```ts
@@ -301,12 +303,23 @@ export const generateStaticParams = route.generateStaticParams // SSG → <hea
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md). świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
```tsx ```tsx
// src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers() // src/app/(frontend)/[locale]/notFoundView.ts — treść 404 z panelu w jednym języku (server action, od 1.12.0)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc' 'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content' import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry' import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, { blocks: blockRegistry /*, fallback: <h1>404</h1> */ }) export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}
// src/app/(frontend)/[locale]/not-found.tsx — 404 w języku z URL, bez headers(); treść ładowana dopiero przy 404,
// a nie w danych RSC każdej strony (pages.md → „Dlaczego leniwy”)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
``` ```
```ts ```ts
@@ -543,6 +556,18 @@ 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 | | 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 | | 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 | | 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 |
| 38 | **1.11.1** — `revalidatePath` owinięte warunkiem `process.env.NEXT_RUNTIME` (seed / `payload run` padał) | usuń warunek — hook sam pomija rewalidację poza Next; celowo: `context: { disableRevalidate: true }` | hooks.md |
| 39 | **1.11.1** — strażnik fokusu wokół `RenderForm` (strona przewijała się do formularza po powrocie) | usuń — `BuilderForm` przenosi fokus tylko przy zmianie kroku | forms.md |
| 40 | **1.11.1** — własny `ThemeScript` / przełącznik motywu / `useSyncExternalStore` na `data-theme` | `<SiteProviders theme>` (albo `<ThemeScript {...shell.theme}>`), `<ThemeSwitcher label={shell.theme.toggleLabel}>`, `useTheme`; ten sam klucz `ipal-theme` — wybór odwiedzających zostaje. Postgres: `migrate:create` (`system`, `themeToggleLabel`) | theme.md |
| 41 | **1.11.1** — własne `anchors.ts` / `TableOfContents` / konwerter nagłówków z `id` | `extractHeadings`, `<TableOfContents>` (`/client`), `RenderRichText headingIds`, `buildTableOfContentsField()` (ten sam kształt `show`/`label` — bez migracji danych) | richtext.md |
| 42 | **1.11.1** — `notFound` łapany w `page.tsx`, żeby przekierować na stronę główną | `createPageRoute(…, { redirect, onMissing: 'redirectHome' })` | pages.md |
| 43 | **1.11.1** — `<Media>` ustawia kolor tła tylko dla JPEG | usuń warunek — `mediaImageProps` robi to sam (`placeholderColor`) | storage.md |
| 44 | **1.11.1** — `CmsLink['appearance']` zastąpione własnym typem, bo typ zależał od kolejności pól | typy per kształt: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`; `pnpm generate:types` i popraw importy | links.md |
| 45 | **1.11.1** — opis formatu w etykiecie pola formularza / godzina jako tekst | pole **Placeholder** w panelu, typ **Time**; Postgres: `migrate:create` | forms.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 | | 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 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
@@ -171,7 +171,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
(zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności), (zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności),
- [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) + - [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
export const revalidate (literał), BEZ searchParams, export const revalidate (literał), BEZ searchParams,
- [locale]/not-found.tsx: createNotFoundPage(content, { blocks }) — BEZ headers() (pages.md). - [locale]/not-found.tsx: createNotFoundPage(content, { load: loadNotFoundView }) + notFoundView.ts ('use server', renderNotFoundView) — BEZ headers() (pages.md).
Plan najpierw. Plan najpierw.
``` ```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`; Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
+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). wartość w bazie jest plaintext (musi być odzyskiwalna do autentykacji SMTP/R2).
Chroni przed patrzeniem przez ramię i przypadkowym pokazaniem panelu. Chroni przed patrzeniem przez ramię i przypadkowym pokazaniem panelu.
Podpięte przez `admin.components.Field: '@intecion/ipal-kit/client#MaskedField'`. Podpięte przez `admin.components.Field: '@intecion/ipal-kit/admin#MaskedField'`.
Działa na dowolnym polu `text`. Po wpięciu w projekcie może być konieczne Działa na dowolnym polu `text`. Po wpięciu w projekcie może być konieczne
`payload generate:importmap`, żeby panel rozpoznał komponent. `payload generate:importmap`, żeby panel rozpoznał komponent.
+1
View File
@@ -49,6 +49,7 @@ używasz).
```ts ```ts
ipalEnvRules({ ipalEnvRules({
storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL) 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) emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER)
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, turnstile?: boolean | { siteKeyVar?: string; secretVar?: string },
serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL' serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL'
+74 -4
View File
@@ -43,7 +43,7 @@ ipalKit({
forms: { forms: {
redirectRelationships: ['pages'], // formularz może przekierować na Page redirectRelationships: ['pages'], // formularz może przekierować na Page
// fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date, // fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
// // select, radio, checkbox, checkboxGroup, message, step // // time, select, radio, checkbox, checkboxGroup, message, step
}, },
}) })
``` ```
@@ -80,14 +80,20 @@ formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładk
ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient). ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient).
### Typy pól w panelu ### Typy pól w panelu
text, email, textarea, number, **date**, select, **radio**, checkbox, **Checkbox group**, text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`. message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea i number mają lokalizowane pole „Placeholder” — podpowiedź
w pustym polu („np. 10:00–12:00”). `BuilderForm` i `useBuilderForm` (`getInputProps`, `getTextareaProps`)
przekazują je same. Własny blok z tym polem: `withPlaceholder(block)` / `placeholderField` z roota;
blok godziny: `timeBlock`. Nowe pola w blokach formularzy = migracja (`pnpm payload migrate:create`).
| Typ | Wartość | Serwer sprawdza | | Typ | Wartość | Serwer sprawdza |
|---|---|---| |---|---|---|
| radio, select | jedna wartość | tylko wartości z panelu | | radio, select | jedna wartość | tylko wartości z panelu |
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` | | Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | prawdziwa data | | date | `YYYY-MM-DD` | prawdziwa data |
| time | `HH:MM` (`<input type="time">`) | godzina 00:00–23:59 |
| Step | — (podział) | nie jest polem | | Step | — (podział) | nie jest polem |
### Formularz krokowy ### Formularz krokowy
@@ -96,6 +102,53 @@ Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`. na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
### Pola i kroki warunkowe („Show only when”)
Każdy blok formularza (wbudowane, **Checkbox group**, **Step**, message) ma w panelu grupę
**Show only when** (`showWhen`): `field` — nazwa techniczna innego pola, `values` — wartości opcji
po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `field` = zawsze widoczne.
- Na polu: pole pokazuje się dopiero przy pasującej odpowiedzi (np. „Z czego wynika termin?”
tylko przy `deadline = fixed`).
- Na **Step**: cały krok (z polami) wypada, gdy warunek nie pasuje — kolejne kroki się przenumerowują
(„Krok 2 z 3”). Tak buduje się brief: ekran 1 wybiera obszary (Checkbox group), każdy następny
Step ma `showWhen: { field: 'areas', values: 'web' }`.
- Pole w ukrytym kroku jest ukryte, nawet gdy jego warunek pasuje; warunek wskazujący ukryte pole też
nie pasuje. Nazwa nieistniejącego pola (literówka) albo cykl ukrywa pole — widać to w podglądzie.
- Wspólna reguła `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — przeglądarka
(`useBuilderForm`/`BuilderForm`: co pokazać, walidować i wysłać) i serwer (`validateSubmission`):
ukryte pole **nie jest wymagane i nie jest zapisywane**, nawet gdy ktoś je dośle ręcznie.
Wyjątek: pole zgody RODO (`consent`) jest egzekwowane zawsze — warunkiem nie da się go wyłączyć.
- Typ `FieldCondition` (`{ field, values }`) dla własnego markupu na `useBuilderForm`; `splitSteps(fields, isShown)`
pomija ukryte pola i kroki, zachowując oryginalny `index` (bloki message renderują się po nim).
- Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy →
po aktualizacji wygeneruj migrację (`payload migrate:create`).
### 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 ### Formularz nietypowy — bez kopiowania silnika
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola: 1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`. `renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
@@ -105,7 +158,7 @@ na krok z tym polem. Teksty przycisków: Notifications → Form messages → `ne
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`, `getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`. `TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`, 3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola). `validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać. `useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
@@ -187,7 +240,24 @@ email: mailAdapter(), // z '@intecion/ipal-kit' — SMTP albo Graph wg panelu
Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i
treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu. treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu.
`submitForm` odpowiada tylko za weryfikację Turnstile i zapis. `submitForm` odpowiada tylko za weryfikację Turnstile i zapis. Zgłoszenie zapisuje w języku strony
(`locale` z `createSubmitAction`), więc form-builder bierze teksty maili i etykiety w tym języku.
### Ładne maile (`emailLayout`)
```ts
forms: { emailLayout: true } // opcjonalnie: beforeEmail: (emails, args) => emails (po layoucie)
```
- `{{*:table}}` zamienia się w **czytelne podsumowanie**: treść pytania zamiast nazwy pola, etykiety opcji
zamiast wartości (także Checkbox group), zaznaczony checkbox = ✓, puste odpowiedzi pominięte, grupy według
kroków (tytuły Step). Tylko pola, które odwiedzający widział (ukrytych warunkiem serwer nie zapisuje).
- Każdy mail dostaje **szablon** (tabele + inline CSS — Gmail, Outlook, Apple Mail): nagłówek z logo,
treść z panelu, stopka. Ustawienia: **Site Settings → Emails** — logo (**PNG/JPG**, SVG nie działa w
Gmailu/Outlooku; puste = nazwa strony), kolor akcentu (hex), stopka (per język). Link do strony i
absolutny adres logo z `serverURL` w `buildConfig` (ustaw go z `NEXT_PUBLIC_SERVER_URL`).
- Błąd przy składaniu szablonu nigdy nie blokuje wysyłki — idzie oryginalny mail, błąd w logu.
- Nowa zakładka = migracja w projekcie (`payload migrate:create`).
## Własne pola w kolekcji formularzy ## Własne pola w kolekcji formularzy
+5
View File
@@ -37,6 +37,11 @@ by wywaliło Payload przy generate:importmap / czystym Node). Projekt podaje.
Obsługuje: wszystkie języki, root (home), zmianę slug (rewaliduje stary I nowy Obsługuje: wszystkie języki, root (home), zmianę slug (rewaliduje stary I nowy
path — stary URL nie serwuje starej treści), delete. path — stary URL nie serwuje starej treści), delete.
**Poza serwerem Next** (1.11.1) hook nic nie robi: `pnpm payload run`, seed przez `tsx`, migracje —
brak `process.env.NEXT_RUNTIME`. Wcześniej Next rzucał `Invariant: static generation store missing`
i seed padał. Celowe pominięcie (masowy import w aplikacji): `context: { disableRevalidate: true }`
w wywołaniu Local API.
--- ---
## setPublishedAtHook — auto-data publikacji ## setPublishedAtHook — auto-data publikacji
+37 -39
View File
@@ -206,42 +206,38 @@ app/(frontend)/[locale]/
[[...slug]]/page.tsx # /pl/o-nas, /en/about [[...slug]]/page.tsx # /pl/o-nas, /en/about
``` ```
### Layout jednojęzyczny — locale z config ### Layout, strona, 404, Markdown — te same helpery, bez `[locale]`
```tsx ```tsx
// app/(frontend)/layout.tsx (bez [locale]) // app/(frontend)/layout.tsx
import { i18nConfig } from '@/i18n.config' import { i18nConfig } from '@/i18n.config'
export default async function Layout({ children }: { children: React.ReactNode }) { export default async function Layout({ children }: { children: React.ReactNode }) {
const locale = i18nConfig.defaultLocale // stałe, nie z params const locale = i18nConfig.defaultLocale // stałe, nie z params
const settings = await getSettings(locale) return (
// ...reszta jak zwykle, ale locale jest stałe <html lang={locale}><body>
return <html lang={locale}>...</html> <SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent">{children}</SiteProviders>
</body></html>
)
} }
// app/(frontend)/[[...slug]]/page.tsx — createPageRoute bierze język z config, gdy nie ma go w params
export const revalidate = 3600
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
// app/(frontend)/not-found.tsx (+ notFoundView.ts z server action — pages.md)
export default createNotFoundPage(content, { load: loadNotFoundView })
// app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
``` ```
Linki (`resolveLink`, `resolveNav`, `getSystemLinks`), sitemap, canonical, llms.txt i MCP dają adresy
### Strony jednojęzyczne — locale z config bez `/pl` same — decyduje liczba języków w `i18n.config.ts`, nie struktura folderów.
(Trasa `md/[locale]/[[...slug]]` na stronie jednojęzycznej też obsłuży podstrony, ale nie `/md` —
```tsx dlatego tu `md/[[...slug]]`.)
// app/(frontend)/[[...slug]]/page.tsx (bez [locale])
import { i18nConfig } from '@/i18n.config'
export async function generateMetadata({ params }) {
const { slug } = await params // TYLKO slug, nie locale
const locale = i18nConfig.defaultLocale // stałe
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
}
export default async function Page({ params }) {
const { slug } = await params
const locale = i18nConfig.defaultLocale // stałe
const route = await resolveRoute(locale, slug ?? [], pageNum)
// ...
}
```
resolveRoute i inne helpery działają bez zmian — dostają stałe locale z config
zamiast z URL. Cała różnica to: brak `[locale]` w strukturze, locale z config.
### Middleware/proxy — jednojęzyczny prawie go nie potrzebuje ### Middleware/proxy — jednojęzyczny prawie go nie potrzebuje
@@ -249,17 +245,19 @@ Dla jednego locale middleware jest pass-through (nic nie przekierowuje). Możesz
go pominąć albo zostawić — plugin i tak wykryje 1 locale i przepuści. Bez go pominąć albo zostawić — plugin i tak wykryje 1 locale i przepuści. Bez
przełącznika języka (jeden język), bez cookie NEXT_LOCALE (nie ma co pamiętać). przełącznika języka (jeden język), bez cookie NEXT_LOCALE (nie ma co pamiętać).
### Przejście jedno- → wielojęzyczny (later) ### Przejście jedno- → wielojęzyczny (później)
Jeśli klient później doda drugi język, to PRZEBUDOWA, nie przełącznik: O prefiksie decyduje **liczba języków w `i18n.config.ts`**: jeden język = adresy bez `/pl` (linki,
- dodaj locale do config sitemap, canonical), dwa i więcej = z prefiksem. Struktury `[locale]` przy jednym języku **nie
- przenieś strukturę do `[locale]/` zakładaj na zapas** — plugin generowałby linki `/kontakt`, a strony byłyby pod `/pl/kontakt`.
- layout/strony czytają locale z params
- wróci prefiks `/pl`, `/en` + hreflang
Warto to przewidzieć na starcie: jeśli jest szansa na drugi język, rozważ od razu Gdy klient doda drugi język:
strukturę wielojęzyczną (z [locale]), nawet dla jednego locale — wtedy prefiks 1. dodaj język do `i18n.config.ts` (i `localization` w Payload przez `ipalKit`),
`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury. 2. przenieś `app/(frontend)/*` do `app/(frontend)/[locale]/`, a `app/md/[[...slug]]` do `app/md/[locale]/[[...slug]]`,
3. layout bierze `locale` z `params` (PROGRAMISTA §2.8) — `createPageRoute` / `createNotFoundPage` bez zmian,
4. przetłumacz slugi i treści w panelu.
Linki, sitemap, hreflang i canonical przełączą się same. Stare adresy (`/kontakt`) proxy przekieruje
na `/pl/kontakt`, więc linki z Google i wizytówek dalej działają.
## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher) ## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher)
+14 -1
View File
@@ -51,10 +51,23 @@ puste → „Feature 02”. Komponent: `@intecion/ipal-kit/admin#RowLabel`. Zasa
Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`, Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`,
`#anchor` · `file` upload), `page`, `url`, `file`, `label` (localized), `newTab`, `#anchor` · `file` upload), `page`, `url`, `file`, `label` (localized), `newTab`,
`appearance`. W `payload-types.ts` powstaje typ **`CmsLink`**. `appearance`. W `payload-types.ts` powstaje typ **`CmsLink`**; link bez stylu (`appearances: false`)
ma typ `CmsLinkPlain`, bez etykiety (`disableLabel`) — `CmsLinkNoLabel`, oba naraz — `CmsLinkPlainNoLabel`
(od 1.11.1; wcześniej wszystkie nazywały się `CmsLink` i typ zależał od kolejności pól). Każdy z nich
pasuje do `CmsLink`, więc `CMSLink` przyjmuje je bez zmian. Różne listy `appearances` albo `relationTo`
w jednym projekcie → nadaj własną nazwę: `buildLinkField({ interfaceName: 'CategoryLink', … })`.
Plik do pobrania to link typu `file` — **nie** osobne pole `pdfUrl`. 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 ## href
```ts ```ts
+47 -8
View File
@@ -62,24 +62,63 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo** - stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`. - nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt — `app/(frontend)/[locale]/not-found.tsx`, jedna linia (od 1.9.2): Projekt — dwa pliki w `app/(frontend)/[locale]/` (od 1.12.0, **wariant leniwy — zalecany**):
```tsx ```ts
import { createNotFoundPage } from '@intecion/ipal-kit/rsc' // notFoundView.ts — server action z treścią 404 w JEDNYM języku
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content' import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry' import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, { export async function loadNotFoundView(locale: string) {
blocks: blockRegistry, return renderNotFoundView(content, {
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …) blocks: blockRegistry,
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }), fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
}) // blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
}, locale)
}
```
```tsx
// not-found.tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
(`fallback` z JSX → plik `notFoundView.tsx`.)
**Dlaczego leniwy:** Next wkłada drzewo `not-found` layoutu do danych RSC (`self.__next_f`) **każdej** strony
pod nim — router potrzebuje go do 404 po stronie klienta. Wariant natychmiastowy renderuje tam stronę 404 z panelu
w każdym języku, więc każda strona wiezie ją w HTML (404 = strona główna przy 2 językach: HTML strony głównej
195 → 146 KB gzip, strony kontaktu 153 → 104 KB). W wariancie leniwym w danych jest tylko `<NotFoundLoader>`
(`/client`); treść przychodzi z server action dopiero, gdy 404 się wyświetla. Język z adresu (`/en/...`);
`renderNotFoundView` przyjmuje tylko skonfigurowane języki (inne → domyślny). Status 404 bez zmian; treść
pojawia się po hydratacji (strona 404 i tak nie jest indeksowana).
Wariant natychmiastowy (do 1.11.x jedyny) — treść już w HTML, za cenę rozmiaru każdej strony:
```tsx
export default createNotFoundPage(content, { blocks: blockRegistry, fallback: <h1>404</h1> })
``` ```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`). 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, Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna. (`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
Opcja `redirect` (z `next/navigation`) włącza tryb „strona w budowie” — [construction.md](./construction.md).
**Brak strony → strona główna** (1.11.1): `onMissing: 'redirectHome'` (wymaga `redirect`) — adres bez strony
i bez starego sluga (np. wycofane `/pl/uslugi`) przekierowuje (307) na stronę główną w tym samym języku
(System Pages → Homepage). Bez przypisanej strony głównej albo gdy brakuje jej samej → zwykłe 404.
Domyślnie `'notFound'`; własna decyzja: `onMissing: ({ locale, segments }) => redirect(…)`.
```tsx
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect, onMissing: 'redirectHome' })
```
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma): Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
+30
View File
@@ -53,6 +53,36 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta
(listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload. (listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload.
## Spis treści i kotwice nagłówków (1.11.1)
Długie dokumenty (polityka prywatności, regulamin) — spis treści z linkami do sekcji.
Id nagłówków w spisie i w treści liczy ta sama funkcja, więc się nie rozjadą.
```tsx
// config bloku
import { buildTableOfContentsField } from '@intecion/ipal-kit'
fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }] // grupa tableOfContents: show, label
// komponent bloku (RSC)
import { extractHeadings, RenderRichText } from '@intecion/ipal-kit/rsc'
import { TableOfContents } from '@intecion/ipal-kit/client'
const items = block.tableOfContents?.show ? extractHeadings(block.content) : [] // [{ id, text, level }]
{items.length ? <TableOfContents items={items} label={block.tableOfContents?.label} classNames={tocClasses} /> : null}
<RenderRichText data={block.content} converters={converters} headingIds={{ className: 'scroll-mt-24' }} />
```
- `extractHeadings(content, { levels: ['h2'] })` — nagłówki w kolejności z tekstu; id = `toSlug(tekst)`,
powtórzenia `-2`, `-3`, puste nagłówki pomijane. Także z roota: `import { extractHeadings, headingText } from '@intecion/ipal-kit'`.
- `RenderRichText headingIds` — `true` (h2) albo `{ levels, className }`. Twój konwerter `heading` dalej
renderuje nagłówek; plugin dokłada `id` (i `className`, np. `scroll-mt-*` pod przyklejonym nagłówkiem).
- `<TableOfContents>` — bez stylów: `<nav aria-label={label}>` + `<ol>` linków. Serwer renderuje całą listę
(działa bez JS); w przeglądarce link czytanej sekcji dostaje `aria-current="location"` i `classNames.linkActive`.
`classNames`: `nav`, `label`, `list`, `item`, `link`, `linkActive`; `offset` (domyślnie 0.3 wysokości ekranu);
`data-ipal="toc"`, `data-level` na pozycjach.
- `buildTableOfContentsField()` — przełącznik „Show table of contents” + lokalizowana etykieta (typ `TableOfContentsSettings`).
Nowe pole w bloku = migracja (`pnpm payload migrate:create`).
## lexicalToMarkdown — richText → Markdown (dla AI) ## lexicalToMarkdown — richText → Markdown (dla AI)
Do czytelności dla agentów AI (Markdown per strona, llms-full) potrzebny jest Do czytelności dla agentów AI (Markdown per strona, llms-full) potrzebny jest
+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 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`: trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`:
`<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />`. `<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 - **`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: globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala:
`getLink` / `getChildren`. `getLink` / `getChildren`.
+29 -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 Bez tego media wgrają się do R2, ale front pokaże 403. Konfiguracja domeny jest
po stronie Cloudflare, publiczny URL po stronie projektu (.env). 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 ## Migracja istniejących mediów
Jeśli projekt miał media lokalnie i przełączasz na R2 — nowe uploady idą do R2, Jeśli projekt miał media lokalnie i przełączasz na R2 — nowe uploady idą do R2,
@@ -315,9 +336,16 @@ env, komponent podąża automatycznie.
- `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu, - `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu,
`lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point → `lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point →
`object-position`, placeholder blur + kolor. `MEDIA_SIZES` — podpowiedzi `sizes`. `object-position`, placeholder blur + kolor. `MEDIA_SIZES` — podpowiedzi `sizes`.
Kolor tła (`style.backgroundColor`) zostaje na `<img>` po załadowaniu, więc od 1.11.1 tylko dla JPEG
(`placeholderColor: 'auto'`) — przezroczyste PNG/SVG/WebP (logotypy, ikony) nie mają już tła.
`placeholderColor: true` wymusza kolor (nieprzezroczyste PNG/WebP), `false` wyłącza. Hook nie zapisuje
koloru dla obrazów z przezroczystością (`color: null`).
- `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`. - `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`.
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy - `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
uploadzie przez `sharp` z configu. Postgres: `migrate:create`. 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. - `<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). - `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów).
+85
View File
@@ -0,0 +1,85 @@
# Motyw jasny / ciemny (1.11.1)
Logika motywu z pluginu, wygląd w projekcie. Plugin daje: skrypt przed malowaniem (bez mignięcia
jasnego motywu), przełącznik bez stylów, hook `useTheme`, pola w Site Settings → Theme i motyw
widżetu Turnstile zgodny ze stroną.
## Jak to działa
- Strony są ISR/SSG — jeden HTML dla wszystkich, więc motyw **nie** trafia do HTML z serwera.
- `<ThemeScript>` (skrypt inline, pierwsze dziecko `<body>`) ustawia `data-theme="light|dark"` i
`color-scheme` na `<html>` przed pierwszym malowaniem.
- Kolejność: wybór odwiedzającego z `localStorage` (klucz `ipal-theme`, tylko gdy „Allow theme toggle”)
→ Site Settings → Default theme → przy `System` ustawienie urządzenia (`prefers-color-scheme`).
- `localStorage`, nie cookie: to preferencja interfejsu, nie śledzi i nie wymaga zgody.
- Zmiana w jednej karcie przechodzi do pozostałych (zdarzenie `storage`).
## Site Settings → Theme
| Pole | Znaczenie |
|---|---|
| `defaultTheme` | `light` · `dark` · `system` (od 1.11.1) |
| `allowThemeToggle` | pokazuj przełącznik; wybór odwiedzającego jest pamiętany |
| `themeToggleLabel` | nazwa przełącznika dla czytników ekranu, np. „Tryb ciemny” (localized, od 1.11.1) |
`getSiteShell(locale).theme` → `{ defaultTheme, allowToggle, toggleLabel }` (`themeConfigFrom(settings)` z roota).
## Podpięcie
```tsx
// src/app/(frontend)/[locale]/layout.tsx
const shell = await getSiteShell(locale)
return (
<html lang={locale} suppressHydrationWarning>
<body>
<SiteProviders shell={shell} theme> {/* theme → <ThemeScript> na początku */}
<Header themeLabel={shell.theme.allowToggle ? shell.theme.toggleLabel : null} … />
…
```
Bez `SiteProviders`: `import { ThemeScript } from '@intecion/ipal-kit/rsc'` i `<ThemeScript {...shell.theme} />`
jako pierwsze dziecko `<body>`. `suppressHydrationWarning` na `<html>` jest potrzebne — atrybut różni się
od HTML z serwera celowo.
```tsx
// przełącznik ('use client' albo w RSC — sam jest komponentem klienckim)
import { ThemeSwitcher } from '@intecion/ipal-kit/client'
<ThemeSwitcher
label={themeLabel}
classNames={{
root: 'inline-flex rounded-full border p-0.5',
light: 'rounded-full p-2 bg-white dark:bg-transparent',
dark: 'rounded-full p-2 dark:bg-surface-raised',
}}
// renderIcon={(t) => (t === 'light' ? <SunIcon /> : <MoonIcon />)} // domyślnie lucide Sun / Moon
/>
```
`<button role="switch" aria-checked>` (zaznaczony = ciemny). Który przycisk wygląda na aktywny, ustala CSS
z atrybutu na `<html>` (`dark:`), nie stan Reacta — po hydratacji nic nie przeskakuje.
Haki: `data-ipal="theme-switch"`, `data-ipal-theme-icon="light|dark"`.
Własny przełącznik: `useTheme()` → `{ theme, setTheme, toggle }` (`theme` = `null` na serwerze);
`applyTheme(theme, { persist, transitionMs })`, `readDocumentTheme()`, stałe `THEME_ATTRIBUTE`,
`THEME_STORAGE_KEY`, `THEME_SWITCHING_ATTRIBUTE`, `isTheme` z `/client`. Z roota także
`isThemeSetting` i `themeScript({ allowToggle, defaultTheme })` (sam tekst skryptu).
## CSS (Tailwind 4)
```css
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
/* płynne przejście kolorów tylko w chwili przełączenia (applyTheme: data-theme-switching, 300 ms) */
[data-theme-switching] *, [data-theme-switching] *::before, [data-theme-switching] *::after {
transition: background-color 0.3s, border-color 0.3s, color 0.3s, fill 0.3s !important;
}
```
Tokeny ciemnego motywu (`surface`, `fg`…) zostają w `styles.css` projektu.
## Turnstile
`BuilderForm` / `RenderForm` → `turnstileTheme` domyślnie `'page'`: widżet bierze motyw strony
(`data-theme`); bez motywu strony — `'auto'` (motyw urządzenia), jak przed 1.11.1. Zmiana motywu
rysuje widżet od nowa (token trzeba zdobyć ponownie). Stały motyw: `turnstileTheme="light"`.
+4 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@intecion/ipal-kit", "name": "@intecion/ipal-kit",
"version": "1.9.4", "version": "1.12.0",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", "description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
@@ -57,6 +57,9 @@
"docs", "docs",
"bin" "bin"
], ],
"sideEffects": [
"**/*.css"
],
"scripts": { "scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc", "build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths", "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
+7 -4
View File
@@ -1,10 +1,13 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/** /**
* Entry point: @intecion/ipal-kit/admin * Entry point: @intecion/ipal-kit/admin
* *
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's * Admin-panel UI components (white-label branding, array row labels, integration fields and
* importMap can resolve them by a stable path when ipalKit injects * banners). Separate export so Payload's importMap can resolve them by a stable path, and so
* admin.components.graphics.Logo/Icon. * nothing importing @payloadcms/ui ends up in /client — that entry ships to every site visitor.
*/ */
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js' export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
+15 -6
View File
@@ -1,6 +1,4 @@
'use client' 'use client'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js' export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js' export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js' export { Analytics } from '../modules/analytics/client.js'
@@ -23,10 +21,13 @@ export {
useConsent, useConsent,
useConsentContext, useConsentContext,
} from '../modules/consent/client.js' } from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js' export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js' export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js' export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js' export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type { export type {
BuilderField, BuilderField,
BuilderFormAction, BuilderFormAction,
@@ -34,6 +35,7 @@ export type {
BuilderFormTexts, BuilderFormTexts,
BuilderOption, BuilderOption,
BuilderStep, BuilderStep,
FieldCondition,
} from '../modules/forms/builderTypes.js' } from '../modules/forms/builderTypes.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js' export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js' export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
@@ -73,9 +75,16 @@ export {
useSetAlternateLinks, useSetAlternateLinks,
} from '../modules/i18n/index.js' } from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { LocaleView } from '../modules/pages/LocaleView.js' export { LocaleView } from '../modules/pages/LocaleView.js'
export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js'
export { TableOfContents } from '../modules/richtext/TableOfContents.js'
export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js' export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { isTheme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from '../modules/theme/theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from '../modules/theme/theme.js'
export { ThemeSwitcher } from '../modules/theme/ThemeSwitcher.js'
export type { ThemeSwitcherClassNames, ThemeSwitcherProps } from '../modules/theme/ThemeSwitcher.js'
export { applyTheme, readDocumentTheme, useTheme } from '../modules/theme/useTheme.js'
export { Turnstile } from '../modules/turnstile/client.js' export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js' export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js' export type { TurnstileProps, TurnstileTheme } from '../modules/turnstile/client.js'
+7 -4
View File
@@ -14,15 +14,18 @@ export type {
} from '../modules/blocks/index.js' } from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js' export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js' export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderForm } from '../modules/forms/RenderForm.js' export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js'
export type { RenderFormProps, SendFormAction } 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 // Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself). // pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js' export { createNotFoundPage, createPageRoute, renderNotFoundView } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js' export type { NotFoundPageOptions, NotFoundViewOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { SiteProviders } from '../modules/frontend/SiteProviders.js' export { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js' export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { extractHeadings } from '../modules/richtext/headings.js'
export { RenderRichText } from '../modules/richtext/index.js' export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js' export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js' export { JsonLdGraph } from '../modules/seo/index.js'
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js' export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'
export { ThemeScript } from '../modules/theme/ThemeScript.js'
export type { ThemeScriptProps } from '../modules/theme/ThemeScript.js'
+40 -1
View File
@@ -22,6 +22,22 @@ export const cookieSettingsFields: Field[] = [
min: 1, min: 1,
required: true, required: true,
}, },
{
name: 'eyebrow',
type: 'text',
admin: {
description: 'Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.',
},
localized: true,
},
{
name: 'title',
type: 'text',
admin: {
description: 'Banner heading, e.g. "We respect your privacy". Empty → not shown.',
},
localized: true,
},
{ {
name: 'message', name: 'message',
type: 'textarea', type: 'textarea',
@@ -38,6 +54,22 @@ export const cookieSettingsFields: Field[] = [
}, },
localized: true, localized: true,
}, },
{
name: 'settingsDescription',
type: 'textarea',
admin: {
description: 'Intro under the settings heading — what cookies are for and that the choice can be changed later.',
},
localized: true,
},
{
name: 'alwaysActiveLabel',
type: 'text',
admin: {
description: 'Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.',
},
localized: true,
},
{ {
name: 'privacyLinkLabel', name: 'privacyLinkLabel',
type: 'text', type: 'text',
@@ -57,8 +89,15 @@ export const cookieSettingsFields: Field[] = [
{ name: 'acceptAll', type: 'text', localized: true }, { name: 'acceptAll', type: 'text', localized: true },
{ name: 'reject', type: 'text', localized: true }, { name: 'reject', type: 'text', localized: true },
{ name: 'settings', type: 'text', localized: true }, { name: 'settings', type: 'text', localized: true },
{ name: 'save', type: 'text', localized: true }, // Not `save`: Mongoose reserves that path name and warns on every start/build.
{ name: 'savePreferences', type: 'text', label: 'Save', localized: true },
{ name: 'back', type: 'text', localized: true }, { name: 'back', type: 'text', localized: true },
{
name: 'close',
type: 'text',
admin: { description: 'Screen-reader label of the ✕ button in the settings dialog.' },
localized: true,
},
], ],
}, },
{ {
+2 -2
View File
@@ -64,7 +64,7 @@ export const smtpFields: Field[] = [
description: 'SMTP account password.', description: 'SMTP account password.',
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth. // Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
components: { components: {
Field: '@intecion/ipal-kit/client#MaskedField', Field: '@intecion/ipal-kit/admin#MaskedField',
}, },
}, },
}, },
@@ -87,7 +87,7 @@ export const smtpFields: Field[] = [
type: 'ui', type: 'ui',
admin: { admin: {
components: { components: {
Field: '@intecion/ipal-kit/client#TestEmailButton', Field: '@intecion/ipal-kit/admin#TestEmailButton',
}, },
}, },
}, },
@@ -27,7 +27,7 @@ export const turnstileFields: Field[] = [
description: 'Secret key used for server-side verification.', description: 'Secret key used for server-side verification.',
// Masked in the UI (••••) — stored plaintext, readable for verification. // Masked in the UI (••••) — stored plaintext, readable for verification.
components: { components: {
Field: '@intecion/ipal-kit/client#MaskedField', Field: '@intecion/ipal-kit/admin#MaskedField',
}, },
}, },
}, },
+12 -1
View File
@@ -12,12 +12,13 @@ export const themeFields: Field[] = [
name: 'defaultTheme', name: 'defaultTheme',
type: 'select', type: 'select',
admin: { admin: {
description: 'Theme applied on a visitor’s first visit.', description: 'Theme applied on a visitor’s first visit. System = the visitor’s device setting.',
}, },
defaultValue: 'light', defaultValue: 'light',
options: [ options: [
{ label: 'Light', value: 'light' }, { label: 'Light', value: 'light' },
{ label: 'Dark', value: 'dark' }, { label: 'Dark', value: 'dark' },
{ label: 'System', value: 'system' },
], ],
required: true, required: true,
}, },
@@ -29,4 +30,14 @@ export const themeFields: Field[] = [
}, },
defaultValue: true, defaultValue: true,
}, },
{
name: 'themeToggleLabel',
type: 'text',
admin: {
condition: (data) => Boolean(data?.allowThemeToggle),
description: 'Name of the switch read by screen readers, e.g. "Dark mode".',
},
label: 'Toggle label',
localized: true,
},
] ]
+8
View File
@@ -6,6 +6,10 @@ import { themeFields } from './fields/theme.js'
type BuildSiteSettingsArgs = { type BuildSiteSettingsArgs = {
/** Extra fields injected by the client project */ /** Extra fields injected by the client project */
additionalFields?: Field[] additionalFields?: Field[]
/** "Under construction" tab (developer tool) — given when the pages module is on. */
constructionFields?: Field[]
/** "Emails" tab — given with `forms: { emailLayout: true }`. */
emailFields?: Field[]
/** /**
* Fields for the "System Pages" tab — page assignments by role (homepage, * Fields for the "System Pages" tab — page assignments by role (homepage,
* privacy policy, collection archives). Assembled by the caller, which is the * privacy policy, collection archives). Assembled by the caller, which is the
@@ -30,6 +34,8 @@ type BuildSiteSettingsArgs = {
*/ */
export function buildSiteSettings({ export function buildSiteSettings({
additionalFields, additionalFields,
constructionFields,
emailFields,
systemPageFields, systemPageFields,
}: BuildSiteSettingsArgs = {}): GlobalConfig { }: BuildSiteSettingsArgs = {}): GlobalConfig {
return { return {
@@ -55,6 +61,8 @@ export function buildSiteSettings({
...(systemPageFields?.length ...(systemPageFields?.length
? [{ fields: systemPageFields, label: 'System Pages' }] ? [{ fields: systemPageFields, label: 'System Pages' }]
: []), : []),
...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []),
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []), ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
], ],
}, },
+13 -6
View File
@@ -42,6 +42,9 @@ export {
updateConsent, updateConsent,
} from './modules/consent/index.js' } from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js' export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export { export {
archiveFieldName, archiveFieldName,
@@ -77,9 +80,9 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys). // Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js' export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js' export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js' export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.js' export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder). // Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js' export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -105,7 +108,7 @@ export {
required, required,
} from './modules/forms/validators.js' } from './modules/forms/validators.js'
export type { Rule } 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' export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip). // Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js' export { createHealthRoute } from './modules/health/index.js'
@@ -169,12 +172,14 @@ export {
SITE_INTEGRATIONS_SLUG, SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG, SITE_SETTINGS_SLUG,
} from './modules/payload/index.js' } from './modules/payload/index.js'
export { buildTableOfContentsField, extractHeadings, headingText } from './modules/richtext/headings.js'
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
// Lexical → Markdown (pure, no React) — for AI-readable output. // Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js' export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js' export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js' export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js' export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
@@ -215,7 +220,7 @@ export { buildSummaryField } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } 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. // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' 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 { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } 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' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
@@ -225,6 +230,8 @@ export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js' export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js' export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js' export { buildR2Storage } from './modules/storage/index.js'
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, themeConfigFrom, themeScript } from './modules/theme/index.js'
export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify, // Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'. // which imports 'server-only'.
export { getTurnstileConfig } from './modules/turnstile/config.js' export { getTurnstileConfig } from './modules/turnstile/config.js'
+273 -80
View File
@@ -1,19 +1,76 @@
'use client' 'use client'
import { Cookie } from 'lucide-react' import { Cookie } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js' import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js' import { useConsentContext } from './ConsentContext.js'
import { useIsMounted } from './useIsMounted.js' import { useIsMounted } from './useIsMounted.js'
/** A button on the banner (first level). */
export type CookieBannerAction = 'accept' | 'reject' | 'settings'
/** A button under the category list (settings view). */
export type CookieSettingsAction = 'accept' | 'back' | 'reject' | 'save'
/** /**
* Optional class overrides — for when tokens aren't enough, e.g. turning the * Optional class overrides — for when tokens aren't enough, e.g. turning the
* bottom bar into a centred modal. Replaces the slot's classes outright. * bottom bar into a centred modal. Each slot replaces its default classes
* outright. Per-button slots (acceptButton, rejectButton…) fall back to
* primaryButton / secondaryButton, so styling those two still restyles all.
*/ */
export type CookieBannerClassNames = { export type CookieBannerClassNames = {
/** Button "Accept all" — falls back to primaryButton. */
acceptButton?: string
/** Button row on the banner. */
actions?: string
/** Settings view: button "Back" (closes the dialog in modal mode) — falls back to secondaryButton. */
backButton?: string
/** Settings view: badge next to Necessary (CookieSettings → alwaysActiveLabel). */
badge?: string
/** Banner inner wrapper (width / centring). */
body?: string
/** Settings view: list of categories. */
categories?: string
/** Settings view: one category row/card. */
category?: string
categoryDescription?: string
categoryTitle?: string
/** Settings dialog (modal mode): the ✕ button. */
closeButton?: string
/** Banner: text + buttons row. */
content?: string
/** Settings view: the switch track or the checkbox. */
control?: string
/** Settings view: the switch knob (controls="switch"). */
controlThumb?: string
/** Settings dialog box (modal mode). */
dialog?: string
/** Small label above the banner title (CookieSettings → eyebrow). */
eyebrow?: string
/** Cookie icon next to the banner text and the settings title. */
icon?: string
/** Privacy-policy link inside the message. */
link?: string
message?: string
/** Backdrop behind the settings dialog (modal mode). */
overlay?: string
primaryButton?: string primaryButton?: string
/** Button "Reject" — falls back to primaryButton with equalChoice, else secondaryButton. */
rejectButton?: string
root?: string root?: string
/** Settings view: button "Save preferences" — falls back to primaryButton. */
saveButton?: string
secondaryButton?: string secondaryButton?: string
/** Settings view: button row under the categories. */
settingsActions?: string
/** Button "Settings" on the banner — falls back to secondaryButton. */
settingsButton?: string
/** Settings view: intro under the title (CookieSettings → settingsDescription). */
settingsDescription?: string
settingsTitle?: string
/** Banner: block with eyebrow, title and message. */
text?: string
/** Banner heading (CookieSettings → title). */
title?: string
} }
/** /**
@@ -35,131 +92,267 @@ export type CookieBannerClassNames = {
* *
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and * Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
* exposing them as tokens would mean re-inventing CSS one variable at a time. * exposing them as tokens would mean re-inventing CSS one variable at a time.
* For a different layout use classNames (every element has a slot).
*/ */
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]' const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]' const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]' const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
const accent = 'text-[var(--ipal-primary,#2563eb)]' const accent = 'text-[var(--ipal-primary,#2563eb)]'
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
const primaryBg = 'bg-[var(--ipal-primary,#2563eb)]'
const defaults = { const defaults: Required<CookieBannerClassNames> = {
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`, acceptButton: '',
actions: 'flex shrink-0 gap-2',
backButton: '',
badge: `shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${border} ${accent}`,
body: 'mx-auto max-w-4xl',
categories: 'flex flex-col gap-3',
category: 'flex items-start justify-between gap-4',
categoryDescription: `text-xs ${mutedText}`,
categoryTitle: `text-sm font-medium ${strongText}`,
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,#f5f5f5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
icon: `h-6 w-6 shrink-0 ${accent}`,
link: `${accent} underline hover:no-underline`,
message: `text-justify text-sm ${bodyText}`,
overlay: 'fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4',
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium ${primaryBg} text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
rejectButton: '',
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`, root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
saveButton: '',
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`, secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
settingsActions: 'flex justify-end gap-2',
settingsButton: '',
settingsDescription: `text-sm ${bodyText}`,
settingsTitle: `flex items-center gap-2 text-base font-semibold ${strongText}`,
text: 'flex items-start gap-3',
title: `mb-1 text-base font-semibold ${strongText}`,
} }
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]' /** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
const strongText = const SWITCH_TRACK =
'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]' 'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
type CookieBannerProps = { type CookieBannerProps = {
classNames?: CookieBannerClassNames classNames?: CookieBannerClassNames
/** Category controls: native checkboxes (default) or accessible switches (role="switch"). */
controls?: 'checkbox' | 'switch'
/** /**
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO, * Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
* EDPB) expect refusing to be as easy and visible as accepting. Default false * EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true. * keeps the existing look; recommended true.
*/ */
equalChoice?: boolean equalChoice?: boolean
/** Cookie icon next to the banner text and the settings title. Default true. */
icon?: boolean
/** Banner buttons, in this order. Default ['settings', 'reject', 'accept']. */
order?: CookieBannerAction[]
/**
* Where category settings open: in the banner itself (default) or in a centred
* dialog over a dimmed page ('modal' — closes with ✕, Escape or a click outside).
*/
settings?: 'inline' | 'modal'
/** Buttons under the categories, in this order. Default ['back', 'save']. */
settingsActions?: CookieSettingsAction[]
} }
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) { const DEFAULT_ORDER: CookieBannerAction[] = ['settings', 'reject', 'accept']
const DEFAULT_SETTINGS_ACTIONS: CookieSettingsAction[] = ['back', 'save']
export function CookieBanner({
classNames,
controls = 'checkbox',
equalChoice = false,
icon = true,
order = DEFAULT_ORDER,
settings = 'inline',
settingsActions = DEFAULT_SETTINGS_ACTIONS,
}: CookieBannerProps = {}) {
const isMounted = useIsMounted() const isMounted = useIsMounted()
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext() const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false) const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state) const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
const closeRef = useRef<HTMLButtonElement>(null)
const modal = settings === 'modal'
useEffect(() => { useEffect(() => {
setChoices(state) setChoices(state)
}, [state]) }, [state])
// Modal: focus the ✕ on open, Escape closes (back to the banner)
useEffect(() => {
if (!modal || !showSettings) {return}
closeRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {setShowSettings(false)}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [modal, showSettings])
// Render nothing until mounted — avoids the React 19 hydration mismatch that // Render nothing until mounted — avoids the React 19 hydration mismatch that
// projects used to work around with a setTimeout ConsentWrapper. No wrapper // projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now. // needed now.
if (!isMounted) {return null} if (!isMounted) {return null}
if (decided) {return null} if (decided) {return null}
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
const primary = cn('primaryButton')
const secondary = cn('secondaryButton')
const buttonClass: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: classNames?.acceptButton ?? primary,
back: classNames?.backButton ?? secondary,
reject: classNames?.rejectButton ?? (equalChoice ? primary : secondary),
save: classNames?.saveButton ?? primary,
settings: classNames?.settingsButton ?? secondary,
}
const run: Record<CookieBannerAction | CookieSettingsAction, () => void> = {
accept: acceptAll,
back: () => setShowSettings(false),
reject: rejectAll,
save: () => savePreferences(choices),
settings: () => setShowSettings(true),
}
const label: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: texts.buttons.acceptAll,
back: texts.buttons.back,
reject: texts.buttons.reject,
save: texts.buttons.save,
settings: texts.buttons.settings,
}
const button = (action: CookieBannerAction | CookieSettingsAction) => (
<button className={buttonClass[action]} data-ipal={action} key={action} onClick={run[action]} type="button">
{label[action]}
</button>
)
const toggle = (cat: ConsentCategory) => { const toggle = (cat: ConsentCategory) => {
if (cat === 'necessary') {return} if (cat === 'necessary') {return}
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] })) setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
} }
const rootClass = classNames?.root ?? defaults.root const control = (cat: ConsentCategory) => {
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton const checked = cat === 'necessary' ? true : choices[cat]
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton if (cat === 'necessary' && texts.alwaysActiveLabel) {
return <span className={cn('badge')}>{texts.alwaysActiveLabel}</span>
}
if (controls === 'switch') {
return (
<button
aria-checked={checked}
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
className={classNames?.control ?? SWITCH_TRACK}
data-checked={checked}
disabled={cat === 'necessary'}
onClick={() => toggle(cat)}
role="switch"
type="button"
>
<span aria-hidden="true" className={cn('controlThumb')} data-checked={checked} />
</button>
)
}
return (
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={checked}
className={cn('control')}
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
)
}
return ( const settingsView = (
<div aria-label={texts.settingsTitle} className={rootClass} data-ipal="banner" role="dialog"> <div className="flex flex-col gap-4">
<div className="mx-auto max-w-4xl"> <div className="flex items-start justify-between gap-4">
{!showSettings ? ( <h2 className={cn('settingsTitle')} id="ipal-consent-title">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"> {icon && !modal && <Cookie aria-hidden="true" className={cn('icon')} />}
<div className="flex items-start gap-3"> {texts.settingsTitle}
<Cookie aria-hidden="true" className={`h-6 w-6 shrink-0 ${accent}`} /> </h2>
<p className={`text-justify text-sm ${bodyText}`}> {modal && (
{texts.message} <button aria-label={texts.buttons.close} className={cn('closeButton')} data-ipal="close" onClick={() => setShowSettings(false)} ref={closeRef} type="button">
{texts.privacyLink && ( <svg aria-hidden="true" fill="none" height="20" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="20">
<> <path d="M18 6 6 18M6 6l12 12" />
{' '} </svg>
<a </button>
className={`${accent} underline hover:no-underline`} )}
href={texts.privacyLink.href} </div>
> {texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
{texts.privacyLink.label} <ul className={cn('categories')}>
</a> {CONSENT_CATEGORIES.map((cat) => (
</> <li className={cn('category')} key={cat}>
)} <div>
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p> </p>
</div> </div>
<div className="flex shrink-0 gap-2"> {control(cat)}
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button"> </li>
{texts.buttons.settings} ))}
</button> </ul>
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button"> <div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
{texts.buttons.reject} </div>
</button> )
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
{texts.buttons.acceptAll} if (modal && showSettings) {
</button> return (
<div
className={cn('overlay')}
data-ipal="consent-overlay"
onClick={(event) => {
if (event.target === event.currentTarget) {setShowSettings(false)}
}}
// klik w tło zamyka dialog; klawiatura: Escape (listener wyżej) i przycisk ✕
role="presentation"
>
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={cn('dialog')} data-ipal="consent-dialog" role="dialog">
{settingsView}
</div>
</div>
)
}
return (
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" role="dialog">
<div className={cn('body')}>
{!showSettings ? (
<div className={cn('content')}>
<div className={cn('text')}>
{icon && <Cookie aria-hidden="true" className={cn('icon')} />}
<div>
{texts.eyebrow && <p className={cn('eyebrow')}>{texts.eyebrow}</p>}
{texts.title && <h2 className={cn('title')}>{texts.title}</h2>}
<p className={cn('message')}>
{texts.message}
{texts.privacyLink && (
<>
{' '}
<a className={cn('link')} href={texts.privacyLink.href}>
{texts.privacyLink.label}
</a>
</>
)}
</p>
</div>
</div> </div>
<div className={cn('actions')}>{order.map(button)}</div>
</div> </div>
) : ( ) : (
<div className="flex flex-col gap-4"> settingsView
<h2 className={`flex items-center gap-2 text-base font-semibold ${strongText}`}>
<Cookie aria-hidden="true" className={`h-5 w-5 ${accent}`} />
{texts.settingsTitle}
</h2>
<ul className="flex flex-col gap-3">
{CONSENT_CATEGORIES.map((cat) => (
<li className="flex items-start justify-between gap-4" key={cat}>
<div>
<p className={`text-sm font-medium ${strongText}`} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={`text-xs ${mutedText}`} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={cat === 'necessary' ? true : choices[cat]}
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
</li>
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)} type="button">
{texts.buttons.back}
</button>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)} type="button">
{texts.buttons.save}
</button>
</div>
</div>
)} )}
</div> </div>
</div> </div>
+1 -1
View File
@@ -2,7 +2,7 @@
export { ConsentProvider, useConsentContext } from './ConsentContext.js' export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js' export { ConsentScript } from './ConsentScript.js'
export { CookieBanner } from './CookieBanner.js' export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js' export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js' export { CookieButton } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components. // Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js' export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
+17 -2
View File
@@ -13,6 +13,7 @@ const FALLBACK: ConsentTexts = {
buttons: { buttons: {
acceptAll: 'Accept all', acceptAll: 'Accept all',
back: 'Back', back: 'Back',
close: 'Close',
reject: 'Reject', reject: 'Reject',
save: 'Save preferences', save: 'Save preferences',
settings: 'Settings', settings: 'Settings',
@@ -37,13 +38,21 @@ const FALLBACK: ConsentTexts = {
const FALLBACK_PRIVACY_LABEL = 'Privacy policy' const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = { type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']> alwaysActiveLabel?: null | string
buttons?: ({
/** Before 1.11.1 the field was `save` — still read, so old MongoDB data keeps working until re-saved. */
save?: null | string
savePreferences?: null | string
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
eyebrow?: null | string
message?: null | string message?: null | string
policyVersion?: null | number policyVersion?: null | number
privacyLinkLabel?: null | string privacyLinkLabel?: null | string
settingsDescription?: null | string
settingsTitle?: null | string settingsTitle?: null | string
title?: null | string
} }
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
@@ -135,14 +144,20 @@ export async function getConsentTexts({
buttons: { buttons: {
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll, acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
back: g.buttons?.back || FALLBACK.buttons.back, back: g.buttons?.back || FALLBACK.buttons.back,
close: g.buttons?.close || FALLBACK.buttons.close,
reject: g.buttons?.reject || FALLBACK.buttons.reject, reject: g.buttons?.reject || FALLBACK.buttons.reject,
save: g.buttons?.save || FALLBACK.buttons.save, save: g.buttons?.savePreferences || g.buttons?.save || FALLBACK.buttons.save,
settings: g.buttons?.settings || FALLBACK.buttons.settings, settings: g.buttons?.settings || FALLBACK.buttons.settings,
}, },
categories, categories,
message: g.message || FALLBACK.message, message: g.message || FALLBACK.message,
privacyLink, privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle, settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
// optional copy — no English fallback: empty in the panel = element not rendered
...(g.eyebrow?.trim() ? { eyebrow: g.eyebrow.trim() } : {}),
...(g.title?.trim() ? { title: g.title.trim() } : {}),
...(g.settingsDescription?.trim() ? { settingsDescription: g.settingsDescription.trim() } : {}),
...(g.alwaysActiveLabel?.trim() ? { alwaysActiveLabel: g.alwaysActiveLabel.trim() } : {}),
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}), ...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
} }
} }
+10
View File
@@ -1,18 +1,28 @@
import type { ConsentCategory } from './categories.js' import type { ConsentCategory } from './categories.js'
export type ConsentTexts = { export type ConsentTexts = {
/** Badge next to the necessary category (e.g. "Always active"). Empty = no badge. */
alwaysActiveLabel?: string
buttons: { buttons: {
acceptAll: string acceptAll: string
back: string back: string
/** Accessible label of the ✕ button closing the settings dialog. */
close: string
reject: string reject: string
save: string save: string
settings: string settings: string
} }
categories: Record<ConsentCategory, { description: string; title: string }> categories: Record<ConsentCategory, { description: string; title: string }>
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
eyebrow?: string
message: string message: string
/** null = no privacy-policy link shown */ /** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null privacyLink: { href: string; label: string } | null
/** Intro under the settings title. Empty = not shown. */
settingsDescription?: string
settingsTitle: string settingsTitle: string
/** Banner heading (e.g. "We respect your privacy"). Empty = not shown. */
title?: string
/** Policy version from the panel — a stored consent from another version asks again. */ /** Policy version from the panel — a stored consent from another version asks again. */
version?: number version?: number
} }
@@ -0,0 +1,85 @@
'use client'
import { useCallback, useEffect, useId, useRef, useState } from 'react'
import type { ConstructionMode } from './types.js'
import { isPathAllowed } from './logic.js'
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
export type ConstructionNoticeClassNames = {
button?: string
dialog?: string
message?: string
overlay?: string
title?: string
}
/**
* The "site under construction" notice (Site Settings → Under construction).
* Opens after a redirect from a blocked address (?notice=construction, then
* removed from the URL) and when a visitor clicks a link to a page that isn't
* available — the click is cancelled. Closes with its button or Escape.
* Renders nothing while the mode is off.
*
* Unstyled (classNames, like CookieBanner); texts come from the panel.
*
* // [locale]/layout.tsx
* <ConstructionNotice mode={await getConstructionMode(locale)} classNames={{ overlay: '…', dialog: '…' }} />
*/
export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) {
const [open, setOpen] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const titleId = useId()
const close = useCallback(() => setOpen(false), [])
const { allowedPaths, enabled } = mode
useEffect(() => {
if (!enabled) {return}
// After a redirect: show the notice once and clean the address bar
const url = new URL(window.location.href)
if (url.searchParams.get(CONSTRUCTION_NOTICE_PARAM) === CONSTRUCTION_NOTICE_VALUE) {
setOpen(true)
url.searchParams.delete(CONSTRUCTION_NOTICE_PARAM)
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`)
}
// Capture phase, before Next's <Link> — a cancelled click doesn't navigate
const onClick = (event: MouseEvent) => {
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {return}
const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute('download')) {return}
if (anchor.target && anchor.target !== '_self') {return}
const target = new URL(anchor.href, window.location.href)
if (target.origin !== window.location.origin || isPathAllowed(target.pathname, allowedPaths)) {return}
event.preventDefault()
event.stopPropagation()
setOpen(true)
}
document.addEventListener('click', onClick, true)
return () => document.removeEventListener('click', onClick, true)
}, [enabled, allowedPaths])
useEffect(() => {
if (!open) {return}
buttonRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {close()}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open, close])
if (!enabled || !open) {return null}
return (
<div className={cn.overlay} data-ipal="construction-notice">
<div aria-labelledby={mode.texts.title ? titleId : undefined} aria-modal="true" className={cn.dialog} role="dialog">
{mode.texts.title ? <p className={cn.title} id={titleId}>{mode.texts.title}</p> : null}
{mode.texts.message ? <p className={cn.message}>{mode.texts.message}</p> : null}
<button className={cn.button} onClick={close} ref={buttonRef} type="button">
{mode.texts.button ?? '×'}
</button>
</div>
</div>
)
}
+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'
+22 -3
View File
@@ -17,7 +17,7 @@ type CreateMarkdownRendererArgs = {
* i18n config — only to know a single-locale site has no /{locale} prefix in * i18n config — only to know a single-locale site has no /{locale} prefix in
* its URLs (for `url:`). Omit on multilingual sites if you like. * its URLs (for `url:`). Omit on multilingual sites if you like.
*/ */
config?: { locales: readonly unknown[] } config?: { defaultLocale?: string; locales: readonly unknown[] }
/** Archive-backed collections, same value as the plugin option (optional). */ /** Archive-backed collections, same value as the plugin option (optional). */
content?: ContentOption content?: ContentOption
/** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */ /** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
@@ -149,7 +149,26 @@ function canonicalOf(baseUrl: string | undefined, config: { locales: readonly un
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '') return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
} }
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> } type MarkdownRouteContext = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* Locale + slug of a Markdown request. Multilingual: app/md/[locale]/[[...slug]].
* Single language (no /pl in URLs): app/md/[[...slug]] — no locale param, the
* only locale is used; the [locale] route also works there for subpages
* ("/md/kontakt" arrives as locale "kontakt" and is read as the slug).
*/
function routeOf(
params: { locale?: string; slug?: string[] },
config: CreateMarkdownRendererArgs['config'],
): { locale: string; slug?: string[] } {
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? (l as { code?: string }).code ?? '' : typeof l === 'string' ? l : ''))
const fallback = config?.defaultLocale ?? codes[0] ?? ''
if (!params.locale) {return { slug: params.slug, locale: fallback }}
if (codes.length === 1 && !codes.includes(params.locale)) {
return { slug: [params.locale, ...(params.slug ?? [])], locale: codes[0] }
}
return { slug: params.slug, locale: params.locale }
}
/** /**
* The whole Markdown route in one call — same options as createMarkdownRenderer * The whole Markdown route in one call — same options as createMarkdownRenderer
@@ -175,7 +194,7 @@ export function createMarkdownRoute(
return { return {
GET: async (_req, { params }) => { GET: async (_req, { params }) => {
try { try {
const { slug, locale } = await params const { slug, locale } = routeOf(await params, rendererArgs.config)
const md = await render({ slug, locale, payload: await getCachedPayload() }) const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) }) return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) { } catch (err) {
+14 -5
View File
@@ -16,7 +16,12 @@ export type IpalEnvFeatures = {
secretVar?: string secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */ /** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
serverUrlVar?: string 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 storage?: boolean
/** /**
* Cloudflare Turnstile. true uses the common var names * Cloudflare Turnstile. true uses the common var names
@@ -69,14 +74,18 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
] ]
if (storage) { 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( rules.push(
{ name: 'R2_BUCKET', description: 'R2 bucket name' }, { name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' }, { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' }, { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' }, { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
{ {
name: 'R2_PUBLIC_URL', name: 'R2_PUBLIC_URL',
description: 'Public base URL media is served from (custom domain of the bucket)', 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 // Production: absolute URL (https://media.example.com). Outside production a
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with // site-relative path ('/media') is accepted — buildR2Storage prefixes it with
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket). // NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
+25 -7
View File
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderField } from './builderTypes.js' import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js' import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
@@ -18,7 +19,7 @@ import { useBuilderForm } from './useBuilderForm.js'
export type BuilderFormClassNames = Partial< export type BuilderFormClassNames = Partial<
Record< Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices' | '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' | 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile', | 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string string
@@ -48,9 +49,13 @@ export type BuilderFormProps = {
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */ /** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode requiredMark?: ReactNode
turnstileTheme?: 'auto' | 'dark' | 'light' /** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
} & UseBuilderFormOptions } & 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 const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/** /**
@@ -74,14 +79,15 @@ export function BuilderForm({
}: BuilderFormProps) { }: BuilderFormProps) {
const f = useBuilderForm(options) const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null) const stepRef = useRef<HTMLDivElement>(null)
const firstRender = useRef(true) const prevStep = useRef(f.stepIndex)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it. // Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
// Compare with the previous step, not a "first render" flag: React re-runs effects
// without a remount (Next restoring a visited page from <Activity>, StrictMode),
// and a stale flag would focus the first field and scroll the page to the form.
useEffect(() => { useEffect(() => {
if (firstRender.current) { if (prevStep.current === f.stepIndex) {return}
firstRender.current = false prevStep.current = f.stepIndex
return
}
const el = stepRef.current const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus() target?.focus()
@@ -108,6 +114,18 @@ export function BuilderForm({
const defaultField = (field: BuilderField, index: number): ReactNode => { const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>} 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) { switch (field.blockType) {
case 'checkbox': { case 'checkbox': {
const props = f.getInputProps(field) const props = f.getInputProps(field)
+71 -18
View File
@@ -3,6 +3,7 @@ import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js' import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderFormClassNames } from './BuilderForm.js' import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js' import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js' import type { SubmitActionResult } from './createSubmitAction.js'
@@ -37,12 +38,15 @@ export type RenderFormProps = {
richTextClassName?: string richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */ /** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light' /** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
/** 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 /** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */ * document still carries Emails (recipient addresses) — those never leave the server. */
function publicForm(form: BuilderFormDoc): BuilderFormDoc { export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return { return {
id: form.id, id: form.id,
analytics: form.analytics, analytics: form.analytics,
@@ -54,27 +58,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 * Returns null for an unpopulated form (an id or nothing).
* 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).
*/ */
export function RenderForm({ export function prepareBuilderForm({
action, action,
classNames,
converters, converters,
form, form,
linkOptions, linkOptions,
locale, locale,
requiredMark,
richTextClassName, richTextClassName,
texts, }: PrepareBuilderFormArgs): null | PreparedBuilderForm {
turnstileTheme,
}: RenderFormProps) {
if (!form || typeof form !== 'object') {return null} // never a placeholder form if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) => const rich = (data: unknown) =>
@@ -93,17 +112,51 @@ export function RenderForm({
: safeHref(form.redirect?.url) : safeHref(form.redirect?.url)
: null : 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 ( return (
<BuilderForm <BuilderForm
action={action.bind(null, String(form.id), locale)} {...prepared}
classNames={classNames} classNames={classNames}
confirmation={rich(form.confirmationMessage)}
form={publicForm(form)}
messages={messages}
redirectHref={redirectHref}
requiredMark={requiredMark} requiredMark={requiredMark}
texts={texts} texts={texts}
turnstileTheme={turnstileTheme} turnstileTheme={turnstileTheme}
values={values}
/> />
) )
} }
+70 -2
View File
@@ -8,9 +8,16 @@ import type { Block, Field } from 'payload'
* Carries no value. * Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several * - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[]. * ("Services you're interested in"). Value: string[].
* - `time` — a time of day (<input type="time">). Value: "HH:MM".
*
* Built-in text · email · textarea · number get a localized "Placeholder"
* (withPlaceholder) — the hint inside the empty field, e.g. "e.g. 10:00–12:00".
* *
* Plain English labels (the panel is EN). Rendered by BuilderForm / * Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field. * useBuilderForm, validated by submitForm like every other field.
*
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
* (`showWhen`) — conditional visibility, evaluated by visibleFields.
*/ */
const name: Field = { const name: Field = {
@@ -24,7 +31,64 @@ const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, lab
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' } const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' } const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
export const stepBlock: Block = { /**
* "Show only when": the field — or, on a Step, the whole step — appears only
* when another field has one of the given values. Evaluated by visibleFields
* in the browser and again on the server (hidden fields are neither required nor stored).
*/
export const showWhenField: Field = {
name: 'showWhen',
type: 'group',
admin: {
description:
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
},
fields: [
{
type: 'row',
fields: [
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
{
name: 'values',
type: 'text',
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
label: 'Values',
},
],
},
],
label: 'Show only when',
}
/** Adds "Show only when" at the end of a block's fields. */
export function withShowWhen<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, showWhenField] }
}
/** Hint inside the empty field. Localized — it is visible text. */
export const placeholderField: Field = {
name: 'placeholder',
type: 'text',
admin: { description: 'Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.' },
label: 'Placeholder',
localized: true,
}
/** Adds a localized "Placeholder" to a block (built-in text, email, textarea, number). */
export function withPlaceholder<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, placeholderField] }
}
const timeBase: Block = {
slug: 'time',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
],
labels: { plural: 'Times', singular: 'Time' },
}
const stepBase: Block = {
slug: 'step', slug: 'step',
fields: [ fields: [
{ {
@@ -42,7 +106,7 @@ export const stepBlock: Block = {
labels: { plural: 'Steps', singular: 'Step' }, labels: { plural: 'Steps', singular: 'Step' },
} }
export const checkboxGroupBlock: Block = { const checkboxGroupBase: Block = {
slug: 'checkboxGroup', slug: 'checkboxGroup',
fields: [ fields: [
{ type: 'row', fields: [name, label] }, { type: 'row', fields: [name, label] },
@@ -72,3 +136,7 @@ export const checkboxGroupBlock: Block = {
], ],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' }, labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
} }
export const stepBlock: Block = withShowWhen(stepBase)
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
export const timeBlock: Block = withShowWhen(timeBase)
+65 -4
View File
@@ -1,4 +1,4 @@
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js' import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js' import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js' import { isEmail } from './validators.js'
@@ -19,16 +19,24 @@ export function inputFields(fields: BuilderField[] | null | undefined): ({ name:
/** /**
* Splits the field list at `step` blocks. Fields before the first Step form * Splits the field list at `step` blocks. Fields before the first Step form
* the first screen; a form without Steps is one screen. * the first screen; a form without Steps is one screen.
*
* `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a
* hidden Step with everything under it — out, while `index` stays the field's
* position in the full list (RenderForm renders `message` blocks by it).
*/ */
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] { export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] {
const steps: BuilderStep[] = [] const steps: BuilderStep[] = []
let current: BuilderStep | null = null let current: BuilderStep | null = null
let skipping = false
;(fields ?? []).forEach((field, index) => { ;(fields ?? []).forEach((field, index) => {
if (field.blockType === 'step') { if (field.blockType === 'step') {
skipping = isShown ? !isShown(field) : false
if (skipping) {return}
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined } current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
steps.push(current) steps.push(current)
return return
} }
if (skipping || (isShown && !isShown(field))) {return}
if (!current) { if (!current) {
current = { fields: [], index: 0 } current = { fields: [], index: 0 }
steps.push(current) steps.push(current)
@@ -40,6 +48,60 @@ export function splitSteps(fields: BuilderField[] | null | undefined): BuilderSt
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i })) return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
} }
const isBlankValue = (v: unknown) =>
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */
type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null }
const conditionValues = (condition: FieldCondition | null | undefined) =>
(condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean)
/**
* The fields (Steps and messages included) a visitor sees for the given values,
* in panel order. A field is hidden when its own "Show only when" fails, when
* its Step's condition fails (the whole step goes), or when the field its
* condition points at is itself hidden. A condition naming a field that doesn't
* exist hides the field — a typo shows up in the preview instead of passing silently.
*
* Shared by the browser (useBuilderForm: which steps and fields to show and
* validate) and the server (validateSubmission: hidden fields are neither
* required nor stored), so both agree on what was on screen.
*/
export function visibleFields<F extends ConditionalField>(fields: F[] | null | undefined, values: Record<string, unknown>): F[] {
const list = fields ?? []
const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f]))
const stepOf = new Map<F, F | undefined>()
let currentStep: F | undefined
for (const field of list) {
if (field.blockType === 'step') {currentStep = field}
stepOf.set(field, field.blockType === 'step' ? undefined : currentStep)
}
const cache = new Map<F, boolean>()
const met = (condition: FieldCondition | null | undefined, seen: Set<F>): boolean => {
const ref = condition?.field?.trim()
if (!ref) {return true}
const target = byName.get(ref)
if (!target || seen.has(target) || !visible(target, seen)) {return false}
const value = values[ref]
const wanted = conditionValues(condition)
if (wanted.length === 0) {return !isBlankValue(value)}
if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))}
return value != null && value !== '' && wanted.includes(String(value as boolean | number | string))
}
const visible = (field: F, seen: Set<F> = new Set()): boolean => {
const cached = cache.get(field)
if (cached !== undefined) {return cached}
const nextSeen = new Set(seen).add(field)
const step = stepOf.get(field)
const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen)
cache.set(field, result)
return result
}
return list.filter((field) => visible(field))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */ /** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> { export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries( return Object.fromEntries(
@@ -52,8 +114,7 @@ export function initialBuilderValues(fields: BuilderField[] | null | undefined):
) )
} }
const isBlank = (v: unknown) => const isBlank = isBlankValue
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** Errors for the given fields (one message per field), empty object = valid. */ /** Errors for the given fields (one message per field), empty object = valid. */
export function validateBuilderFields( export function validateBuilderFields(
+10 -1
View File
@@ -6,9 +6,16 @@ import type { FormAnalyticsConfig } from './formAnalytics.js'
*/ */
export type BuilderOption = { label?: null | string; value: string } export type BuilderOption = { label?: null | string; value: string }
/**
* "Show only when" of a field or a Step (panel group `showWhen`): visible only
* when the field named `field` has one of `values` (comma-separated). Empty
* `values` = when that field is filled in / ticked. Empty `field` = always.
*/
export type FieldCondition = { field?: null | string; values?: null | string }
export type BuilderField = { export type BuilderField = {
blockName?: null | string blockName?: null | string
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */ /** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string blockType: string
defaultValue?: unknown defaultValue?: unknown
/** step */ /** step */
@@ -23,6 +30,8 @@ export type BuilderField = {
options?: BuilderOption[] | null options?: BuilderOption[] | null
placeholder?: null | string placeholder?: null | string
required?: boolean | null required?: boolean | null
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
showWhen?: FieldCondition | null
/** step */ /** step */
title?: null | string title?: null | string
width?: null | number width?: null | number
+1
View File
@@ -75,6 +75,7 @@ export function createSubmitAction({
data: fields, data: fields,
formId: String(formId), formId: String(formId),
ip, ip,
locale,
maxPerMinute, maxPerMinute,
payload, payload,
turnstileOnConfigError, turnstileOnConfigError,
+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
}
}
}
+34 -14
View File
@@ -1,14 +1,22 @@
import type { Field, Plugin } from 'payload' import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { Block, Field, Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder' import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js' import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js' import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js' import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } } type AccessArgs = { req: { user?: unknown } }
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
withShowWhen(builtinBlocks[key] as Block)
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ /** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user) const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/** /**
@@ -52,25 +60,37 @@ function hideEmails(fields: Field[]): Field[] {
export function buildFormsPlugin(forms: FormsOption): Plugin { export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {} const group = adminGroup ? { group: adminGroup } : {}
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
const beforeEmail: BeforeEmail | undefined =
layout || forms.beforeEmail
? async (emails, args) => {
const laidOut = layout ? await layout(emails, args) : emails
return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut
}
: undefined
return formBuilderPlugin({ return formBuilderPlugin({
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are ...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on // panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false. // existing forms. Switch any off with forms.fields.<type>: false.
fields: { fields: {
checkbox: true, // every block carries "Show only when" (showWhen) — conditional fields and steps
checkbox: builtin('checkbox'),
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock, checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: true, date: builtin('date'),
email: true, email: withHint('email'),
message: true, message: builtin('message'),
number: true, number: withHint('number'),
payment: false, payment: false,
radio: true, radio: builtin('radio'),
select: true, select: builtin('select'),
step: forms.fields?.step === false ? false : stepBlock, step: forms.fields?.step === false ? false : stepBlock,
text: true, text: withHint('text'),
textarea: true, textarea: withHint('textarea'),
time: forms.fields?.time === false ? false : timeBlock,
...Object.fromEntries( ...Object.fromEntries(
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'), // `true` keeps ipal's block (with "Show only when"); false / an object override it
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
), ),
}, },
...(forms.redirectRelationships ...(forms.redirectRelationships
+3 -3
View File
@@ -1,8 +1,8 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default). // Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js' export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm. // Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js' export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js' export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js' export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js' export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client). // Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+4
View File
@@ -19,6 +19,8 @@ export type SubmitFormArgs = {
formId: string formId: string
/** Client IP — used for Turnstile and rate limiting. */ /** Client IP — used for Turnstile and rate limiting. */
ip?: string ip?: string
/** Page language — the form-builder reads the form (e-mail texts, labels) in it. */
locale?: string
/** /**
* Rate limit: max submissions per IP per minute. Defaults to 5. * Rate limit: max submissions per IP per minute. Defaults to 5.
* Set to 0 to disable (e.g. when a real limiter sits in front). * Set to 0 to disable (e.g. when a real limiter sits in front).
@@ -96,6 +98,7 @@ export async function submitForm({
data, data,
formId, formId,
ip, ip,
locale,
maxPerMinute = 5, maxPerMinute = 5,
payload, payload,
turnstileOnConfigError = 'allow', turnstileOnConfigError = 'allow',
@@ -143,6 +146,7 @@ export async function submitForm({
try { try {
const submission = await payload.create({ const submission = await payload.create({
collection: 'form-submissions', collection: 'form-submissions',
...(locale ? { locale: locale as never } : {}),
data: { data: {
form: formId, form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({ submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
+14
View File
@@ -1,3 +1,4 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { CollectionConfig, Field } from 'payload' import type { CollectionConfig, Field } from 'payload'
/** /**
@@ -25,12 +26,23 @@ export type FormsOption = {
* formOverrides / formSubmissionOverrides still wins. * formOverrides / formSubmissionOverrides still wins.
*/ */
adminGroup?: false | string adminGroup?: false | string
/**
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
* the ipal layout when `emailLayout` is on.
*/
beforeEmail?: BeforeEmail
/** /**
* Name of the checkbox field treated as a GDPR consent gate. A form field * Name of the checkbox field treated as a GDPR consent gate. A form field
* with this name must be checked for submission to succeed — enforced * with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'. * server-side in submitForm. Defaults to 'consent'.
*/ */
consentFieldName?: string consentFieldName?: string
/**
* Branded e-mails (emailLayout.ts): `{{*:table}}` becomes a readable summary
* (questions, option labels, grouped by step) and every e-mail gets a layout
* with the logo, accent colour and footer from Site Settings → Emails. Default false.
*/
emailLayout?: boolean
/** Field types available in the form builder. Sensible defaults applied. */ /** Field types available in the form builder. Sensible defaults applied. */
fields?: { fields?: {
checkbox?: boolean checkbox?: boolean
@@ -50,6 +62,8 @@ export type FormsOption = {
step?: boolean step?: boolean
text?: boolean text?: boolean
textarea?: boolean textarea?: boolean
/** Time of day, <input type="time"> (ipal). Default on. */
time?: boolean
} }
/** /**
* Override the forms collection. The plugin stays opinion-free about what a * Override the forms collection. The plugin stays opinion-free about what a
+40 -10
View File
@@ -8,7 +8,7 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
import { safeHref } from '../links/resolveLinkHref.js' import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js' import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js' import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js' import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { useForm } from './useForm.js' import { useForm } from './useForm.js'
@@ -23,6 +23,12 @@ export type UseBuilderFormOptions = {
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */ /** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string redirectHref?: null | string
texts: BuilderFormTexts 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,10 +46,10 @@ export type UseBuilderFormOptions = {
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button> * <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form> * </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]) const fields = useMemo(() => form.fields ?? [], [form.fields])
const steps = useMemo(() => splitSteps(fields), [fields]) // Fields behind a failed "Show only when" are neither shown, validated nor sent.
const inputs = useMemo(() => inputFields(fields), [fields]) const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
const [stepIndex, setStepIndex] = useState(0) const [stepIndex, setStepIndex] = useState(0)
const [resultMessage, setResultMessage] = useState<null | string>(null) const [resultMessage, setResultMessage] = useState<null | string>(null)
const ts = useOptionalTurnstile() const ts = useOptionalTurnstile()
@@ -52,19 +58,24 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
const serverFieldError = useRef<{ field: string; message: string } | null>(null) const serverFieldError = useRef<{ field: string; message: string } | null>(null)
const submitAction = useCallback( const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => { async (values: Record<string, unknown>, token?: string) => {
const result = await action(values, token) const shown = new Set(visibleInputs(values).map((field) => field.name))
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
if (result.success) {setResultMessage(result.message ?? null)} if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }} else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
return result return result
}, },
[action, texts.validation], [action, texts.validation, visibleInputs],
) )
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts]) const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
const f = useForm<Record<string, unknown>>({ const f = useForm<Record<string, unknown>>({
errorFallback: texts.error, errorFallback: texts.error,
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) => { onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values) formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values) onSuccess?.(values)
@@ -77,7 +88,24 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
submitAction, submitAction,
validate, 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))
return splitSteps(fields, (field) => shown.has(field))
}, [fields, f.values])
// Turnstile token lives in the provider; the engine needs it at submit. // Turnstile token lives in the provider; the engine needs it at submit.
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken]) useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
@@ -161,7 +189,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
return typeof value === 'string' ? value : value == null ? '' : String(value as number) return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values]) }, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */ /** Everything an <input> needs, by field type: text · email · number · date · time · tel · checkbox. */
const getInputProps = useCallback( const getInputProps = useCallback(
(field: BuilderField) => { (field: BuilderField) => {
const name = field.name ?? '' const name = field.name ?? ''
@@ -173,6 +201,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
field.blockType === 'email' ? 'email' field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number' : field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date' : field.blockType === 'date' ? 'date'
: field.blockType === 'time' ? 'time'
: base.autoComplete === 'tel' ? 'tel' : base.autoComplete === 'tel' ? 'tel'
: 'text' : 'text'
return { return {
@@ -252,6 +281,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
getTextareaProps, getTextareaProps,
goTo, goTo,
isFirst, isFirst,
isFixed,
isLast, isLast,
next, next,
/** Message the server returned on success (Notifications → success). */ /** Message the server returned on success (Notifications → success). */
+16
View File
@@ -1,5 +1,9 @@
import type { BasePayload } from 'payload' import type { BasePayload } from 'payload'
import type { FieldCondition } from './builderTypes.js'
import { visibleFields } from './builderLogic.js'
/** A form-builder field, trimmed to what validation needs. */ /** A form-builder field, trimmed to what validation needs. */
type FormField = { type FormField = {
blockType?: string blockType?: string
@@ -11,6 +15,8 @@ type FormField = {
/** select / radio / checkboxGroup choices defined in the panel. */ /** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null options?: { value?: unknown }[] | null
required?: boolean | null required?: boolean | null
/** "Show only when" — hidden fields are neither required nor stored. */
showWhen?: FieldCondition | null
} }
type FormDoc = { type FormDoc = {
@@ -40,6 +46,9 @@ export type FormValidationResult =
/** Field block types that don't carry a submittable value. */ /** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message', 'step']) const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** HH:MM or HH:MM:SS (a time input), 00:00–23:59. */
const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */ /** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/ const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
@@ -117,6 +126,8 @@ function checkValue(field: FormField, value: unknown): Checked {
} }
case 'textarea': case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' } return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
case 'time':
return typeof value === 'string' && TIME.test(value.trim()) ? { value: value.trim() } : { error: 'invalid_format' }
default: default:
// text, country, state and custom blocks: one line of plain text. // text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }} if (typeof value === 'number') {return { value }}
@@ -171,10 +182,15 @@ export async function validateSubmission(
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''), typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
) )
const known = new Map(fields.map((f) => [f.name, f])) const known = new Map(fields.map((f) => [f.name, f]))
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
const shown = new Set(visibleFields(form.fields, data))
const cleaned: Record<string, unknown> = {} const cleaned: Record<string, unknown> = {}
for (const field of fields) { for (const field of fields) {
// Hidden by a condition: not required, not stored. The consent gate never hides —
// an editor can't switch GDPR consent off with a condition.
if (!shown.has(field) && field.name !== consentFieldName) {continue}
const value = data[field.name] const value = data[field.name]
const isBlank = const isBlank =
value == null || value == null ||
+9
View File
@@ -10,6 +10,7 @@ import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js' import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js' import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js' import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { ThemeScript } from '../theme/ThemeScript.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js' import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = { export type SiteProvidersProps = {
@@ -30,6 +31,12 @@ export type SiteProvidersProps = {
preconnect?: boolean preconnect?: boolean
/** getSiteShell(locale) from lib/content. */ /** getSiteShell(locale) from lib/content. */
shell: SiteShell shell: SiteShell
/**
* Light / dark theme from Site Settings → Theme: renders <ThemeScript> first,
* so the theme is on <html> before the first paint. Put <SiteProviders> first in
* <body> and add `suppressHydrationWarning` to <html>. Default false.
*/
theme?: boolean
} }
/** /**
@@ -58,9 +65,11 @@ export function SiteProviders({
logEndpoint, logEndpoint,
preconnect = true, preconnect = true,
shell, shell,
theme = false,
}: SiteProvidersProps) { }: SiteProvidersProps) {
return ( return (
<> <>
{theme ? <ThemeScript {...shell.theme} /> : null}
{preconnect ? <MediaPreconnect /> : null} {preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} /> <JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}> <ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
+85 -5
View File
@@ -5,6 +5,7 @@ import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.js' import type { AnalyticsConfig } from '../analytics/types.js'
import type { ConsentTexts } from '../consent/texts.js' import type { ConsentTexts } from '../consent/texts.js'
import type { ConstructionMode } from '../construction/types.js'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js' import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js' import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
@@ -18,6 +19,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js' import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { archiveFieldName } from '../content/types.js'
import { createHealthRoute } from '../health/createHealthRoute.js' import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js' import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
import { createMcpRoute } from '../mcp/createMcpRoute.js' import { createMcpRoute } from '../mcp/createMcpRoute.js'
@@ -28,6 +30,7 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js' import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { createIndexNowKeyRoute } from '../seo/indexNow.js' import { createIndexNowKeyRoute } from '../seo/indexNow.js'
import { createLlmsTxtRoute } from '../seo/routeHandlers.js' import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
import { getTurnstileConfig } from '../turnstile/config.js' import { getTurnstileConfig } from '../turnstile/config.js'
type CreateContentHelpersArgs = { type CreateContentHelpersArgs = {
@@ -93,9 +96,30 @@ type CreateContentHelpersArgs = {
summaryField?: string 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 = { export type PageJsonLdOptions = {
/** BreadcrumbList (home › archive › page) from the real route. Default true. */ /** BreadcrumbList (home › archive › page) from the real route. Default true. */
breadcrumbs?: boolean 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'. */ /** schema.org type of archive entries. Default 'BlogPosting'. */
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle' entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
/** /**
@@ -269,7 +293,10 @@ export function createContentHelpers({
const image = meta.openGraph?.images?.[0]?.url const image = meta.openGraph?.images?.[0]?.url
const nodes: (null | Record<string, unknown>)[] = [] 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( nodes.push(
buildArticleJsonLd({ buildArticleJsonLd({
type: opts.entryType ?? 'BlogPosting', type: opts.entryType ?? 'BlogPosting',
@@ -571,8 +598,23 @@ export function createContentHelpers({
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */ /** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => { const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
const homeSlug = await getHomeSlug(locale) const settings = await getSettings(locale)
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) } 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 +646,40 @@ export function createContentHelpers({
segments, segments,
}) })
/**
* Site Settings → Under construction, for this locale: whether it's on, the
* paths still reachable (homepage + chosen pages, in every language), the
* homepage to redirect to and the notice texts. createPageRoute (with
* `redirect`) and <ConstructionNotice> (/client) use it.
*/
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
const settings = (await getSettings(locale)) as null | Record<string, unknown>
const options = await getLinkOptions(locale)
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }}
const configured = await getConfiguredLocales()
const paths = await Promise.all(
(configured.length ? configured : [locale]).map(async (code) => {
const localized = (await getSettings(code)) as null | Record<string, unknown>
const linkOptions = await getLinkOptions(code)
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
}),
)
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
return {
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
enabled: true,
homePath,
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
}
})
// ── Layout ──────────────────────────────────────────────────────────────── // ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */ /** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> => const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -642,6 +718,7 @@ export function createContentHelpers({
formTexts, formTexts,
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node), jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
settings: settings ?? {}, settings: settings ?? {},
theme: themeConfigFrom(settings),
turnstileSiteKey: turnstile.siteKey, turnstileSiteKey: turnstile.siteKey,
} }
}) })
@@ -665,8 +742,8 @@ export function createContentHelpers({
const llmsRoute = () => llms()() const llmsRoute = () => llms()()
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */ /** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
const llmsFullRoute = () => llmsFull()() const llmsFullRoute = () => llmsFull()()
/** app/md/[locale]/[[...slug]]/route.ts: `export { markdownRoute as GET } from '@/lib/content'` */ /** app/md/[locale]/[[...slug]]/route.ts (single language: app/md/[[...slug]]/route.ts): `export { markdownRoute as GET } from '@/lib/content'` */
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale: string; slug?: string[] }> }) => md().GET(req, ctx) const markdownRoute = (req: Request, ctx: { params: Promise<{ locale?: string; slug?: string[] }> }) => md().GET(req, ctx)
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */ /** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
const mcpGET = () => mcp().GET() const mcpGET = () => mcp().GET()
const mcpPOST = (req: Request) => mcp().POST(req) const mcpPOST = (req: Request) => mcp().POST(req)
@@ -682,6 +759,7 @@ export function createContentHelpers({
generateStaticParams, generateStaticParams,
getCachedPayload, getCachedPayload,
getConfiguredLocales, getConfiguredLocales,
getConstructionMode,
getEntries, getEntries,
getFormTexts, getFormTexts,
getHomeSlug, getHomeSlug,
@@ -718,6 +796,8 @@ export type SiteShell = {
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */ /** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
jsonLd: Record<string, unknown>[] jsonLd: Record<string, unknown>[]
settings: Record<string, unknown> settings: Record<string, unknown>
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
theme: ThemeConfig
turnstileSiteKey: null | string turnstileSiteKey: null | string
} }
+110 -23
View File
@@ -5,10 +5,12 @@ import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js' import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js' import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js' import { LocaleView } from '../pages/LocaleView.js'
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js' import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Pick< type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
ContentHelpers, ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute' 'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
> >
@@ -16,7 +18,11 @@ type Helpers = Pick<
type BlockPropsContext = { doc: Record<string, unknown>; locale: string } type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
export type PageRouteOptions = { 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> blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
/** blockType → component (the project's registry). */ /** blockType → component (the project's registry). */
blocks: BlockComponentMap blocks: BlockComponentMap
@@ -26,8 +32,21 @@ export type PageRouteOptions = {
layoutField?: string layoutField?: string
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */ /** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
notFound: () => never notFound: () => never
/**
* An address with no page (and no old-slug redirect):
* - 'notFound' (default) — the 404 page;
* - 'redirectHome' — 307 to the homepage in the same language (System Pages → Homepage;
* needs `redirect`). No homepage assigned, or the homepage itself missing → 404;
* - a function — your own decision, e.g. `({ locale }) => redirect(\`/${locale}/kontakt\`)`.
*/
onMissing?: 'notFound' | 'redirectHome' | ((ctx: { locale: string; segments: string[] }) => never | Promise<never>)
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */ /** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never permanentRedirect: (url: string) => never
/**
* `redirect` from 'next/navigation' — enables Site Settings → Under construction:
* pages that aren't available (and unknown addresses) go to the homepage with the notice.
*/
redirect?: (url: string) => never
/** /**
* Render a route yourself — an archive listing, a blog entry template. * Render a route yourself — an archive listing, a blog entry template.
* Return undefined to keep the default (the document's blocks). * Return undefined to keep the default (the document's blocks).
@@ -57,7 +76,10 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required. * yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/ */
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) { export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
if (onMissing === 'redirectHome' && !redirect) {
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
}
const localeOf = (locale: string | undefined) => { const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')} if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
@@ -69,14 +91,32 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
return helpers.generatePageMetadata(localeOf(locale), slug) return helpers.generatePageMetadata(localeOf(locale), slug)
} }
async function missing(locale: string, segments: string[]): Promise<never> {
if (typeof onMissing === 'function') {return onMissing({ locale, segments })}
// segments.length: the homepage itself is missing — redirecting to it would loop.
if (onMissing === 'redirectHome' && redirect && helpers.getSystemLinks && segments.length) {
const [home] = await helpers.getSystemLinks(locale, ['homepage'])
if (home?.href) {return redirect(home.href)}
}
return notFound()
}
async function Page({ params }: PageArgs) { async function Page({ params }: PageArgs) {
const { slug, locale: param } = await params const { slug, locale: param } = await params
const locale = localeOf(param) const locale = localeOf(param)
const segments = slug ?? [] const segments = slug ?? []
// Under construction: anything but the homepage and the chosen pages → homepage + notice
if (redirect && helpers.getConstructionMode) {
const construction = await helpers.getConstructionMode(locale)
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))}
}
const route = await helpers.resolveRoute(locale, segments, 1) const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) { if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments) const target = await helpers.resolvePageRedirect(locale, segments)
return target ? permanentRedirect(target) : notFound() if (target) {return permanentRedirect(target)}
return missing(locale, segments)
} }
const doc = route.doc const doc = route.doc
const extra = blockProps ? await blockProps({ doc, locale }) : {} const extra = blockProps ? await blockProps({ doc, locale }) : {}
@@ -84,7 +124,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
<RenderBlocks <RenderBlocks
blocks={doc[layoutField] as BlockData[] | undefined} blocks={doc[layoutField] as BlockData[] | undefined}
components={blocks} components={blocks}
enhanceProps={() => ({ locale, ...extra })} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })}
/> />
) )
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
@@ -100,7 +140,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page } return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
} }
export type NotFoundPageOptions = { type NotFoundViewOptions = {
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown> blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
blocks: BlockComponentMap blocks: BlockComponentMap
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */ /** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
@@ -108,31 +148,78 @@ export type NotFoundPageOptions = {
layoutField?: string layoutField?: string
} }
export type NotFoundPageOptions =
| {
/**
* Lazy 404 (recommended): the project's server action returning
* `renderNotFoundView(content, options, locale)`. Next puts the not-found tree
* into the RSC payload of EVERY page; with `load` that tree is a small loader
* and the content is fetched only when a 404 is shown. Without it every page
* carries the whole 404 page in every locale.
*/
load: (locale: string) => Promise<ReactNode>
}
| ({ load?: undefined } & NotFoundViewOptions)
export type { NotFoundViewOptions }
type NotFoundHelpers = Pick<ContentHelpers, 'getConfiguredLocales' | 'getNotFoundPage' | 'i18n'>
async function localesOf(helpers: NotFoundHelpers): Promise<string[]> {
const configured = await helpers.getConfiguredLocales()
return configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
}
async function notFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: string): Promise<ReactNode> {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
if (!doc || !layout?.length) {return typeof fallback === 'function' ? fallback(locale) : fallback}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} />
}
/**
* The 404 page from the panel in ONE locale — for the server action behind
* `createNotFoundPage(content, { load })`. The locale comes from the browser,
* so it is checked against the configured locales (anything else → default).
*
* // src/app/(frontend)/[locale]/notFoundView.ts
* 'use server'
* export async function loadNotFoundView(locale: string) {
* return renderNotFoundView(content, { blocks: blockRegistry }, locale)
* }
*/
export async function renderNotFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: unknown): Promise<ReactNode> {
const locales = await localesOf(helpers)
const safe = typeof locale === 'string' && locales.includes(locale) ? locale : (helpers.i18n?.defaultLocale ?? locales[0])
return notFoundView(helpers, options, safe)
}
/** /**
* app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the * app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the
* visitor's language, WITHOUT headers() (the route stays static): one view per * visitor's language, WITHOUT headers() (the route stays static).
* locale rendered here, <LocaleView> picks the one from the URL.
* *
* Lazy (recommended) — the content is fetched only when a 404 is shown:
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc' * import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
* import { loadNotFoundView } from './notFoundView'
* export default createNotFoundPage(content, { load: loadNotFoundView })
*
* Eager — one view per locale rendered here, <LocaleView> picks the one from the
* URL; Next ships all of them in the payload of every page:
* export default createNotFoundPage(content, { blocks: blockRegistry }) * export default createNotFoundPage(content, { blocks: blockRegistry })
*/ */
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) { export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPageOptions) {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
return async function NotFoundPage() { return async function NotFoundPage() {
const configured = await helpers.getConfiguredLocales() const locales = await localesOf(helpers)
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? ''] const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
if (options.load) {
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} />
}
const eager = options
const views = Object.fromEntries( const views = Object.fromEntries(
await Promise.all( await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)),
locales.map(async (locale) => {
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
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 <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} /> return <LocaleView defaultLocale={defaultLocale} views={views} />
} }
} }
+17 -2
View File
@@ -20,6 +20,17 @@ type BuildRevalidateHookArgs = {
type DocWithSlug = { slug?: unknown } type DocWithSlug = { slug?: unknown }
/**
* Revalidation only makes sense inside a running Next server. Outside it
* (`payload run`, seeds via tsx, migrations) next/cache throws "Invariant: static
* generation store missing". `context.disableRevalidate` (Payload templates'
* convention) skips it on purpose, e.g. in a bulk import.
*/
function shouldRevalidate(context: unknown): boolean {
if (!process.env.NEXT_RUNTIME) {return false}
return !(context && typeof context === 'object' && (context as { disableRevalidate?: unknown }).disableRevalidate)
}
/** Resolve a doc's path in one locale (root for home). Null if no slug there. */ /** Resolve a doc's path in one locale (root for home). Null if no slug there. */
function pathForLocale( function pathForLocale(
doc: DocWithSlug, doc: DocWithSlug,
@@ -47,6 +58,8 @@ function pathForLocale(
* Handles every locale, the root (home), AND a changed slug (revalidates both the * Handles every locale, the root (home), AND a changed slug (revalidates both the
* old and new path so neither goes stale). revalidatePath is injected — the * old and new path so neither goes stale). revalidatePath is injected — the
* plugin never imports next/cache (safe under generate:importmap / plain Node). * plugin never imports next/cache (safe under generate:importmap / plain Node).
* Outside a Next server (no NEXT_RUNTIME: `payload run`, seeds, migrations) and
* with `context: { disableRevalidate: true }` the hooks do nothing.
* *
* // in your Media/Pages collection config, from a project file that CAN import next/cache: * // in your Media/Pages collection config, from a project file that CAN import next/cache:
* import { revalidatePath } from 'next/cache' * import { revalidatePath } from 'next/cache'
@@ -64,7 +77,8 @@ export function buildRevalidateHook({
} { } {
const locales = getLocaleCodes(config) const locales = getLocaleCodes(config)
const afterChange: CollectionAfterChangeHook = ({ doc, previousDoc }) => { const afterChange: CollectionAfterChangeHook = ({ context, doc, previousDoc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>() const seen = new Set<string>()
for (const locale of locales) { for (const locale of locales) {
// New path. // New path.
@@ -85,7 +99,8 @@ export function buildRevalidateHook({
return doc return doc
} }
const afterDelete: CollectionAfterDeleteHook = ({ doc }) => { const afterDelete: CollectionAfterDeleteHook = ({ context, doc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>() const seen = new Set<string>()
for (const locale of locales) { for (const locale of locales) {
const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug) const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
+1 -1
View File
@@ -54,7 +54,7 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
components: { components: {
Field: { Field: {
clientProps: { label, statusField }, clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner', path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
}, },
}, },
}, },
+20 -11
View File
@@ -17,10 +17,18 @@ export type BuildLinkFieldOptions = {
appearances?: false | readonly LinkAppearanceOption[] appearances?: false | readonly LinkAppearanceOption[]
/** Hide the label — for links that wrap something (a whole card, an image). */ /** Hide the label — for links that wrap something (a whole card, an image). */
disableLabel?: boolean disableLabel?: boolean
/**
* Name of the generated TypeScript type. Default depends on the shape, so links of
* different shapes never share one name (payload generate:types would keep only the
* last one processed): `CmsLink`, `CmsLinkPlain` (appearances: false),
* `CmsLinkNoLabel` (disableLabel), `CmsLinkPlainNoLabel` (both). Set it yourself
* when you mix different `appearances` lists or `relationTo` values.
*/
interfaceName?: string
/** Field name. Default 'link'. */ /** Field name. Default 'link'. */
name?: string name?: string
/** Collection the "Page" option points at. Default 'pages'. */ /** Collection the "Page" option points at. Default 'pages'. */
relationTo?: string relationTo?: readonly string[] | string
required?: boolean required?: boolean
/** Upload collection for "File" links (PDF, documents). Default 'media'. */ /** Upload collection for "File" links (PDF, documents). Default 'media'. */
uploadTo?: string uploadTo?: string
@@ -37,7 +45,8 @@ type SiblingWithType = { type?: string } | undefined
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer * there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all. * (resolveLinkHref + the project's CMSLink) handles them all.
* *
* Generates a named TypeScript type `CmsLink` in payload-types.ts. * Generates a named TypeScript type in payload-types.ts — `CmsLink` for the default
* shape, a suffixed name for others (see `interfaceName`). All are assignable to `CmsLink`.
* *
* fields: [buildLinkField()] // single link * fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card * fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
@@ -46,10 +55,13 @@ export function buildLinkField({
name = 'link', name = 'link',
appearances = ['primary', 'secondary', 'link'], appearances = ['primary', 'secondary', 'link'],
disableLabel = false, disableLabel = false,
interfaceName,
relationTo = 'pages', relationTo = 'pages',
required = false, required = false,
uploadTo = 'media', uploadTo = 'media',
}: BuildLinkFieldOptions = {}): GroupField { }: BuildLinkFieldOptions = {}): GroupField {
const hasAppearance = Boolean(appearances && appearances.length)
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
const fields: Field[] = [ const fields: Field[] = [
{ {
type: 'row', type: 'row',
@@ -73,13 +85,10 @@ export function buildLinkField({
}, },
], ],
}, },
{ // One collection → plain relation; several (pages + content entries) → polymorphic.
name: 'page', typeof relationTo === 'string'
type: 'relationship', ? { name: 'page', type: 'relationship', admin: pageAdmin, relationTo, required }
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }, : { name: 'page', type: 'relationship', admin: pageAdmin, relationTo: [...relationTo], required },
relationTo,
required,
},
{ {
name: 'url', name: 'url',
type: 'text', type: 'text',
@@ -107,7 +116,7 @@ export function buildLinkField({
fields.push({ name: 'label', type: 'text', localized: true, required }) fields.push({ name: 'label', type: 'text', localized: true, required })
} }
if (appearances && appearances.length) { if (appearances && hasAppearance) {
const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a)) const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a))
fields.push({ fields.push({
name: 'appearance', name: 'appearance',
@@ -122,7 +131,7 @@ export function buildLinkField({
type: 'group', type: 'group',
admin: { hideGutter: true }, admin: { hideGutter: true },
fields, fields,
interfaceName: 'CmsLink', interfaceName: interfaceName ?? `CmsLink${hasAppearance ? '' : 'Plain'}${disableLabel ? 'NoLabel' : ''}`,
} }
} }
+22 -3
View File
@@ -1,5 +1,6 @@
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import { buildEntryPath } from '../content/paths.js'
import { buildLocalizedPath } from '../i18n/index.js' import { buildLocalizedPath } from '../i18n/index.js'
/** /**
@@ -32,6 +33,12 @@ export type LinkValue = {
} }
export type ResolveLinkHrefOptions = { 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 config: I18nConfig
/** /**
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a * 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 homeSlug?: Record<string, string> | string
locale: 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( export function resolveLinkHref(
link: LinkValue | null | undefined, link: LinkValue | null | undefined,
{ config, homeSlug, locale }: ResolveLinkHrefOptions, { archives, config, homeSlug, locale, pagesSlug = 'pages' }: ResolveLinkHrefOptions,
): null | string { ): null | string {
if (!link) {return null} if (!link) {return null}
@@ -69,12 +78,22 @@ export function resolveLinkHref(
return null return null
} }
// internal (default) // internal (default) — a page, or (polymorphic relation) an entry of a content collection
const page = link.page 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} if (!page || typeof page !== 'object') {return null}
const slug = (page as { slug?: unknown }).slug const slug = (page as { slug?: unknown }).slug
if (typeof slug !== 'string' || !slug) {return null} if (typeof slug !== 'string' || !slug) {return null}
if (collection !== pagesSlug) {
const archiveSlug = archives?.[collection]
return archiveSlug ? buildEntryPath({ archiveSlug, entrySlug: slug, locale }) : null
}
return ( return (
buildLocalizedPath({ buildLocalizedPath({
config, config,
+17 -3
View File
@@ -42,6 +42,13 @@ export const MEDIA_SIZES = {
export type MediaImageOptions = { export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */ /** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string alt?: string
/**
* Dominant colour as the <img> background while it loads. The style stays after
* load, so it would show through transparent pixels (white logo on a black box).
* 'auto' (default): only for JPEG, which has no alpha channel. true: always
* (opaque PNG/WebP photos). false: never.
*/
placeholderColor?: 'auto' | boolean
/** /**
* The LCP image (first visible image — usually the hero): loads eagerly with * The LCP image (first visible image — usually the hero): loads eagerly with
* fetchPriority="high". Exactly one per page; everything else is lazy. * fetchPriority="high". Exactly one per page; everything else is lazy.
@@ -66,6 +73,9 @@ export type MediaImageProps = {
width: number width: number
} }
/** Formats that cannot be transparent — a background colour never shows through. */
const NO_ALPHA = new Set(['image/jpeg', 'image/jpg', 'image/pjpeg'])
const asDoc = (resource: unknown): MediaDoc | null => const asDoc = (resource: unknown): MediaDoc | null =>
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
@@ -74,14 +84,18 @@ const asDoc = (resource: unknown): MediaDoc | null =>
* a bare id). Width/height always come from the document — no layout shift. * a bare id). Width/height always come from the document — no layout shift.
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped * Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a * image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
* blur-up and background colour. * blur-up and — for JPEG only, see `placeholderColor` — a background colour.
*/ */
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null { export function mediaImageProps(
resource: unknown,
{ alt, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
): MediaImageProps | null {
const doc = asDoc(resource) const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null} if (!doc || doc.mimeType?.startsWith('video/')) {return null}
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
const blur = doc.placeholder?.blurDataURL ?? undefined const blur = doc.placeholder?.blurDataURL ?? undefined
const color = doc.placeholder?.color ?? undefined const useColor = placeholderColor === 'auto' ? NO_ALPHA.has(doc.mimeType ?? '') : placeholderColor
const color = useColor ? (doc.placeholder?.color ?? undefined) : undefined
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50) const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
const style = { const style = {
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}), ...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
+3 -2
View File
@@ -48,11 +48,12 @@ export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined
if (!buffer) {return} if (!buffer) {return}
const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer() const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
const { dominant } = await sharp(buffer).stats() const { dominant, isOpaque } = await sharp(buffer).stats()
const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0') const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0')
data[field] = { data[field] = {
blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`, blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`,
color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}`, // Transparent images (logos, icons) get no colour — it would show through the alpha.
color: isOpaque ? `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}` : null,
} }
} catch (err) { } catch (err) {
// A placeholder is a nicety — never block the upload. // A placeholder is a nicety — never block the upload.
+3 -3
View File
@@ -5,6 +5,8 @@ import type { ReactNode } from 'react'
// Bundlers in the project resolve the same file either way. // Bundlers in the project resolve the same file either way.
import { usePathname } from 'next/navigation.js' import { usePathname } from 'next/navigation.js'
import { localeFromPath } from './localeFromPath.js'
type LocaleViewProps = { type LocaleViewProps = {
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */ /** Used when the URL has no locale segment (single-locale site) or an unknown one. */
defaultLocale: string defaultLocale: string
@@ -25,8 +27,6 @@ type LocaleViewProps = {
* it also runs during SSR, so the HTML already contains the right language. * it also runs during SSR, so the HTML already contains the right language.
*/ */
export function LocaleView({ defaultLocale, views }: LocaleViewProps) { export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
const pathname = usePathname() ?? '' const locale = localeFromPath(usePathname() ?? '', Object.keys(views), defaultLocale)
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = segment in views ? segment : defaultLocale
return <>{views[locale] ?? views[defaultLocale] ?? null}</> return <>{views[locale] ?? views[defaultLocale] ?? null}</>
} }
+47
View File
@@ -0,0 +1,47 @@
'use client'
import type { ReactNode } from 'react'
// '.js' is required: `next` has no package.json "exports" (see LocaleView.tsx).
import { usePathname } from 'next/navigation.js'
import { useEffect, useState } from 'react'
import { localeFromPath } from './localeFromPath.js'
type NotFoundLoaderProps = {
defaultLocale: string
/** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */
load: (locale: string) => Promise<ReactNode>
locales: string[]
}
/**
* The 404 content, fetched only when the 404 is actually shown.
*
* Next puts the `not-found` tree of a layout into the RSC payload of EVERY page
* under it (the router needs it for a client-side 404). A 404 page with real
* content (often the homepage) rendered there in every locale multiplied the
* size of each page. Here only this small component is in the payload; the
* content comes from a server action on mount.
*/
export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) {
const pathname = usePathname() ?? ''
const locale = localeFromPath(pathname, locales, defaultLocale)
const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null)
useEffect(() => {
let active = true
load(locale)
.then((node) => {
if (active) {setView({ locale, node })}
})
.catch((error: unknown) => {
// the status is already 404 — without the content the page stays empty, the error goes to the console
console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error)
})
return () => {
active = false
}
}, [load, locale])
return <>{view?.locale === locale ? view.node : null}</>
}
+8
View File
@@ -0,0 +1,8 @@
/**
* The locale from the first URL segment (`/en/...` → `en`), or `defaultLocale`
* when the segment isn't one of `locales` (single-locale site, unknown prefix).
*/
export function localeFromPath(pathname: string, locales: readonly string[], defaultLocale: string): string {
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
return locales.includes(segment) ? segment : defaultLocale
}
+56 -2
View File
@@ -1,7 +1,10 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical' import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react' import type { JSXConverters, JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react' import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
export type RenderRichTextProps = { export type RenderRichTextProps = {
/** Wrapper class (e.g. Tailwind prose classes). */ /** Wrapper class (e.g. Tailwind prose classes). */
@@ -20,6 +23,46 @@ export type RenderRichTextProps = {
* is needed here (unlike hand-rolled renderers that hardcode `.pl`). * is needed here (unlike hand-rolled renderers that hardcode `.pl`).
*/ */
data: null | SerializedEditorState | undefined data: null | SerializedEditorState | undefined
/**
* Anchor ids on headings — the same ids as extractHeadings, so a
* <TableOfContents> links to them. `true` = h2; or `{ levels, className }`
* (className e.g. `scroll-mt-24` under a sticky header). Your own `heading`
* converter still renders the heading; the id is added to what it returns.
*/
headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean
}
type HeadingNode = { children?: unknown[]; tag: HeadingLevel }
/** Adds ids (and an optional class) to headings, on top of the project's converters. */
function withHeadingIds(
converters: JSXConvertersFunction | undefined,
ids: Map<object, { id: string }>,
className: string | undefined,
): JSXConvertersFunction {
return (args) => {
const base: JSXConverters = converters ? converters(args) : args.defaultConverters
const inner = base.heading
return {
...base,
heading: (props: { node: HeadingNode; nodesToJSX: (a: { nodes: unknown[] }) => ReactNode[] }) => {
const anchor = ids.get(props.node)
const rendered: ReactNode =
typeof inner === 'function'
? (inner as (p: typeof props) => ReactNode)(props)
: (() => {
const Tag = props.node.tag
return <Tag>{props.nodesToJSX({ nodes: props.node.children ?? [] })}</Tag>
})()
if (!anchor || !isValidElement(rendered)) {return rendered}
const el = rendered as ReactElement<{ className?: string; id?: string }>
const cls = [el.props.className, className].filter(Boolean).join(' ') || undefined
// The project's converter owns the markup; only the id is added to what it returned.
// eslint-disable-next-line @eslint-react/no-clone-element
return cloneElement(el, { id: anchor.id, ...(cls ? { className: cls } : {}) })
},
} as JSXConverters
}
} }
/** /**
@@ -48,8 +91,19 @@ export type RenderRichTextProps = {
* }, * },
* }) * })
* <RenderRichText data={page.content} converters={converters} /> * <RenderRichText data={page.content} converters={converters} />
*
* // long document with a table of contents (same ids on both sides):
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
*/ */
export function RenderRichText({ className, converters, data }: RenderRichTextProps) { export function RenderRichText({ className, converters, data, headingIds }: RenderRichTextProps) {
if (!data) {return null} if (!data) {return null}
if (headingIds) {
const opts = headingIds === true ? {} : headingIds
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
if (ids.size) {
return <PayloadRichText className={className} converters={withHeadingIds(converters, ids, opts.className)} data={data} />
}
}
return <PayloadRichText className={className} converters={converters} data={data} /> return <PayloadRichText className={className} converters={converters} data={data} />
} }
+83
View File
@@ -0,0 +1,83 @@
'use client'
import { useEffect, useState } from 'react'
import type { HeadingItem } from './headings.js'
export type TableOfContentsClassNames = {
item?: string
label?: string
/** Every link. */
link?: string
/** Added to the link of the section being read. */
linkActive?: string
list?: string
nav?: string
}
export type TableOfContentsProps = {
classNames?: TableOfContentsClassNames
/** From extractHeadings — the same ids as the headings rendered with `headingIds`. */
items: readonly ({ level?: HeadingItem['level'] } & Pick<HeadingItem, 'id' | 'text'>)[]
/** Text above the list (from the panel). Also the nav's accessible name. Empty → none. */
label?: null | string
/**
* Where the "reading line" is, as a fraction of the viewport height: the
* current section is the last heading above it. Default 0.3.
*/
offset?: number
}
/**
* Table of contents with no styles: a <nav> with links to the headings. The
* server renders the full list (works without JS); in the browser the link of
* the section being read gets `aria-current="location"` and `classNames.linkActive`.
* Hooks for CSS: data-ipal="toc", data-level on each item.
*/
export function TableOfContents({ classNames: cn = {}, items, label, offset = 0.3 }: TableOfContentsProps) {
const [active, setActive] = useState<string | undefined>(items[0]?.id)
useEffect(() => {
const headings = items.map((item) => document.getElementById(item.id)).filter((el): el is HTMLElement => el !== null)
if (headings.length === 0) {return}
const update = () => {
const line = window.innerHeight * offset
let current = headings[0].id
for (const heading of headings) {
if (heading.getBoundingClientRect().top <= line) {current = heading.id}
}
setActive(current)
}
update()
window.addEventListener('scroll', update, { passive: true })
window.addEventListener('resize', update)
return () => {
window.removeEventListener('scroll', update)
window.removeEventListener('resize', update)
}
}, [items, offset])
if (items.length === 0) {return null}
const text = label?.trim()
return (
<nav aria-label={text || undefined} className={cn.nav} data-ipal="toc">
{text ? <p aria-hidden className={cn.label}>{text}</p> : null}
<ol className={cn.list}>
{items.map((item) => {
const current = item.id === active
return (
<li className={cn.item} data-level={item.level} key={item.id}>
<a
aria-current={current ? 'location' : undefined}
className={[cn.link, current ? cn.linkActive : undefined].filter(Boolean).join(' ') || undefined}
href={`#${item.id}`}
>
{item.text}
</a>
</li>
)
})}
</ol>
</nav>
)
}
+80
View File
@@ -0,0 +1,80 @@
import type { Field, GroupField } from 'payload'
import { toSlug } from '../slug/buildSlugField.js'
export type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
/** One table-of-contents entry: the heading's anchor id, its plain text and level. */
export type HeadingItem = { id: string; level: HeadingLevel; text: string }
export type ExtractHeadingsOptions = {
/** Heading levels that get an anchor and a TOC entry. Default ['h2'] (sections of a document). */
levels?: readonly HeadingLevel[]
}
type LexicalNode = { children?: LexicalNode[]; tag?: string; text?: string; type?: string }
/** Plain text of a Lexical node (a heading with bold parts, links…). */
export function headingText(node: unknown): string {
const n = node as LexicalNode
if (typeof n?.text === 'string') {return n.text}
return (n?.children ?? []).map(headingText).join('')
}
/**
* Walks the document in reading order and gives every heading of the chosen
* levels an id: slug of its text (toSlug), repeats get "-2", "-3"; an empty
* heading gets "section". Keyed by the node object, so RenderRichText puts
* exactly these ids on exactly these headings.
*/
export function headingIds(data: unknown, { levels = ['h2'] }: ExtractHeadingsOptions = {}): Map<object, HeadingItem> {
const wanted = new Set<string>(levels)
const seen = new Map<string, number>()
const out = new Map<object, HeadingItem>()
const walk = (node: LexicalNode) => {
if (node.type === 'heading' && node.tag && wanted.has(node.tag)) {
const text = headingText(node).replace(/\s+/g, ' ').trim()
const base = toSlug(text) || 'section'
const count = (seen.get(base) ?? 0) + 1
seen.set(base, count)
out.set(node, { id: count === 1 ? base : `${base}-${count}`, level: node.tag as HeadingLevel, text })
return
}
for (const child of node.children ?? []) {walk(child)}
}
const root = (data as { root?: LexicalNode } | null | undefined)?.root
if (root) {walk(root)}
return out
}
/**
* Table-of-contents entries of a rich-text field — the same ids RenderRichText
* gives the headings with `headingIds`. Empty headings are left out.
*
* const items = extractHeadings(block.content) // h2 only
* <TableOfContents items={items} label={block.tableOfContents?.label} />
* <RenderRichText data={block.content} headingIds />
*/
export function extractHeadings(data: unknown, options: ExtractHeadingsOptions = {}): HeadingItem[] {
return [...headingIds(data, options).values()].filter((h) => h.text.length > 0)
}
/**
* Panel switch for a table of contents on a text section: `show` + the label
* above the list ("Contents"), localized. Named type `TableOfContentsSettings`.
*
* fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }]
*/
export function buildTableOfContentsField({ name = 'tableOfContents' }: { name?: string } = {}): GroupField {
const fields: Field[] = [
{ name: 'show', type: 'checkbox', admin: { description: 'List of the section headings (H2) with links to them — for long documents.' }, label: 'Show table of contents' },
{
name: 'label',
type: 'text',
admin: { condition: (_: unknown, s: { show?: boolean } | undefined) => Boolean(s?.show), description: 'Heading above the list, e.g. "Contents". Empty → none.' },
label: 'Label',
localized: true,
},
]
return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: 'Table of contents' }
}
+2
View File
@@ -1,3 +1,5 @@
export { buildTableOfContentsField, extractHeadings, headingIds, headingText } from './headings.js'
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './headings.js'
export { lexicalToMarkdown } from './lexicalToMarkdown.js' export { lexicalToMarkdown } from './lexicalToMarkdown.js'
export { RenderRichText } from './RenderRichText.js' export { RenderRichText } from './RenderRichText.js'
export type { RenderRichTextProps } from './RenderRichText.js' export type { RenderRichTextProps } from './RenderRichText.js'
+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, locale,
order: site.order, order: site.order,
separator: site.separator, separator: site.separator,
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
siteDescription: site.siteDescription,
siteName: site.siteName, siteName: site.siteName,
} }
+1
View File
@@ -11,6 +11,7 @@ export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js' export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js' export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js' export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
export { buildProductJsonLd } from './buildProductJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js' export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js' export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.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' } type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
export type ImagesConfig = { export type ImagesConfig = {
/** Development only: lets next/image optimize files served by the app itself on localhost. */
dangerouslyAllowLocalIP?: boolean
formats: ('image/avif' | 'image/webp')[] formats: ('image/avif' | 'image/webp')[]
minimumCacheTTL: number minimumCacheTTL: number
remotePatterns: RemotePattern[] remotePatterns: RemotePattern[]
@@ -11,15 +13,20 @@ export type ImagesConfig = {
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality; * - 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 * - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
* optimize R2 files — otherwise it refuses them; * 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' * import { buildImagesConfig } from '@intecion/ipal-kit'
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } }) * export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
*/ */
export function buildImagesConfig({ export function buildImagesConfig({
extraHosts = [], extraHosts = [],
production = process.env.NODE_ENV === 'production',
publicUrl = process.env.R2_PUBLIC_URL, 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[] = [] const remotePatterns: RemotePattern[] = []
if (publicUrl && /^https?:\/\//i.test(publicUrl)) { if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
const u = new URL(publicUrl) const u = new URL(publicUrl)
@@ -31,5 +38,21 @@ export function buildImagesConfig({
}) })
} }
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })} 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 } : {}),
}
} }
+17
View File
@@ -0,0 +1,17 @@
import type { ThemeConfig } from './theme.js'
import { themeScript } from './theme.js'
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
/**
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
* theme. Put it first in <body> (or turn on `theme` in <SiteProviders>), and
* add `suppressHydrationWarning` to <html>: the attribute differs from the server HTML on purpose.
*
* const shell = await getSiteShell(locale)
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
*/
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
}
+52
View File
@@ -0,0 +1,52 @@
'use client'
import type { ReactNode } from 'react'
import { Moon, Sun } from 'lucide-react'
import type { Theme } from './theme.js'
import { useTheme } from './useTheme.js'
export type ThemeSwitcherClassNames = {
/** Wrapper of the dark icon. */
dark?: string
/** Wrapper of the light icon. */
light?: string
/** The <button>. */
root?: string
}
export type ThemeSwitcherProps = {
classNames?: ThemeSwitcherClassNames
/** Accessible name — Site Settings → Theme → Toggle label (shell.theme.toggleLabel). */
label?: null | string
/** Your icons. Default lucide Sun / Moon. `null` → no icon. */
renderIcon?: (theme: Theme) => ReactNode
}
/**
* Light / dark switch with no styles: a <button role="switch"> (checked = dark)
* holding a light and a dark icon. Which one looks active is CSS's job — from
* the attribute on <html> (`[data-theme=dark] …`, Tailwind `dark:`), so the
* server HTML is already right and nothing jumps after hydration.
* Hooks: data-ipal="theme-switch", data-ipal-theme-icon="light|dark".
*/
export function ThemeSwitcher({ classNames: cn = {}, label, renderIcon }: ThemeSwitcherProps) {
const { theme, toggle } = useTheme()
const icon = (t: Theme) => (renderIcon ? renderIcon(t) : t === 'light' ? <Sun aria-hidden size="1.25em" /> : <Moon aria-hidden size="1.15em" />)
return (
<button
aria-checked={theme === 'dark'}
aria-label={label ?? undefined}
className={cn.root}
data-ipal="theme-switch"
onClick={toggle}
role="switch"
type="button"
>
<span className={cn.light} data-ipal-theme-icon="light">{icon('light')}</span>
<span className={cn.dark} data-ipal-theme-icon="dark">{icon('dark')}</span>
</button>
)
}
+2
View File
@@ -0,0 +1,2 @@
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE, themeConfigFrom, themeScript } from './theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from './theme.js'
+60
View File
@@ -0,0 +1,60 @@
/**
* Light / dark theme — shared names and the pre-paint script. Pure: safe on the
* server and in the browser.
*
* The theme never reaches the server HTML (pages are ISR/SSG, one HTML for
* everyone): <ThemeScript> sets `data-theme` on <html> before the first paint,
* from the visitor's choice (localStorage — an interface preference, no cookie,
* no tracking, no consent needed) or Site Settings → Theme → Default theme.
*/
export type Theme = 'dark' | 'light'
/** Site Settings → Default theme. 'system' follows the device (prefers-color-scheme). */
export type ThemeSetting = 'system' | Theme
/** localStorage key of the visitor's choice. */
export const THEME_STORAGE_KEY = 'ipal-theme'
/** Attribute on <html>: `[data-theme=dark]`, Tailwind `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`. */
export const THEME_ATTRIBUTE = 'data-theme'
/** Set on <html> for a moment while switching — for a colour transition only then (`[data-theme-switching] * { transition: … }`). */
export const THEME_SWITCHING_ATTRIBUTE = 'data-theme-switching'
export const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark'
export const isThemeSetting = (value: unknown): value is ThemeSetting => value === 'system' || isTheme(value)
/** Theme options from Site Settings — what getSiteShell(locale).theme holds. */
export type ThemeConfig = {
/** Visitors may switch (and their choice is remembered). */
allowToggle: boolean
/** null: no Site Settings — no attribute, the base (light) CSS applies. */
defaultTheme: null | ThemeSetting
/** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */
toggleLabel: null | string
}
/** Reads Theme options from a Site Settings document. */
export function themeConfigFrom(settings: unknown): ThemeConfig {
const s = (settings && typeof settings === 'object' ? settings : {}) as Record<string, unknown>
const label = typeof s.themeToggleLabel === 'string' && s.themeToggleLabel.trim() ? s.themeToggleLabel.trim() : null
return {
allowToggle: s.allowThemeToggle === true,
defaultTheme: isThemeSetting(s.defaultTheme) ? s.defaultTheme : null,
toggleLabel: label,
}
}
/**
* The inline script for <ThemeScript>: stored choice (only when the toggle is
* allowed) → default theme → for 'system' the device setting. Sets
* `data-theme` and `color-scheme` (native controls, scrollbars) on <html>.
*/
export function themeScript({ allowToggle, defaultTheme }: Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>): string {
const stored = allowToggle
? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}`
: ''
return (
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${stored}` +
`if(t==='system')t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';` +
`if(t==='light'||t==='dark'){d.setAttribute(${JSON.stringify(THEME_ATTRIBUTE)},t);d.style.colorScheme=t}})()`
)
}
+62
View File
@@ -0,0 +1,62 @@
'use client'
import { useCallback, useSyncExternalStore } from 'react'
import { isTheme, type Theme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from './theme.js'
/** The theme on <html> (after ThemeScript); null before it ran / without a theme. */
export function readDocumentTheme(): null | Theme {
if (typeof document === 'undefined') {return null}
const value = document.documentElement.getAttribute(THEME_ATTRIBUTE)
return isTheme(value) ? value : null
}
/**
* Puts a theme on <html> and remembers the choice. `transitionMs` keeps
* `data-theme-switching` on <html> for that long — style a colour transition
* with it, so normal hovers stay instant.
*/
export function applyTheme(theme: Theme, { persist = true, transitionMs = 300 }: { persist?: boolean; transitionMs?: number } = {}): void {
const root = document.documentElement
if (transitionMs > 0) {
root.setAttribute(THEME_SWITCHING_ATTRIBUTE, '')
window.setTimeout(() => root.removeAttribute(THEME_SWITCHING_ATTRIBUTE), transitionMs)
}
root.setAttribute(THEME_ATTRIBUTE, theme)
root.style.colorScheme = theme
if (!persist) {return}
try {
localStorage.setItem(THEME_STORAGE_KEY, theme)
} catch {
// private mode / blocked storage: the theme works until reload, the choice isn't kept
}
}
// <html data-theme> is external state: ThemeScript sets it, another tab changes it (storage event).
function subscribe(onChange: () => void): () => void {
const observer = new MutationObserver(onChange)
observer.observe(document.documentElement, { attributeFilter: [THEME_ATTRIBUTE], attributes: true })
const onStorage = (event: StorageEvent) => {
if (event.key === THEME_STORAGE_KEY && isTheme(event.newValue)) {applyTheme(event.newValue, { persist: false, transitionMs: 0 })}
}
window.addEventListener('storage', onStorage)
return () => {
observer.disconnect()
window.removeEventListener('storage', onStorage)
}
}
const serverSnapshot = (): null | Theme => null
/**
* The current theme and a setter. `theme` is null on the server and during
* hydration of a page without a theme — style the switch from CSS
* (`[data-theme=dark] …`, Tailwind `dark:`), not from this value, so nothing
* jumps after hydration.
*/
export function useTheme(): { setTheme: (theme: Theme) => void; theme: null | Theme; toggle: () => void } {
const theme = useSyncExternalStore(subscribe, readDocumentTheme, serverSnapshot)
const setTheme = useCallback((next: Theme) => applyTheme(next), [])
const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark'), [])
return { setTheme, theme, toggle }
}
+28 -4
View File
@@ -1,9 +1,12 @@
'use client' 'use client'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { useTheme } from '../theme/useTheme.js'
declare global { declare global {
interface Window { interface Window {
turnstile?: { turnstile?: {
remove?: (id: string) => void
render: (el: HTMLElement, opts: Record<string, unknown>) => string render: (el: HTMLElement, opts: Record<string, unknown>) => string
reset: (id?: string) => void reset: (id?: string) => void
} }
@@ -32,9 +35,15 @@ export type TurnstileProps = {
* client component and can't read Payload itself. * client component and can't read Payload itself.
*/ */
siteKey: string siteKey: string
theme?: 'auto' | 'dark' | 'light' /**
* 'page' (default): the site's theme (data-theme on <html>, ThemeScript) — a dark
* widget on a dark page; no site theme → 'auto' (the device's). Or fixed.
*/
theme?: TurnstileTheme
} }
export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page'
/** /**
* Cloudflare Turnstile widget — reusable across any form. Renders the challenge * Cloudflare Turnstile widget — reusable across any form. Renders the challenge
* and reports the token via onToken. The token must then be verified * and reports the token via onToken. The token must then be verified
@@ -45,9 +54,24 @@ export type TurnstileProps = {
* The script is injected directly (no next/script dependency) so the widget * The script is injected directly (no next/script dependency) so the widget
* stays framework-agnostic. * stays framework-agnostic.
*/ */
export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps) { export function Turnstile({ onToken, siteKey, theme = 'page' }: TurnstileProps) {
const ref = useRef<HTMLDivElement>(null) const ref = useRef<HTMLDivElement>(null)
const widgetId = useRef<null | string>(null) const widgetId = useRef<null | string>(null)
const pageTheme = useTheme().theme
const widgetTheme = theme === 'page' ? (pageTheme ?? 'auto') : theme
const renderedTheme = useRef(widgetTheme)
// The page switched theme: drop the widget so the effect below draws it again in the new one.
// Declared first, so it runs before the render effect.
useEffect(() => {
if (renderedTheme.current === widgetTheme) {return}
renderedTheme.current = widgetTheme
if (widgetId.current && window.turnstile?.remove) {
window.turnstile.remove(widgetId.current)
widgetId.current = null
onToken(null)
}
}, [widgetTheme, onToken])
useEffect(() => { useEffect(() => {
if (!siteKey) {return} if (!siteKey) {return}
@@ -61,7 +85,7 @@ export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps)
'error-callback': () => onToken(null), 'error-callback': () => onToken(null),
'expired-callback': () => onToken(null), 'expired-callback': () => onToken(null),
sitekey: siteKey, sitekey: siteKey,
theme, theme: widgetTheme,
}) })
} }
@@ -69,7 +93,7 @@ export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps)
// Script may load after mount — retry briefly until ready. // Script may load after mount — retry briefly until ready.
const interval = setInterval(render, 300) const interval = setInterval(render, 300)
return () => clearInterval(interval) return () => clearInterval(interval)
}, [siteKey, theme, onToken]) }, [siteKey, widgetTheme, onToken])
if (!siteKey) {return null} if (!siteKey) {return null}
+4 -2
View File
@@ -2,6 +2,8 @@
import { createContext, use, useCallback, useState } from 'react' import { createContext, use, useCallback, useState } from 'react'
import type { TurnstileTheme } from './Turnstile.js'
import { Turnstile } from './Turnstile.js' import { Turnstile } from './Turnstile.js'
type TurnstileContextValue = { type TurnstileContextValue = {
@@ -58,7 +60,7 @@ export function useTurnstile(): {
enabled: boolean enabled: boolean
reset: () => void reset: () => void
token: null | string token: null | string
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
} { } {
const ctx = use(TurnstileContext) const ctx = use(TurnstileContext)
if (!ctx) { if (!ctx) {
@@ -84,7 +86,7 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
const reset = useCallback(() => setToken(null), [setToken]) const reset = useCallback(() => setToken(null), [setToken])
const TurnstileWidget = useCallback( const TurnstileWidget = useCallback(
(props?: { theme?: 'auto' | 'dark' | 'light' }) => { (props?: { theme?: TurnstileTheme }) => {
if (!siteKey) {return null} if (!siteKey) {return null}
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} /> return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
}, },
+1 -1
View File
@@ -2,5 +2,5 @@
// Client-only exports — the Turnstile widget. Kept separate from index.ts so // Client-only exports — the Turnstile widget. Kept separate from index.ts so
// the server-only verify never leaks into a browser bundle. // the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js' export { Turnstile } from './Turnstile.js'
export type { TurnstileProps } from './Turnstile.js' export type { TurnstileProps, TurnstileTheme } from './Turnstile.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js' export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'
+4
View File
@@ -8,8 +8,10 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js' import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js' import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { emailSettingsFields } from './modules/forms/emailLayout.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSystemPagesFields } from './modules/pages/index.js'
@@ -212,6 +214,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.globals ?? []), ...(config.globals ?? []),
buildSiteSettings({ buildSiteSettings({
additionalFields: options.siteSettingsFields, additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
systemPageFields, systemPageFields,
}), }),
buildSiteIntegrations({ additionalFields: options.integrationsFields }), buildSiteIntegrations({ additionalFields: options.integrationsFields }),
+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 { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.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', () => ({})) vi.mock('server-only', () => ({}))
@@ -131,3 +131,51 @@ describe('RenderForm', () => {
expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull() 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()
})
})
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, test } from 'vitest'
import type { BuilderField } from '../src/modules/forms/builderTypes.js'
import { inputFields, splitSteps, validateBuilderFields, visibleFields } from '../src/modules/forms/builderLogic.js'
import { validateSubmission } from '../src/modules/forms/validateSubmission.js'
import { fakePayload } from './helpers.js'
// A brief: screen 1 picks the areas, each later Step shows only for its area.
const fields: BuilderField[] = [
{ name: 'company', blockType: 'text', required: true },
{ name: 'areas', blockType: 'checkboxGroup', options: [{ value: 'web' }, { value: 'mkt' }, { value: 'it' }], required: true },
{ name: 'deadline', blockType: 'radio', options: [{ value: 'fixed' }, { value: 'flexible' }] },
{ name: 'deadline_reason', blockType: 'text', showWhen: { field: 'deadline', values: 'fixed' } },
{ name: 'consent', blockType: 'checkbox', required: true },
{ blockType: 'step', showWhen: { field: 'areas', values: 'web' }, title: 'Website' },
{ name: 'site_type', blockType: 'radio', options: [{ value: 'new' }, { value: 'redesign' }], required: true },
{ name: 'site_problems', blockType: 'textarea', showWhen: { field: 'site_type', values: 'redesign' } },
{ blockType: 'step', showWhen: { field: 'areas', values: 'mkt' }, title: 'Marketing' },
{ name: 'ads_budget', blockType: 'text', required: true },
{ blockType: 'step', showWhen: { field: 'areas', values: 'it, web' }, title: 'IT' },
{ name: 'it_scope', blockType: 'text' },
]
const names = (list: BuilderField[]) => inputFields(list).map((f) => f.name)
const texts = { validation: 'Check {field}' }
describe('conditional fields and steps (showWhen)', () => {
test('nothing picked → only the first screen; a field shows when its value matches', () => {
expect(names(visibleFields(fields, {}))).toEqual(['company', 'areas', 'deadline', 'consent'])
expect(names(visibleFields(fields, { deadline: 'fixed' }))).toContain('deadline_reason')
expect(names(visibleFields(fields, { deadline: 'flexible' }))).not.toContain('deadline_reason')
})
test('a Step with a failed condition drops out with all its fields; any of the listed values matches', () => {
const steps = splitSteps(visibleFields(fields, { areas: ['mkt'] }))
expect(steps.map((s) => s.title)).toEqual([undefined, 'Marketing'])
expect(splitSteps(visibleFields(fields, { areas: ['web'] })).map((s) => s.title)).toEqual([undefined, 'Website', 'IT'])
})
test('hidden fields and Steps leave the rest with their original index (message blocks render by it)', () => {
const list: BuilderField[] = [
{ name: 'pick', blockType: 'radio', options: [{ value: 'a' }, { value: 'b' }] },
{ blockType: 'step', showWhen: { field: 'pick', values: 'a' }, title: 'A' },
{ blockType: 'message' },
{ blockType: 'step', showWhen: { field: 'pick', values: 'b' }, title: 'B' },
{ blockType: 'message' },
]
const shown = new Set(visibleFields(list, { pick: 'b' }))
const steps = splitSteps(list, (field) => shown.has(field))
expect(steps.map((s) => ({ indexes: s.fields.map(({ index }) => index), title: s.title }))).toEqual([
{ indexes: [0], title: undefined },
{ indexes: [4], title: 'B' },
])
})
test('a field inside a hidden Step stays hidden even when its own condition matches', () => {
expect(names(visibleFields(fields, { areas: ['mkt'], site_type: 'redesign' }))).not.toContain('site_problems')
expect(names(visibleFields(fields, { areas: ['web'], site_type: 'redesign' }))).toContain('site_problems')
})
test('empty values = when the field is filled in or ticked; unknown field or a cycle hides', () => {
const list: BuilderField[] = [
{ name: 'a', blockType: 'checkbox' },
{ name: 'b', blockType: 'text', showWhen: { field: 'a' } },
{ name: 'c', blockType: 'text', showWhen: { field: 'typo' } },
{ name: 'd', blockType: 'text', showWhen: { field: 'e' } },
{ name: 'e', blockType: 'text', showWhen: { field: 'd' } },
]
expect(names(visibleFields(list, { a: false }))).toEqual(['a'])
expect(names(visibleFields(list, { a: true }))).toEqual(['a', 'b'])
})
test('validation of visible fields only: a hidden required field does not block', () => {
const values = { areas: ['mkt'], company: 'X', consent: true }
expect(validateBuilderFields(inputFields(visibleFields(fields, values)), values, texts)).toEqual({ ads_budget: 'Check ads_budget' })
expect(validateBuilderFields(inputFields(visibleFields(fields, { ...values, areas: ['it'] })), values, texts)).toEqual({})
})
})
describe('server: validateSubmission follows the same conditions', () => {
const { payload } = fakePayload({ forms: { brief: { fields } } })
const check = (data: Record<string, unknown>) => validateSubmission(payload, 'brief', data)
test('a required field in a hidden Step is not required — and its value is not stored', async () => {
const result = await check({ ads_budget: 'smuggled', areas: ['it'], company: 'X', consent: true, it_scope: 'servers' })
expect(result).toMatchObject({ cleaned: { areas: ['it'], company: 'X', consent: true, it_scope: 'servers' }, ok: true })
expect(result.ok && 'ads_budget' in result.cleaned).toBe(false)
})
test('a required field in a visible Step is still enforced', async () => {
expect(await check({ areas: ['mkt'], company: 'X', consent: true })).toMatchObject({ field: 'ads_budget', kind: 'required', ok: false })
})
test('GDPR consent is enforced even if an editor hides it with a condition', async () => {
const { payload: p } = fakePayload({
forms: { f: { fields: [{ name: 'company', blockType: 'text' }, { name: 'consent', blockType: 'checkbox', showWhen: { field: 'company', values: 'never' } }] } },
})
expect(await validateSubmission(p, 'f', { company: 'X' })).toMatchObject({ field: 'consent', ok: false, reason: 'consent' })
})
})
+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) 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([])
})
})
+7
View File
@@ -74,6 +74,7 @@ describe('form validation — choice lists and dates', () => {
{ name: 'services', blockType: 'checkboxGroup', maxSelected: 2, minSelected: 1, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] }, { name: 'services', blockType: 'checkboxGroup', maxSelected: 2, minSelected: 1, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ name: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] }, { name: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] },
{ name: 'deadline', blockType: 'date' }, { name: 'deadline', blockType: 'date' },
{ name: 'hour', blockType: 'time' },
{ blockType: 'step' }, { blockType: 'step' },
], ],
}, },
@@ -96,6 +97,12 @@ describe('form validation — choice lists and dates', () => {
expect(await v({ deadline: '2026-13-45' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' }) expect(await v({ deadline: '2026-13-45' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
}) })
test('time: HH:MM within a day', async () => {
expect(await v({ hour: ' 09:30 ' })).toMatchObject({ cleaned: { hour: '09:30' }, ok: true })
expect(await v({ hour: '24:00' })).toMatchObject({ field: 'hour', kind: 'invalid_format' })
expect(await v({ hour: 'rano' })).toMatchObject({ field: 'hour', kind: 'invalid_format' })
})
test('a Step block carries no value and is not an unknown field', async () => { test('a Step block carries no value and is not an unknown field', async () => {
expect(await v({})).toMatchObject({ ok: true }) expect(await v({})).toMatchObject({ ok: true })
}) })
+54 -1
View File
@@ -13,7 +13,7 @@ import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js' import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js' import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConsentTexts.js'
import { submitForm } from '../src/modules/forms/submitForm.js' import { submitForm } from '../src/modules/forms/submitForm.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js' import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
@@ -239,6 +239,10 @@ describe('one-call helpers — layout, page, GEO routes', () => {
const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect }) const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect })
const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } } const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } }
expect(JSON.stringify(el.props.children[0])).toContain('Usługi') 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') 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') expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi')
}) })
@@ -257,6 +261,22 @@ describe('one-call helpers — layout, page, GEO routes', () => {
const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) }) const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) })
expect(md.status).toBe(200) expect(md.status).toBe(200)
}) })
test('single-language Markdown: app/md/[[...slug]] (no locale param) and the [locale] route both serve the page', async () => {
const helpers = h()
const noLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'] }) })
expect(noLocale.status).toBe(200)
const plain = await noLocale.text()
expect(plain).toContain('url: https://acme.pl/uslugi')
expect(plain).toContain('locale: pl')
// [locale] route on a one-language site: "/md/uslugi" arrives as locale "uslugi"
const asLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ locale: 'uslugi' }) })
expect(asLocale.status).toBe(200)
const body = await asLocale.text()
expect(body).toContain('# Usługi')
expect(body).toContain('url: https://acme.pl/uslugi')
expect(body).toContain('locale: pl')
})
}) })
describe('consent log', () => { describe('consent log', () => {
@@ -288,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', () => { describe('cookie table', () => {
test('rows from Cookie Settings in the requested language', async () => { test('rows from Cookie Settings in the requested language', async () => {
await payload.updateGlobal({ await payload.updateGlobal({
+28
View File
@@ -1,12 +1,24 @@
import { describe, expect, test } from 'vitest' import { describe, expect, test } from 'vitest'
import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js' 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' 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 const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const
const opts = { config, homeSlug: 'start', locale: 'pl' } const opts = { config, homeSlug: 'start', locale: 'pl' }
const page = (slug: string) => ({ type: 'internal' as const, label: slug, page: { slug } }) const page = (slug: string) => ({ type: 'internal' as const, label: slug, page: { slug } })
describe('buildLinkField interface names', () => {
test('each shape has its own type name, so generate:types never depends on field order', () => {
expect(buildLinkField().interfaceName).toBe('CmsLink')
expect(buildLinkField({ appearances: false }).interfaceName).toBe('CmsLinkPlain')
expect(buildLinkField({ disableLabel: true }).interfaceName).toBe('CmsLinkNoLabel')
expect(buildLinkField({ appearances: false, disableLabel: true }).interfaceName).toBe('CmsLinkPlainNoLabel')
expect(buildLinkField({ appearances: false, interfaceName: 'CardLink' }).interfaceName).toBe('CardLink')
})
})
describe('resolveLink', () => { describe('resolveLink', () => {
test('internal page → next/link, no target', () => { test('internal page → next/link, no target', () => {
expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} }) expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} })
@@ -104,3 +116,19 @@ describe('resolveSystemLinks', () => {
expect(resolveSystemLinks(null, opts)).toEqual([]) 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()
})
})
+28 -3
View File
@@ -24,11 +24,19 @@ describe('mediaImageProps', () => {
}) })
test('placeholder and focal point', () => { test('placeholder and focal point', () => {
const p = mediaImageProps({ ...image, focalX: 30, focalY: 70, placeholder: { blurDataURL: 'data:x', color: '#123456' } }) const p = mediaImageProps({ ...image, focalX: 30, focalY: 70, mimeType: 'image/jpeg', placeholder: { blurDataURL: 'data:x', color: '#123456' } })
expect(p).toMatchObject({ blurDataURL: 'data:x', placeholder: 'blur', style: { backgroundColor: '#123456', objectPosition: '30% 70%' } }) expect(p).toMatchObject({ blurDataURL: 'data:x', placeholder: 'blur', style: { backgroundColor: '#123456', objectPosition: '30% 70%' } })
expect(mediaImageProps({ ...image, focalX: 50, focalY: 50 })?.style).toBeUndefined() expect(mediaImageProps({ ...image, focalX: 50, focalY: 50 })?.style).toBeUndefined()
}) })
test('placeholder colour only where no alpha can show it (JPEG), unless forced', () => {
const png = { ...image, mimeType: 'image/png', placeholder: { blurDataURL: 'data:x', color: '#000000' } }
expect(mediaImageProps(png)?.style).toBeUndefined()
expect(mediaImageProps(png)?.placeholder).toBe('blur')
expect(mediaImageProps(png, { placeholderColor: true })?.style).toEqual({ backgroundColor: '#000000' })
expect(mediaImageProps({ ...png, mimeType: 'image/jpeg' }, { placeholderColor: false })?.style).toBeUndefined()
})
test('video, PDF and bare ids give null; decorative alt override', () => { test('video, PDF and bare ids give null; decorative alt override', () => {
expect(mediaImageProps({ ...image, mimeType: 'video/mp4' })).toBeNull() expect(mediaImageProps({ ...image, mimeType: 'video/mp4' })).toBeNull()
expect(mediaImageProps({ mimeType: 'application/pdf', url: '/x.pdf' })).toBeNull() expect(mediaImageProps({ mimeType: 'application/pdf', url: '/x.pdf' })).toBeNull()
@@ -57,12 +65,19 @@ describe('videoProps', () => {
describe('buildImagesConfig', () => { describe('buildImagesConfig', () => {
test('AVIF/WebP and the R2 domain', () => { 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'], formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 2678400, minimumCacheTTL: 2678400,
remotePatterns: [{ hostname: 'media.acme.pl', pathname: '/**', protocol: 'https' }], 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()
}) })
}) })
@@ -81,4 +96,14 @@ describe('buildMediaPlaceholderHook', () => {
await buildMediaPlaceholderHook()({ args: { data: svgData }, operation: 'create', req: { ...req, file: { data: png, mimetype: 'image/svg+xml' } } } as never) await buildMediaPlaceholderHook()({ args: { data: svgData }, operation: 'create', req: { ...req, file: { data: png, mimetype: 'image/svg+xml' } } } as never)
expect(svgData.placeholder).toBeUndefined() expect(svgData.placeholder).toBeUndefined()
}) })
test('transparent image: blur kept, no colour', async () => {
const logo = await sharp({ create: { background: { alpha: 0, b: 255, g: 255, r: 255 }, channels: 4, height: 100, width: 300 } }).png().toBuffer()
const data: Record<string, unknown> = {}
const req = { file: { data: logo, mimetype: 'image/png' }, payload: { config: { sharp }, logger: { warn: vi.fn() } } }
await buildMediaPlaceholderHook()({ args: { data }, operation: 'create', req } as never)
const ph = data.placeholder as { blurDataURL: string; color: null | string }
expect(ph.blurDataURL).toMatch(/^data:image\/webp;base64,/)
expect(ph.color).toBeNull()
})
}) })
+67
View File
@@ -0,0 +1,67 @@
import { isValidElement, type ReactElement } from 'react'
import { describe, expect, test, vi } from 'vitest'
vi.mock('next/navigation.js', () => ({ usePathname: () => '/en/missing' }))
import { createNotFoundPage, renderNotFoundView } from '../src/modules/frontend/pageRoute.js'
import { localeFromPath } from '../src/modules/pages/localeFromPath.js'
import { LocaleView } from '../src/modules/pages/LocaleView.js'
import { NotFoundLoader } from '../src/modules/pages/NotFoundLoader.js'
const layout = [{ id: '1', blockType: 'hero' }]
const helpers = () =>
({
getConfiguredLocales: vi.fn(async () => ['pl', 'en']),
getNotFoundPage: vi.fn(async (locale: string) => ({ layout, locale })),
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] },
}) as never as { getNotFoundPage: ReturnType<typeof vi.fn> } & Parameters<typeof renderNotFoundView>[0]
describe('localeFromPath', () => {
test('first segment when it is a locale, default otherwise', () => {
expect(localeFromPath('/en/missing', ['pl', 'en'], 'pl')).toBe('en')
expect(localeFromPath('/de/missing', ['pl', 'en'], 'pl')).toBe('pl')
expect(localeFromPath('', ['pl'], 'pl')).toBe('pl')
})
})
describe('createNotFoundPage', () => {
test('lazy (load): only the loader goes into the payload — no 404 page is read or rendered', async () => {
const h = helpers()
const load = vi.fn(async () => null)
const element = (await createNotFoundPage(h, { load })()) as ReactElement<{ load: unknown; locales: string[] }>
expect(element.type).toBe(NotFoundLoader)
expect(element.props.locales).toEqual(['pl', 'en'])
expect(element.props.load).toBe(load)
expect(h.getNotFoundPage).not.toHaveBeenCalled()
})
test('eager (blocks): one view per locale in LocaleView', async () => {
const h = helpers()
const element = (await createNotFoundPage(h, { blocks: {} })()) as ReactElement<{ views: Record<string, unknown> }>
expect(element.type).toBe(LocaleView)
expect(Object.keys(element.props.views)).toEqual(['pl', 'en'])
expect(h.getNotFoundPage).toHaveBeenCalledTimes(2)
})
})
describe('renderNotFoundView', () => {
test('renders the requested configured locale', async () => {
const h = helpers()
const node = await renderNotFoundView(h, { blocks: {} }, 'en')
expect(isValidElement(node)).toBe(true)
expect(h.getNotFoundPage).toHaveBeenCalledWith('en')
})
test('a locale from the browser outside the configured ones → default locale', async () => {
const h = helpers()
await renderNotFoundView(h, { blocks: {} }, '../admin')
await renderNotFoundView(h, { blocks: {} }, 42)
expect(h.getNotFoundPage.mock.calls).toEqual([['pl'], ['pl']])
})
test('no 404 page in the panel → fallback for that locale', async () => {
const h = helpers()
h.getNotFoundPage.mockResolvedValueOnce(null)
expect(await renderNotFoundView(h, { blocks: {}, fallback: (locale) => `missing:${locale}` }, 'en')).toBe('missing:en')
})
})

Some files were not shown because too many files have changed in this diff Show More