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 { const wanted = new Set(levels) const seen = new Map() const out = new Map() 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 * * */ 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: { en: 'Lists the section headings with links to them, for long pages.', pl: 'Lista nagłówków sekcji z linkami do nich, przydatna na długich stronach.', }, }, label: { en: 'Show contents', pl: 'Pokaż spis treści' }, }, { name: 'label', type: 'text', admin: { condition: (_: unknown, s: { show?: boolean } | undefined) => Boolean(s?.show), description: { en: 'Heading above the list, e.g. "Contents"; leave empty for none.', pl: 'Nagłówek nad listą, np. „Spis treści”; zostaw puste, aby go pominąć.', }, }, label: { en: 'List heading', pl: 'Nagłówek listy' }, localized: true, }, ] return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: { en: 'Table of contents', pl: 'Spis treści' } } }