Theme switcher, table of contents, missing-page redirect, form placeholders and time field; audit and revalidate fixes

- buildRevalidateHook skips outside Next (no NEXT_RUNTIME) and with context.disableRevalidate
- BuilderForm focuses only on a real step change (no scroll to the form on remount)
- mediaImageProps: placeholder colour only for JPEG (placeholderColor); hook stores no colour for transparent images
- buildLinkField: interface name per shape (CmsLink, CmsLinkPlain, CmsLinkNoLabel) + interfaceName option
- Cookie Settings: buttons.save -> buttons.savePreferences (Mongoose reserved name)
- ThemeScript, ThemeSwitcher, useTheme; Site Settings defaultTheme 'system' + themeToggleLabel; Turnstile follows page theme
- extractHeadings, RenderRichText headingIds, TableOfContents, buildTableOfContentsField
- createPageRoute onMissing: 'redirectHome'
- Form builder: localized placeholder on text/email/textarea/number, new time field
- ipal-audit: no false positive for object keys between JSX elements; /md route not reported as dynamic

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-19 21:32:40 +02:00
co-authored by Claude Opus 5.5
parent 23e033d7d7
commit faa4ad679c
55 changed files with 1298 additions and 58 deletions
+6 -2
View File
@@ -39,7 +39,11 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = {
alwaysActiveLabel?: null | string
buttons?: null | Partial<ConsentTexts['buttons']>
buttons?: ({
/** Before 1.11.1 the field was `save` — still read, so old MongoDB data keeps working until re-saved. */
save?: null | string
savePreferences?: null | string
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
eyebrow?: null | string
@@ -142,7 +146,7 @@ export async function getConsentTexts({
back: g.buttons?.back || FALLBACK.buttons.back,
close: g.buttons?.close || FALLBACK.buttons.close,
reject: g.buttons?.reject || FALLBACK.buttons.reject,
save: g.buttons?.save || FALLBACK.buttons.save,
save: g.buttons?.savePreferences || g.buttons?.save || FALLBACK.buttons.save,
settings: g.buttons?.settings || FALLBACK.buttons.settings,
},
categories,
+9 -6
View File
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
@@ -48,7 +49,8 @@ export type BuilderFormProps = {
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
turnstileTheme?: 'auto' | 'dark' | 'light'
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
} & UseBuilderFormOptions
/** A page-supplied value (always a string from `values`) as text. */
@@ -77,14 +79,15 @@ export function BuilderForm({
}: BuilderFormProps) {
const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null)
const firstRender = useRef(true)
const prevStep = useRef(f.stepIndex)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
// Compare with the previous step, not a "first render" flag: React re-runs effects
// without a remount (Next restoring a visited page from <Activity>, StrictMode),
// and a stale flag would focus the first field and scroll the page to the form.
useEffect(() => {
if (firstRender.current) {
firstRender.current = false
return
}
if (prevStep.current === f.stepIndex) {return}
prevStep.current = f.stepIndex
const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus()
+3 -1
View File
@@ -3,6 +3,7 @@ import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
@@ -37,7 +38,8 @@ export type RenderFormProps = {
richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light'
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
/** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */
values?: Record<string, string>
}
+28
View File
@@ -8,6 +8,10 @@ import type { Block, Field } from 'payload'
* Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[].
* - `time` — a time of day (<input type="time">). Value: "HH:MM".
*
* Built-in text · email · textarea · number get a localized "Placeholder"
* (withPlaceholder) — the hint inside the empty field, e.g. "e.g. 10:00–12:00".
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
@@ -61,6 +65,29 @@ export function withShowWhen<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, showWhenField] }
}
/** Hint inside the empty field. Localized — it is visible text. */
export const placeholderField: Field = {
name: 'placeholder',
type: 'text',
admin: { description: 'Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.' },
label: 'Placeholder',
localized: true,
}
/** Adds a localized "Placeholder" to a block (built-in text, email, textarea, number). */
export function withPlaceholder<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, placeholderField] }
}
const timeBase: Block = {
slug: 'time',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
],
labels: { plural: 'Times', singular: 'Time' },
}
const stepBase: Block = {
slug: 'step',
fields: [
@@ -112,3 +139,4 @@ const checkboxGroupBase: Block = {
export const stepBlock: Block = withShowWhen(stepBase)
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
export const timeBlock: Block = withShowWhen(timeBase)
+1 -1
View File
@@ -15,7 +15,7 @@ export type FieldCondition = { field?: null | string; values?: null | string }
export type BuilderField = {
blockName?: null | string
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
/** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
+10 -7
View File
@@ -6,7 +6,7 @@ import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-f
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
@@ -14,6 +14,8 @@ type AccessArgs = { req: { user?: unknown } }
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
withShowWhen(builtinBlocks[key] as Block)
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
@@ -68,7 +70,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
: undefined
return formBuilderPlugin({
...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: {
@@ -76,18 +78,19 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
checkbox: builtin('checkbox'),
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: builtin('date'),
email: builtin('email'),
email: withHint('email'),
message: builtin('message'),
number: builtin('number'),
number: withHint('number'),
payment: false,
radio: builtin('radio'),
select: builtin('select'),
step: forms.fields?.step === false ? false : stepBlock,
text: builtin('text'),
textarea: builtin('textarea'),
text: withHint('text'),
textarea: withHint('textarea'),
time: forms.fields?.time === false ? false : timeBlock,
...Object.fromEntries(
// `true` keeps ipal's block (with "Show only when"); false / an object override it
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
),
},
...(forms.redirectRelationships
+1 -1
View File
@@ -1,5 +1,5 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
+2
View File
@@ -62,6 +62,8 @@ export type FormsOption = {
step?: boolean
text?: boolean
textarea?: boolean
/** Time of day, <input type="time"> (ipal). Default on. */
time?: boolean
}
/**
* Override the forms collection. The plugin stays opinion-free about what a
+2 -1
View File
@@ -189,7 +189,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */
/** Everything an <input> needs, by field type: text · email · number · date · time · tel · checkbox. */
const getInputProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
@@ -201,6 +201,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date'
: field.blockType === 'time' ? 'time'
: base.autoComplete === 'tel' ? 'tel'
: 'text'
return {
+5
View File
@@ -46,6 +46,9 @@ export type FormValidationResult =
/** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** HH:MM or HH:MM:SS (a time input), 00:00–23:59. */
const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
@@ -123,6 +126,8 @@ function checkValue(field: FormField, value: unknown): Checked {
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
case 'time':
return typeof value === 'string' && TIME.test(value.trim()) ? { value: value.trim() } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
+9
View File
@@ -10,6 +10,7 @@ import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { ThemeScript } from '../theme/ThemeScript.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = {
@@ -30,6 +31,12 @@ export type SiteProvidersProps = {
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
shell: SiteShell
/**
* Light / dark theme from Site Settings → Theme: renders <ThemeScript> first,
* so the theme is on <html> before the first paint. Put <SiteProviders> first in
* <body> and add `suppressHydrationWarning` to <html>. Default false.
*/
theme?: boolean
}
/**
@@ -58,9 +65,11 @@ export function SiteProviders({
logEndpoint,
preconnect = true,
shell,
theme = false,
}: SiteProvidersProps) {
return (
<>
{theme ? <ThemeScript {...shell.theme} /> : null}
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
@@ -30,6 +30,7 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
import { getTurnstileConfig } from '../turnstile/config.js'
type CreateContentHelpersArgs = {
@@ -717,6 +718,7 @@ export function createContentHelpers({
formTexts,
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
settings: settings ?? {},
theme: themeConfigFrom(settings),
turnstileSiteKey: turnstile.siteKey,
}
})
@@ -794,6 +796,8 @@ export type SiteShell = {
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
jsonLd: Record<string, unknown>[]
settings: Record<string, unknown>
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
theme: ThemeConfig
turnstileSiteKey: null | string
}
+25 -3
View File
@@ -9,7 +9,7 @@ import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
@@ -31,6 +31,14 @@ export type PageRouteOptions = {
layoutField?: string
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
notFound: () => never
/**
* An address with no page (and no old-slug redirect):
* - 'notFound' (default) — the 404 page;
* - 'redirectHome' — 307 to the homepage in the same language (System Pages → Homepage;
* needs `redirect`). No homepage assigned, or the homepage itself missing → 404;
* - a function — your own decision, e.g. `({ locale }) => redirect(\`/${locale}/kontakt\`)`.
*/
onMissing?: 'notFound' | 'redirectHome' | ((ctx: { locale: string; segments: string[] }) => never | Promise<never>)
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never
/**
@@ -67,7 +75,10 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, render } = options
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
if (onMissing === 'redirectHome' && !redirect) {
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
}
const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
@@ -79,6 +90,16 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
return helpers.generatePageMetadata(localeOf(locale), slug)
}
async function missing(locale: string, segments: string[]): Promise<never> {
if (typeof onMissing === 'function') {return onMissing({ locale, segments })}
// segments.length: the homepage itself is missing — redirecting to it would loop.
if (onMissing === 'redirectHome' && redirect && helpers.getSystemLinks && segments.length) {
const [home] = await helpers.getSystemLinks(locale, ['homepage'])
if (home?.href) {return redirect(home.href)}
}
return notFound()
}
async function Page({ params }: PageArgs) {
const { slug, locale: param } = await params
const locale = localeOf(param)
@@ -93,7 +114,8 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
return target ? permanentRedirect(target) : notFound()
if (target) {return permanentRedirect(target)}
return missing(locale, segments)
}
const doc = route.doc
const extra = blockProps ? await blockProps({ doc, locale }) : {}
+17 -2
View File
@@ -20,6 +20,17 @@ type BuildRevalidateHookArgs = {
type DocWithSlug = { slug?: unknown }
/**
* Revalidation only makes sense inside a running Next server. Outside it
* (`payload run`, seeds via tsx, migrations) next/cache throws "Invariant: static
* generation store missing". `context.disableRevalidate` (Payload templates'
* convention) skips it on purpose, e.g. in a bulk import.
*/
function shouldRevalidate(context: unknown): boolean {
if (!process.env.NEXT_RUNTIME) {return false}
return !(context && typeof context === 'object' && (context as { disableRevalidate?: unknown }).disableRevalidate)
}
/** Resolve a doc's path in one locale (root for home). Null if no slug there. */
function pathForLocale(
doc: DocWithSlug,
@@ -47,6 +58,8 @@ function pathForLocale(
* Handles every locale, the root (home), AND a changed slug (revalidates both the
* old and new path so neither goes stale). revalidatePath is injected — the
* plugin never imports next/cache (safe under generate:importmap / plain Node).
* Outside a Next server (no NEXT_RUNTIME: `payload run`, seeds, migrations) and
* with `context: { disableRevalidate: true }` the hooks do nothing.
*
* // in your Media/Pages collection config, from a project file that CAN import next/cache:
* import { revalidatePath } from 'next/cache'
@@ -64,7 +77,8 @@ export function buildRevalidateHook({
} {
const locales = getLocaleCodes(config)
const afterChange: CollectionAfterChangeHook = ({ doc, previousDoc }) => {
const afterChange: CollectionAfterChangeHook = ({ context, doc, previousDoc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>()
for (const locale of locales) {
// New path.
@@ -85,7 +99,8 @@ export function buildRevalidateHook({
return doc
}
const afterDelete: CollectionAfterDeleteHook = ({ doc }) => {
const afterDelete: CollectionAfterDeleteHook = ({ context, doc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>()
for (const locale of locales) {
const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
+14 -3
View File
@@ -17,6 +17,14 @@ export type BuildLinkFieldOptions = {
appearances?: false | readonly LinkAppearanceOption[]
/** Hide the label — for links that wrap something (a whole card, an image). */
disableLabel?: boolean
/**
* Name of the generated TypeScript type. Default depends on the shape, so links of
* different shapes never share one name (payload generate:types would keep only the
* last one processed): `CmsLink`, `CmsLinkPlain` (appearances: false),
* `CmsLinkNoLabel` (disableLabel), `CmsLinkPlainNoLabel` (both). Set it yourself
* when you mix different `appearances` lists or `relationTo` values.
*/
interfaceName?: string
/** Field name. Default 'link'. */
name?: string
/** Collection the "Page" option points at. Default 'pages'. */
@@ -37,7 +45,8 @@ type SiblingWithType = { type?: string } | undefined
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all.
*
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
* Generates a named TypeScript type in payload-types.ts — `CmsLink` for the default
* shape, a suffixed name for others (see `interfaceName`). All are assignable to `CmsLink`.
*
* fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
@@ -46,10 +55,12 @@ export function buildLinkField({
name = 'link',
appearances = ['primary', 'secondary', 'link'],
disableLabel = false,
interfaceName,
relationTo = 'pages',
required = false,
uploadTo = 'media',
}: BuildLinkFieldOptions = {}): GroupField {
const hasAppearance = Boolean(appearances && appearances.length)
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
const fields: Field[] = [
{
@@ -105,7 +116,7 @@ export function buildLinkField({
fields.push({ name: 'label', type: 'text', localized: true, required })
}
if (appearances && appearances.length) {
if (appearances && hasAppearance) {
const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a))
fields.push({
name: 'appearance',
@@ -120,7 +131,7 @@ export function buildLinkField({
type: 'group',
admin: { hideGutter: true },
fields,
interfaceName: 'CmsLink',
interfaceName: interfaceName ?? `CmsLink${hasAppearance ? '' : 'Plain'}${disableLabel ? 'NoLabel' : ''}`,
}
}
+17 -3
View File
@@ -42,6 +42,13 @@ export const MEDIA_SIZES = {
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* Dominant colour as the <img> background while it loads. The style stays after
* load, so it would show through transparent pixels (white logo on a black box).
* 'auto' (default): only for JPEG, which has no alpha channel. true: always
* (opaque PNG/WebP photos). false: never.
*/
placeholderColor?: 'auto' | boolean
/**
* The LCP image (first visible image — usually the hero): loads eagerly with
* fetchPriority="high". Exactly one per page; everything else is lazy.
@@ -66,6 +73,9 @@ export type MediaImageProps = {
width: number
}
/** Formats that cannot be transparent — a background colour never shows through. */
const NO_ALPHA = new Set(['image/jpeg', 'image/jpg', 'image/pjpeg'])
const asDoc = (resource: unknown): MediaDoc | null =>
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
@@ -74,14 +84,18 @@ const asDoc = (resource: unknown): MediaDoc | null =>
* a bare id). Width/height always come from the document — no layout shift.
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
* blur-up and background colour.
* blur-up and — for JPEG only, see `placeholderColor` — a background colour.
*/
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null {
export function mediaImageProps(
resource: unknown,
{ alt, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
const blur = doc.placeholder?.blurDataURL ?? undefined
const color = doc.placeholder?.color ?? undefined
const useColor = placeholderColor === 'auto' ? NO_ALPHA.has(doc.mimeType ?? '') : placeholderColor
const color = useColor ? (doc.placeholder?.color ?? undefined) : undefined
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
const style = {
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
+3 -2
View File
@@ -48,11 +48,12 @@ export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined
if (!buffer) {return}
const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
const { dominant } = await sharp(buffer).stats()
const { dominant, isOpaque } = await sharp(buffer).stats()
const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0')
data[field] = {
blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`,
color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}`,
// Transparent images (logos, icons) get no colour — it would show through the alpha.
color: isOpaque ? `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}` : null,
}
} catch (err) {
// A placeholder is a nicety — never block the upload.
+56 -2
View File
@@ -1,7 +1,10 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { JSXConverters, JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
export type RenderRichTextProps = {
/** Wrapper class (e.g. Tailwind prose classes). */
@@ -20,6 +23,46 @@ export type RenderRichTextProps = {
* is needed here (unlike hand-rolled renderers that hardcode `.pl`).
*/
data: null | SerializedEditorState | undefined
/**
* Anchor ids on headings — the same ids as extractHeadings, so a
* <TableOfContents> links to them. `true` = h2; or `{ levels, className }`
* (className e.g. `scroll-mt-24` under a sticky header). Your own `heading`
* converter still renders the heading; the id is added to what it returns.
*/
headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean
}
type HeadingNode = { children?: unknown[]; tag: HeadingLevel }
/** Adds ids (and an optional class) to headings, on top of the project's converters. */
function withHeadingIds(
converters: JSXConvertersFunction | undefined,
ids: Map<object, { id: string }>,
className: string | undefined,
): JSXConvertersFunction {
return (args) => {
const base: JSXConverters = converters ? converters(args) : args.defaultConverters
const inner = base.heading
return {
...base,
heading: (props: { node: HeadingNode; nodesToJSX: (a: { nodes: unknown[] }) => ReactNode[] }) => {
const anchor = ids.get(props.node)
const rendered: ReactNode =
typeof inner === 'function'
? (inner as (p: typeof props) => ReactNode)(props)
: (() => {
const Tag = props.node.tag
return <Tag>{props.nodesToJSX({ nodes: props.node.children ?? [] })}</Tag>
})()
if (!anchor || !isValidElement(rendered)) {return rendered}
const el = rendered as ReactElement<{ className?: string; id?: string }>
const cls = [el.props.className, className].filter(Boolean).join(' ') || undefined
// The project's converter owns the markup; only the id is added to what it returned.
// eslint-disable-next-line @eslint-react/no-clone-element
return cloneElement(el, { id: anchor.id, ...(cls ? { className: cls } : {}) })
},
} as JSXConverters
}
}
/**
@@ -48,8 +91,19 @@ export type RenderRichTextProps = {
* },
* })
* <RenderRichText data={page.content} converters={converters} />
*
* // long document with a table of contents (same ids on both sides):
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
*/
export function RenderRichText({ className, converters, data }: RenderRichTextProps) {
export function RenderRichText({ className, converters, data, headingIds }: RenderRichTextProps) {
if (!data) {return null}
if (headingIds) {
const opts = headingIds === true ? {} : headingIds
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
if (ids.size) {
return <PayloadRichText className={className} converters={withHeadingIds(converters, ids, opts.className)} data={data} />
}
}
return <PayloadRichText className={className} converters={converters} data={data} />
}
+83
View File
@@ -0,0 +1,83 @@
'use client'
import { useEffect, useState } from 'react'
import type { HeadingItem } from './headings.js'
export type TableOfContentsClassNames = {
item?: string
label?: string
/** Every link. */
link?: string
/** Added to the link of the section being read. */
linkActive?: string
list?: string
nav?: string
}
export type TableOfContentsProps = {
classNames?: TableOfContentsClassNames
/** From extractHeadings — the same ids as the headings rendered with `headingIds`. */
items: readonly ({ level?: HeadingItem['level'] } & Pick<HeadingItem, 'id' | 'text'>)[]
/** Text above the list (from the panel). Also the nav's accessible name. Empty → none. */
label?: null | string
/**
* Where the "reading line" is, as a fraction of the viewport height: the
* current section is the last heading above it. Default 0.3.
*/
offset?: number
}
/**
* Table of contents with no styles: a <nav> with links to the headings. The
* server renders the full list (works without JS); in the browser the link of
* the section being read gets `aria-current="location"` and `classNames.linkActive`.
* Hooks for CSS: data-ipal="toc", data-level on each item.
*/
export function TableOfContents({ classNames: cn = {}, items, label, offset = 0.3 }: TableOfContentsProps) {
const [active, setActive] = useState<string | undefined>(items[0]?.id)
useEffect(() => {
const headings = items.map((item) => document.getElementById(item.id)).filter((el): el is HTMLElement => el !== null)
if (headings.length === 0) {return}
const update = () => {
const line = window.innerHeight * offset
let current = headings[0].id
for (const heading of headings) {
if (heading.getBoundingClientRect().top <= line) {current = heading.id}
}
setActive(current)
}
update()
window.addEventListener('scroll', update, { passive: true })
window.addEventListener('resize', update)
return () => {
window.removeEventListener('scroll', update)
window.removeEventListener('resize', update)
}
}, [items, offset])
if (items.length === 0) {return null}
const text = label?.trim()
return (
<nav aria-label={text || undefined} className={cn.nav} data-ipal="toc">
{text ? <p aria-hidden className={cn.label}>{text}</p> : null}
<ol className={cn.list}>
{items.map((item) => {
const current = item.id === active
return (
<li className={cn.item} data-level={item.level} key={item.id}>
<a
aria-current={current ? 'location' : undefined}
className={[cn.link, current ? cn.linkActive : undefined].filter(Boolean).join(' ') || undefined}
href={`#${item.id}`}
>
{item.text}
</a>
</li>
)
})}
</ol>
</nav>
)
}
+80
View File
@@ -0,0 +1,80 @@
import type { Field, GroupField } from 'payload'
import { toSlug } from '../slug/buildSlugField.js'
export type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
/** One table-of-contents entry: the heading's anchor id, its plain text and level. */
export type HeadingItem = { id: string; level: HeadingLevel; text: string }
export type ExtractHeadingsOptions = {
/** Heading levels that get an anchor and a TOC entry. Default ['h2'] (sections of a document). */
levels?: readonly HeadingLevel[]
}
type LexicalNode = { children?: LexicalNode[]; tag?: string; text?: string; type?: string }
/** Plain text of a Lexical node (a heading with bold parts, links…). */
export function headingText(node: unknown): string {
const n = node as LexicalNode
if (typeof n?.text === 'string') {return n.text}
return (n?.children ?? []).map(headingText).join('')
}
/**
* Walks the document in reading order and gives every heading of the chosen
* levels an id: slug of its text (toSlug), repeats get "-2", "-3"; an empty
* heading gets "section". Keyed by the node object, so RenderRichText puts
* exactly these ids on exactly these headings.
*/
export function headingIds(data: unknown, { levels = ['h2'] }: ExtractHeadingsOptions = {}): Map<object, HeadingItem> {
const wanted = new Set<string>(levels)
const seen = new Map<string, number>()
const out = new Map<object, HeadingItem>()
const walk = (node: LexicalNode) => {
if (node.type === 'heading' && node.tag && wanted.has(node.tag)) {
const text = headingText(node).replace(/\s+/g, ' ').trim()
const base = toSlug(text) || 'section'
const count = (seen.get(base) ?? 0) + 1
seen.set(base, count)
out.set(node, { id: count === 1 ? base : `${base}-${count}`, level: node.tag as HeadingLevel, text })
return
}
for (const child of node.children ?? []) {walk(child)}
}
const root = (data as { root?: LexicalNode } | null | undefined)?.root
if (root) {walk(root)}
return out
}
/**
* Table-of-contents entries of a rich-text field — the same ids RenderRichText
* gives the headings with `headingIds`. Empty headings are left out.
*
* const items = extractHeadings(block.content) // h2 only
* <TableOfContents items={items} label={block.tableOfContents?.label} />
* <RenderRichText data={block.content} headingIds />
*/
export function extractHeadings(data: unknown, options: ExtractHeadingsOptions = {}): HeadingItem[] {
return [...headingIds(data, options).values()].filter((h) => h.text.length > 0)
}
/**
* Panel switch for a table of contents on a text section: `show` + the label
* above the list ("Contents"), localized. Named type `TableOfContentsSettings`.
*
* fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }]
*/
export function buildTableOfContentsField({ name = 'tableOfContents' }: { name?: string } = {}): GroupField {
const fields: Field[] = [
{ name: 'show', type: 'checkbox', admin: { description: 'List of the section headings (H2) with links to them — for long documents.' }, label: 'Show table of contents' },
{
name: 'label',
type: 'text',
admin: { condition: (_: unknown, s: { show?: boolean } | undefined) => Boolean(s?.show), description: 'Heading above the list, e.g. "Contents". Empty → none.' },
label: 'Label',
localized: true,
},
]
return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: 'Table of contents' }
}
+2
View File
@@ -1,3 +1,5 @@
export { buildTableOfContentsField, extractHeadings, headingIds, headingText } from './headings.js'
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './headings.js'
export { lexicalToMarkdown } from './lexicalToMarkdown.js'
export { RenderRichText } from './RenderRichText.js'
export type { RenderRichTextProps } from './RenderRichText.js'
+17
View File
@@ -0,0 +1,17 @@
import type { ThemeConfig } from './theme.js'
import { themeScript } from './theme.js'
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
/**
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
* theme. Put it first in <body> (or turn on `theme` in <SiteProviders>), and
* add `suppressHydrationWarning` to <html>: the attribute differs from the server HTML on purpose.
*
* const shell = await getSiteShell(locale)
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
*/
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
}
+52
View File
@@ -0,0 +1,52 @@
'use client'
import type { ReactNode } from 'react'
import { Moon, Sun } from 'lucide-react'
import type { Theme } from './theme.js'
import { useTheme } from './useTheme.js'
export type ThemeSwitcherClassNames = {
/** Wrapper of the dark icon. */
dark?: string
/** Wrapper of the light icon. */
light?: string
/** The <button>. */
root?: string
}
export type ThemeSwitcherProps = {
classNames?: ThemeSwitcherClassNames
/** Accessible name — Site Settings → Theme → Toggle label (shell.theme.toggleLabel). */
label?: null | string
/** Your icons. Default lucide Sun / Moon. `null` → no icon. */
renderIcon?: (theme: Theme) => ReactNode
}
/**
* Light / dark switch with no styles: a <button role="switch"> (checked = dark)
* holding a light and a dark icon. Which one looks active is CSS's job — from
* the attribute on <html> (`[data-theme=dark] …`, Tailwind `dark:`), so the
* server HTML is already right and nothing jumps after hydration.
* Hooks: data-ipal="theme-switch", data-ipal-theme-icon="light|dark".
*/
export function ThemeSwitcher({ classNames: cn = {}, label, renderIcon }: ThemeSwitcherProps) {
const { theme, toggle } = useTheme()
const icon = (t: Theme) => (renderIcon ? renderIcon(t) : t === 'light' ? <Sun aria-hidden size="1.25em" /> : <Moon aria-hidden size="1.15em" />)
return (
<button
aria-checked={theme === 'dark'}
aria-label={label ?? undefined}
className={cn.root}
data-ipal="theme-switch"
onClick={toggle}
role="switch"
type="button"
>
<span className={cn.light} data-ipal-theme-icon="light">{icon('light')}</span>
<span className={cn.dark} data-ipal-theme-icon="dark">{icon('dark')}</span>
</button>
)
}
+2
View File
@@ -0,0 +1,2 @@
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE, themeConfigFrom, themeScript } from './theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from './theme.js'
+60
View File
@@ -0,0 +1,60 @@
/**
* Light / dark theme — shared names and the pre-paint script. Pure: safe on the
* server and in the browser.
*
* The theme never reaches the server HTML (pages are ISR/SSG, one HTML for
* everyone): <ThemeScript> sets `data-theme` on <html> before the first paint,
* from the visitor's choice (localStorage — an interface preference, no cookie,
* no tracking, no consent needed) or Site Settings → Theme → Default theme.
*/
export type Theme = 'dark' | 'light'
/** Site Settings → Default theme. 'system' follows the device (prefers-color-scheme). */
export type ThemeSetting = 'system' | Theme
/** localStorage key of the visitor's choice. */
export const THEME_STORAGE_KEY = 'ipal-theme'
/** Attribute on <html>: `[data-theme=dark]`, Tailwind `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`. */
export const THEME_ATTRIBUTE = 'data-theme'
/** Set on <html> for a moment while switching — for a colour transition only then (`[data-theme-switching] * { transition: … }`). */
export const THEME_SWITCHING_ATTRIBUTE = 'data-theme-switching'
export const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark'
export const isThemeSetting = (value: unknown): value is ThemeSetting => value === 'system' || isTheme(value)
/** Theme options from Site Settings — what getSiteShell(locale).theme holds. */
export type ThemeConfig = {
/** Visitors may switch (and their choice is remembered). */
allowToggle: boolean
/** null: no Site Settings — no attribute, the base (light) CSS applies. */
defaultTheme: null | ThemeSetting
/** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */
toggleLabel: null | string
}
/** Reads Theme options from a Site Settings document. */
export function themeConfigFrom(settings: unknown): ThemeConfig {
const s = (settings && typeof settings === 'object' ? settings : {}) as Record<string, unknown>
const label = typeof s.themeToggleLabel === 'string' && s.themeToggleLabel.trim() ? s.themeToggleLabel.trim() : null
return {
allowToggle: s.allowThemeToggle === true,
defaultTheme: isThemeSetting(s.defaultTheme) ? s.defaultTheme : null,
toggleLabel: label,
}
}
/**
* The inline script for <ThemeScript>: stored choice (only when the toggle is
* allowed) → default theme → for 'system' the device setting. Sets
* `data-theme` and `color-scheme` (native controls, scrollbars) on <html>.
*/
export function themeScript({ allowToggle, defaultTheme }: Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>): string {
const stored = allowToggle
? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}`
: ''
return (
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${stored}` +
`if(t==='system')t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';` +
`if(t==='light'||t==='dark'){d.setAttribute(${JSON.stringify(THEME_ATTRIBUTE)},t);d.style.colorScheme=t}})()`
)
}
+62
View File
@@ -0,0 +1,62 @@
'use client'
import { useCallback, useSyncExternalStore } from 'react'
import { isTheme, type Theme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from './theme.js'
/** The theme on <html> (after ThemeScript); null before it ran / without a theme. */
export function readDocumentTheme(): null | Theme {
if (typeof document === 'undefined') {return null}
const value = document.documentElement.getAttribute(THEME_ATTRIBUTE)
return isTheme(value) ? value : null
}
/**
* Puts a theme on <html> and remembers the choice. `transitionMs` keeps
* `data-theme-switching` on <html> for that long — style a colour transition
* with it, so normal hovers stay instant.
*/
export function applyTheme(theme: Theme, { persist = true, transitionMs = 300 }: { persist?: boolean; transitionMs?: number } = {}): void {
const root = document.documentElement
if (transitionMs > 0) {
root.setAttribute(THEME_SWITCHING_ATTRIBUTE, '')
window.setTimeout(() => root.removeAttribute(THEME_SWITCHING_ATTRIBUTE), transitionMs)
}
root.setAttribute(THEME_ATTRIBUTE, theme)
root.style.colorScheme = theme
if (!persist) {return}
try {
localStorage.setItem(THEME_STORAGE_KEY, theme)
} catch {
// private mode / blocked storage: the theme works until reload, the choice isn't kept
}
}
// <html data-theme> is external state: ThemeScript sets it, another tab changes it (storage event).
function subscribe(onChange: () => void): () => void {
const observer = new MutationObserver(onChange)
observer.observe(document.documentElement, { attributeFilter: [THEME_ATTRIBUTE], attributes: true })
const onStorage = (event: StorageEvent) => {
if (event.key === THEME_STORAGE_KEY && isTheme(event.newValue)) {applyTheme(event.newValue, { persist: false, transitionMs: 0 })}
}
window.addEventListener('storage', onStorage)
return () => {
observer.disconnect()
window.removeEventListener('storage', onStorage)
}
}
const serverSnapshot = (): null | Theme => null
/**
* The current theme and a setter. `theme` is null on the server and during
* hydration of a page without a theme — style the switch from CSS
* (`[data-theme=dark] …`, Tailwind `dark:`), not from this value, so nothing
* jumps after hydration.
*/
export function useTheme(): { setTheme: (theme: Theme) => void; theme: null | Theme; toggle: () => void } {
const theme = useSyncExternalStore(subscribe, readDocumentTheme, serverSnapshot)
const setTheme = useCallback((next: Theme) => applyTheme(next), [])
const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark'), [])
return { setTheme, theme, toggle }
}
+28 -4
View File
@@ -1,9 +1,12 @@
'use client'
import { useEffect, useRef } from 'react'
import { useTheme } from '../theme/useTheme.js'
declare global {
interface Window {
turnstile?: {
remove?: (id: string) => void
render: (el: HTMLElement, opts: Record<string, unknown>) => string
reset: (id?: string) => void
}
@@ -32,9 +35,15 @@ export type TurnstileProps = {
* client component and can't read Payload itself.
*/
siteKey: string
theme?: 'auto' | 'dark' | 'light'
/**
* 'page' (default): the site's theme (data-theme on <html>, ThemeScript) — a dark
* widget on a dark page; no site theme → 'auto' (the device's). Or fixed.
*/
theme?: TurnstileTheme
}
export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page'
/**
* Cloudflare Turnstile widget — reusable across any form. Renders the challenge
* and reports the token via onToken. The token must then be verified
@@ -45,9 +54,24 @@ export type TurnstileProps = {
* The script is injected directly (no next/script dependency) so the widget
* stays framework-agnostic.
*/
export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps) {
export function Turnstile({ onToken, siteKey, theme = 'page' }: TurnstileProps) {
const ref = useRef<HTMLDivElement>(null)
const widgetId = useRef<null | string>(null)
const pageTheme = useTheme().theme
const widgetTheme = theme === 'page' ? (pageTheme ?? 'auto') : theme
const renderedTheme = useRef(widgetTheme)
// The page switched theme: drop the widget so the effect below draws it again in the new one.
// Declared first, so it runs before the render effect.
useEffect(() => {
if (renderedTheme.current === widgetTheme) {return}
renderedTheme.current = widgetTheme
if (widgetId.current && window.turnstile?.remove) {
window.turnstile.remove(widgetId.current)
widgetId.current = null
onToken(null)
}
}, [widgetTheme, onToken])
useEffect(() => {
if (!siteKey) {return}
@@ -61,7 +85,7 @@ export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps)
'error-callback': () => onToken(null),
'expired-callback': () => onToken(null),
sitekey: siteKey,
theme,
theme: widgetTheme,
})
}
@@ -69,7 +93,7 @@ export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps)
// Script may load after mount — retry briefly until ready.
const interval = setInterval(render, 300)
return () => clearInterval(interval)
}, [siteKey, theme, onToken])
}, [siteKey, widgetTheme, onToken])
if (!siteKey) {return null}
+4 -2
View File
@@ -2,6 +2,8 @@
import { createContext, use, useCallback, useState } from 'react'
import type { TurnstileTheme } from './Turnstile.js'
import { Turnstile } from './Turnstile.js'
type TurnstileContextValue = {
@@ -58,7 +60,7 @@ export function useTurnstile(): {
enabled: boolean
reset: () => void
token: null | string
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode
TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
} {
const ctx = use(TurnstileContext)
if (!ctx) {
@@ -84,7 +86,7 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
const reset = useCallback(() => setToken(null), [setToken])
const TurnstileWidget = useCallback(
(props?: { theme?: 'auto' | 'dark' | 'light' }) => {
(props?: { theme?: TurnstileTheme }) => {
if (!siteKey) {return null}
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
},
+1 -1
View File
@@ -2,5 +2,5 @@
// Client-only exports — the Turnstile widget. Kept separate from index.ts so
// the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js'
export type { TurnstileProps } from './Turnstile.js'
export type { TurnstileProps, TurnstileTheme } from './Turnstile.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'