Files
ipal-kit/docs/richtext.md
T
Radosław SmolińskiandClaude Opus 5.5 ecf03c8dc0 IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches
- Request bodies from strangers are read only up to a cap, declared length or not:
  mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves
  to shared/ (the consent log keeps exporting it).
- searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters,
  10 words) before the database; an unknown ?locale is the default locale throughout.
- Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown
  drops unsafe link targets.
- truncate() never returns more than its limit (summary / meta autofill after validation).
- resolveRoute answers null for a locale the site does not have (xx, all, *): no
  default-locale page under another code (page route past the proxy, /md/xx, MCP).
- A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage).
- readPublished() access rule (exported); Site integrations readVersions: admin.
- Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense
  values at start; an unknown role name is met by nobody, requireRole throws on one.
- Docs, AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:25:26 +01:00

7.7 KiB

Rich text (Lexical) — RenderRichText

Rendering richText fields (the Lexical editor) on the frontend. The plugin ships RenderRichText — a thin wrapper over Payload's OFFICIAL converter (@payloadcms/richtext-lexical/react). It is the RenderBlocks of rich text: the plugin provides the engine, the project provides the look.

NEVER write your own Lexical renderer (a switch on node.type, bit flags node.format & 1). It duplicates what Payload already does, misses node types, drifts with Lexical updates and tempts you into dangerouslySetInnerHTML (XSS) and a hardcoded locale (.pl). Use RenderRichText.

Basic use (RSC)

import { RenderRichText } from '@intecion/ipal-kit/rsc'

<RenderRichText data={page.content} className="prose prose-slate max-w-none" />

Props: data (empty → null), className, converters, headingIds, safeLinks (default true). data is the richText field from the document — ALREADY localized (Payload returns the value for the current locale). No per-language keys, no hardcoded .pl.

Your own styles per node (converters)

The style stays in the project (Tailwind), the parsing in the plugin. Override the JSX of specific nodes through converters:

import { RenderRichText } from '@intecion/ipal-kit/rsc'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'

const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
  ...defaultConverters,
  heading: ({ node, nodesToJSX }) => {
    const children = nodesToJSX({ nodes: node.children })
    const cls: Record<string, string> = {
      h2: 'font-display text-2xl font-semibold mt-10 mb-4',
      h3: 'font-display text-xl font-semibold mt-7 mb-3',
    }
    const Tag = node.tag as 'h1' | 'h2' | 'h3' | 'h4'
    return <Tag className={cls[node.tag] ?? ''}>{children}</Tag>
  },
  paragraph: ({ node, nodesToJSX }) => (
    <p className="text-base leading-relaxed mb-5">{nodesToJSX({ nodes: node.children })}</p>
  ),
})

<RenderRichText data={page.content} converters={converters} />

Spread defaultConverters — you override only the nodes you want. The rest (lists, tables, images, links) works through Payload's official handling.

Links are filtered as in <CMSLink> (safeHref). A custom link with an address outside http(s), mailto, tel, sms, #, / (e.g. javascript:, data:) gets href="#" — also when it reached the database through an import, a seed or the API, bypassing the panel field. Since 1.17.1 one rule covers every stored link URL: an autolink, and a link marked linkType: 'internal', are checked too (Payload's autolink converter prints fields.url whatever the link type), and lexicalToMarkdown (the .md routes, llms-full.txt) drops an unsafe target and keeps the label. Turn off (fully trusted content only): <RenderRichText data={…} safeLinks={false} />.

Table of contents and heading anchors (1.11.1)

Long documents (privacy policy, terms) — a table of contents with links to sections. Heading ids in the table and in the content are computed by the same function, so they never drift apart.

// block config
import { buildTableOfContentsField } from '@intecion/ipal-kit'
fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }]   // group tableOfContents: show, label

// block component (RSC)
import { extractHeadings, RenderRichText } from '@intecion/ipal-kit/rsc'
import { TableOfContents } from '@intecion/ipal-kit/client'

const items = block.tableOfContents?.show ? extractHeadings(block.content) : []   // [{ id, text, level }]
{items.length ? <TableOfContents items={items} label={block.tableOfContents?.label} classNames={tocClasses} /> : null}
<RenderRichText data={block.content} converters={converters} headingIds={{ className: 'scroll-mt-24' }} />
  • extractHeadings(content, { levels: ['h2'] }) — headings in text order; id = toSlug(text), repeats -2, -3, empty headings skipped. Also from the root: import { extractHeadings, headingText } from '@intecion/ipal-kit'.
  • RenderRichText headingIds — true (h2) or { levels, className }. Your heading converter still renders the heading; the plugin adds the id (and className, e.g. scroll-mt-* under a sticky header).
  • <TableOfContents> — no styles: <nav aria-label={label}> + an <ol> of links. The server renders the whole list (works without JS); in the browser the link of the section being read gets aria-current="location" and classNames.linkActive. classNames: nav, label, list, item, link, linkActive; offset (default 0.3 of the screen height); data-ipal="toc", data-level on items.
  • buildTableOfContentsField({ name = 'tableOfContents' }) — a "Show contents" switch + a localized label (type TableOfContentsSettings). A new field in a block = a migration (pnpm payload migrate:create).

Click-to-enlarge images (lightbox, opt-in)

<RenderRichText data={post.content} lightbox />
<RenderRichText data={post.content} lightbox={{ group: 'post', image: { size: 'hero' }, triggerClassName: 'my-8' }} />

Each image upload is wrapped in <LightboxTrigger> (/client); the images of the page browse as one gallery (default group 'richtext', group: false = each alone). Your own upload converter still renders the inline image. Your own renderer: converters={withLightboxUploads(myConverters, options)} (/rsc). Details, labels and styling: lightbox.md.

lexicalToMarkdown — richText → Markdown (for AI)

For readability by AI agents (Markdown per page, llms-full) you need text, not JSX. lexicalToMarkdown converts a richText field to plain Markdown:

import { lexicalToMarkdown } from '@intecion/ipal-kit'
const md = lexicalToMarkdown(page.content)   // '## Heading\n\nParagraph **bold**…'

It handles headings, paragraphs, bold/italic/code/strikethrough, links, lists (nested), quotes, ---, images (upload). It is the text sibling of RenderRichText — the same input shape, a different output. A standalone walker, it does NOT depend on a specific MD export from @payloadcms/richtext-lexical (those change between versions), so a Payload bump will not break it. An unknown node degrades to its content and does not throw.

For a whole page (blocks, not a single field) use blocksToMarkdown / createMarkdownRenderer — see content.md.

Dependency

The official converter is part of @payloadcms/richtext-lexical, which a Payload project already has (it is the editor). No extra dependencies.

What this avoids (vs a hand-written renderer)

  • XSS — no dangerouslySetInnerHTML, and unsafe link URLs are neutralised
  • Hardcoded locale — no val.alt.pl (the data is already localized)
  • Missing nodes — the official converter handles all of them (nested lists, upload, relationships, horizontal rule…)
  • Drift on updates — Payload maintains the converter, not you
  • any — typed (SerializedEditorState)

Turn off, override, extend

  • The module has no option in iapl() — it adds nothing to the schema; you use the components and functions or you don't.
  • Override the look of nodes through converters (spread defaultConverters); heading ids through headingIds (levels, className).
  • Image lightbox: off by default; lightbox turns it on, withLightboxUploads is the building block (lightbox.md).
  • Link filtering: on by default; safeLinks={false} turns it off for fully trusted content.
  • extractHeadings(data, { levels }) and headingText(node) — building blocks for your own table of contents; style <TableOfContents> with classNames, the active-section threshold with offset.
  • lexicalToMarkdown has no options (the handled nodes are fixed; unknown ones degrade to text) — another format needs your own converter.