Under construction mode (developer tool)
Site Settings -> Under construction: a switch, 'Pages still available' and notice texts. When on, only the homepage and the chosen pages open (every language); other addresses redirect to the homepage with the notice (createPageRoute redirect option), and <ConstructionNotice> cancels clicks on links to blocked pages and shows the notice. getConstructionMode(locale). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -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'
|
||||
@@ -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 <ConstructionNotice> (/client) use it.
|
||||
*/
|
||||
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
|
||||
const settings = (await getSettings(locale)) as null | Record<string, unknown>
|
||||
const options = await getLinkOptions(locale)
|
||||
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
|
||||
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
|
||||
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
|
||||
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }}
|
||||
|
||||
const configured = await getConfiguredLocales()
|
||||
const paths = await Promise.all(
|
||||
(configured.length ? configured : [locale]).map(async (code) => {
|
||||
const localized = (await getSettings(code)) as null | Record<string, unknown>
|
||||
const linkOptions = await getLinkOptions(code)
|
||||
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
|
||||
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
|
||||
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
|
||||
}),
|
||||
)
|
||||
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
|
||||
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
|
||||
return {
|
||||
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
|
||||
enabled: true,
|
||||
homePath,
|
||||
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
|
||||
}
|
||||
})
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||
@@ -682,6 +717,7 @@ export function createContentHelpers({
|
||||
generateStaticParams,
|
||||
getCachedPayload,
|
||||
getConfiguredLocales,
|
||||
getConstructionMode,
|
||||
getEntries,
|
||||
getFormTexts,
|
||||
getHomeSlug,
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user