Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
305c564d13 | ||
|
|
166bf51e53 | ||
|
|
8b35986635 | ||
|
|
faa4ad679c |
+304
-4
@@ -213,6 +213,19 @@ export interface Form {
|
||||
width?: number | null;
|
||||
required?: 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'checkbox';
|
||||
@@ -231,6 +244,23 @@ export interface Form {
|
||||
label?: string | null;
|
||||
width?: number | 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'email';
|
||||
@@ -251,6 +281,19 @@ export interface Form {
|
||||
};
|
||||
[k: string]: unknown;
|
||||
} | 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: 'message';
|
||||
@@ -261,6 +304,23 @@ export interface Form {
|
||||
width?: number | null;
|
||||
defaultValue?: number | 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'number';
|
||||
@@ -279,6 +339,19 @@ export interface Form {
|
||||
}[]
|
||||
| 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: 'select';
|
||||
@@ -298,6 +371,23 @@ export interface Form {
|
||||
width?: number | null;
|
||||
defaultValue?: string | 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'text';
|
||||
@@ -308,6 +398,23 @@ export interface Form {
|
||||
width?: number | null;
|
||||
defaultValue?: string | 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'textarea';
|
||||
@@ -335,6 +442,19 @@ export interface Form {
|
||||
* Empty = no limit.
|
||||
*/
|
||||
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;
|
||||
blockName?: string | null;
|
||||
blockType: 'checkboxGroup';
|
||||
@@ -345,6 +465,19 @@ export interface Form {
|
||||
width?: number | null;
|
||||
required?: boolean | 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;
|
||||
blockName?: string | null;
|
||||
blockType: 'date';
|
||||
@@ -362,6 +495,19 @@ export interface Form {
|
||||
}[]
|
||||
| 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: 'radio';
|
||||
@@ -372,10 +518,48 @@ export interface Form {
|
||||
*/
|
||||
title?: 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;
|
||||
blockName?: string | null;
|
||||
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;
|
||||
submitButtonLabel?: string | null;
|
||||
@@ -701,6 +885,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
required?: T;
|
||||
defaultValue?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -721,6 +911,13 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
label?: T;
|
||||
width?: T;
|
||||
required?: T;
|
||||
placeholder?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -728,6 +925,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
| T
|
||||
| {
|
||||
message?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -739,6 +942,13 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
defaultValue?: T;
|
||||
required?: T;
|
||||
placeholder?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -758,6 +968,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
id?: T;
|
||||
};
|
||||
required?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -779,6 +995,13 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
defaultValue?: T;
|
||||
required?: T;
|
||||
placeholder?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -790,6 +1013,13 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
defaultValue?: T;
|
||||
required?: T;
|
||||
placeholder?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -809,6 +1039,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
};
|
||||
minSelected?: T;
|
||||
maxSelected?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -820,6 +1056,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
required?: T;
|
||||
defaultValue?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -838,6 +1080,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
id?: T;
|
||||
};
|
||||
required?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -846,6 +1094,28 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
| {
|
||||
title?: 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;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -991,13 +1261,17 @@ export interface SiteSetting {
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
allowThemeToggle?: boolean | null;
|
||||
/**
|
||||
* Name of the switch read by screen readers, e.g. "Dark mode".
|
||||
*/
|
||||
themeToggleLabel?: string | null;
|
||||
updatedAt?: 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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
@@ -1100,6 +1382,14 @@ export interface CookieSetting {
|
||||
* Heading for the detailed settings panel.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
@@ -1111,8 +1401,12 @@ export interface CookieSetting {
|
||||
acceptAll?: string | null;
|
||||
reject?: string | null;
|
||||
settings?: string | null;
|
||||
save?: string | null;
|
||||
savePreferences?: string | null;
|
||||
back?: string | null;
|
||||
/**
|
||||
* Screen-reader label of the ✕ button in the settings dialog.
|
||||
*/
|
||||
close?: string | null;
|
||||
};
|
||||
/**
|
||||
* Per-category titles and descriptions.
|
||||
@@ -1206,6 +1500,7 @@ export interface SiteSettingsSelect<T extends boolean = true> {
|
||||
favicon?: T;
|
||||
defaultTheme?: T;
|
||||
allowThemeToggle?: T;
|
||||
themeToggleLabel?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
globalType?: T;
|
||||
@@ -1259,8 +1554,12 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
|
||||
*/
|
||||
export interface CookieSettingsSelect<T extends boolean = true> {
|
||||
policyVersion?: T;
|
||||
eyebrow?: T;
|
||||
title?: T;
|
||||
message?: T;
|
||||
settingsTitle?: T;
|
||||
settingsDescription?: T;
|
||||
alwaysActiveLabel?: T;
|
||||
privacyLinkLabel?: T;
|
||||
buttons?:
|
||||
| T
|
||||
@@ -1268,8 +1567,9 @@ export interface CookieSettingsSelect<T extends boolean = true> {
|
||||
acceptAll?: T;
|
||||
reject?: T;
|
||||
settings?: T;
|
||||
save?: T;
|
||||
savePreferences?: T;
|
||||
back?: T;
|
||||
close?: T;
|
||||
};
|
||||
categories?:
|
||||
| T
|
||||
|
||||
@@ -8,6 +8,64 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
|
||||
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
||||
dopiero powyżej 20.
|
||||
|
||||
## 1.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
|
||||
|
||||
+2
-1
@@ -28,10 +28,11 @@ Szczegóły API — jeden plik na moduł:
|
||||
| Komunikaty formularzy | [notifications.md](./notifications.md) |
|
||||
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.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) |
|
||||
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
|
||||
| Auto-slug | [slug.md](./slug.md) |
|
||||
| Motyw jasny / ciemny, przełącznik | [theme.md](./theme.md) |
|
||||
| Media, R2 | [storage.md](./storage.md) |
|
||||
| Turnstile | [turnstile.md](./turnstile.md) |
|
||||
| White-label panelu | [white-label.md](./white-label.md) |
|
||||
|
||||
+6
-4
@@ -52,7 +52,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
|
||||
|
||||
| # | 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 |
|
||||
| 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 |
|
||||
@@ -285,7 +285,8 @@ src/
|
||||
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
|
||||
layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
|
||||
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
|
||||
(payload)/ # panel (generowany)
|
||||
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
|
||||
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
|
||||
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ę:
|
||||
`manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery
|
||||
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 |
|
||||
| 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 |
|
||||
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md |
|
||||
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
|
||||
|
||||
@@ -320,7 +320,8 @@ if [ "$QUICK" -eq 0 ]; then
|
||||
echo "== pnpm build =="
|
||||
BUILD_LOG=$(mktemp)
|
||||
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"
|
||||
else
|
||||
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
|
||||
// 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*[:?)\]}]|&&|\|\|/
|
||||
// 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 walk = (p) => {
|
||||
@@ -44,7 +47,7 @@ for (const file of files) {
|
||||
const src = stripComments(readFileSync(file, 'utf8'))
|
||||
for (const m of src.matchAll(OPEN_OR_CLOSE)) {
|
||||
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
|
||||
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 /
|
||||
`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`.
|
||||
|
||||
|
||||
|
||||
@@ -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),
|
||||
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
|
||||
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`
|
||||
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
|
||||
`images: buildImagesConfig()`,
|
||||
|
||||
@@ -43,6 +43,13 @@ przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres
|
||||
`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)
|
||||
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
|
||||
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
|
||||
|
||||
@@ -207,6 +207,7 @@ Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się
|
||||
| `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.
|
||||
|
||||
|
||||
+22
-3
@@ -303,12 +303,23 @@ export const generateStaticParams = route.generateStaticParams // SSG → <hea
|
||||
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
|
||||
|
||||
```tsx
|
||||
// src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers()
|
||||
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
// src/app/(frontend)/[locale]/notFoundView.ts — treść 404 z panelu w jednym języku (server action, od 1.12.0)
|
||||
'use server'
|
||||
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
|
||||
import * as content from '@/lib/content'
|
||||
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
|
||||
@@ -549,6 +560,14 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
|
||||
| 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 |
|
||||
|
||||
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
|
||||
|
||||
+1
-1
@@ -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),
|
||||
- [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
|
||||
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.
|
||||
```
|
||||
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
|
||||
|
||||
+8
-2
@@ -43,7 +43,7 @@ ipalKit({
|
||||
forms: {
|
||||
redirectRelationships: ['pages'], // formularz może przekierować na Page
|
||||
// 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).
|
||||
|
||||
### 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 }`.
|
||||
|
||||
**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 |
|
||||
|---|---|---|
|
||||
| radio, select | jedna wartość | tylko wartości z panelu |
|
||||
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
|
||||
| date | `YYYY-MM-DD` | prawdziwa data |
|
||||
| time | `HH:MM` (`<input type="time">`) | godzina 00:00–23:59 |
|
||||
| Step | — (podział) | nie jest polem |
|
||||
|
||||
### Formularz krokowy
|
||||
|
||||
@@ -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
|
||||
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
|
||||
|
||||
+2
-2
@@ -227,8 +227,8 @@ export default route.Page
|
||||
export const generateMetadata = route.generateMetadata
|
||||
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
|
||||
|
||||
// app/(frontend)/not-found.tsx
|
||||
export default createNotFoundPage(content, { blocks: blockRegistry })
|
||||
// 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'
|
||||
|
||||
+5
-1
@@ -51,7 +51,11 @@ puste → „Feature 02”. Komponent: `@intecion/ipal-kit/admin#RowLabel`. Zasa
|
||||
|
||||
Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`,
|
||||
`#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`.
|
||||
|
||||
|
||||
+43
-8
@@ -62,18 +62,44 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
|
||||
- stronę główną (część klientów tak woli), **albo**
|
||||
- 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
|
||||
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
```ts
|
||||
// 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 { blockRegistry } from '@/blocks/registry'
|
||||
|
||||
export default createNotFoundPage(content, {
|
||||
blocks: blockRegistry,
|
||||
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 }),
|
||||
})
|
||||
export async function loadNotFoundView(locale: string) {
|
||||
return renderNotFoundView(content, {
|
||||
blocks: blockRegistry,
|
||||
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()`).
|
||||
|
||||
@@ -85,6 +111,15 @@ blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny wido
|
||||
(`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):
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -53,6 +53,36 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
|
||||
Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta
|
||||
(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)
|
||||
|
||||
Do czytelności dla agentów AI (Markdown per strona, llms-full) potrzebny jest
|
||||
|
||||
@@ -336,6 +336,10 @@ env, komponent podąża automatycznie.
|
||||
- `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu,
|
||||
`lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point →
|
||||
`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 })`.
|
||||
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
|
||||
uploadzie przez `sharp` z configu. Postgres: `migrate:create`.
|
||||
|
||||
@@ -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"`.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.11.0",
|
||||
"version": "1.12.0",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -76,7 +76,15 @@ export {
|
||||
} from '../modules/i18n/index.js'
|
||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.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 { 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 { 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'
|
||||
|
||||
+5
-2
@@ -18,11 +18,14 @@ export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/Ren
|
||||
export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
|
||||
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
|
||||
// pieces stay available for a project that composes them itself).
|
||||
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js'
|
||||
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
|
||||
export { createNotFoundPage, createPageRoute, renderNotFoundView } from '../modules/frontend/pageRoute.js'
|
||||
export type { NotFoundPageOptions, NotFoundViewOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
|
||||
export { SiteProviders } 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 type { RenderRichTextProps } from '../modules/richtext/index.js'
|
||||
export { JsonLdGraph } from '../modules/seo/index.js'
|
||||
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'
|
||||
export { ThemeScript } from '../modules/theme/ThemeScript.js'
|
||||
export type { ThemeScriptProps } from '../modules/theme/ThemeScript.js'
|
||||
|
||||
@@ -89,7 +89,8 @@ export const cookieSettingsFields: Field[] = [
|
||||
{ name: 'acceptAll', type: 'text', localized: true },
|
||||
{ name: 'reject', 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: 'close',
|
||||
|
||||
@@ -12,12 +12,13 @@ export const themeFields: Field[] = [
|
||||
name: 'defaultTheme',
|
||||
type: 'select',
|
||||
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',
|
||||
options: [
|
||||
{ label: 'Light', value: 'light' },
|
||||
{ label: 'Dark', value: 'dark' },
|
||||
{ label: 'System', value: 'system' },
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
@@ -29,4 +30,14 @@ export const themeFields: Field[] = [
|
||||
},
|
||||
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,
|
||||
},
|
||||
]
|
||||
|
||||
+6
-2
@@ -80,7 +80,7 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||
export { assertEnv, ipalEnvRules } 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, visibleFields } from './modules/forms/builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
|
||||
// Panel-managed form analytics (config-time field builder).
|
||||
@@ -172,12 +172,14 @@ export {
|
||||
SITE_INTEGRATIONS_SLUG,
|
||||
SITE_SETTINGS_SLUG,
|
||||
} 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.
|
||||
export { lexicalToMarkdown } from './modules/richtext/index.js'
|
||||
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
|
||||
|
||||
export { buildCsp } from './modules/security/index.js'
|
||||
export type { BuildCspArgs } from './modules/security/index.js'
|
||||
|
||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
|
||||
export type { OgImage } from './modules/seo/buildMetadata.js'
|
||||
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
|
||||
@@ -228,6 +230,8 @@ export { buildSlugField, toSlug } from './modules/slug/index.js'
|
||||
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
|
||||
export type { ImagesConfig } from './modules/storage/buildImagesConfig.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,
|
||||
// which imports 'server-only'.
|
||||
export { getTurnstileConfig } from './modules/turnstile/config.js'
|
||||
|
||||
@@ -39,7 +39,11 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||
|
||||
type CookieSettingsData = {
|
||||
alwaysActiveLabel?: null | string
|
||||
buttons?: null | Partial<ConsentTexts['buttons']>
|
||||
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
|
||||
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
|
||||
eyebrow?: null | string
|
||||
@@ -142,7 +146,7 @@ export async function getConsentTexts({
|
||||
back: g.buttons?.back || FALLBACK.buttons.back,
|
||||
close: g.buttons?.close || FALLBACK.buttons.close,
|
||||
reject: g.buttons?.reject || FALLBACK.buttons.reject,
|
||||
save: g.buttons?.save || FALLBACK.buttons.save,
|
||||
save: g.buttons?.savePreferences || g.buttons?.save || FALLBACK.buttons.save,
|
||||
settings: g.buttons?.settings || FALLBACK.buttons.settings,
|
||||
},
|
||||
categories,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
|
||||
import type { BuilderField } from './builderTypes.js'
|
||||
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
|
||||
|
||||
@@ -48,7 +49,8 @@ export type BuilderFormProps = {
|
||||
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
|
||||
/** Appended to required labels, e.g. "*". Default: nothing. */
|
||||
requiredMark?: ReactNode
|
||||
turnstileTheme?: 'auto' | 'dark' | 'light'
|
||||
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
|
||||
turnstileTheme?: TurnstileTheme
|
||||
} & UseBuilderFormOptions
|
||||
|
||||
/** A page-supplied value (always a string from `values`) as text. */
|
||||
@@ -77,14 +79,15 @@ export function BuilderForm({
|
||||
}: BuilderFormProps) {
|
||||
const f = useBuilderForm(options)
|
||||
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.
|
||||
// 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(() => {
|
||||
if (firstRender.current) {
|
||||
firstRender.current = false
|
||||
return
|
||||
}
|
||||
if (prevStep.current === f.stepIndex) {return}
|
||||
prevStep.current = f.stepIndex
|
||||
const el = stepRef.current
|
||||
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
|
||||
target?.focus()
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
|
||||
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
|
||||
import type { BuilderFormClassNames } from './BuilderForm.js'
|
||||
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
|
||||
import type { SubmitActionResult } from './createSubmitAction.js'
|
||||
@@ -37,7 +38,8 @@ export type RenderFormProps = {
|
||||
richTextClassName?: string
|
||||
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
|
||||
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>
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ import type { Block, Field } from 'payload'
|
||||
* Carries no value.
|
||||
* - `checkboxGroup` — a list of options where the visitor ticks several
|
||||
* ("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 /
|
||||
* useBuilderForm, validated by submitForm like every other field.
|
||||
@@ -61,6 +65,29 @@ 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',
|
||||
fields: [
|
||||
@@ -112,3 +139,4 @@ const checkboxGroupBase: Block = {
|
||||
|
||||
export const stepBlock: Block = withShowWhen(stepBase)
|
||||
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
|
||||
export const timeBlock: Block = withShowWhen(timeBase)
|
||||
|
||||
@@ -15,7 +15,7 @@ export type FieldCondition = { field?: null | string; values?: null | string }
|
||||
|
||||
export type BuilderField = {
|
||||
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
|
||||
defaultValue?: unknown
|
||||
/** step */
|
||||
|
||||
@@ -6,7 +6,7 @@ import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-f
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
||||
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
|
||||
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
|
||||
import { buildEmailLayoutHook } from './emailLayout.js'
|
||||
|
||||
type AccessArgs = { req: { user?: unknown } }
|
||||
@@ -14,6 +14,8 @@ 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. */
|
||||
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
||||
@@ -68,7 +70,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
: undefined
|
||||
return formBuilderPlugin({
|
||||
...(beforeEmail ? { beforeEmail } : {}),
|
||||
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
|
||||
// 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
|
||||
// existing forms. Switch any off with forms.fields.<type>: false.
|
||||
fields: {
|
||||
@@ -76,18 +78,19 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
checkbox: builtin('checkbox'),
|
||||
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
||||
date: builtin('date'),
|
||||
email: builtin('email'),
|
||||
email: withHint('email'),
|
||||
message: builtin('message'),
|
||||
number: builtin('number'),
|
||||
number: withHint('number'),
|
||||
payment: false,
|
||||
radio: builtin('radio'),
|
||||
select: builtin('select'),
|
||||
step: forms.fields?.step === false ? false : stepBlock,
|
||||
text: builtin('text'),
|
||||
textarea: builtin('textarea'),
|
||||
text: withHint('text'),
|
||||
textarea: withHint('textarea'),
|
||||
time: forms.fields?.time === false ? false : timeBlock,
|
||||
...Object.fromEntries(
|
||||
// `true` keeps ipal's block (with "Show only when"); false / an object override it
|
||||
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
|
||||
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
|
||||
),
|
||||
},
|
||||
...(forms.redirectRelationships
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 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.
|
||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||
|
||||
@@ -62,6 +62,8 @@ export type FormsOption = {
|
||||
step?: boolean
|
||||
text?: 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
|
||||
|
||||
@@ -189,7 +189,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
|
||||
}, [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(
|
||||
(field: BuilderField) => {
|
||||
const name = field.name ?? ''
|
||||
@@ -201,6 +201,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
field.blockType === 'email' ? 'email'
|
||||
: field.blockType === 'number' ? 'number'
|
||||
: field.blockType === 'date' ? 'date'
|
||||
: field.blockType === 'time' ? 'time'
|
||||
: base.autoComplete === 'tel' ? 'tel'
|
||||
: 'text'
|
||||
return {
|
||||
|
||||
@@ -46,6 +46,9 @@ export type FormValidationResult =
|
||||
/** Field block types that don't carry a submittable value. */
|
||||
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. */
|
||||
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
|
||||
|
||||
@@ -123,6 +126,8 @@ function checkValue(field: FormField, value: unknown): Checked {
|
||||
}
|
||||
case 'textarea':
|
||||
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:
|
||||
// text, country, state and custom blocks: one line of plain text.
|
||||
if (typeof value === 'number') {return { value }}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { CookieBanner } from '../consent/CookieBanner.js'
|
||||
import { CookieButton } from '../consent/CookieButton.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
|
||||
import { ThemeScript } from '../theme/ThemeScript.js'
|
||||
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
|
||||
|
||||
export type SiteProvidersProps = {
|
||||
@@ -30,6 +31,12 @@ export type SiteProvidersProps = {
|
||||
preconnect?: boolean
|
||||
/** getSiteShell(locale) from lib/content. */
|
||||
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,
|
||||
preconnect = true,
|
||||
shell,
|
||||
theme = false,
|
||||
}: SiteProvidersProps) {
|
||||
return (
|
||||
<>
|
||||
{theme ? <ThemeScript {...shell.theme} /> : null}
|
||||
{preconnect ? <MediaPreconnect /> : null}
|
||||
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
|
||||
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
|
||||
|
||||
@@ -30,6 +30,7 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
|
||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||||
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
|
||||
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
|
||||
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
|
||||
type CreateContentHelpersArgs = {
|
||||
@@ -717,6 +718,7 @@ export function createContentHelpers({
|
||||
formTexts,
|
||||
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
|
||||
settings: settings ?? {},
|
||||
theme: themeConfigFrom(settings),
|
||||
turnstileSiteKey: turnstile.siteKey,
|
||||
}
|
||||
})
|
||||
@@ -794,6 +796,8 @@ export type SiteShell = {
|
||||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||||
jsonLd: Record<string, unknown>[]
|
||||
settings: Record<string, unknown>
|
||||
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
|
||||
theme: ThemeConfig
|
||||
turnstileSiteKey: null | string
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.j
|
||||
import { RenderBlocks } from '../blocks/RenderBlocks.js'
|
||||
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
|
||||
import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
|
||||
ContentHelpers,
|
||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||
>
|
||||
@@ -31,6 +32,14 @@ export type PageRouteOptions = {
|
||||
layoutField?: string
|
||||
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
|
||||
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: (url: string) => never
|
||||
/**
|
||||
@@ -67,7 +76,10 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||
*/
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, 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 l = locale ?? helpers.i18n?.defaultLocale
|
||||
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||
@@ -79,6 +91,16 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
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) {
|
||||
const { slug, locale: param } = await params
|
||||
const locale = localeOf(param)
|
||||
@@ -93,7 +115,8 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const route = await helpers.resolveRoute(locale, segments, 1)
|
||||
if (!route) {
|
||||
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 extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
@@ -117,7 +140,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
|
||||
}
|
||||
|
||||
export type NotFoundPageOptions = {
|
||||
type NotFoundViewOptions = {
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
blocks: BlockComponentMap
|
||||
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
|
||||
@@ -125,31 +148,78 @@ export type NotFoundPageOptions = {
|
||||
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
|
||||
* visitor's language, WITHOUT headers() (the route stays static): one view per
|
||||
* locale rendered here, <LocaleView> picks the one from the URL.
|
||||
* visitor's language, WITHOUT headers() (the route stays static).
|
||||
*
|
||||
* Lazy (recommended) — the content is fetched only when a 404 is shown:
|
||||
* 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 function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
|
||||
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
|
||||
export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPageOptions) {
|
||||
return async function NotFoundPage() {
|
||||
const configured = await helpers.getConfiguredLocales()
|
||||
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
|
||||
const locales = await localesOf(helpers)
|
||||
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(
|
||||
await Promise.all(
|
||||
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={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const
|
||||
}),
|
||||
),
|
||||
await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)),
|
||||
)
|
||||
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
|
||||
return <LocaleView defaultLocale={defaultLocale} views={views} />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,17 @@ type BuildRevalidateHookArgs = {
|
||||
|
||||
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. */
|
||||
function pathForLocale(
|
||||
doc: DocWithSlug,
|
||||
@@ -47,6 +58,8 @@ function pathForLocale(
|
||||
* 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
|
||||
* 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:
|
||||
* import { revalidatePath } from 'next/cache'
|
||||
@@ -64,7 +77,8 @@ export function buildRevalidateHook({
|
||||
} {
|
||||
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>()
|
||||
for (const locale of locales) {
|
||||
// New path.
|
||||
@@ -85,7 +99,8 @@ export function buildRevalidateHook({
|
||||
return doc
|
||||
}
|
||||
|
||||
const afterDelete: CollectionAfterDeleteHook = ({ doc }) => {
|
||||
const afterDelete: CollectionAfterDeleteHook = ({ context, doc }) => {
|
||||
if (!shouldRevalidate(context)) {return doc}
|
||||
const seen = new Set<string>()
|
||||
for (const locale of locales) {
|
||||
const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
|
||||
|
||||
@@ -17,6 +17,14 @@ export type BuildLinkFieldOptions = {
|
||||
appearances?: false | readonly LinkAppearanceOption[]
|
||||
/** Hide the label — for links that wrap something (a whole card, an image). */
|
||||
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'. */
|
||||
name?: string
|
||||
/** Collection the "Page" option points at. Default 'pages'. */
|
||||
@@ -37,7 +45,8 @@ type SiblingWithType = { type?: string } | undefined
|
||||
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
|
||||
* (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({ disableLabel: true, appearances: false })] // clickable card
|
||||
@@ -46,10 +55,12 @@ export function buildLinkField({
|
||||
name = 'link',
|
||||
appearances = ['primary', 'secondary', 'link'],
|
||||
disableLabel = false,
|
||||
interfaceName,
|
||||
relationTo = 'pages',
|
||||
required = false,
|
||||
uploadTo = 'media',
|
||||
}: BuildLinkFieldOptions = {}): GroupField {
|
||||
const hasAppearance = Boolean(appearances && appearances.length)
|
||||
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
|
||||
const fields: Field[] = [
|
||||
{
|
||||
@@ -105,7 +116,7 @@ export function buildLinkField({
|
||||
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))
|
||||
fields.push({
|
||||
name: 'appearance',
|
||||
@@ -120,7 +131,7 @@ export function buildLinkField({
|
||||
type: 'group',
|
||||
admin: { hideGutter: true },
|
||||
fields,
|
||||
interfaceName: 'CmsLink',
|
||||
interfaceName: interfaceName ?? `CmsLink${hasAppearance ? '' : 'Plain'}${disableLabel ? 'NoLabel' : ''}`,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,13 @@ export const MEDIA_SIZES = {
|
||||
export type MediaImageOptions = {
|
||||
/** Alt override (decorative images: ''). Default: the document's alt. */
|
||||
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
|
||||
* fetchPriority="high". Exactly one per page; everything else is lazy.
|
||||
@@ -66,6 +73,9 @@ export type MediaImageProps = {
|
||||
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 =>
|
||||
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.
|
||||
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
|
||||
* 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)
|
||||
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
|
||||
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
|
||||
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 style = {
|
||||
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
|
||||
|
||||
@@ -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
|
||||
if (!buffer) {return}
|
||||
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')
|
||||
data[field] = {
|
||||
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) {
|
||||
// A placeholder is a nicety — never block the upload.
|
||||
|
||||
@@ -5,6 +5,8 @@ import type { ReactNode } from 'react'
|
||||
// Bundlers in the project resolve the same file either way.
|
||||
import { usePathname } from 'next/navigation.js'
|
||||
|
||||
import { localeFromPath } from './localeFromPath.js'
|
||||
|
||||
type LocaleViewProps = {
|
||||
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
|
||||
defaultLocale: string
|
||||
@@ -25,8 +27,6 @@ type LocaleViewProps = {
|
||||
* it also runs during SSR, so the HTML already contains the right language.
|
||||
*/
|
||||
export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
|
||||
const pathname = usePathname() ?? ''
|
||||
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
|
||||
const locale = segment in views ? segment : defaultLocale
|
||||
const locale = localeFromPath(usePathname() ?? '', Object.keys(views), defaultLocale)
|
||||
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
|
||||
}
|
||||
|
||||
@@ -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}</>
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
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 { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
|
||||
|
||||
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
|
||||
|
||||
export type RenderRichTextProps = {
|
||||
/** Wrapper class (e.g. Tailwind prose classes). */
|
||||
@@ -20,6 +23,46 @@ export type RenderRichTextProps = {
|
||||
* is needed here (unlike hand-rolled renderers that hardcode `.pl`).
|
||||
*/
|
||||
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} />
|
||||
*
|
||||
* // 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 (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} />
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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 { RenderRichText } from './RenderRichText.js'
|
||||
export type { RenderRichTextProps } from './RenderRichText.js'
|
||||
|
||||
@@ -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 }) }} />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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}})()`
|
||||
)
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
'use client'
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
import { useTheme } from '../theme/useTheme.js'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
remove?: (id: string) => void
|
||||
render: (el: HTMLElement, opts: Record<string, unknown>) => string
|
||||
reset: (id?: string) => void
|
||||
}
|
||||
@@ -32,9 +35,15 @@ export type TurnstileProps = {
|
||||
* client component and can't read Payload itself.
|
||||
*/
|
||||
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
|
||||
* 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
|
||||
* 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 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(() => {
|
||||
if (!siteKey) {return}
|
||||
@@ -61,7 +85,7 @@ export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps)
|
||||
'error-callback': () => onToken(null),
|
||||
'expired-callback': () => onToken(null),
|
||||
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.
|
||||
const interval = setInterval(render, 300)
|
||||
return () => clearInterval(interval)
|
||||
}, [siteKey, theme, onToken])
|
||||
}, [siteKey, widgetTheme, onToken])
|
||||
|
||||
if (!siteKey) {return null}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { createContext, use, useCallback, useState } from 'react'
|
||||
|
||||
import type { TurnstileTheme } from './Turnstile.js'
|
||||
|
||||
import { Turnstile } from './Turnstile.js'
|
||||
|
||||
type TurnstileContextValue = {
|
||||
@@ -58,7 +60,7 @@ export function useTurnstile(): {
|
||||
enabled: boolean
|
||||
reset: () => void
|
||||
token: null | string
|
||||
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode
|
||||
TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
|
||||
} {
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx) {
|
||||
@@ -84,7 +86,7 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
|
||||
const reset = useCallback(() => setToken(null), [setToken])
|
||||
|
||||
const TurnstileWidget = useCallback(
|
||||
(props?: { theme?: 'auto' | 'dark' | 'light' }) => {
|
||||
(props?: { theme?: TurnstileTheme }) => {
|
||||
if (!siteKey) {return null}
|
||||
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
|
||||
},
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
// Client-only exports — the Turnstile widget. Kept separate from index.ts so
|
||||
// the server-only verify never leaks into a browser bundle.
|
||||
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'
|
||||
|
||||
@@ -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: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] },
|
||||
{ name: 'deadline', blockType: 'date' },
|
||||
{ name: 'hour', blockType: 'time' },
|
||||
{ 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' })
|
||||
})
|
||||
|
||||
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 () => {
|
||||
expect(await v({})).toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
@@ -9,6 +9,16 @@ const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { c
|
||||
const opts = { config, homeSlug: 'start', locale: 'pl' }
|
||||
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', () => {
|
||||
test('internal page → next/link, no target', () => {
|
||||
expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} })
|
||||
|
||||
+19
-1
@@ -24,11 +24,19 @@ describe('mediaImageProps', () => {
|
||||
})
|
||||
|
||||
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(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', () => {
|
||||
expect(mediaImageProps({ ...image, mimeType: 'video/mp4' })).toBeNull()
|
||||
expect(mediaImageProps({ mimeType: 'application/pdf', url: '/x.pdf' })).toBeNull()
|
||||
@@ -88,4 +96,14 @@ describe('buildMediaPlaceholderHook', () => {
|
||||
await buildMediaPlaceholderHook()({ args: { data: svgData }, operation: 'create', req: { ...req, file: { data: png, mimetype: 'image/svg+xml' } } } as never)
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||
|
||||
const thrower = (code: string) => vi.fn((url?: string) => { throw new Error(`${code}${url ? ` ${url}` : ''}`) }) as unknown as (url?: string) => never
|
||||
|
||||
const helpers = (home: null | string) =>
|
||||
({
|
||||
getSystemLinks: vi.fn(async () => (home ? [{ href: home, role: 'homepage' }] : [])),
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] },
|
||||
resolvePageRedirect: vi.fn(async () => null),
|
||||
resolveRoute: vi.fn(async () => null),
|
||||
}) as never
|
||||
|
||||
const page = (segments: string[], locale = 'pl') => ({ params: Promise.resolve({ slug: segments, locale }) })
|
||||
|
||||
describe('createPageRoute onMissing', () => {
|
||||
test('default: 404', async () => {
|
||||
const route = createPageRoute(helpers('/pl'), { blocks: {}, notFound: thrower('NOT_FOUND'), permanentRedirect: thrower('308') })
|
||||
await expect(route.Page(page(['uslugi']))).rejects.toThrow('NOT_FOUND')
|
||||
})
|
||||
|
||||
test("'redirectHome': 307 to the homepage in the same language", async () => {
|
||||
const route = createPageRoute(helpers('/en'), {
|
||||
blocks: {}, notFound: thrower('NOT_FOUND'), onMissing: 'redirectHome', permanentRedirect: thrower('308'), redirect: thrower('REDIRECT'),
|
||||
})
|
||||
await expect(route.Page(page(['services'], 'en'))).rejects.toThrow('REDIRECT /en')
|
||||
})
|
||||
|
||||
test("'redirectHome': no homepage assigned, or the homepage itself missing → 404 (no loop)", async () => {
|
||||
const opts = { blocks: {}, notFound: thrower('NOT_FOUND'), onMissing: 'redirectHome' as const, permanentRedirect: thrower('308'), redirect: thrower('REDIRECT') }
|
||||
await expect(createPageRoute(helpers(null), opts).Page(page(['uslugi']))).rejects.toThrow('NOT_FOUND')
|
||||
await expect(createPageRoute(helpers('/pl'), opts).Page(page([]))).rejects.toThrow('NOT_FOUND')
|
||||
})
|
||||
|
||||
test("'redirectHome' without redirect fails at setup; a function decides itself", async () => {
|
||||
expect(() => createPageRoute(helpers('/pl'), { blocks: {}, notFound: thrower('NOT_FOUND'), onMissing: 'redirectHome', permanentRedirect: thrower('308') })).toThrow(/redirect/)
|
||||
const onMissing = vi.fn(({ locale }: { locale: string }) => { throw new Error(`CUSTOM ${locale}`) }) as never
|
||||
const route = createPageRoute(helpers('/pl'), { blocks: {}, notFound: thrower('NOT_FOUND'), onMissing, permanentRedirect: thrower('308') })
|
||||
await expect(route.Page(page(['x']))).rejects.toThrow('CUSTOM pl')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createElement as h } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildTableOfContentsField, extractHeadings } from '../src/modules/richtext/headings.js'
|
||||
import { RenderRichText } from '../src/modules/richtext/RenderRichText.js'
|
||||
import { TableOfContents } from '../src/modules/richtext/TableOfContents.js'
|
||||
|
||||
const text = (t: string, format = 0) => ({ type: 'text', detail: 0, format, mode: 'normal', style: '', text: t, version: 1 })
|
||||
const heading = (tag: string, ...children: object[]) => ({ type: 'heading', children, direction: 'ltr', format: '', indent: 0, tag, version: 1 })
|
||||
const paragraph = (t: string) => ({ type: 'paragraph', children: [text(t)], direction: 'ltr', format: '', indent: 0, textFormat: 0, version: 1 })
|
||||
|
||||
const doc = {
|
||||
root: {
|
||||
type: 'root',
|
||||
children: [
|
||||
heading('h2', text('Administrator '), text('danych', 1)),
|
||||
paragraph('Treść'),
|
||||
heading('h3', text('Szczegóły')),
|
||||
heading('h2', text('Pliki cookies')),
|
||||
heading('h2', text('Pliki cookies')),
|
||||
heading('h2'),
|
||||
],
|
||||
direction: 'ltr',
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
},
|
||||
} as never
|
||||
|
||||
describe('table of contents', () => {
|
||||
test('extractHeadings: h2 in order, slug ids, repeats numbered, empty skipped', () => {
|
||||
expect(extractHeadings(doc)).toEqual([
|
||||
{ id: 'administrator-danych', level: 'h2', text: 'Administrator danych' },
|
||||
{ id: 'pliki-cookies', level: 'h2', text: 'Pliki cookies' },
|
||||
{ id: 'pliki-cookies-2', level: 'h2', text: 'Pliki cookies' },
|
||||
])
|
||||
expect(extractHeadings(doc, { levels: ['h2', 'h3'] }).map((h) => h.id)).toContain('szczegoly')
|
||||
expect(extractHeadings(null)).toEqual([])
|
||||
})
|
||||
|
||||
test('RenderRichText headingIds: the same ids on the headings, project converter kept', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
h(RenderRichText, {
|
||||
converters: ({ defaultConverters }) => ({
|
||||
...defaultConverters,
|
||||
heading: ({ node, nodesToJSX }) => h(node.tag, { className: 'title' }, ...nodesToJSX({ nodes: node.children })),
|
||||
}),
|
||||
data: doc,
|
||||
headingIds: { className: 'scroll-mt-24' },
|
||||
}),
|
||||
)
|
||||
expect(html).toContain('<h2 class="title scroll-mt-24" id="administrator-danych">')
|
||||
expect(html).toContain('id="pliki-cookies-2"')
|
||||
expect(html).toMatch(/<h3 class="title">Szczegóły<\/h3>/)
|
||||
expect(renderToStaticMarkup(h(RenderRichText, { data: doc, headingIds: true }))).toContain('<h2 id="pliki-cookies">')
|
||||
})
|
||||
|
||||
test('TableOfContents: links to the ids, first section current before JS', () => {
|
||||
const html = renderToStaticMarkup(h(TableOfContents, { classNames: { linkActive: 'on' }, items: extractHeadings(doc), label: 'Spis treści' }))
|
||||
expect(html).toContain('aria-label="Spis treści"')
|
||||
expect(html).toContain('<a aria-current="location" class="on" href="#administrator-danych">')
|
||||
expect(html).toContain('href="#pliki-cookies-2"')
|
||||
expect(renderToStaticMarkup(h(TableOfContents, { items: [] }))).toBe('')
|
||||
})
|
||||
|
||||
test('panel field: show + localized label', () => {
|
||||
const field = buildTableOfContentsField()
|
||||
expect(field).toMatchObject({ name: 'tableOfContents', interfaceName: 'TableOfContentsSettings' })
|
||||
expect(field.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['show', 'label'])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user