1.18.0 performance items: reference 404 placeholder and heading font without preload, lazy form and Turnstile code (eager entry /client/eager), Turnstile space kept, background video paused for reduced motion, card hover on opacity, metadata stripped on upload, MongoDB TTL indexes for the consent log and statistics, unused-media notice, version limit for the plugin's entities
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
076b3ef707
commit
d628839235
@@ -0,0 +1,34 @@
|
||||
'use client'
|
||||
import type { VideoHTMLAttributes } from 'react'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
const QUERY = '(prefers-reduced-motion: reduce)'
|
||||
|
||||
/**
|
||||
* A background video that stops for visitors who asked for less motion (WCAG 2.2.2, 2.3.3;
|
||||
* web.dev/articles/prefers-reduced-motion). The server renders the same <video autoplay muted loop>, so nothing
|
||||
* changes for anyone else; after hydration a visitor with "reduce motion" gets it paused on its first frame (the
|
||||
* poster stays), and the setting is followed if it changes while the page is open. Used by the library's <Media>
|
||||
* for `videoMode="background"`; off with `<Media pauseForReducedMotion={false}>`.
|
||||
*/
|
||||
export function BackgroundVideo(props: VideoHTMLAttributes<HTMLVideoElement>) {
|
||||
const ref = useRef<HTMLVideoElement>(null)
|
||||
useEffect(() => {
|
||||
const video = ref.current
|
||||
if (!video || typeof window.matchMedia !== 'function') {return}
|
||||
const media = window.matchMedia(QUERY)
|
||||
const apply = () => {
|
||||
if (media.matches) {
|
||||
video.pause()
|
||||
} else if (props.autoPlay) {
|
||||
void video.play().catch(() => {})
|
||||
}
|
||||
}
|
||||
apply()
|
||||
media.addEventListener('change', apply)
|
||||
return () => media.removeEventListener('change', apply)
|
||||
}, [props.autoPlay])
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption -- a silent background loop (aria-hidden by Media)
|
||||
return <video {...props} ref={ref} />
|
||||
}
|
||||
@@ -3,7 +3,15 @@ import type { ElementType, ReactNode } from 'react'
|
||||
import { cx } from './cx.js'
|
||||
|
||||
export const CARD_CLASS = 'flex flex-col rounded-card border border-border bg-surface text-fg shadow-sm'
|
||||
export const CARD_INTERACTIVE_CLASS = 'relative transition-shadow duration-fast ease-out hover:shadow-md focus-within:shadow-md'
|
||||
/**
|
||||
* Hover and focus lift (1.18.0): the larger shadow sits on an ::after layer whose opacity fades in — the browser
|
||||
* composites it instead of repainting the card's shadow on every frame (web.dev/articles/animations-guide). The
|
||||
* token duration makes it instant with "reduce motion". The 1.17 look: CARD_INTERACTIVE_SHADOW_CLASS.
|
||||
*/
|
||||
export const CARD_INTERACTIVE_CLASS =
|
||||
'relative after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:shadow-md after:opacity-0 after:transition-opacity after:duration-fast after:ease-out hover:after:opacity-100 focus-within:after:opacity-100'
|
||||
/** The 1.17 hover: `box-shadow` itself transitions (a repaint per frame) — for a project that wants it back. */
|
||||
export const CARD_INTERACTIVE_SHADOW_CLASS = 'relative transition-shadow duration-fast ease-out hover:shadow-md focus-within:shadow-md'
|
||||
|
||||
export type CardProps = { as?: ElementType; children: ReactNode; className?: string; interactive?: boolean }
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { MediaImageProps, VideoMode } from '../../media/mediaProps.js'
|
||||
import type { MediaValue } from '../data.js'
|
||||
|
||||
import { MEDIA_SIZES, mediaImageProps, videoProps } from '../../media/mediaProps.js'
|
||||
import { BackgroundVideo } from './BackgroundVideo.js'
|
||||
|
||||
/** next/image, passed in by the project (the plugin never imports next/*). */
|
||||
export type ImageComponent = ComponentType<{ className?: string } & MediaImageProps>
|
||||
@@ -14,6 +15,8 @@ export type MediaProps = {
|
||||
className?: string
|
||||
/** Above the fold, not the LCP image (a logo): eager, without fetchPriority="high" or a preload. */
|
||||
eager?: boolean
|
||||
/** `videoMode="background"`: paused for visitors with "reduce motion" (default true; 1.18.0). */
|
||||
pauseForReducedMotion?: boolean
|
||||
poster?: MediaValue
|
||||
/** Only the first visible image of the page (the LCP image). */
|
||||
priority?: boolean
|
||||
@@ -27,9 +30,10 @@ export type MediaProps = {
|
||||
* Every image or video of the library blocks. With `Image` (next/image, bound by createBlockRegistry)
|
||||
* images are optimized with blur-up; without it a plain <img> with width, height, lazy loading and focal point.
|
||||
*/
|
||||
export function Media({ alt, className, eager = false, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
|
||||
export function Media({ alt, className, eager = false, Image, pauseForReducedMotion = true, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
|
||||
const video = videoProps(resource, { mode: videoMode, poster })
|
||||
if (video) {
|
||||
if (videoMode === 'background' && pauseForReducedMotion) {return <BackgroundVideo {...video} aria-hidden className={className} />}
|
||||
// Captions are not stored with media uploads; a project that needs them swaps Media (ui option).
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
return <video {...video} aria-hidden={videoMode === 'background' ? true : undefined} className={className} />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { TTL_FIELD } from '../shared/ttl.js'
|
||||
import type { CollectionOverride } from '../shared/collectionOverride.js'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
@@ -44,6 +45,12 @@ export type ConsentLogOptions = {
|
||||
collectionOverrides?: CollectionOverride
|
||||
/** Days a record is kept. Default 1095 (3 years). */
|
||||
retentionDays?: number
|
||||
/**
|
||||
* MongoDB: a TTL index deletes records older than `retentionDays` by itself, also when no new record comes
|
||||
* (1.18.0; shared/ttl.ts). Default true; `false` drops the index at the next start — the purge after a new record
|
||||
* stays. Postgres / SQLite: not used.
|
||||
*/
|
||||
ttlIndex?: boolean
|
||||
}
|
||||
|
||||
export function buildConsentLogCollection(): CollectionConfig {
|
||||
@@ -154,6 +161,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
|
||||
data: {
|
||||
choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])),
|
||||
consentId: b.id,
|
||||
[TTL_FIELD]: new Date().toISOString(), // MongoDB TTL counts from here (dropped where the field is not there)
|
||||
version: b.version,
|
||||
} as never,
|
||||
overrideAccess: true,
|
||||
|
||||
@@ -96,45 +96,89 @@ export async function collectGrowth(payload: BasePayload): Promise<GrowthStatus>
|
||||
}
|
||||
}
|
||||
|
||||
// Orphaned media: ids of the upload collections that no other document or global mentions (any field, any depth)
|
||||
const uploads = collections.filter((c) => c.upload)
|
||||
if (uploads.length) {
|
||||
const ids = new Set<string>()
|
||||
for (const u of uploads) {
|
||||
const res = await payload.find({ collection: u.slug as never, depth: 0, limit: ORPHAN_SCAN_LIMIT, overrideAccess: true, pagination: false, select: {} as never })
|
||||
for (const d of res.docs as Array<{ id: number | string }>) {ids.add(String(d.id))}
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
let checked = 0
|
||||
// every string and number anywhere in a document (relations, uploads, rich text, blocks) — ids are among them
|
||||
const mark = (value: unknown, depth = 0): void => {
|
||||
if (depth > 40 || value == null) {return}
|
||||
if (typeof value === 'string' || typeof value === 'number') {
|
||||
const key = String(value)
|
||||
if (ids.has(key)) {seen.add(key)}
|
||||
return
|
||||
}
|
||||
if (Array.isArray(value)) {for (const v of value) {mark(v, depth + 1)}}
|
||||
else if (typeof value === 'object') {for (const v of Object.values(value)) {mark(v, depth + 1)}}
|
||||
}
|
||||
for (const c of collections) {
|
||||
if (c.upload || c.slug.startsWith('payload-') || checked >= ORPHAN_SCAN_LIMIT) {continue}
|
||||
try {
|
||||
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: ORPHAN_SCAN_LIMIT - checked, locale: 'all' as never, overrideAccess: true, pagination: false })
|
||||
checked += res.docs.length
|
||||
for (const d of res.docs) {mark(d)}
|
||||
} catch {
|
||||
// not readable this way: its references are not counted (the orphan count can then be too high, never too low)
|
||||
}
|
||||
}
|
||||
for (const g of globals) {
|
||||
try {
|
||||
mark(await payload.findGlobal({ slug: g.slug as never, depth: 0, draft: true, locale: 'all' as never, overrideAccess: true }))
|
||||
} catch {
|
||||
// not readable
|
||||
}
|
||||
}
|
||||
out.media = { capped: checked >= ORPHAN_SCAN_LIMIT, checked, orphaned: [...ids].filter((id) => !seen.has(id)).length, total: ids.size }
|
||||
const unused = await findUnusedMedia(payload)
|
||||
if (unused) {
|
||||
const orphaned = Object.values(unused.byCollection).reduce((n, list) => n + list.length, 0)
|
||||
out.media = { capped: !unused.complete, checked: unused.checked, orphaned, total: unused.total }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export type UnusedMedia = {
|
||||
/** Unused files per upload collection: id and file name. */
|
||||
byCollection: Record<string, Array<{ filename: null | string; id: number | string }>>
|
||||
/** Documents read (all collections and globals together). */
|
||||
checked: number
|
||||
/** false when the cap was reached or a collection could not be read: then some listed files may be used. */
|
||||
complete: boolean
|
||||
total: number
|
||||
}
|
||||
|
||||
const FILE_NAME = /[\w.-]+\.(?:avif|gif|jpe?g|mp4|pdf|png|svg|webm|webp)\b/gi
|
||||
|
||||
/**
|
||||
* Media of the upload collections that no other document or global mentions — by id (relations, uploads in rich
|
||||
* text and blocks, any depth, drafts and every language included) or by file name inside a text (a link to
|
||||
* `/api/media/file/plan.pdf`). Reads only; deletes nothing. null = no upload collection. The doctor counts them
|
||||
* (`growth-media`); the panel lists them (`unusedMedia`) only when `complete`.
|
||||
*/
|
||||
export async function findUnusedMedia(payload: BasePayload, { limit = ORPHAN_SCAN_LIMIT, only }: { limit?: number; only?: string[] } = {}): Promise<null | UnusedMedia> {
|
||||
const collections = (payload.config.collections ?? []) as unknown as CollectionLike[]
|
||||
const globals = (payload.config.globals ?? []) as unknown as GlobalLike[]
|
||||
const uploads = collections.filter((c) => c.upload && (!only || only.includes(c.slug)))
|
||||
if (!uploads.length) {return null}
|
||||
const files = new Map<string, { filename: null | string; id: number | string; slug: string }>()
|
||||
const byName = new Map<string, string>()
|
||||
for (const u of uploads) {
|
||||
const res = await payload.find({ collection: u.slug as never, depth: 0, limit, overrideAccess: true, pagination: false, select: { filename: true } as never })
|
||||
for (const d of res.docs as Array<{ filename?: null | string; id: number | string }>) {
|
||||
files.set(String(d.id), { filename: d.filename ?? null, id: d.id, slug: u.slug })
|
||||
if (d.filename) {byName.set(d.filename.toLowerCase(), String(d.id))}
|
||||
}
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
let checked = 0
|
||||
let complete = true
|
||||
// every string and number anywhere in a document — ids are among them, file names inside texts
|
||||
const mark = (value: unknown, depth = 0): void => {
|
||||
if (depth > 40 || value == null) {return}
|
||||
if (typeof value === 'string' || typeof value === 'number') {
|
||||
const key = String(value)
|
||||
if (files.has(key)) {seen.add(key)}
|
||||
if (typeof value === 'string' && byName.size) {
|
||||
for (const m of value.matchAll(FILE_NAME)) {
|
||||
const id = byName.get(m[0].toLowerCase())
|
||||
if (id) {seen.add(id)}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (Array.isArray(value)) {for (const v of value) {mark(v, depth + 1)}}
|
||||
else if (typeof value === 'object') {for (const v of Object.values(value)) {mark(v, depth + 1)}}
|
||||
}
|
||||
for (const c of collections) {
|
||||
if (c.upload || c.slug.startsWith('payload-')) {continue}
|
||||
if (checked >= limit) {
|
||||
complete = false
|
||||
break
|
||||
}
|
||||
try {
|
||||
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: limit - checked + 1, locale: 'all' as never, overrideAccess: true, pagination: false })
|
||||
if (res.docs.length > limit - checked) {complete = false}
|
||||
checked += Math.min(res.docs.length, limit - checked)
|
||||
for (const d of res.docs) {mark(d)}
|
||||
} catch {
|
||||
complete = false // not readable this way: its references are not known
|
||||
}
|
||||
}
|
||||
for (const g of globals) {
|
||||
try {
|
||||
mark(await payload.findGlobal({ slug: g.slug as never, depth: 0, draft: true, locale: 'all' as never, overrideAccess: true }))
|
||||
} catch {
|
||||
complete = false
|
||||
}
|
||||
}
|
||||
const byCollection: UnusedMedia['byCollection'] = Object.fromEntries(uploads.map((u) => [u.slug, []]))
|
||||
for (const [key, f] of files) {if (!seen.has(key)) {byCollection[f.slug].push({ filename: f.filename, id: f.id })}}
|
||||
return { byCollection, checked, complete, total: files.size }
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import path from 'node:path'
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, GrowthThresholds, RuleFinding } from '../types.js'
|
||||
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/**
|
||||
* The growth group (docs/performance.md → "What grows"): what makes a site and its database swell over the years.
|
||||
* Deep rules read counts, sizes and dates (never values) from the status; the static one measures two folders on this
|
||||
@@ -95,6 +97,38 @@ export const growthRules: DoctorRule[] = [
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// The project turns versions on itself: Payload keeps 100 per document unless the config says less
|
||||
id: 'growth-versions-config',
|
||||
check: (ctx) => {
|
||||
const out: RuleFinding[] = []
|
||||
for (const dir of [`${ctx.src}collections`, `${ctx.src}globals`]) {
|
||||
for (const name of ctx.list(dir).filter((n) => /\.(?:ts|js)$/.test(n))) {
|
||||
const file = `${dir}/${name}`
|
||||
const code = stripComments(ctx.read(file))
|
||||
for (const m of code.matchAll(/\bversions\s*:\s*(true|\{)/g)) {
|
||||
let body = ''
|
||||
if (m[1] === '{') {
|
||||
let depth = 0
|
||||
let i = m.index + m[0].length - 1
|
||||
for (; i < code.length; i++) {
|
||||
if (code[i] === '{') {depth++}
|
||||
else if (code[i] === '}' && --depth === 0) {break}
|
||||
}
|
||||
body = code.slice(m.index, i + 1)
|
||||
}
|
||||
if (/\bmaxPerDoc\s*:|\bmax\s*:/.test(body)) {continue}
|
||||
const global = dir.endsWith('globals')
|
||||
out.push({ file, fix: `versions: { ${m[1] === '{' ? '…, ' : ''}${global ? 'max' : 'maxPerDoc'}: 20 }`, message: `versions are on without a limit: Payload keeps 100 per ${global ? 'global' : 'document'} (every save, drafts and autosave included)`, severity: 'info' })
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// A log with a retention whose oldest record is older than it: the purge is not running (it runs after a new
|
||||
// record, at most once a day per process — a site without new records keeps the old ones)
|
||||
|
||||
@@ -50,6 +50,8 @@ export type BuilderFormProps = {
|
||||
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
|
||||
/** Appended to required labels, e.g. "*". Default: nothing. */
|
||||
requiredMark?: ReactNode
|
||||
/** Space kept for the Turnstile widget before it is drawn (default 73 px; 0 for an invisible widget). */
|
||||
turnstileReserveHeight?: number
|
||||
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
|
||||
turnstileTheme?: TurnstileTheme
|
||||
} & UseBuilderFormOptions
|
||||
@@ -75,6 +77,7 @@ export function BuilderForm({
|
||||
messages = {},
|
||||
renderField,
|
||||
requiredMark,
|
||||
turnstileReserveHeight,
|
||||
turnstileTheme,
|
||||
...options
|
||||
}: BuilderFormProps) {
|
||||
@@ -249,7 +252,7 @@ export function BuilderForm({
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
|
||||
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget reserveHeight={turnstileReserveHeight} theme={turnstileTheme} /></div> : null}
|
||||
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
|
||||
<div className={cn.actions}>
|
||||
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
'use client'
|
||||
import { lazy, Suspense } from 'react'
|
||||
|
||||
import type { BuilderFormProps } from './BuilderForm.js'
|
||||
|
||||
/**
|
||||
* <BuilderForm> loaded only on a page that renders a form (1.18.0). RenderForm uses this: the catch-all route can
|
||||
* render any block, so a static import put the form engine (fields, steps, validation, the Turnstile widget) into
|
||||
* the JavaScript of every page. The server still renders the whole form (the HTML is complete without JavaScript,
|
||||
* search engines and the first paint see it); the browser fetches the code while it hydrates the rest of the page.
|
||||
* It is `BuilderForm` in `@intecion/ipal-kit/client` (same props). The eager component, in every page's bundle:
|
||||
* `@intecion/ipal-kit/client/eager` → `<RenderForm Form={BuilderForm}>` (docs/forms.md).
|
||||
*/
|
||||
const Impl = lazy(() => import('./BuilderForm.js').then((m) => ({ default: m.BuilderForm })))
|
||||
|
||||
export function LazyBuilderForm(props: BuilderFormProps) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Impl {...props} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
|
||||
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { ComponentType, 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 { BuilderFormClassNames, BuilderFormProps } from './BuilderForm.js'
|
||||
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
|
||||
import type { SubmitActionResult } from './createSubmitAction.js'
|
||||
|
||||
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
|
||||
import { RenderRichText } from '../richtext/RenderRichText.js'
|
||||
import { BuilderForm } from './BuilderForm.js'
|
||||
import { LazyBuilderForm } from './LazyBuilderForm.js'
|
||||
|
||||
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
|
||||
export type SendFormAction = (
|
||||
@@ -24,6 +24,11 @@ export type RenderFormProps = {
|
||||
/** The project's `sendForm` server action (createSubmitAction). */
|
||||
action: SendFormAction
|
||||
classNames?: BuilderFormClassNames
|
||||
/**
|
||||
* The client form component. Default: the lazy one (1.18.0) — its code loads only on pages with a form, the HTML
|
||||
* is complete either way. `Form={BuilderForm}` from `@intecion/ipal-kit/client/eager` = in every page's bundle.
|
||||
*/
|
||||
Form?: ComponentType<BuilderFormProps>
|
||||
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
|
||||
converters?: JSXConvertersFunction
|
||||
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
|
||||
@@ -39,6 +44,8 @@ export type RenderFormProps = {
|
||||
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
|
||||
texts: BuilderFormTexts
|
||||
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
|
||||
/** Space kept for the Turnstile widget before it is drawn (default 73 px; 0 for an invisible widget). */
|
||||
turnstileReserveHeight?: number
|
||||
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>
|
||||
@@ -143,22 +150,26 @@ export function RenderForm({
|
||||
classNames,
|
||||
converters,
|
||||
form,
|
||||
Form = LazyBuilderForm,
|
||||
linkOptions,
|
||||
locale,
|
||||
requiredMark,
|
||||
richTextClassName,
|
||||
texts,
|
||||
turnstileReserveHeight,
|
||||
turnstileTheme,
|
||||
values,
|
||||
}: RenderFormProps) {
|
||||
const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName })
|
||||
if (!prepared) {return null}
|
||||
// the form's code is fetched only on pages that have a form (the HTML stays complete): LazyBuilderForm.tsx
|
||||
return (
|
||||
<BuilderForm
|
||||
<Form
|
||||
{...prepared}
|
||||
classNames={classNames}
|
||||
requiredMark={requiredMark}
|
||||
texts={texts}
|
||||
turnstileReserveHeight={turnstileReserveHeight}
|
||||
turnstileTheme={turnstileTheme}
|
||||
values={values}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
|
||||
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
|
||||
// /client entry shipped it with every page (docs/performance.md).
|
||||
import type { ChangeEvent } from 'react'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
|
||||
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
|
||||
// /client entry shipped it with every page (docs/performance.md).
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import { type FormSubmitAction, useForm } from './useForm.js'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
|
||||
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
|
||||
// /client entry shipped it with every page (docs/performance.md).
|
||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
import { findUnusedMedia } from '../doctor/growth.js'
|
||||
|
||||
type Props = {
|
||||
adminRoute?: string
|
||||
/** The upload collection this list shows (set by iapl). */
|
||||
collection?: string
|
||||
/** Injected by Payload into admin server components. */
|
||||
i18n?: { language?: string }
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload
|
||||
/** Injected by Payload into admin server components. */
|
||||
user?: null | Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Files listed in one link: a longer address may be cut by a proxy. */
|
||||
export const UNUSED_MEDIA_LINK_LIMIT = 100
|
||||
|
||||
const TEXT = {
|
||||
en: {
|
||||
incomplete: 'Unused files: the site has too many documents to check them all here — run iapl-doctor --deep (growth-media).',
|
||||
none: '',
|
||||
show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Show the first ${UNUSED_MEDIA_LINK_LIMIT}` : 'Show them'),
|
||||
title: (n: number) => `${n} file${n === 1 ? ' is' : 's are'} not used on any page, entry or setting.`,
|
||||
why: 'Check each one before you delete it (select them in the list → Delete). Nothing is deleted by itself.',
|
||||
},
|
||||
pl: {
|
||||
incomplete: 'Nieużywane pliki: strona ma zbyt wiele dokumentów, by sprawdzić je tutaj — uruchom iapl-doctor --deep (growth-media).',
|
||||
none: '',
|
||||
show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Pokaż pierwsze ${UNUSED_MEDIA_LINK_LIMIT}` : 'Pokaż je'),
|
||||
title: (n: number) => `Plików nieużywanych na żadnej stronie, we wpisie ani w ustawieniach: ${n}.`,
|
||||
why: 'Sprawdź każdy przed usunięciem (zaznacz je na liście → Usuń). Nic nie jest usuwane samo.',
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* `iapl({ unusedMedia: true })` (1.18.0; docs/media.md): above the list of an upload collection, how many files no
|
||||
* document or global uses, and a link that opens Payload's own list filtered to them — deleting stays the panel's
|
||||
* manual bulk delete, with its confirmation and access rules. For editors and admins; renders nothing when every
|
||||
* file is used, and only a hint when the site is too big to check every document here. Never throws.
|
||||
*/
|
||||
export async function UnusedMediaNotice({ adminRoute = '/admin', collection, i18n, payload, user }: Props) {
|
||||
if (!payload || !collection || !user || !userMeetsRole({ payload, user }, 'editor')) {return null}
|
||||
const t = i18n?.language === 'pl' ? TEXT.pl : TEXT.en
|
||||
let ids: Array<number | string>
|
||||
try {
|
||||
const unused = await findUnusedMedia(payload, { only: [collection] })
|
||||
if (!unused) {return null}
|
||||
if (!unused.complete) {return <p style={BOX}>{t.incomplete}</p>}
|
||||
ids = (unused.byCollection[collection] ?? []).map((f) => f.id)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!ids.length) {return null}
|
||||
const query = ids.slice(0, UNUSED_MEDIA_LINK_LIMIT).map((id, i) => `where[id][in][${i}]=${encodeURIComponent(String(id))}`).join('&')
|
||||
return (
|
||||
<div data-iapl="unused-media" style={BOX}>
|
||||
<strong>{t.title(ids.length)}</strong> {t.why}{' '}
|
||||
<a href={`${adminRoute}/collections/${collection}?${query}`}>{t.show(ids.length)}</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const BOX = { border: '1px solid var(--theme-elevation-150)', borderRadius: 4, margin: '0 0 1rem', padding: '0.75rem 1rem' } as const
|
||||
@@ -4,3 +4,5 @@ export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js
|
||||
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
|
||||
export type { OptimizeUploadOptions } from './optimizeUpload.js'
|
||||
export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js'
|
||||
export { exifOrientation, stripImageMetadata } from './stripMetadata.js'
|
||||
export type { StripResult } from './stripMetadata.js'
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { CheckboxField, CollectionBeforeOperationHook } from 'payload'
|
||||
import type { CheckboxField, CollectionBeforeOperationHook, PayloadRequest } from 'payload'
|
||||
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { APIError } from 'payload'
|
||||
|
||||
import { stripImageMetadata } from './stripMetadata.js'
|
||||
|
||||
/**
|
||||
* Safety net for oversized uploads — NOT an image pipeline. The developer and
|
||||
* editor are expected to upload prepared files; this only catches the 8 MB
|
||||
@@ -35,9 +37,33 @@ export type OptimizeUploadOptions = {
|
||||
png?: 'lossless' | 'lossy'
|
||||
/** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */
|
||||
quality?: number
|
||||
/**
|
||||
* Remove the metadata (camera, date, GPS position, comments) of every JPEG and PNG upload that passes the limits,
|
||||
* without re-encoding it (stripImageMetadata; 1.18.0). A photo whose EXIF says "rotate" is turned once (sharp,
|
||||
* JPEG quality 92) so it does not show sideways. Default true; `false` keeps uploads byte for byte as before.
|
||||
* Images over the limits lose their metadata anyway when the editor lets the plugin optimise them.
|
||||
*/
|
||||
stripMetadata?: boolean
|
||||
}
|
||||
|
||||
const OPTIMIZABLE = new Set(['image/jpeg', 'image/png'])
|
||||
|
||||
type Sharp = NonNullable<PayloadRequest['payload']['config']['sharp']>
|
||||
|
||||
/** The upload without its metadata (stripImageMetadata); a "rotate" in the EXIF is applied to the pixels first. */
|
||||
async function stripUploadMetadata(file: UploadFile, buffer: Buffer, sharp: Sharp | undefined): Promise<void> {
|
||||
const result = stripImageMetadata(buffer, file.mimetype)
|
||||
if (!result.changed) {return}
|
||||
let output = result.buffer
|
||||
if (result.orientation !== 1) {
|
||||
// without sharp the file stays as it was: an upright picture matters more than its metadata
|
||||
if (!sharp) {return}
|
||||
output = await sharp(buffer).rotate().jpeg({ quality: 92 }).toBuffer()
|
||||
}
|
||||
file.data = output
|
||||
file.size = output.length
|
||||
delete file.tempFilePath // Payload must read the new buffer, not the temp file
|
||||
}
|
||||
const MB = 1024 * 1024
|
||||
/** Size in MB with one decimal, in the admin language's number format. */
|
||||
const fmt = (bytes: number, language: string) =>
|
||||
@@ -90,6 +116,7 @@ export function buildOptimizeUploadHook(
|
||||
maxVideoBytes = 20 * MB,
|
||||
png = 'lossless',
|
||||
quality = 82,
|
||||
stripMetadata = true,
|
||||
} = options
|
||||
|
||||
return async ({ args, operation, req }) => {
|
||||
@@ -142,7 +169,10 @@ export function buildOptimizeUploadHook(
|
||||
|
||||
const tooHeavy = size > maxImageBytes
|
||||
const tooWide = width !== undefined && width > maxImageWidth
|
||||
if (!tooHeavy && !tooWide) {return}
|
||||
if (!tooHeavy && !tooWide) {
|
||||
if (stripMetadata) {await stripUploadMetadata(file, buffer, sharp)}
|
||||
return
|
||||
}
|
||||
|
||||
const problem = [
|
||||
tooHeavy ? `${fmt(size, lang)} (limit ${fmt(maxImageBytes, lang)})` : null,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Removes the metadata a photo carries (camera, date, GPS position, editing software, comments) from a JPEG or a PNG
|
||||
* WITHOUT re-encoding it: the pixels and the file's quality stay byte for byte, only the metadata blocks go
|
||||
* (1.18.0; docs/media.md). Kept: what changes how the image looks — the JFIF header and Adobe marker, the colour
|
||||
* profile (ICC), PNG gamma, chromaticity, sRGB and pixel density.
|
||||
*
|
||||
* JPEG: the APP1 (EXIF, XMP), APP13 (IPTC / Photoshop) and COM segments before the image data are dropped. EXIF also
|
||||
* holds the orientation: `orientation` reports it (1 = upright), so a caller can rotate the pixels first — otherwise a
|
||||
* phone photo taken sideways would show sideways.
|
||||
* PNG: tEXt, zTXt, iTXt, eXIf and tIME chunks are dropped.
|
||||
* Anything it cannot read is returned unchanged (`changed: false`).
|
||||
*/
|
||||
export type StripResult = { buffer: Buffer; changed: boolean; orientation: number }
|
||||
|
||||
const JPEG_DROP = new Set([0xe1, 0xed, 0xfe]) // APP1 (EXIF/XMP), APP13 (IPTC), COM
|
||||
const PNG_DROP = new Set(['eXIf', 'iTXt', 'tEXt', 'tIME', 'zTXt'])
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
|
||||
/** EXIF orientation (tag 0x0112 of IFD0) in an APP1 payload, or 1. */
|
||||
export function exifOrientation(app1: Buffer): number {
|
||||
if (app1.length < 14 || app1.toString('latin1', 0, 6) !== 'Exif\0\0') {return 1}
|
||||
const tiff = app1.subarray(6)
|
||||
const little = tiff.toString('latin1', 0, 2) === 'II'
|
||||
if (!little && tiff.toString('latin1', 0, 2) !== 'MM') {return 1}
|
||||
const u16 = (at: number) => (little ? tiff.readUInt16LE(at) : tiff.readUInt16BE(at))
|
||||
const u32 = (at: number) => (little ? tiff.readUInt32LE(at) : tiff.readUInt32BE(at))
|
||||
try {
|
||||
const ifd = u32(4)
|
||||
const entries = u16(ifd)
|
||||
for (let i = 0; i < entries; i++) {
|
||||
const at = ifd + 2 + i * 12
|
||||
if (u16(at) === 0x0112) {
|
||||
const value = u16(at + 8)
|
||||
return value >= 1 && value <= 8 ? value : 1
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// truncated EXIF: no orientation
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
function stripJpeg(input: Buffer): StripResult {
|
||||
const same = { buffer: input, changed: false, orientation: 1 }
|
||||
if (input.length < 4 || input[0] !== 0xff || input[1] !== 0xd8) {return same}
|
||||
const parts: Buffer[] = [input.subarray(0, 2)]
|
||||
let orientation = 1
|
||||
let changed = false
|
||||
let at = 2
|
||||
while (at + 4 <= input.length) {
|
||||
if (input[at] !== 0xff) {return same} // not a marker where one must be: leave the file alone
|
||||
const marker = input[at + 1]
|
||||
if (marker === 0xff) {at++; continue} // fill byte
|
||||
if (marker === 0xda || marker === 0xd9) { // start of scan / end: the rest is image data
|
||||
parts.push(input.subarray(at))
|
||||
break
|
||||
}
|
||||
const length = input.readUInt16BE(at + 2)
|
||||
if (length < 2 || at + 2 + length > input.length) {return same}
|
||||
const segment = input.subarray(at, at + 2 + length)
|
||||
if (JPEG_DROP.has(marker)) {
|
||||
if (marker === 0xe1 && orientation === 1) {orientation = exifOrientation(segment.subarray(4))}
|
||||
changed = true
|
||||
} else {
|
||||
parts.push(segment)
|
||||
}
|
||||
at += 2 + length
|
||||
}
|
||||
return changed ? { buffer: Buffer.concat(parts), changed, orientation } : same
|
||||
}
|
||||
|
||||
function stripPng(input: Buffer): StripResult {
|
||||
const same = { buffer: input, changed: false, orientation: 1 }
|
||||
if (input.length < 8 || !input.subarray(0, 8).equals(PNG_SIGNATURE)) {return same}
|
||||
const parts: Buffer[] = [PNG_SIGNATURE]
|
||||
let changed = false
|
||||
let at = 8
|
||||
while (at + 12 <= input.length) {
|
||||
const length = input.readUInt32BE(at)
|
||||
const type = input.toString('latin1', at + 4, at + 8)
|
||||
const end = at + 12 + length
|
||||
if (end > input.length) {return same}
|
||||
if (PNG_DROP.has(type)) {changed = true} else {parts.push(input.subarray(at, end))}
|
||||
at = end
|
||||
if (type === 'IEND') {break}
|
||||
}
|
||||
return changed ? { buffer: Buffer.concat(parts), changed, orientation: 1 } : same
|
||||
}
|
||||
|
||||
export function stripImageMetadata(input: Buffer, mimeType: string): StripResult {
|
||||
if (mimeType === 'image/jpeg' || mimeType === 'image/jpg' || mimeType === 'image/pjpeg') {return stripJpeg(input)}
|
||||
if (mimeType === 'image/png') {return stripPng(input)}
|
||||
return { buffer: input, changed: false, orientation: 1 }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { BasePayload, Config, DateField } from 'payload'
|
||||
|
||||
/**
|
||||
* MongoDB TTL index for a plugin log (1.18.0; docs/performance.md §6): the database itself deletes records once
|
||||
* they are older than the retention — also on a quiet site, where the purge after a new record never runs.
|
||||
*
|
||||
* Why a field of its own: Payload already keeps a plain index on `createdAt` (and the statistics on `lastAt`), and
|
||||
* Mongoose recreates its indexes at every start — turning that index into a TTL one makes the start fail with
|
||||
* IndexOptionsConflict. So the TTL counts from `iaplTtlFrom` (hidden; the record's `createdAt`, the visit's `lastAt`),
|
||||
* with an index named `iapl_ttl` that only the plugin manages. At every start its time is set to the current
|
||||
* `retentionDays` (collMod), so a changed retention applies at once; records written before 1.18.0 get the field
|
||||
* from their own date once (a single updateMany). Postgres and SQLite: no field, no index — the purge does it.
|
||||
* Opt-out: `ttlIndex: false` on the option; the index is then dropped at the next start (nothing more is deleted
|
||||
* by it), the purge stays.
|
||||
*/
|
||||
export const TTL_FIELD = 'iaplTtlFrom'
|
||||
export const TTL_INDEX = 'iapl_ttl'
|
||||
|
||||
export const isMongo = (config: Pick<Config, 'db'>) => (config.db as { name?: string } | undefined)?.name === 'mongoose'
|
||||
|
||||
/** The hidden date the TTL counts from. Not indexed by Payload (the plugin's own index is the TTL one). */
|
||||
export const ttlField = (): DateField => ({
|
||||
name: TTL_FIELD,
|
||||
type: 'date',
|
||||
admin: { disableBulkEdit: true, hidden: true },
|
||||
})
|
||||
|
||||
type NativeCollection = {
|
||||
collectionName: string
|
||||
createIndex: (key: object, options: object) => Promise<string>
|
||||
dropIndex: (name: string) => Promise<unknown>
|
||||
indexes: () => Promise<Array<{ expireAfterSeconds?: number; name?: string }>>
|
||||
updateMany: (filter: object, update: object[]) => Promise<{ modifiedCount?: number }>
|
||||
}
|
||||
|
||||
export type TtlSyncResult = 'created' | 'dropped' | 'none' | 'updated'
|
||||
|
||||
/** Creates, updates or drops the TTL index of one collection (MongoDB only; anything else does nothing). */
|
||||
export async function syncTtlIndex(
|
||||
payload: BasePayload,
|
||||
slug: string,
|
||||
{ days, enabled, from }: { days: number; enabled: boolean; from: string },
|
||||
): Promise<TtlSyncResult> {
|
||||
const db = payload.db as unknown as { collections?: Record<string, { collection?: NativeCollection }>; connection?: { db?: { command: (c: object) => Promise<unknown> } }; name?: string }
|
||||
const coll = db.collections?.[slug]?.collection
|
||||
if (db.name !== 'mongoose' || !coll) {return 'none'}
|
||||
const existing = (await coll.indexes()).find((i) => i.name === TTL_INDEX)
|
||||
if (!enabled) {
|
||||
if (!existing) {return 'none'}
|
||||
await coll.dropIndex(TTL_INDEX)
|
||||
return 'dropped'
|
||||
}
|
||||
// records from before 1.18.0 (or written by another path): the TTL counts from their own date
|
||||
await coll.updateMany({ [TTL_FIELD]: { $exists: false }, [from]: { $type: 'date' } }, [{ $set: { [TTL_FIELD]: `$${from}` } }])
|
||||
const seconds = Math.round(days * 86_400)
|
||||
if (!existing) {
|
||||
await coll.createIndex({ [TTL_FIELD]: 1 }, { expireAfterSeconds: seconds, name: TTL_INDEX })
|
||||
return 'created'
|
||||
}
|
||||
if (existing.expireAfterSeconds === seconds) {return 'none'}
|
||||
await db.connection!.db!.command({ collMod: coll.collectionName, index: { expireAfterSeconds: seconds, name: TTL_INDEX } })
|
||||
return 'updated'
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The plugin's own collections and globals turn versions on nowhere. When a project turns them on (globalOverrides,
|
||||
* collectionOverrides, formOverrides…) without a limit, each keeps at most 20 versions per document (1.18.0;
|
||||
* docs/performance.md §6) instead of Payload's 100 — a global like Site integrations is saved by the site itself on
|
||||
* every status change. A limit the project writes wins (`max` for globals, `maxPerDoc` for collections, 0 =
|
||||
* unlimited). Payload trims the oldest versions of a document on its next save.
|
||||
*/
|
||||
export const PLUGIN_VERSION_LIMIT = 20
|
||||
|
||||
type Versioned = { slug: string; versions?: unknown }
|
||||
|
||||
export function withVersionLimit<T extends Versioned>(entity: T, kind: 'collection' | 'global', limit = PLUGIN_VERSION_LIMIT): T {
|
||||
const v = entity.versions
|
||||
if (!v) {return entity}
|
||||
const key = kind === 'global' ? 'max' : 'maxPerDoc'
|
||||
if (v === true) {return { ...entity, versions: { [key]: limit } }}
|
||||
if (typeof v === 'object' && typeof (v as Record<string, unknown>)[key] !== 'number') {return { ...entity, versions: { ...(v as object), [key]: limit } }}
|
||||
return entity
|
||||
}
|
||||
@@ -30,6 +30,11 @@ export type StatsOptions = {
|
||||
retentionDays?: number
|
||||
/** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */
|
||||
timeZone?: string
|
||||
/**
|
||||
* MongoDB: a TTL index deletes visits whose last page view is older than `retentionDays`, also on a quiet site
|
||||
* (1.18.0). Default true; `false` drops the index at the next start, the purge stays. Postgres / SQLite: not used.
|
||||
*/
|
||||
ttlIndex?: boolean
|
||||
}
|
||||
|
||||
export type StatsPage = { p: string; t: string }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { TTL_FIELD } from '../shared/ttl.js'
|
||||
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
|
||||
|
||||
import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js'
|
||||
@@ -119,6 +120,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
|
||||
data: {
|
||||
exit: path,
|
||||
lastAt: now.toISOString(),
|
||||
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
|
||||
pageCount: pages.length,
|
||||
pages,
|
||||
...(visitorId && !visit.visitorId ? { visitorId } : {}),
|
||||
@@ -136,6 +138,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
|
||||
entry: path,
|
||||
exit: path,
|
||||
lastAt: now.toISOString(),
|
||||
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
|
||||
pageCount: 1,
|
||||
pages: [{ p: path, t: now.toISOString() }],
|
||||
referrer: referrerHost(body.r, host),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
'use client'
|
||||
import type { ComponentProps } from 'react'
|
||||
|
||||
import { lazy, Suspense } from 'react'
|
||||
|
||||
import type { Turnstile as TurnstileType } from './Turnstile.js'
|
||||
|
||||
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
|
||||
|
||||
const Impl = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile })))
|
||||
|
||||
/**
|
||||
* The Turnstile widget, loaded where it is shown (1.18.0): `<Turnstile>` from `@intecion/ipal-kit/client` is this
|
||||
* wrapper, so a page without a form carries none of its code. Same props; the eager one:
|
||||
* `@intecion/ipal-kit/client/eager`.
|
||||
*/
|
||||
export function LazyTurnstile(props: ComponentProps<typeof TurnstileType>) {
|
||||
return (
|
||||
<Suspense fallback={(props.reserveHeight ?? TURNSTILE_HEIGHT) ? <div style={{ minHeight: props.reserveHeight ?? TURNSTILE_HEIGHT }} /> : null}>
|
||||
<Impl {...props} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
'use client'
|
||||
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
import { useTheme } from '../theme/useTheme.js'
|
||||
@@ -29,6 +30,11 @@ function ensureScript(): void {
|
||||
export type TurnstileProps = {
|
||||
/** Called with the token once solved, or null on expiry/error. */
|
||||
onToken: (token: null | string) => void
|
||||
/**
|
||||
* Height kept free for the widget before Cloudflare draws it (1.18.0): the form below does not jump when it
|
||||
* appears (layout shift). Default 73 (the standard widget as drawn); 0 for an invisible widget.
|
||||
*/
|
||||
reserveHeight?: number
|
||||
/**
|
||||
* Change this value to make the widget issue a NEW token (a token is
|
||||
* single-use: after a submission the server refused, the next one needs a
|
||||
@@ -60,7 +66,7 @@ export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page'
|
||||
* The script is injected directly (no next/script dependency) so the widget
|
||||
* stays framework-agnostic.
|
||||
*/
|
||||
export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }: TurnstileProps) {
|
||||
export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page', reserveHeight = TURNSTILE_HEIGHT }: TurnstileProps) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const widgetId = useRef<null | string>(null)
|
||||
const pageTheme = useTheme().theme
|
||||
@@ -115,5 +121,5 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
|
||||
|
||||
if (!siteKey) {return null}
|
||||
|
||||
return <div ref={ref} />
|
||||
return <div ref={ref} style={reserveHeight ? { minHeight: reserveHeight } : undefined} />
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, use, useCallback, useState } from 'react'
|
||||
import { createContext, lazy, Suspense, use, useCallback, useState } from 'react'
|
||||
|
||||
import type { TurnstileTheme } from './Turnstile.js'
|
||||
|
||||
import { Turnstile } from './Turnstile.js'
|
||||
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
|
||||
|
||||
// The widget is loaded where a form shows it (1.18.0): the provider sits in the layout of every page.
|
||||
const Turnstile = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile })))
|
||||
|
||||
type TurnstileContextValue = {
|
||||
/** Clears the token and makes the widget issue a new one. */
|
||||
@@ -69,7 +72,7 @@ export function useTurnstile(): {
|
||||
enabled: boolean
|
||||
reset: () => void
|
||||
token: null | string
|
||||
TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
|
||||
TurnstileWidget: (props?: { reserveHeight?: number; theme?: TurnstileTheme }) => React.ReactNode
|
||||
} {
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx) {
|
||||
@@ -93,9 +96,9 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
|
||||
const { reset, siteKey, token } = ctx
|
||||
|
||||
const TurnstileWidget = useCallback(
|
||||
(props?: { theme?: TurnstileTheme }) => {
|
||||
(props?: { reserveHeight?: number; theme?: TurnstileTheme }) => {
|
||||
if (!siteKey) {return null}
|
||||
return <ProvidedTurnstile theme={props?.theme} />
|
||||
return <ProvidedTurnstile reserveHeight={props?.reserveHeight} theme={props?.theme} />
|
||||
},
|
||||
[siteKey],
|
||||
)
|
||||
@@ -104,8 +107,13 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
|
||||
}
|
||||
|
||||
/** The provider's widget: reads the key and the reset signal from the context, so `reset()` reaches it without a remount. */
|
||||
function ProvidedTurnstile({ theme }: { theme?: TurnstileTheme }) {
|
||||
function ProvidedTurnstile({ reserveHeight = TURNSTILE_HEIGHT, theme }: { reserveHeight?: number; theme?: TurnstileTheme }) {
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx?.siteKey) {return null}
|
||||
return <Turnstile onToken={ctx.setToken} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
|
||||
// the same reserved height while the widget's code loads: nothing below moves when it arrives
|
||||
return (
|
||||
<Suspense fallback={reserveHeight ? <div style={{ minHeight: reserveHeight }} /> : null}>
|
||||
<Turnstile onToken={ctx.setToken} reserveHeight={reserveHeight} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
|
||||
// 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'
|
||||
// `Turnstile` is the lazy wrapper since 1.18.0 (same props): the widget's code loads where a form shows it
|
||||
export { LazyTurnstile as Turnstile } from './LazyTurnstile.js'
|
||||
export type { TurnstileProps, TurnstileTheme } from './Turnstile.js'
|
||||
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Height kept free for the Turnstile widget before Cloudflare draws it: the widget measures 72.6 px in the browser
|
||||
* (Cloudflare documents 300×65 for the frame; the container adds the rest). Measured 2026-12 on the reference site.
|
||||
*/
|
||||
export const TURNSTILE_HEIGHT = 73
|
||||
Reference in New Issue
Block a user