diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3c5f67e..9ee9b98 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,19 @@ 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)`, + `` (`/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 `` tryb nie działa (nic się nie zmienia). + ## 1.9.7 ### Nowe diff --git a/docs/README.md b/docs/README.md index fd85893..47ae91e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) | diff --git a/docs/construction.md b/docs/construction.md new file mode 100644 index 0000000..cdc8262 --- /dev/null +++ b/docs/construction.md @@ -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 → `` 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' + +``` + +`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`). diff --git a/docs/pages.md b/docs/pages.md index dc600fd..7169085 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -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): diff --git a/src/exports/client.ts b/src/exports/client.ts index 95ff4f9..3947f42 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -24,6 +24,9 @@ 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, visibleFields } from '../modules/forms/builderLogic.js' diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index f692afc..ffb85b3 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -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' }] : []), ], }, diff --git a/src/index.ts b/src/index.ts index 7919b2b..3b0efff 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, diff --git a/src/modules/construction/ConstructionNotice.tsx b/src/modules/construction/ConstructionNotice.tsx new file mode 100644 index 0000000..b398c12 --- /dev/null +++ b/src/modules/construction/ConstructionNotice.tsx @@ -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 + * + */ +export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) { + const [open, setOpen] = useState(false) + const buttonRef = useRef(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 — 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 ( +
+
+ {mode.texts.title ?

{mode.texts.title}

: null} + {mode.texts.message ?

{mode.texts.message}

: null} + +
+
+ ) +} diff --git a/src/modules/construction/fields.ts b/src/modules/construction/fields.ts new file mode 100644 index 0000000..015d602 --- /dev/null +++ b/src/modules/construction/fields.ts @@ -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, + }, + ] +} diff --git a/src/modules/construction/logic.ts b/src/modules/construction/logic.ts new file mode 100644 index 0000000..cd0a4cc --- /dev/null +++ b/src/modules/construction/logic.ts @@ -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}` diff --git a/src/modules/construction/types.ts b/src/modules/construction/types.ts new file mode 100644 index 0000000..dab0ce3 --- /dev/null +++ b/src/modules/construction/types.ts @@ -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' diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 63089ae..8126bf1 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -5,6 +5,7 @@ import { cache } from 'react' import type { AnalyticsConfig } from '../analytics/types.js' import type { ConsentTexts } from '../consent/texts.js' +import type { ConstructionMode } from '../construction/types.js' import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js' @@ -604,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 (/client) use it. + */ + const getConstructionMode = cache(async (locale: string): Promise => { + const settings = (await getSettings(locale)) as null | Record + 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 + 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 => @@ -682,6 +717,7 @@ export function createContentHelpers({ generateStaticParams, getCachedPayload, getConfiguredLocales, + getConstructionMode, getEntries, getFormTexts, getHomeSlug, diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index c530e39..1b66b2b 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -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, '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) diff --git a/src/plugin.ts b/src/plugin.ts index fd047e8..90c3dcb 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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 }), diff --git a/test/construction.test.ts b/test/construction.test.ts new file mode 100644 index 0000000..8fd19ba --- /dev/null +++ b/test/construction.test.ts @@ -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[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') + }) +})