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:
co-authored by
Claude Opus 5.5
parent
23e033d7d7
commit
faa4ad679c
@@ -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} />
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
Reference in New Issue
Block a user