Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78e4e0f8e6 | ||
|
|
8f8b79d003 | ||
|
|
91d5e986c5 | ||
|
|
080086adfe | ||
|
|
8c1a8b0e8e | ||
|
|
002eef56d1 | ||
|
|
924b5cf8be | ||
|
|
3e17f92af1 | ||
|
|
c83d2dec0c | ||
|
|
df0f5e03c3 | ||
|
|
67e8da6ec3 | ||
|
|
191cf44361 | ||
|
|
6a0fefdbae |
@@ -8,6 +8,78 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
|
||||
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
||||
dopiero powyżej 20.
|
||||
|
||||
## 1.9.8
|
||||
|
||||
### Nowe
|
||||
- **Strona w budowie** (narzędzie deweloperskie): Site Settings → Under construction — przełącznik, lista
|
||||
„Pages still available” i teksty popupu. Gdy włączone, otwiera się tylko strona główna i wybrane strony
|
||||
(w każdym języku); inne adresy → strona główna z popupem, kliknięcie linku do zablokowanej strony →
|
||||
popup zamiast przejścia. `createPageRoute(…, { redirect })`, `getConstructionMode(locale)`,
|
||||
`<ConstructionNotice>` (`/client`). Opis: construction.md.
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
- Nowe pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`, jeśli projekt ich używa).
|
||||
Bez `redirect` w `createPageRoute` i bez `<ConstructionNotice>` tryb nie działa (nic się nie zmienia).
|
||||
|
||||
## 1.9.7
|
||||
|
||||
### Nowe
|
||||
- **Pola i kroki warunkowe w formularzach z panelu** („Show only when”, `showWhen`): każde pole,
|
||||
Checkbox group, message i **Step** może pokazywać się tylko przy wybranej odpowiedzi innego pola
|
||||
(`field` + `values` po przecinku). Ukryty Step wypada z formularza razem z polami, kolejne kroki
|
||||
się przenumerowują. Przeglądarka i serwer stosują tę samą regułę (`visibleFields`): ukryte pole nie
|
||||
jest wymagane ani zapisywane; zgoda RODO (`consent`) jest egzekwowana zawsze. Opis: forms.md →
|
||||
„Pola i kroki warunkowe”.
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
- Nowa grupa w blokach formularzy = nowe kolumny w bazie. Po aktualizacji: `pnpm payload migrate:create`
|
||||
(z kompletem `R2_*`, jeśli projekt ich używa) i `pnpm payload migrate`. Istniejące formularze działają
|
||||
bez zmian (puste „Show only when” = pole zawsze widoczne).
|
||||
|
||||
## 1.9.6
|
||||
|
||||
### Poprawki
|
||||
- Trasa Markdown: bezpieczny typ przy odczycie kodów języków z configu (bez zmian w działaniu).
|
||||
Wydanie zbiorcze — zawiera wszystko z 1.9.2–1.9.5 (formularze krokowe, `SiteProviders`,
|
||||
`createPageRoute`, trasy z jednej linii, własne style linków, `getSystemLinks`, Markdown na
|
||||
stronie jednojęzycznej, nowe reguły audytu). Przy aktualizacji ze starszej wersji przejdź sekcje
|
||||
„Wymaga zmian w projekcie” od swojej wersji w górę.
|
||||
|
||||
## 1.9.5
|
||||
|
||||
### Poprawki
|
||||
- **Markdown (GEO) na stronie jednojęzycznej:** `/md/kontakt` szło do trasy `md/[locale]/[[...slug]]`
|
||||
jako język „kontakt” → 404, a `/md` (strona główna) nie miało trasy. `markdownRoute` /
|
||||
`createMarkdownRoute` działa teraz bez parametru `locale` (`app/md/[[...slug]]/route.ts`, język z config),
|
||||
a trasa z `[locale]` na stronie jednojęzycznej czyta ten segment jako slug.
|
||||
|
||||
### Dokumentacja
|
||||
- i18n.md: strona jednojęzyczna na `SiteProviders`, `createPageRoute`, `createNotFoundPage` i
|
||||
`app/md/[[...slug]]`. Usunięta błędna rada „załóż `[locale]` na zapas przy jednym języku” (linki byłyby
|
||||
bez `/pl`, strony z `/pl`); opisane przejście na kilka języków (proxy przekieruje stare adresy).
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
- Strona jednojęzyczna z `app/md/[locale]/[[...slug]]/route.ts` → przenieś plik do `app/md/[[...slug]]/route.ts`
|
||||
(bez zmian treści), żeby działało `/md` dla strony głównej.
|
||||
|
||||
## 1.9.4
|
||||
|
||||
### Nowe
|
||||
- **Style linków z projektu:** `buildLinkField` / `buildLinksField({ appearances })` przyjmują dowolne nazwy
|
||||
i etykiety panelu — `['primary', { label: 'Highlighted', value: 'highlight' }]`. Wcześniej tylko
|
||||
primary / secondary / link, co pchało projekty do warunków po treści (`label === 'Tesla'`).
|
||||
- **Linki prawne:** `getSystemLinks(locale, roles?)` w `lib/content` (i `resolveSystemLinks`) — href i
|
||||
etykieta (tytuł strony w danym języku) z Site Settings → System Pages.
|
||||
|
||||
### Audyt
|
||||
- ERROR: logika po treści (`label?.toLowerCase() === '…'`), polski tekst w literałach kodu frontu,
|
||||
pola linków/przycisków w globalach (`prefooterButtonUrl`, `ctaLabel`…); WARNING: relacja do `pages` w
|
||||
globalu zamiast `buildLinkField`.
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
- Globale Header/Footer z polami `page` + `url` + `label` → `buildLinkField` (dane trzeba przenieść —
|
||||
skill **ipal-migrate-fields**), potem `resolveNav` / `resolveLink`; linki prawne → `getSystemLinks`.
|
||||
|
||||
## 1.9.3
|
||||
|
||||
### Audyt
|
||||
|
||||
@@ -16,6 +16,7 @@ Szczegóły API — jeden plik na moduł:
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||
| Zgoda cookies, baner | [consent.md](./consent.md) |
|
||||
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
|
||||
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
|
||||
| Email SMTP / Graph | [email.md](./email.md) |
|
||||
| Walidacja env | [env.md](./env.md) |
|
||||
|
||||
+7
-3
@@ -57,7 +57,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
|
||||
| 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 |
|
||||
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S |
|
||||
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
|
||||
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (jednojęzyczna: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
|
||||
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S |
|
||||
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S |
|
||||
| 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
|
||||
@@ -66,7 +66,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
|
||||
| 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A |
|
||||
| 14 | Operacje | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
|
||||
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę | `getSystemPagePath`, `getNotFoundPage` | P |
|
||||
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
|
||||
| 16 | **Zero hardkodów** | każdy tekst, link, obraz, plik, dane firmy z panelu; domeny i klucze z `.env` (§2) | — | A, P |
|
||||
| 17 | **Treść** | jedno h1, odpowiedź na początku sekcji, fakty, linki wewnętrzne, FAQ z prawdziwych pytań, `aiSummary`, sameAs, spójne dane firmy (§0c) | — | S, P |
|
||||
| 18 | **Skalowanie** | `fluid.css` / `fluid-wide.css`, hero na `--ipal-hero-min-h`, lista ekranów §6.11a (w tym 1366×768) | — | A, przeglądarka |
|
||||
@@ -90,6 +90,7 @@ Nie warunkujesz providera ani widgetu w kodzie — wpinasz zawsze.
|
||||
| własny `sitemap.ts` / tekstowy `robots.txt` w `public/` | bez hreflang, noindex i stron systemowych | `sitemapRoute`, `robots` z `lib/content` |
|
||||
| własny `llms.txt` w `public/` | statyczny, starzeje się | `createLlmsTxtRoute` |
|
||||
| własna funkcja linku (`resolveHref`, `getHref`…): slug strony głównej w kodzie (`=== 'home'`), `` `/${slug}` `` | brak prefiksu języka, strona główna zależy od Site Settings, `javascript:` z panelu w `href`, martwy link prowadzi na `/` | `resolveLink(link, locale)` / `resolveNav` z `lib/content` (pole: `buildLinkField`) |
|
||||
| pola `page` + `url` + `label` w globalach, `prefooterButtonUrl`, `ctaLabel`; styl po treści (`label === 'Tesla'`); etykiety linków prawnych w kodzie | redaktor nie wybierze pliku / nowej karty / stylu; zmiana nazwy psuje wygląd; tekst PL w wersji EN | `buildLinkField` / `buildLinksField` z `appearances`, `resolveNav`, `getSystemLinks` |
|
||||
| `@aws-sdk/client-s3` / własny upload do bucketa | omija hooki mediów i URL z `R2_PUBLIC_URL` | `buildR2Storage` |
|
||||
|
||||
### Świadomy wyjątek (tylko z decyzji klienta)
|
||||
@@ -647,7 +648,8 @@ Skill: **ipal-nav**.
|
||||
zbudowane z `buildLinkField` — model danych firmy zależy od kraju (NIP/ABN/EIN).
|
||||
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
|
||||
- Logo i nazwa z Site Settings — nie duplikuj pól w Header.
|
||||
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
|
||||
- **Linki prawne w stopce** z ról System Pages: `await getSystemLinks(locale)` (href + tytuł strony), nie ręcznie i bez etykiet w kodzie.
|
||||
- Wyróżnienie pozycji menu / wariant przycisku = `appearance` z panelu (`buildLinkField({ appearances: [...] })`, dowolne nazwy), nigdy warunek na treści (`label === '…'`).
|
||||
- Linki rozwiązuj **na serwerze**: `await resolveNav(header.navItems, locale)` z `lib/content`
|
||||
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte); do
|
||||
komponentu klienckiego (MobileNav) idą tylko te dane — `CMSLink` jest serwerowy.
|
||||
@@ -791,6 +793,8 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
|---|---|---|
|
||||
| href + nowa karta + rel + internal dla linku z panelu | `resolveLink(link, locale)` (`lib/content`) / `resolveLink(link, opts)` | links.md |
|
||||
| Menu z globala (dowolna głębokość, martwe linki pominięte) | `resolveNav(items, locale)` | links.md |
|
||||
| Linki prawne w stopce (href + tytuł strony) | `getSystemLinks(locale)` / `resolveSystemLinks` | links.md |
|
||||
| Wyróżniona pozycja, wariant przycisku | `buildLinkField({ appearances: [...] })` — nazwy projektu | links.md |
|
||||
| Ścieżki językowe, przełącznik, hreflang | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher`, `buildLocalizedPath` | i18n.md |
|
||||
| Bezpieczny URL (bez `javascript:`) | `safeHref` | links.md |
|
||||
|
||||
|
||||
@@ -199,6 +199,19 @@ if [ -n "$FRONT" ]; then
|
||||
report ERROR "URL built from a slug by hand" "links.md — resolveLink / resolveNav (lib/content) or buildLocalizedPath: locale prefix, homepage, unsafe and dead links" \
|
||||
"$(g '`/\$\{[^}]*[Ss]lug|['"'"'"]/['"'"'"] *\+ *[A-Za-z_.?]*[Ss]lug' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
|
||||
fi
|
||||
if [ -n "$FRONT" ]; then
|
||||
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
|
||||
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
|
||||
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
|
||||
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
|
||||
fi
|
||||
GLOBALS=$(dirs src/globals)
|
||||
if [ -n "$GLOBALS" ]; then
|
||||
report ERROR "link/button fields in globals" "§6.5 Header/Footer links and buttons = buildLinkField / buildLinksField (page, URL or file + label + style), never ctaLabel/buttonUrl/…Url" \
|
||||
"$(g "name: *'[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df)[a-zA-Z]*'" $GLOBALS --include=*.ts)"
|
||||
report WARNING "page relationship in a global" "links.md — a link to a page is buildLinkField (it also handles URL, file, new tab, style); then resolveNav / resolveLink" \
|
||||
"$(g "relationTo: *'pages'" $GLOBALS --include=*.ts)"
|
||||
fi
|
||||
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
|
||||
"$(g 'node\.type *===' src --include=*.tsx | nc 'node')"
|
||||
HTML=$(node "$(dirname "$0")/html-check.mjs" src)
|
||||
@@ -235,7 +248,7 @@ if [ -n "$APP" ]; then
|
||||
# GEO
|
||||
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app
|
||||
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt
|
||||
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
|
||||
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts (one language: src/app/md/[[...slug]]/route.ts) → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
|
||||
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
|
||||
need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts
|
||||
need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src
|
||||
|
||||
@@ -24,7 +24,7 @@ Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-blo
|
||||
Nie twórz `lib/navigation.ts`.
|
||||
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
|
||||
(`'use client'`, tylko stan otwarcia, dane przez props, `import type { NavItem } from '@intecion/ipal-kit'`).
|
||||
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
|
||||
5. **Linki prawne w stopce** z ról System Pages: `getSystemLinks(locale)` (href + tytuł
|
||||
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
|
||||
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
|
||||
7. Podepnij w `src/app/(frontend)/[locale]/layout.tsx` (pobranie globali przez
|
||||
|
||||
@@ -78,8 +78,10 @@ export const Footer: GlobalConfig = {
|
||||
}
|
||||
```
|
||||
|
||||
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
|
||||
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
|
||||
- **Linki prawne w stopce** (polityka, cookies, regulamin): `await getSystemLinks(locale)` z `lib/content`
|
||||
— href i etykieta (tytuł strony) z System Pages; nie dodawaj ich ręcznie do `columns`, nie wpisuj etykiet w kod.
|
||||
- Wyróżniona pozycja menu / przycisk w innym kolorze = styl w panelu:
|
||||
`buildLinkField({ appearances: ['default', { label: 'Highlighted', value: 'highlight' }] })` → klasa w projekcie.
|
||||
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
|
||||
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
|
||||
(`new Date().getFullYear()`), nazwę bierz z globala.
|
||||
|
||||
@@ -223,7 +223,7 @@ if (!skipped('markdown') && checkedPaths.length) {
|
||||
const path = checkedPaths[0]
|
||||
const md = await ok(`/md${path === '/' ? '' : path}`)
|
||||
const type = md?.res.headers.get('content-type') ?? ''
|
||||
if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts (content.md)')
|
||||
if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts; one language: src/app/md/[[...slug]]/route.ts (i18n.md)')
|
||||
}
|
||||
if (!skipped('mcp')) {
|
||||
let mcpOk = false
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Strona w budowie (narzędzie deweloperskie)
|
||||
|
||||
Tryb dla strony, która nie jest jeszcze gotowa: odwiedzający widzą tylko stronę główną i wybrane
|
||||
podstrony (np. brief), a cała reszta jest zablokowana — bez zmian w kodzie, jednym przełącznikiem w panelu.
|
||||
|
||||
## Panel
|
||||
|
||||
**Site Settings → Under construction** (zakładka jest, gdy włączony moduł `pages`):
|
||||
|
||||
| Pole | Znaczenie |
|
||||
|---|---|
|
||||
| Site under construction | włącza tryb |
|
||||
| Pages still available | strony, które dalej się otwierają; **strona główna jest dostępna zawsze** |
|
||||
| Notice title / text / Close button label | treść popupu (per język) |
|
||||
|
||||
Lista stron i teksty pokazują się dopiero po zaznaczeniu przełącznika. Wyłączenie trybu przywraca
|
||||
normalne działanie strony.
|
||||
|
||||
## Jak działa
|
||||
|
||||
- **Adres spoza listy** (także nieistniejący) → przekierowanie na stronę główną w tym języku z
|
||||
`?notice=construction` (`createPageRoute` z opcją `redirect`). Strony dozwolone liczone są w
|
||||
**każdym języku** (`/pl/brief` i `/en/project-brief`), więc przełącznik języka działa.
|
||||
- **Kliknięcie linku** do strony spoza listy → `<ConstructionNotice>` anuluje przejście (przed
|
||||
`next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"`
|
||||
i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie.
|
||||
- Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu.
|
||||
- **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania
|
||||
sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings).
|
||||
|
||||
## Wpięcie w projekcie
|
||||
|
||||
```tsx
|
||||
// app/(frontend)/[locale]/[[...slug]]/page.tsx — redirect włącza blokadę adresów
|
||||
import { notFound, permanentRedirect, redirect } from 'next/navigation'
|
||||
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect })
|
||||
|
||||
// app/(frontend)/[locale]/layout.tsx — popup + przechwytywanie linków (bez stylów, classNames)
|
||||
import { ConstructionNotice } from '@intecion/ipal-kit/client'
|
||||
<ConstructionNotice
|
||||
mode={await getConstructionMode(locale)} // z lib/content (createContentHelpers)
|
||||
classNames={{ overlay: '…', dialog: '…', title: '…', message: '…', button: '…' }}
|
||||
/>
|
||||
```
|
||||
|
||||
`getConstructionMode(locale)` zwraca `{ enabled, allowedPaths, homePath, texts }` (typ
|
||||
`ConstructionMode`). Czysta logika: `isPathAllowed(pathname, allowedPaths)`,
|
||||
`constructionNoticeHref(homePath)`, stała `CONSTRUCTION_NOTICE_PARAM` (`@intecion/ipal-kit`).
|
||||
|
||||
Nowe pola w Site Settings = migracja w projekcie (`payload migrate:create`).
|
||||
@@ -106,7 +106,9 @@ export const i18nConfig = {
|
||||
],
|
||||
} as const satisfies I18nConfig
|
||||
```
|
||||
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` (i18n.md).
|
||||
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` — layout z `i18nConfig.defaultLocale`,
|
||||
`createPageRoute` / `createNotFoundPage` bez zmian, Markdown w `app/md/[[...slug]]/route.ts` (i18n.md).
|
||||
Nie zakładaj `[locale]` „na zapas” przy jednym języku — linki byłyby bez `/pl`, strony z `/pl`.
|
||||
|
||||
### 2.3 payload.config.ts
|
||||
```ts
|
||||
@@ -219,7 +221,7 @@ export const {
|
||||
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
|
||||
generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
|
||||
// layout, formularze, linki
|
||||
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav,
|
||||
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav, getSystemLinks,
|
||||
// trasy (re-eksport w app/)
|
||||
sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
|
||||
mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
|
||||
|
||||
+22
-1
@@ -96,6 +96,27 @@ Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym
|
||||
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
|
||||
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
|
||||
|
||||
### Pola i kroki warunkowe („Show only when”)
|
||||
Każdy blok formularza (wbudowane, **Checkbox group**, **Step**, message) ma w panelu grupę
|
||||
**Show only when** (`showWhen`): `field` — nazwa techniczna innego pola, `values` — wartości opcji
|
||||
po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `field` = zawsze widoczne.
|
||||
|
||||
- Na polu: pole pokazuje się dopiero przy pasującej odpowiedzi (np. „Z czego wynika termin?”
|
||||
tylko przy `deadline = fixed`).
|
||||
- Na **Step**: cały krok (z polami) wypada, gdy warunek nie pasuje — kolejne kroki się przenumerowują
|
||||
(„Krok 2 z 3”). Tak buduje się brief: ekran 1 wybiera obszary (Checkbox group), każdy następny
|
||||
Step ma `showWhen: { field: 'areas', values: 'web' }`.
|
||||
- Pole w ukrytym kroku jest ukryte, nawet gdy jego warunek pasuje; warunek wskazujący ukryte pole też
|
||||
nie pasuje. Nazwa nieistniejącego pola (literówka) albo cykl ukrywa pole — widać to w podglądzie.
|
||||
- Wspólna reguła `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — przeglądarka
|
||||
(`useBuilderForm`/`BuilderForm`: co pokazać, walidować i wysłać) i serwer (`validateSubmission`):
|
||||
ukryte pole **nie jest wymagane i nie jest zapisywane**, nawet gdy ktoś je dośle ręcznie.
|
||||
Wyjątek: pole zgody RODO (`consent`) jest egzekwowane zawsze — warunkiem nie da się go wyłączyć.
|
||||
- Typ `FieldCondition` (`{ field, values }`) dla własnego markupu na `useBuilderForm`; `splitSteps(fields, isShown)`
|
||||
pomija ukryte pola i kroki, zachowując oryginalny `index` (bloki message renderują się po nim).
|
||||
- Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy →
|
||||
po aktualizacji wygeneruj migrację (`payload migrate:create`).
|
||||
|
||||
### Formularz nietypowy — bez kopiowania silnika
|
||||
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
|
||||
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
|
||||
@@ -105,7 +126,7 @@ na krok z tym polem. Teksty przycisków: Notifications → Form messages → `ne
|
||||
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
|
||||
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
|
||||
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
|
||||
`validateBuilderFields`, `stepOfField`, `inputFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
|
||||
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
|
||||
|
||||
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
|
||||
|
||||
|
||||
+37
-39
@@ -206,42 +206,38 @@ app/(frontend)/[locale]/
|
||||
[[...slug]]/page.tsx # /pl/o-nas, /en/about
|
||||
```
|
||||
|
||||
### Layout jednojęzyczny — locale z config
|
||||
### Layout, strona, 404, Markdown — te same helpery, bez `[locale]`
|
||||
|
||||
```tsx
|
||||
// app/(frontend)/layout.tsx (bez [locale])
|
||||
// app/(frontend)/layout.tsx
|
||||
import { i18nConfig } from '@/i18n.config'
|
||||
|
||||
export default async function Layout({ children }: { children: React.ReactNode }) {
|
||||
const locale = i18nConfig.defaultLocale // stałe, nie z params
|
||||
const settings = await getSettings(locale)
|
||||
// ...reszta jak zwykle, ale locale jest stałe
|
||||
return <html lang={locale}>...</html>
|
||||
const locale = i18nConfig.defaultLocale // stałe, nie z params
|
||||
return (
|
||||
<html lang={locale}><body>
|
||||
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent">{children}</SiteProviders>
|
||||
</body></html>
|
||||
)
|
||||
}
|
||||
|
||||
// app/(frontend)/[[...slug]]/page.tsx — createPageRoute bierze język z config, gdy nie ma go w params
|
||||
export const revalidate = 3600
|
||||
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
|
||||
export default route.Page
|
||||
export const generateMetadata = route.generateMetadata
|
||||
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
|
||||
|
||||
// app/(frontend)/not-found.tsx
|
||||
export default createNotFoundPage(content, { blocks: blockRegistry })
|
||||
|
||||
// app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt
|
||||
export { markdownRoute as GET } from '@/lib/content'
|
||||
export const dynamic = 'force-dynamic'
|
||||
```
|
||||
|
||||
### Strony jednojęzyczne — locale z config
|
||||
|
||||
```tsx
|
||||
// app/(frontend)/[[...slug]]/page.tsx (bez [locale])
|
||||
import { i18nConfig } from '@/i18n.config'
|
||||
|
||||
export async function generateMetadata({ params }) {
|
||||
const { slug } = await params // TYLKO slug, nie locale
|
||||
const locale = i18nConfig.defaultLocale // stałe
|
||||
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
|
||||
}
|
||||
|
||||
export default async function Page({ params }) {
|
||||
const { slug } = await params
|
||||
const locale = i18nConfig.defaultLocale // stałe
|
||||
const route = await resolveRoute(locale, slug ?? [], pageNum)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
resolveRoute i inne helpery działają bez zmian — dostają stałe locale z config
|
||||
zamiast z URL. Cała różnica to: brak `[locale]` w strukturze, locale z config.
|
||||
Linki (`resolveLink`, `resolveNav`, `getSystemLinks`), sitemap, canonical, llms.txt i MCP dają adresy
|
||||
bez `/pl` same — decyduje liczba języków w `i18n.config.ts`, nie struktura folderów.
|
||||
(Trasa `md/[locale]/[[...slug]]` na stronie jednojęzycznej też obsłuży podstrony, ale nie `/md` —
|
||||
dlatego tu `md/[[...slug]]`.)
|
||||
|
||||
### Middleware/proxy — jednojęzyczny prawie go nie potrzebuje
|
||||
|
||||
@@ -249,17 +245,19 @@ Dla jednego locale middleware jest pass-through (nic nie przekierowuje). Możesz
|
||||
go pominąć albo zostawić — plugin i tak wykryje 1 locale i przepuści. Bez
|
||||
przełącznika języka (jeden język), bez cookie NEXT_LOCALE (nie ma co pamiętać).
|
||||
|
||||
### Przejście jedno- → wielojęzyczny (later)
|
||||
### Przejście jedno- → wielojęzyczny (później)
|
||||
|
||||
Jeśli klient później doda drugi język, to PRZEBUDOWA, nie przełącznik:
|
||||
- dodaj locale do config
|
||||
- przenieś strukturę do `[locale]/`
|
||||
- layout/strony czytają locale z params
|
||||
- wróci prefiks `/pl`, `/en` + hreflang
|
||||
O prefiksie decyduje **liczba języków w `i18n.config.ts`**: jeden język = adresy bez `/pl` (linki,
|
||||
sitemap, canonical), dwa i więcej = z prefiksem. Struktury `[locale]` przy jednym języku **nie
|
||||
zakładaj na zapas** — plugin generowałby linki `/kontakt`, a strony byłyby pod `/pl/kontakt`.
|
||||
|
||||
Warto to przewidzieć na starcie: jeśli jest szansa na drugi język, rozważ od razu
|
||||
strukturę wielojęzyczną (z [locale]), nawet dla jednego locale — wtedy prefiks
|
||||
`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury.
|
||||
Gdy klient doda drugi język:
|
||||
1. dodaj język do `i18n.config.ts` (i `localization` w Payload przez `ipalKit`),
|
||||
2. przenieś `app/(frontend)/*` do `app/(frontend)/[locale]/`, a `app/md/[[...slug]]` do `app/md/[locale]/[[...slug]]`,
|
||||
3. layout bierze `locale` z `params` (PROGRAMISTA §2.8) — `createPageRoute` / `createNotFoundPage` bez zmian,
|
||||
4. przetłumacz slugi i treści w panelu.
|
||||
Linki, sitemap, hreflang i canonical przełączą się same. Stare adresy (`/kontakt`) proxy przekieruje
|
||||
na `/pl/kontakt`, więc linki z Google i wizytówek dalej działają.
|
||||
|
||||
## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher)
|
||||
|
||||
|
||||
+16
-1
@@ -22,7 +22,7 @@ fields: [
|
||||
| `name` | `'link'` / `'links'` | nazwa pola |
|
||||
| `relationTo` | `'pages'` | kolekcja dla typu „Page” |
|
||||
| `uploadTo` | `'media'` | kolekcja dla typu „File” (PDF, dokumenty) |
|
||||
| `appearances` | `['primary','secondary','link']` | style do wyboru; `false` = bez pola |
|
||||
| `appearances` | `['primary','secondary','link']` | style do wyboru — **dowolne nazwy projektu**, np. `['primary', { label: 'Highlighted', value: 'highlight' }]` (menu z wyróżnioną pozycją, przycisk w kolorze marki); `false` = bez pola |
|
||||
| `disableLabel` | `false` | bez etykiety (link owija kartę / obraz) — tylko `buildLinkField` |
|
||||
| `required` | `false` | wymagane pola celu i etykiety |
|
||||
| `maxRows` | `2` | tylko `buildLinksField` |
|
||||
@@ -107,6 +107,21 @@ języka, stronę główną z Site Settings, filtr `javascript:` i martwe linki.
|
||||
ERROR. Pole w innym kształcie (np. `page` + `url`) mapujesz na kształt pluginu zamiast liczyć href:
|
||||
`resolveLink(url?.trim() ? { type: 'external', url } : { type: 'internal', page }, locale)`.
|
||||
|
||||
Wyróżnienie, kolor, wariant pozycji = **styl z panelu** (`appearances`), mapowany na klasy w projekcie
|
||||
(`l.appearance === 'highlight'` → klasa). Nigdy logika po treści (`label === 'Tesla'`) — redaktor zmieni
|
||||
nazwę i styl zniknie; `ipal-audit` zgłasza to jako ERROR.
|
||||
|
||||
## Linki prawne — `getSystemLinks`
|
||||
|
||||
```ts
|
||||
const legal = await getSystemLinks(locale) // z lib/content
|
||||
// [{ role: 'privacyPolicy', href: '/pl/polityka-prywatnosci', label: 'Polityka prywatności', internal, targetProps }, …]
|
||||
await getSystemLinks(locale, ['privacyPolicy', 'termsOfService']) // wybrane role
|
||||
// bez lib/content: resolveSystemLinks(settings, { locale, config: i18nConfig, homeSlug, roles })
|
||||
```
|
||||
Strony przypisane w Site Settings → System Pages; **etykieta to tytuł strony** w danym języku, więc w kodzie
|
||||
nie ma tekstów („Polityka prywatności” na sztywno psuje wersję EN). Nieprzypisana rola → pominięta.
|
||||
|
||||
## Menu — `resolveNav`
|
||||
|
||||
```ts
|
||||
|
||||
@@ -80,6 +80,7 @@ Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `Local
|
||||
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
|
||||
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
|
||||
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
|
||||
Opcja `redirect` (z `next/navigation`) włącza tryb „strona w budowie” — [construction.md](./construction.md).
|
||||
|
||||
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.8",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -24,9 +24,12 @@ export {
|
||||
useConsentContext,
|
||||
} from '../modules/consent/client.js'
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
||||
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
|
||||
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
|
||||
export type { ConstructionMode } from '../modules/construction/types.js'
|
||||
export { BuilderForm } from '../modules/forms/BuilderForm.js'
|
||||
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
|
||||
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js'
|
||||
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
|
||||
export type {
|
||||
BuilderField,
|
||||
BuilderFormAction,
|
||||
@@ -34,6 +37,7 @@ export type {
|
||||
BuilderFormTexts,
|
||||
BuilderOption,
|
||||
BuilderStep,
|
||||
FieldCondition,
|
||||
} from '../modules/forms/builderTypes.js'
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
|
||||
|
||||
@@ -6,6 +6,8 @@ import { themeFields } from './fields/theme.js'
|
||||
type BuildSiteSettingsArgs = {
|
||||
/** Extra fields injected by the client project */
|
||||
additionalFields?: Field[]
|
||||
/** "Under construction" tab (developer tool) — given when the pages module is on. */
|
||||
constructionFields?: Field[]
|
||||
/**
|
||||
* Fields for the "System Pages" tab — page assignments by role (homepage,
|
||||
* privacy policy, collection archives). Assembled by the caller, which is the
|
||||
@@ -30,6 +32,7 @@ type BuildSiteSettingsArgs = {
|
||||
*/
|
||||
export function buildSiteSettings({
|
||||
additionalFields,
|
||||
constructionFields,
|
||||
systemPageFields,
|
||||
}: BuildSiteSettingsArgs = {}): GlobalConfig {
|
||||
return {
|
||||
@@ -55,6 +58,7 @@ export function buildSiteSettings({
|
||||
...(systemPageFields?.length
|
||||
? [{ fields: systemPageFields, label: 'System Pages' }]
|
||||
: []),
|
||||
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
|
||||
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
|
||||
],
|
||||
},
|
||||
|
||||
+8
-3
@@ -42,6 +42,9 @@ export {
|
||||
updateConsent,
|
||||
} from './modules/consent/index.js'
|
||||
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
||||
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
|
||||
export type { ConstructionMode } from './modules/construction/types.js'
|
||||
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
|
||||
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
|
||||
export {
|
||||
archiveFieldName,
|
||||
@@ -78,8 +81,8 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||
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 { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.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).
|
||||
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
|
||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||
@@ -132,16 +135,18 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
|
||||
export { resolveLocalized } from './modules/i18n/index.js'
|
||||
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
|
||||
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
|
||||
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, safeHref } from './modules/links/index.js'
|
||||
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js'
|
||||
export type {
|
||||
BuildLinkFieldOptions,
|
||||
BuildLinksFieldOptions,
|
||||
LinkAppearance,
|
||||
LinkAppearanceOption,
|
||||
LinkValue,
|
||||
NavItem,
|
||||
ResolvedLink,
|
||||
ResolveLinkHrefOptions,
|
||||
ResolveNavOptions,
|
||||
SystemLink,
|
||||
} from './modules/links/index.js'
|
||||
// Read-only MCP server (Claude/agents connect to the site and query it).
|
||||
export { createMcpRoute } from './modules/mcp/index.js'
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useId, useRef, useState } from 'react'
|
||||
|
||||
import type { ConstructionMode } from './types.js'
|
||||
|
||||
import { isPathAllowed } from './logic.js'
|
||||
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
|
||||
|
||||
export type ConstructionNoticeClassNames = {
|
||||
button?: string
|
||||
dialog?: string
|
||||
message?: string
|
||||
overlay?: string
|
||||
title?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The "site under construction" notice (Site Settings → Under construction).
|
||||
* Opens after a redirect from a blocked address (?notice=construction, then
|
||||
* removed from the URL) and when a visitor clicks a link to a page that isn't
|
||||
* available — the click is cancelled. Closes with its button or Escape.
|
||||
* Renders nothing while the mode is off.
|
||||
*
|
||||
* Unstyled (classNames, like CookieBanner); texts come from the panel.
|
||||
*
|
||||
* // [locale]/layout.tsx
|
||||
* <ConstructionNotice mode={await getConstructionMode(locale)} classNames={{ overlay: '…', dialog: '…' }} />
|
||||
*/
|
||||
export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const buttonRef = useRef<HTMLButtonElement>(null)
|
||||
const titleId = useId()
|
||||
const close = useCallback(() => setOpen(false), [])
|
||||
const { allowedPaths, enabled } = mode
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {return}
|
||||
// After a redirect: show the notice once and clean the address bar
|
||||
const url = new URL(window.location.href)
|
||||
if (url.searchParams.get(CONSTRUCTION_NOTICE_PARAM) === CONSTRUCTION_NOTICE_VALUE) {
|
||||
setOpen(true)
|
||||
url.searchParams.delete(CONSTRUCTION_NOTICE_PARAM)
|
||||
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`)
|
||||
}
|
||||
|
||||
// Capture phase, before Next's <Link> — a cancelled click doesn't navigate
|
||||
const onClick = (event: MouseEvent) => {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {return}
|
||||
const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null
|
||||
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute('download')) {return}
|
||||
if (anchor.target && anchor.target !== '_self') {return}
|
||||
const target = new URL(anchor.href, window.location.href)
|
||||
if (target.origin !== window.location.origin || isPathAllowed(target.pathname, allowedPaths)) {return}
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setOpen(true)
|
||||
}
|
||||
document.addEventListener('click', onClick, true)
|
||||
return () => document.removeEventListener('click', onClick, true)
|
||||
}, [enabled, allowedPaths])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {return}
|
||||
buttonRef.current?.focus()
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {close()}
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [open, close])
|
||||
|
||||
if (!enabled || !open) {return null}
|
||||
return (
|
||||
<div className={cn.overlay} data-ipal="construction-notice">
|
||||
<div aria-labelledby={mode.texts.title ? titleId : undefined} aria-modal="true" className={cn.dialog} role="dialog">
|
||||
{mode.texts.title ? <p className={cn.title} id={titleId}>{mode.texts.title}</p> : null}
|
||||
{mode.texts.message ? <p className={cn.message}>{mode.texts.message}</p> : null}
|
||||
<button className={cn.button} onClick={close} ref={buttonRef} type="button">
|
||||
{mode.texts.button ?? '×'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
const whenEnabled = (_: unknown, siblingData: { enabled?: boolean } | undefined) => Boolean(siblingData?.enabled)
|
||||
|
||||
/**
|
||||
* Site Settings → "Under construction" tab: a developer tool for a site that
|
||||
* isn't finished. When enabled, only the homepage and the chosen pages are
|
||||
* reachable — any other address redirects to the homepage with a notice, and a
|
||||
* link to another page shows the notice instead of navigating. One rule for
|
||||
* every visitor (pages stay static, there is no per-user check).
|
||||
*/
|
||||
export function buildConstructionFields(pagesSlug: string): Field[] {
|
||||
return [
|
||||
{
|
||||
name: 'construction',
|
||||
type: 'group',
|
||||
admin: { hideGutter: true },
|
||||
fields: [
|
||||
{
|
||||
name: 'enabled',
|
||||
type: 'checkbox',
|
||||
admin: {
|
||||
description:
|
||||
'Only the homepage and the pages below can be opened. Other addresses redirect to the homepage with the notice; links to other pages show it instead of navigating.',
|
||||
},
|
||||
defaultValue: false,
|
||||
label: 'Site under construction',
|
||||
},
|
||||
{
|
||||
name: 'allowedPages',
|
||||
type: 'relationship',
|
||||
admin: { condition: whenEnabled, description: 'The homepage is always available.' },
|
||||
hasMany: true,
|
||||
label: 'Pages still available',
|
||||
relationTo: pagesSlug as never,
|
||||
},
|
||||
{ name: 'title', type: 'text', admin: { condition: whenEnabled }, label: 'Notice title', localized: true },
|
||||
{ name: 'message', type: 'textarea', admin: { condition: whenEnabled }, label: 'Notice text', localized: true },
|
||||
{ name: 'buttonLabel', type: 'text', admin: { condition: whenEnabled }, label: 'Close button label', localized: true },
|
||||
],
|
||||
label: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
|
||||
|
||||
/** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */
|
||||
export const normalizePath = (path: string): string => {
|
||||
const trimmed = path.replace(/\/+$/, '')
|
||||
return trimmed === '' ? '/' : trimmed
|
||||
}
|
||||
|
||||
/** Is this pathname one of the allowed ones? Exact match, trailing slash ignored. */
|
||||
export function isPathAllowed(pathname: string, allowedPaths: readonly string[]): boolean {
|
||||
const path = normalizePath(pathname)
|
||||
return allowedPaths.some((allowed) => normalizePath(allowed) === path)
|
||||
}
|
||||
|
||||
/** Where a blocked address goes: the homepage with the notice parameter. */
|
||||
export const constructionNoticeHref = (homePath: string): string =>
|
||||
`${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}`
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* "Site under construction" (Site Settings → Under construction) as the
|
||||
* frontend needs it: getConstructionMode(locale) in createContentHelpers.
|
||||
*/
|
||||
export type ConstructionMode = {
|
||||
/** Paths a visitor may open, in every language: the homepage and "Pages still available". */
|
||||
allowedPaths: string[]
|
||||
enabled: boolean
|
||||
/** Homepage in the current language — blocked addresses redirect here (with the notice). */
|
||||
homePath: string
|
||||
/** Notice texts from the panel, in the current language. Empty = not set. */
|
||||
texts: { button?: string; message?: string; title?: string }
|
||||
}
|
||||
|
||||
/** Query parameter that opens the notice after a redirect: /pl?notice=construction */
|
||||
export const CONSTRUCTION_NOTICE_PARAM = 'notice'
|
||||
export const CONSTRUCTION_NOTICE_VALUE = 'construction'
|
||||
@@ -17,7 +17,7 @@ type CreateMarkdownRendererArgs = {
|
||||
* i18n config — only to know a single-locale site has no /{locale} prefix in
|
||||
* its URLs (for `url:`). Omit on multilingual sites if you like.
|
||||
*/
|
||||
config?: { locales: readonly unknown[] }
|
||||
config?: { defaultLocale?: string; locales: readonly unknown[] }
|
||||
/** Archive-backed collections, same value as the plugin option (optional). */
|
||||
content?: ContentOption
|
||||
/** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
|
||||
@@ -149,7 +149,26 @@ function canonicalOf(baseUrl: string | undefined, config: { locales: readonly un
|
||||
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> }
|
||||
type MarkdownRouteContext = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
|
||||
/**
|
||||
* Locale + slug of a Markdown request. Multilingual: app/md/[locale]/[[...slug]].
|
||||
* Single language (no /pl in URLs): app/md/[[...slug]] — no locale param, the
|
||||
* only locale is used; the [locale] route also works there for subpages
|
||||
* ("/md/kontakt" arrives as locale "kontakt" and is read as the slug).
|
||||
*/
|
||||
function routeOf(
|
||||
params: { locale?: string; slug?: string[] },
|
||||
config: CreateMarkdownRendererArgs['config'],
|
||||
): { locale: string; slug?: string[] } {
|
||||
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? (l as { code?: string }).code ?? '' : typeof l === 'string' ? l : ''))
|
||||
const fallback = config?.defaultLocale ?? codes[0] ?? ''
|
||||
if (!params.locale) {return { slug: params.slug, locale: fallback }}
|
||||
if (codes.length === 1 && !codes.includes(params.locale)) {
|
||||
return { slug: [params.locale, ...(params.slug ?? [])], locale: codes[0] }
|
||||
}
|
||||
return { slug: params.slug, locale: params.locale }
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole Markdown route in one call — same options as createMarkdownRenderer
|
||||
@@ -175,7 +194,7 @@ export function createMarkdownRoute(
|
||||
return {
|
||||
GET: async (_req, { params }) => {
|
||||
try {
|
||||
const { slug, locale } = await params
|
||||
const { slug, locale } = routeOf(await params, rendererArgs.config)
|
||||
const md = await render({ slug, locale, payload: await getCachedPayload() })
|
||||
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
|
||||
} catch (err) {
|
||||
|
||||
@@ -11,6 +11,9 @@ import type { Block, Field } from 'payload'
|
||||
*
|
||||
* Plain English labels (the panel is EN). Rendered by BuilderForm /
|
||||
* useBuilderForm, validated by submitForm like every other field.
|
||||
*
|
||||
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
|
||||
* (`showWhen`) — conditional visibility, evaluated by visibleFields.
|
||||
*/
|
||||
|
||||
const name: Field = {
|
||||
@@ -24,7 +27,41 @@ const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, lab
|
||||
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
|
||||
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
|
||||
|
||||
export const stepBlock: Block = {
|
||||
/**
|
||||
* "Show only when": the field — or, on a Step, the whole step — appears only
|
||||
* when another field has one of the given values. Evaluated by visibleFields
|
||||
* in the browser and again on the server (hidden fields are neither required nor stored).
|
||||
*/
|
||||
export const showWhenField: Field = {
|
||||
name: 'showWhen',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
|
||||
{
|
||||
name: 'values',
|
||||
type: 'text',
|
||||
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
|
||||
label: 'Values',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
label: 'Show only when',
|
||||
}
|
||||
|
||||
/** Adds "Show only when" at the end of a block's fields. */
|
||||
export function withShowWhen<B extends Block>(block: B): B {
|
||||
return { ...block, fields: [...block.fields, showWhenField] }
|
||||
}
|
||||
|
||||
const stepBase: Block = {
|
||||
slug: 'step',
|
||||
fields: [
|
||||
{
|
||||
@@ -42,7 +79,7 @@ export const stepBlock: Block = {
|
||||
labels: { plural: 'Steps', singular: 'Step' },
|
||||
}
|
||||
|
||||
export const checkboxGroupBlock: Block = {
|
||||
const checkboxGroupBase: Block = {
|
||||
slug: 'checkboxGroup',
|
||||
fields: [
|
||||
{ type: 'row', fields: [name, label] },
|
||||
@@ -72,3 +109,6 @@ export const checkboxGroupBlock: Block = {
|
||||
],
|
||||
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
|
||||
}
|
||||
|
||||
export const stepBlock: Block = withShowWhen(stepBase)
|
||||
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
||||
import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||
|
||||
import { NON_INPUT_TYPES } from './builderTypes.js'
|
||||
import { isEmail } from './validators.js'
|
||||
@@ -19,16 +19,24 @@ export function inputFields(fields: BuilderField[] | null | undefined): ({ name:
|
||||
/**
|
||||
* Splits the field list at `step` blocks. Fields before the first Step form
|
||||
* the first screen; a form without Steps is one screen.
|
||||
*
|
||||
* `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a
|
||||
* hidden Step with everything under it — out, while `index` stays the field's
|
||||
* position in the full list (RenderForm renders `message` blocks by it).
|
||||
*/
|
||||
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
|
||||
export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] {
|
||||
const steps: BuilderStep[] = []
|
||||
let current: BuilderStep | null = null
|
||||
let skipping = false
|
||||
;(fields ?? []).forEach((field, index) => {
|
||||
if (field.blockType === 'step') {
|
||||
skipping = isShown ? !isShown(field) : false
|
||||
if (skipping) {return}
|
||||
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
|
||||
steps.push(current)
|
||||
return
|
||||
}
|
||||
if (skipping || (isShown && !isShown(field))) {return}
|
||||
if (!current) {
|
||||
current = { fields: [], index: 0 }
|
||||
steps.push(current)
|
||||
@@ -40,6 +48,60 @@ export function splitSteps(fields: BuilderField[] | null | undefined): BuilderSt
|
||||
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
|
||||
}
|
||||
|
||||
const isBlankValue = (v: unknown) =>
|
||||
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
||||
|
||||
/** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */
|
||||
type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null }
|
||||
|
||||
const conditionValues = (condition: FieldCondition | null | undefined) =>
|
||||
(condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||
|
||||
/**
|
||||
* The fields (Steps and messages included) a visitor sees for the given values,
|
||||
* in panel order. A field is hidden when its own "Show only when" fails, when
|
||||
* its Step's condition fails (the whole step goes), or when the field its
|
||||
* condition points at is itself hidden. A condition naming a field that doesn't
|
||||
* exist hides the field — a typo shows up in the preview instead of passing silently.
|
||||
*
|
||||
* Shared by the browser (useBuilderForm: which steps and fields to show and
|
||||
* validate) and the server (validateSubmission: hidden fields are neither
|
||||
* required nor stored), so both agree on what was on screen.
|
||||
*/
|
||||
export function visibleFields<F extends ConditionalField>(fields: F[] | null | undefined, values: Record<string, unknown>): F[] {
|
||||
const list = fields ?? []
|
||||
const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f]))
|
||||
const stepOf = new Map<F, F | undefined>()
|
||||
let currentStep: F | undefined
|
||||
for (const field of list) {
|
||||
if (field.blockType === 'step') {currentStep = field}
|
||||
stepOf.set(field, field.blockType === 'step' ? undefined : currentStep)
|
||||
}
|
||||
|
||||
const cache = new Map<F, boolean>()
|
||||
const met = (condition: FieldCondition | null | undefined, seen: Set<F>): boolean => {
|
||||
const ref = condition?.field?.trim()
|
||||
if (!ref) {return true}
|
||||
const target = byName.get(ref)
|
||||
if (!target || seen.has(target) || !visible(target, seen)) {return false}
|
||||
const value = values[ref]
|
||||
const wanted = conditionValues(condition)
|
||||
if (wanted.length === 0) {return !isBlankValue(value)}
|
||||
if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))}
|
||||
return value != null && value !== '' && wanted.includes(String(value as boolean | number | string))
|
||||
}
|
||||
const visible = (field: F, seen: Set<F> = new Set()): boolean => {
|
||||
const cached = cache.get(field)
|
||||
if (cached !== undefined) {return cached}
|
||||
const nextSeen = new Set(seen).add(field)
|
||||
const step = stepOf.get(field)
|
||||
const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen)
|
||||
cache.set(field, result)
|
||||
return result
|
||||
}
|
||||
return list.filter((field) => visible(field))
|
||||
}
|
||||
|
||||
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
|
||||
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
@@ -52,8 +114,7 @@ export function initialBuilderValues(fields: BuilderField[] | null | undefined):
|
||||
)
|
||||
}
|
||||
|
||||
const isBlank = (v: unknown) =>
|
||||
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
||||
const isBlank = isBlankValue
|
||||
|
||||
/** Errors for the given fields (one message per field), empty object = valid. */
|
||||
export function validateBuilderFields(
|
||||
|
||||
@@ -6,6 +6,13 @@ import type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||
*/
|
||||
export type BuilderOption = { label?: null | string; value: string }
|
||||
|
||||
/**
|
||||
* "Show only when" of a field or a Step (panel group `showWhen`): visible only
|
||||
* when the field named `field` has one of `values` (comma-separated). Empty
|
||||
* `values` = when that field is filled in / ticked. Empty `field` = always.
|
||||
*/
|
||||
export type FieldCondition = { field?: null | string; values?: null | string }
|
||||
|
||||
export type BuilderField = {
|
||||
blockName?: null | string
|
||||
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
||||
@@ -23,6 +30,8 @@ export type BuilderField = {
|
||||
options?: BuilderOption[] | null
|
||||
placeholder?: null | string
|
||||
required?: boolean | null
|
||||
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
|
||||
showWhen?: FieldCondition | null
|
||||
/** step */
|
||||
title?: null | string
|
||||
width?: null | number
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import type { Field, Plugin } from 'payload'
|
||||
import type { Block, Field, Plugin } from 'payload'
|
||||
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
||||
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
|
||||
|
||||
type AccessArgs = { req: { user?: unknown } }
|
||||
|
||||
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
|
||||
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
|
||||
withShowWhen(builtinBlocks[key] as Block)
|
||||
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
||||
/**
|
||||
@@ -57,20 +61,22 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
// panel choices only — a form uses what the editor adds, nothing changes on
|
||||
// existing forms. Switch any off with forms.fields.<type>: false.
|
||||
fields: {
|
||||
checkbox: true,
|
||||
// every block carries "Show only when" (showWhen) — conditional fields and steps
|
||||
checkbox: builtin('checkbox'),
|
||||
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
||||
date: true,
|
||||
email: true,
|
||||
message: true,
|
||||
number: true,
|
||||
date: builtin('date'),
|
||||
email: builtin('email'),
|
||||
message: builtin('message'),
|
||||
number: builtin('number'),
|
||||
payment: false,
|
||||
radio: true,
|
||||
select: true,
|
||||
radio: builtin('radio'),
|
||||
select: builtin('select'),
|
||||
step: forms.fields?.step === false ? false : stepBlock,
|
||||
text: true,
|
||||
textarea: true,
|
||||
text: builtin('text'),
|
||||
textarea: builtin('textarea'),
|
||||
...Object.fromEntries(
|
||||
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
|
||||
// `true` keeps ipal's block (with "Show only when"); false / an object override it
|
||||
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
|
||||
),
|
||||
},
|
||||
...(forms.redirectRelationships
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Panel field types: step-by-step forms + multiple choice (enabled by default).
|
||||
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
|
||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||
export { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
|
||||
|
||||
import { safeHref } from '../links/resolveLinkHref.js'
|
||||
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
|
||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
import { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
import { useForm } from './useForm.js'
|
||||
|
||||
@@ -42,8 +42,8 @@ export type UseBuilderFormOptions = {
|
||||
*/
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
||||
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
||||
const steps = useMemo(() => splitSteps(fields), [fields])
|
||||
const inputs = useMemo(() => inputFields(fields), [fields])
|
||||
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
|
||||
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
|
||||
const [stepIndex, setStepIndex] = useState(0)
|
||||
const [resultMessage, setResultMessage] = useState<null | string>(null)
|
||||
const ts = useOptionalTurnstile()
|
||||
@@ -52,15 +52,16 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
|
||||
const submitAction = useCallback(
|
||||
async (values: Record<string, unknown>, token?: string) => {
|
||||
const result = await action(values, token)
|
||||
const shown = new Set(visibleInputs(values).map((field) => field.name))
|
||||
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
|
||||
if (result.success) {setResultMessage(result.message ?? null)}
|
||||
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
|
||||
return result
|
||||
},
|
||||
[action, texts.validation],
|
||||
[action, texts.validation, visibleInputs],
|
||||
)
|
||||
|
||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
|
||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
|
||||
|
||||
const f = useForm<Record<string, unknown>>({
|
||||
errorFallback: texts.error,
|
||||
@@ -78,6 +79,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
validate,
|
||||
})
|
||||
const { setErrors, setTurnstileToken } = f
|
||||
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
|
||||
const steps = useMemo(() => {
|
||||
const shown = new Set(visibleFields(fields, f.values))
|
||||
return splitSteps(fields, (field) => shown.has(field))
|
||||
}, [fields, f.values])
|
||||
|
||||
// Turnstile token lives in the provider; the engine needs it at submit.
|
||||
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { FieldCondition } from './builderTypes.js'
|
||||
|
||||
import { visibleFields } from './builderLogic.js'
|
||||
|
||||
/** A form-builder field, trimmed to what validation needs. */
|
||||
type FormField = {
|
||||
blockType?: string
|
||||
@@ -11,6 +15,8 @@ type FormField = {
|
||||
/** select / radio / checkboxGroup choices defined in the panel. */
|
||||
options?: { value?: unknown }[] | null
|
||||
required?: boolean | null
|
||||
/** "Show only when" — hidden fields are neither required nor stored. */
|
||||
showWhen?: FieldCondition | null
|
||||
}
|
||||
|
||||
type FormDoc = {
|
||||
@@ -171,10 +177,15 @@ export async function validateSubmission(
|
||||
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
|
||||
)
|
||||
const known = new Map(fields.map((f) => [f.name, f]))
|
||||
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
|
||||
const shown = new Set(visibleFields(form.fields, data))
|
||||
|
||||
const cleaned: Record<string, unknown> = {}
|
||||
|
||||
for (const field of fields) {
|
||||
// Hidden by a condition: not required, not stored. The consent gate never hides —
|
||||
// an editor can't switch GDPR consent off with a condition.
|
||||
if (!shown.has(field) && field.name !== consentFieldName) {continue}
|
||||
const value = data[field.name]
|
||||
const isBlank =
|
||||
value == null ||
|
||||
|
||||
@@ -5,9 +5,10 @@ import { cache } from 'react'
|
||||
|
||||
import type { AnalyticsConfig } from '../analytics/types.js'
|
||||
import type { ConsentTexts } from '../consent/texts.js'
|
||||
import type { ConstructionMode } from '../construction/types.js'
|
||||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions } from '../links/index.js'
|
||||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
|
||||
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
|
||||
import type { FormNotificationTexts } from '../notifications/types.js'
|
||||
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js'
|
||||
@@ -19,7 +20,7 @@ import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/i
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||||
import { createHealthRoute } from '../health/createHealthRoute.js'
|
||||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw } from '../links/resolveNav.js'
|
||||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
|
||||
import { createMcpRoute } from '../mcp/createMcpRoute.js'
|
||||
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
|
||||
import { buildOrganizationJsonLd, sameAsUrls } from '../seo/buildOrganizationJsonLd.js'
|
||||
@@ -586,6 +587,13 @@ export function createContentHelpers({
|
||||
const resolveNav = async (items: unknown, locale: string, options: { childrenField?: string; linkField?: string } = {}): Promise<NavItem[]> =>
|
||||
resolveNavRaw(items, { ...(await getLinkOptions(locale)), ...options })
|
||||
|
||||
/**
|
||||
* Legal links for the footer from Site Settings → System Pages — href and label
|
||||
* (the page title) in this locale. Default roles: privacy policy, cookie policy, terms.
|
||||
*/
|
||||
const getSystemLinks = async (locale: string, roles?: readonly string[]): Promise<SystemLink[]> =>
|
||||
resolveSystemLinks(await getSettings(locale), { ...(await getLinkOptions(locale)), ...(roles ? { roles } : {}) })
|
||||
|
||||
/** Old slug → its new URL (308), for the catch-all page before notFound(). */
|
||||
const resolvePageRedirect = async (locale: string, segments: string[] | undefined): Promise<null | string> =>
|
||||
resolveRedirectRaw({
|
||||
@@ -597,6 +605,40 @@ export function createContentHelpers({
|
||||
segments,
|
||||
})
|
||||
|
||||
/**
|
||||
* Site Settings → Under construction, for this locale: whether it's on, the
|
||||
* paths still reachable (homepage + chosen pages, in every language), the
|
||||
* homepage to redirect to and the notice texts. createPageRoute (with
|
||||
* `redirect`) and <ConstructionNotice> (/client) use it.
|
||||
*/
|
||||
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
|
||||
const settings = (await getSettings(locale)) as null | Record<string, unknown>
|
||||
const options = await getLinkOptions(locale)
|
||||
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
|
||||
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
|
||||
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
|
||||
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }}
|
||||
|
||||
const configured = await getConfiguredLocales()
|
||||
const paths = await Promise.all(
|
||||
(configured.length ? configured : [locale]).map(async (code) => {
|
||||
const localized = (await getSettings(code)) as null | Record<string, unknown>
|
||||
const linkOptions = await getLinkOptions(code)
|
||||
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
|
||||
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
|
||||
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
|
||||
}),
|
||||
)
|
||||
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
|
||||
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
|
||||
return {
|
||||
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
|
||||
enabled: true,
|
||||
homePath,
|
||||
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
|
||||
}
|
||||
})
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||
@@ -658,8 +700,8 @@ export function createContentHelpers({
|
||||
const llmsRoute = () => llms()()
|
||||
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
|
||||
const llmsFullRoute = () => llmsFull()()
|
||||
/** app/md/[locale]/[[...slug]]/route.ts: `export { markdownRoute as GET } from '@/lib/content'` */
|
||||
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale: string; slug?: string[] }> }) => md().GET(req, ctx)
|
||||
/** app/md/[locale]/[[...slug]]/route.ts (single language: app/md/[[...slug]]/route.ts): `export { markdownRoute as GET } from '@/lib/content'` */
|
||||
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale?: string; slug?: string[] }> }) => md().GET(req, ctx)
|
||||
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
|
||||
const mcpGET = () => mcp().GET()
|
||||
const mcpPOST = (req: Request) => mcp().POST(req)
|
||||
@@ -675,6 +717,7 @@ export function createContentHelpers({
|
||||
generateStaticParams,
|
||||
getCachedPayload,
|
||||
getConfiguredLocales,
|
||||
getConstructionMode,
|
||||
getEntries,
|
||||
getFormTexts,
|
||||
getHomeSlug,
|
||||
@@ -683,6 +726,7 @@ export function createContentHelpers({
|
||||
getPageJsonLd,
|
||||
getSettings,
|
||||
getSiteShell,
|
||||
getSystemLinks,
|
||||
healthRoute,
|
||||
i18n,
|
||||
indexNowKeyRoute,
|
||||
|
||||
@@ -5,10 +5,11 @@ import type { ResolvedRoute } from '../content/index.js'
|
||||
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
|
||||
|
||||
import { RenderBlocks } from '../blocks/RenderBlocks.js'
|
||||
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
|
||||
import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = Pick<
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||
ContentHelpers,
|
||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||
>
|
||||
@@ -28,6 +29,11 @@ export type PageRouteOptions = {
|
||||
notFound: () => never
|
||||
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
|
||||
permanentRedirect: (url: string) => never
|
||||
/**
|
||||
* `redirect` from 'next/navigation' — enables Site Settings → Under construction:
|
||||
* pages that aren't available (and unknown addresses) go to the homepage with the notice.
|
||||
*/
|
||||
redirect?: (url: string) => never
|
||||
/**
|
||||
* Render a route yourself — an archive listing, a blog entry template.
|
||||
* Return undefined to keep the default (the document's blocks).
|
||||
@@ -57,7 +63,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||
*/
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, render } = options
|
||||
const localeOf = (locale: string | undefined) => {
|
||||
const l = locale ?? helpers.i18n?.defaultLocale
|
||||
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||
@@ -73,6 +79,13 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { slug, locale: param } = await params
|
||||
const locale = localeOf(param)
|
||||
const segments = slug ?? []
|
||||
// Under construction: anything but the homepage and the chosen pages → homepage + notice
|
||||
if (redirect && helpers.getConstructionMode) {
|
||||
const construction = await helpers.getConstructionMode(locale)
|
||||
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
|
||||
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
|
||||
if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))}
|
||||
}
|
||||
const route = await helpers.resolveRoute(locale, segments, 1)
|
||||
if (!route) {
|
||||
const target = await helpers.resolvePageRedirect(locale, segments)
|
||||
|
||||
@@ -2,11 +2,19 @@ import type { ArrayField, Field, GroupField } from 'payload'
|
||||
|
||||
import { rowLabel } from '../admin-ui/rowLabel.js'
|
||||
|
||||
/** The default styles. A project may use any names of its own — see `appearances`. */
|
||||
export type LinkAppearance = 'link' | 'primary' | 'secondary'
|
||||
|
||||
/** One style the editor may pick: a value (`'highlight'`) or `{ label, value }` for a friendlier panel label. */
|
||||
export type LinkAppearanceOption = { label: string; value: string } | string
|
||||
|
||||
export type BuildLinkFieldOptions = {
|
||||
/** Visual styles the editor may pick. `false` → no appearance select. Default all three. */
|
||||
appearances?: false | LinkAppearance[]
|
||||
/**
|
||||
* Visual styles the editor may pick — the project's own names, mapped to its
|
||||
* classes in Button.tsx / the menu: `['primary', 'secondary', { label: 'Highlighted', value: 'highlight' }]`.
|
||||
* `false` → no appearance select. Default primary / secondary / link.
|
||||
*/
|
||||
appearances?: false | readonly LinkAppearanceOption[]
|
||||
/** Hide the label — for links that wrap something (a whole card, an image). */
|
||||
disableLabel?: boolean
|
||||
/** Field name. Default 'link'. */
|
||||
@@ -100,11 +108,12 @@ export function buildLinkField({
|
||||
}
|
||||
|
||||
if (appearances && appearances.length) {
|
||||
const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a))
|
||||
fields.push({
|
||||
name: 'appearance',
|
||||
type: 'select',
|
||||
defaultValue: appearances[0],
|
||||
options: appearances.map((a) => ({ label: a, value: a })),
|
||||
defaultValue: options[0].value,
|
||||
options,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export { buildLinkField, buildLinksField } from './buildLinkField.js'
|
||||
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
|
||||
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkAppearanceOption } from './buildLinkField.js'
|
||||
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
|
||||
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
|
||||
export { homeSlugFrom, resolveLink, resolveNav } from './resolveNav.js'
|
||||
export type { NavItem, ResolvedLink, ResolveNavOptions } from './resolveNav.js'
|
||||
export { homeSlugFrom, resolveLink, resolveNav, resolveSystemLinks } from './resolveNav.js'
|
||||
export type { NavItem, ResolvedLink, ResolveNavOptions, SystemLink } from './resolveNav.js'
|
||||
|
||||
@@ -75,3 +75,31 @@ export function homeSlugFrom(settings: unknown, field = 'homepage'): string | un
|
||||
const slug = home && typeof home === 'object' ? (home as { slug?: unknown }).slug : undefined
|
||||
return typeof slug === 'string' && slug ? slug : undefined
|
||||
}
|
||||
|
||||
export type SystemLink = { role: string } & ResolvedLink
|
||||
|
||||
/**
|
||||
* Links to the pages assigned in Site Settings → System Pages (privacy policy,
|
||||
* cookie policy, terms…) — href AND label from the panel: the label is the
|
||||
* page's own title in this locale, so nothing is typed in code and a renamed
|
||||
* or translated page updates the footer by itself. Unassigned roles are skipped.
|
||||
*
|
||||
* resolveSystemLinks(settings, { locale, config, homeSlug }) // privacy, cookies, terms
|
||||
* resolveSystemLinks(settings, { …, roles: ['termsOfService'] })
|
||||
*
|
||||
* `settings` = SiteSettings read with depth ≥ 1 (lib/content getSettings is depth 2).
|
||||
*/
|
||||
export function resolveSystemLinks(
|
||||
settings: unknown,
|
||||
{ roles = ['privacyPolicy', 'cookiePolicy', 'termsOfService'], ...options }: { roles?: readonly string[] } & ResolveLinkHrefOptions,
|
||||
): SystemLink[] {
|
||||
if (!settings || typeof settings !== 'object') {return []}
|
||||
const record = settings as Record<string, unknown>
|
||||
return roles.flatMap((role) => {
|
||||
const page = record[role]
|
||||
if (!page || typeof page !== 'object') {return []}
|
||||
const title = (page as { title?: unknown }).title
|
||||
const link = resolveLink({ type: 'internal', label: typeof title === 'string' ? title : '', page }, options)
|
||||
return link && link.label ? [{ ...link, role }] : []
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
import { injectRoles } from './modules/access/index.js'
|
||||
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
||||
import { buildConstructionFields } from './modules/construction/fields.js'
|
||||
import { buildArchiveFields } from './modules/content/index.js'
|
||||
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||
@@ -212,6 +213,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
...(config.globals ?? []),
|
||||
buildSiteSettings({
|
||||
additionalFields: options.siteSettingsFields,
|
||||
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
|
||||
systemPageFields,
|
||||
}),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import type { BuilderField } from '../src/modules/forms/builderTypes.js'
|
||||
|
||||
import { inputFields, splitSteps, validateBuilderFields, visibleFields } from '../src/modules/forms/builderLogic.js'
|
||||
import { validateSubmission } from '../src/modules/forms/validateSubmission.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
// A brief: screen 1 picks the areas, each later Step shows only for its area.
|
||||
const fields: BuilderField[] = [
|
||||
{ name: 'company', blockType: 'text', required: true },
|
||||
{ name: 'areas', blockType: 'checkboxGroup', options: [{ value: 'web' }, { value: 'mkt' }, { value: 'it' }], required: true },
|
||||
{ name: 'deadline', blockType: 'radio', options: [{ value: 'fixed' }, { value: 'flexible' }] },
|
||||
{ name: 'deadline_reason', blockType: 'text', showWhen: { field: 'deadline', values: 'fixed' } },
|
||||
{ name: 'consent', blockType: 'checkbox', required: true },
|
||||
{ blockType: 'step', showWhen: { field: 'areas', values: 'web' }, title: 'Website' },
|
||||
{ name: 'site_type', blockType: 'radio', options: [{ value: 'new' }, { value: 'redesign' }], required: true },
|
||||
{ name: 'site_problems', blockType: 'textarea', showWhen: { field: 'site_type', values: 'redesign' } },
|
||||
{ blockType: 'step', showWhen: { field: 'areas', values: 'mkt' }, title: 'Marketing' },
|
||||
{ name: 'ads_budget', blockType: 'text', required: true },
|
||||
{ blockType: 'step', showWhen: { field: 'areas', values: 'it, web' }, title: 'IT' },
|
||||
{ name: 'it_scope', blockType: 'text' },
|
||||
]
|
||||
const names = (list: BuilderField[]) => inputFields(list).map((f) => f.name)
|
||||
const texts = { validation: 'Check {field}' }
|
||||
|
||||
describe('conditional fields and steps (showWhen)', () => {
|
||||
test('nothing picked → only the first screen; a field shows when its value matches', () => {
|
||||
expect(names(visibleFields(fields, {}))).toEqual(['company', 'areas', 'deadline', 'consent'])
|
||||
expect(names(visibleFields(fields, { deadline: 'fixed' }))).toContain('deadline_reason')
|
||||
expect(names(visibleFields(fields, { deadline: 'flexible' }))).not.toContain('deadline_reason')
|
||||
})
|
||||
|
||||
test('a Step with a failed condition drops out with all its fields; any of the listed values matches', () => {
|
||||
const steps = splitSteps(visibleFields(fields, { areas: ['mkt'] }))
|
||||
expect(steps.map((s) => s.title)).toEqual([undefined, 'Marketing'])
|
||||
expect(splitSteps(visibleFields(fields, { areas: ['web'] })).map((s) => s.title)).toEqual([undefined, 'Website', 'IT'])
|
||||
})
|
||||
|
||||
test('hidden fields and Steps leave the rest with their original index (message blocks render by it)', () => {
|
||||
const list: BuilderField[] = [
|
||||
{ name: 'pick', blockType: 'radio', options: [{ value: 'a' }, { value: 'b' }] },
|
||||
{ blockType: 'step', showWhen: { field: 'pick', values: 'a' }, title: 'A' },
|
||||
{ blockType: 'message' },
|
||||
{ blockType: 'step', showWhen: { field: 'pick', values: 'b' }, title: 'B' },
|
||||
{ blockType: 'message' },
|
||||
]
|
||||
const shown = new Set(visibleFields(list, { pick: 'b' }))
|
||||
const steps = splitSteps(list, (field) => shown.has(field))
|
||||
expect(steps.map((s) => ({ indexes: s.fields.map(({ index }) => index), title: s.title }))).toEqual([
|
||||
{ indexes: [0], title: undefined },
|
||||
{ indexes: [4], title: 'B' },
|
||||
])
|
||||
})
|
||||
|
||||
test('a field inside a hidden Step stays hidden even when its own condition matches', () => {
|
||||
expect(names(visibleFields(fields, { areas: ['mkt'], site_type: 'redesign' }))).not.toContain('site_problems')
|
||||
expect(names(visibleFields(fields, { areas: ['web'], site_type: 'redesign' }))).toContain('site_problems')
|
||||
})
|
||||
|
||||
test('empty values = when the field is filled in or ticked; unknown field or a cycle hides', () => {
|
||||
const list: BuilderField[] = [
|
||||
{ name: 'a', blockType: 'checkbox' },
|
||||
{ name: 'b', blockType: 'text', showWhen: { field: 'a' } },
|
||||
{ name: 'c', blockType: 'text', showWhen: { field: 'typo' } },
|
||||
{ name: 'd', blockType: 'text', showWhen: { field: 'e' } },
|
||||
{ name: 'e', blockType: 'text', showWhen: { field: 'd' } },
|
||||
]
|
||||
expect(names(visibleFields(list, { a: false }))).toEqual(['a'])
|
||||
expect(names(visibleFields(list, { a: true }))).toEqual(['a', 'b'])
|
||||
})
|
||||
|
||||
test('validation of visible fields only: a hidden required field does not block', () => {
|
||||
const values = { areas: ['mkt'], company: 'X', consent: true }
|
||||
expect(validateBuilderFields(inputFields(visibleFields(fields, values)), values, texts)).toEqual({ ads_budget: 'Check ads_budget' })
|
||||
expect(validateBuilderFields(inputFields(visibleFields(fields, { ...values, areas: ['it'] })), values, texts)).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('server: validateSubmission follows the same conditions', () => {
|
||||
const { payload } = fakePayload({ forms: { brief: { fields } } })
|
||||
const check = (data: Record<string, unknown>) => validateSubmission(payload, 'brief', data)
|
||||
|
||||
test('a required field in a hidden Step is not required — and its value is not stored', async () => {
|
||||
const result = await check({ ads_budget: 'smuggled', areas: ['it'], company: 'X', consent: true, it_scope: 'servers' })
|
||||
expect(result).toMatchObject({ cleaned: { areas: ['it'], company: 'X', consent: true, it_scope: 'servers' }, ok: true })
|
||||
expect(result.ok && 'ads_budget' in result.cleaned).toBe(false)
|
||||
})
|
||||
|
||||
test('a required field in a visible Step is still enforced', async () => {
|
||||
expect(await check({ areas: ['mkt'], company: 'X', consent: true })).toMatchObject({ field: 'ads_budget', kind: 'required', ok: false })
|
||||
})
|
||||
|
||||
test('GDPR consent is enforced even if an editor hides it with a condition', async () => {
|
||||
const { payload: p } = fakePayload({
|
||||
forms: { f: { fields: [{ name: 'company', blockType: 'text' }, { name: 'consent', blockType: 'checkbox', showWhen: { field: 'company', values: 'never' } }] } },
|
||||
})
|
||||
expect(await validateSubmission(p, 'f', { company: 'X' })).toMatchObject({ field: 'consent', ok: false, reason: 'consent' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { buildConfig, getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js'
|
||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
describe('under construction — path logic', () => {
|
||||
test('paths compare without a trailing slash; the notice link carries the parameter', () => {
|
||||
expect(normalizePath('/pl/')).toBe('/pl')
|
||||
expect(normalizePath('')).toBe('/')
|
||||
expect(isPathAllowed('/pl/brief/', ['/pl', '/pl/brief'])).toBe(true)
|
||||
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
|
||||
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
|
||||
})
|
||||
})
|
||||
|
||||
describe('under construction — Site Settings → createPageRoute', () => {
|
||||
let payload: Payload
|
||||
let configPromise: Parameters<typeof getPayload>[0]['config']
|
||||
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
|
||||
|
||||
beforeAll(async () => {
|
||||
configPromise = buildConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-construction') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
|
||||
secret: 'construction-test-secret',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config: configPromise })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
const redirectError = (url: string): never => {
|
||||
throw new Error(`REDIRECT ${url}`)
|
||||
}
|
||||
const route = () =>
|
||||
createPageRoute(createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }), {
|
||||
blocks: {},
|
||||
notFound: () => {
|
||||
throw new Error('NEXT_NOT_FOUND')
|
||||
},
|
||||
permanentRedirect: vi.fn() as unknown as (url: string) => never,
|
||||
redirect: redirectError,
|
||||
})
|
||||
const open = (locale: string, slug?: string[]) => route().Page({ params: Promise.resolve({ slug, locale }) })
|
||||
|
||||
test('off: pages open normally; on: only the homepage and the chosen pages, everything else → homepage + notice', async () => {
|
||||
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', title: 'Start' } as never, locale: 'pl' as never })
|
||||
const brief = await payload.create({ collection: 'pages' as never, data: { slug: 'brief', title: 'Brief' } as never, locale: 'pl' as never })
|
||||
await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never, locale: 'pl' as never })
|
||||
await payload.update({ id: brief.id, collection: 'pages' as never, data: { slug: 'project-brief' } as never, locale: 'en' as never })
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
|
||||
|
||||
await expect(open('pl', ['o-nas'])).resolves.toBeTruthy()
|
||||
|
||||
await payload.updateGlobal({
|
||||
slug: 'site-settings' as never,
|
||||
data: { construction: { allowedPages: [brief.id], enabled: true, message: 'Strona w budowie', title: 'Pracujemy nad stroną' } } as never,
|
||||
locale: 'pl' as never,
|
||||
})
|
||||
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
|
||||
const mode = await helpers.getConstructionMode('pl')
|
||||
expect(mode).toMatchObject({ enabled: true, homePath: '/pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } })
|
||||
expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief']))
|
||||
|
||||
await expect(open('pl')).resolves.toBeTruthy()
|
||||
await expect(open('pl', ['brief'])).resolves.toBeTruthy()
|
||||
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||
})
|
||||
})
|
||||
@@ -257,6 +257,22 @@ describe('one-call helpers — layout, page, GEO routes', () => {
|
||||
const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) })
|
||||
expect(md.status).toBe(200)
|
||||
})
|
||||
|
||||
test('single-language Markdown: app/md/[[...slug]] (no locale param) and the [locale] route both serve the page', async () => {
|
||||
const helpers = h()
|
||||
const noLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'] }) })
|
||||
expect(noLocale.status).toBe(200)
|
||||
const plain = await noLocale.text()
|
||||
expect(plain).toContain('url: https://acme.pl/uslugi')
|
||||
expect(plain).toContain('locale: pl')
|
||||
// [locale] route on a one-language site: "/md/uslugi" arrives as locale "uslugi"
|
||||
const asLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ locale: 'uslugi' }) })
|
||||
expect(asLocale.status).toBe(200)
|
||||
const body = await asLocale.text()
|
||||
expect(body).toContain('# Usługi')
|
||||
expect(body).toContain('url: https://acme.pl/uslugi')
|
||||
expect(body).toContain('locale: pl')
|
||||
})
|
||||
})
|
||||
|
||||
describe('consent log', () => {
|
||||
|
||||
@@ -76,3 +76,31 @@ describe('section fields', () => {
|
||||
expect(buildSectionSettingsField({ backgrounds: false }).fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('project-defined link styles', () => {
|
||||
test('appearances accept the project\'s own names and panel labels', async () => {
|
||||
const { buildLinkField } = await import('../src/modules/links/buildLinkField.js')
|
||||
const field = buildLinkField({ appearances: ['primary', { label: 'Highlighted', value: 'highlight' }] })
|
||||
const select = field.fields.find((f) => 'name' in f && f.name === 'appearance') as { defaultValue: string; options: unknown[] }
|
||||
expect(select.options).toEqual([{ label: 'primary', value: 'primary' }, { label: 'Highlighted', value: 'highlight' }])
|
||||
expect(select.defaultValue).toBe('primary')
|
||||
expect(resolveLink({ ...page('oferta'), appearance: 'highlight' }, opts)?.appearance).toBe('highlight')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveSystemLinks', () => {
|
||||
test('href and label (page title) from System Pages; unassigned roles skipped', async () => {
|
||||
const { resolveSystemLinks } = await import('../src/modules/links/resolveNav.js')
|
||||
const settings = {
|
||||
cookiePolicy: null,
|
||||
privacyPolicy: { slug: 'polityka-prywatnosci', title: 'Polityka prywatności' },
|
||||
termsOfService: { slug: 'regulamin', title: 'Regulamin' },
|
||||
}
|
||||
expect(resolveSystemLinks(settings, opts).map((l) => [l.role, l.href, l.label])).toEqual([
|
||||
['privacyPolicy', '/pl/polityka-prywatnosci', 'Polityka prywatności'],
|
||||
['termsOfService', '/pl/regulamin', 'Regulamin'],
|
||||
])
|
||||
expect(resolveSystemLinks(settings, { ...opts, roles: ['termsOfService'] })).toHaveLength(1)
|
||||
expect(resolveSystemLinks(null, opts)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user