npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@focus-reactive/payload-plugin-visual-editing

v1.7.1

Published

Visual editing for Payload CMS — click-to-edit overlays on your frontend via Vercel stega and a postMessage bridge back to the admin.

Readme

@focus-reactive/payload-plugin-visual-editing

Click-to-edit for Payload CMS. On draft reads the plugin writes an invisible marker into every text value. The frontend overlay finds those markers in the rendered page, frames the elements and adds an Edit badge. A click focuses the field in the Payload admin. With the optional instant preview, text typed in the admin form appears in the Live Preview before it is saved.

AI Integration Prompt

Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload project.

Add click-to-edit to my Payload CMS v3 project with @focus-reactive/payload-plugin-visual-editing.

What it does: draft reads get invisible markers in their text values. An overlay on the frontend frames
the marked elements with an Edit badge, and a click focuses that field in the admin (in Live Preview or
in a new admin tab). Markers are removed from every write, and published reads stay clean.
First find out how my frontend renders: React / Next.js (step 4a) or no React, such as a static site
generator, server templates, Vue or Svelte (step 4b).

1. Install: bun add @focus-reactive/payload-plugin-visual-editing
   (payload and @payloadcms/ui 3.79+, react 19 in the admin; a React frontend needs react 18.2+,
   a frontend without React needs nothing)

2. In payload.config.ts:

   import { visualEditingPlugin } from '@focus-reactive/payload-plugin-visual-editing'

   visualEditingPlugin({ enrichment: 'explicit' })   // optionally: instantPreview: true

3. Editable collections and globals need versions: { drafts: true } and admin.livePreview.url pointing
   at the preview of the page. On Next.js that is a route that enables draft mode and redirects to the
   page (/next/preview?path=/<slug>), plus /next/exit-preview. Accept only paths that start with one "/".
   Then run: payload generate:importmap

4a. React / Next.js frontend:
   - Read with the draft mode flag:
     const { isEnabled: draft } = await draftMode()
     payload.find({ collection: 'pages', draft, depth: 1, context: { visualEditing: draft }, where: ... })
   - Wrap the layout:
     import { VisualEditing } from '@focus-reactive/payload-plugin-visual-editing/client'
     <VisualEditing.Provider available={isEnabled} framedOnly adminBasePath="/admin">
       <VisualEditing.Toggle />
       <VisualEditing.Overlay>{children}</VisualEditing.Overlay>
     </VisualEditing.Provider>
   - Rich text, uploads and relationships: spread withVisualEditingPath(value) from /client on the
     element that renders them, e.g. <img {...withVisualEditingPath(page.image)} />

4b. Frontend without React:
   - Read drafts over REST or GraphQL with draft=true, the x-visual-editing header and the session of a
     Payload user (a service user that may only read drafts: Authorization: JWT <token>, or
     users API-Key <key>). Leave the header out of production builds.
   - In the preview only, after the page has rendered:
     import { mountVisualEditing } from '@focus-reactive/payload-plugin-visual-editing/dom'
     mountVisualEditing({ adminOrigin: 'https://cms.example.com', framedOnly: true,
                          onSave: () => location.reload() })
   - Rich text, uploads and relationships: print the attributes of withVisualEditingPath(value) from
     /dom on the element that renders them. Where a template turns text into an id, slug or selector,
     clean it with stripMarkers(value) first.

Check: open a page in the admin, open Live Preview, set the toggle to Always, click a heading and see
its field focused in the form. Instant preview of rich text structure, editing on the page and the
options: see the plugin README.

Installation

bun add @focus-reactive/payload-plugin-visual-editing

Peer dependencies, all optional: payload ^3.79, @payloadcms/ui ^3.79, react and react-dom ^18.2.0 || ^19.0.0. What you need depends on where you use the package:

  • The Payload app (the plugin and its admin components) needs payload, @payloadcms/ui and React 19, which Payload 3 requires anyway.
  • A React frontend that imports ./client needs react and react-dom 18.2 or newer.
  • A site that imports only ./dom needs none of them.
  • A site that lets its editors write rich text on the page imports ./rich-text and needs Lexical: lexical, @lexical/rich-text, @lexical/list, @lexical/history, @lexical/selection and @lexical/utils, all 0.50.0, the version @payloadcms/richtext-lexical 3.90 uses. Before 3.90 it uses Lexical 0.41, so a site on Payload 3.79 to 3.89 installs 0.50 next to it. No other entry of the package imports them, see The Lexical packages.

The plugin does not import next; the setup below uses Next.js because the Payload admin runs on it. It is built and tested against Payload 3.90.1.

Setup

The plugin has a server half (Payload hooks that mark draft reads and strip markers from writes, plus an admin component) and a client half (the overlay on your frontend). Markers are written only into draft reads outside the admin: reads made with the Local API, and REST or GraphQL reads that send the x-visual-editing header with the session of a signed-in user, see Pages without React. The steps below use the Local API and wire Next.js draft mode end to end. apps/cms in this repository uses the plugin with enrichment: 'explicit', instant preview and LiveRichText, and is the working reference.

1. Register the plugin

// payload.config.ts
import { buildConfig } from 'payload'
import { visualEditingPlugin } from '@focus-reactive/payload-plugin-visual-editing'

export default buildConfig({
  // ...
  plugins: [visualEditingPlugin()],
})

See Options for what you can pass.

2. Enable drafts on editable collections

export const Pages: CollectionConfig = {
  slug: 'pages',
  versions: { drafts: true },
  // fields...
}

3. Add draft-mode routes

// app/(frontend)/next/preview/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'

export async function GET(req: Request) {
  const path = new URL(req.url).searchParams.get('path')
  if (!path || !path.startsWith('/') || path.startsWith('//')) {
    return new Response('Invalid path', { status: 400 })
  }
  ;(await draftMode()).enable()
  redirect(path)
}
// app/(frontend)/next/exit-preview/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'

export async function GET(req: Request) {
  const path = new URL(req.url).searchParams.get('path')
  ;(await draftMode()).disable()
  redirect(path && path.startsWith('/') && !path.startsWith('//') ? path : '/')
}

4. Point Live Preview at the preview route

export const Pages: CollectionConfig = {
  slug: 'pages',
  admin: {
    livePreview: {
      url: ({ data }) => {
        const slug = typeof data?.slug === 'string' ? data.slug : ''
        return `${process.env.NEXT_PUBLIC_SERVER_URL}/next/preview?path=${encodeURIComponent(`/${slug}`)}`
      },
    },
  },
  versions: { drafts: true },
  // fields...
}

The example assumes two things of your project: that NEXT_PUBLIC_SERVER_URL holds the origin of the frontend, and that a document has a slug field from which its route is built. Build the URL from whatever your routes use.

5. Read drafts in the frontend page

// app/(frontend)/[slug]/page.tsx
import { draftMode } from 'next/headers'
import { getPayload } from 'payload'
import config from '@payload-config'

export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const { isEnabled: draft } = await draftMode()
  const payload = await getPayload({ config })

  const { docs } = await payload.find({
    collection: 'pages',
    draft,
    depth: 1,
    where: { slug: { equals: slug } },
  })
  // render docs[0]
}

A global is read the same way, payload.findGlobal({ slug: 'header', draft }), and is marked at every depth. With enrichment: 'explicit', also pass context: { visualEditing: draft }, see Enrichment modes.

6. Wrap the frontend layout

// app/(frontend)/layout.tsx
import { VisualEditing } from '@focus-reactive/payload-plugin-visual-editing/client'
import { draftMode } from 'next/headers'

export default async function Layout({ children }: { children: React.ReactNode }) {
  const { isEnabled } = await draftMode()

  return (
    <html>
      <body>
        <VisualEditing.Provider available={isEnabled} framedOnly adminBasePath="/admin">
          <VisualEditing.Toggle />
          <VisualEditing.Overlay>{children}</VisualEditing.Overlay>
        </VisualEditing.Provider>
      </body>
    </html>
  )
}
  • VisualEditing.Toggle is the floating Off / Hover / Always control. It starts on Off: a page shows no outlines until the editor picks Hover or Always. With editing on the page it starts on Hover instead. A mode the editor picked, Off too, is used from then on. The chosen mode is kept in localStorage under the key visual-editing, per origin of the page. It starts in the top right corner and can be dragged anywhere in the window; the place it was dropped is kept in localStorage under visual-editing-toggle-position.
  • VisualEditing.Overlay scans its children for markers. Content outside it is not touched.

7. Mark rich text, uploads and relationships

Text fields work on their own. Rich text, uploads and related documents need one spread in your renderer, see Rich text, uploads and relationships.

8. Regenerate the admin import map

bunx payload generate:importmap

Using it

Open a document in the admin, open Live Preview and set the toggle to Always or Hover. Editable text gets a frame and an Edit badge. The frame is one rectangle around the element, also when its text wraps, and it is drawn above the page, so the page's own styles are not changed. On a page that sets CSS zoom on an ancestor, such as body { zoom: 1.25 }, the frames, the badge, the toolbar of rich text and the toggle sit where the zoomed content is drawn, in a browser that reports the zoom of an element (currentCSSZoom); elsewhere they are placed as without a zoom. A click on the badge or anywhere inside the frame focuses the field in the admin form; the field's border turns blue and pulses briefly, then the field keeps Payload's normal focus style. A click with a modifier key and a text selection keep the page's own behaviour; a double click does nothing. A click on text of another document opens that document in a new admin tab.

To leave draft mode in a normal browser tab, open /next/exit-preview.

Frames and the badge are drawn above the whole page, so they would also cross a sticky header or another bar that stays over the content while it scrolls. Mark such an element with data-ve-cover and the part of every frame and badge that lies under it is hidden:

<header className="sticky top-0" data-ve-cover>

The cover hides nothing of its own content: a field rendered inside it keeps its whole frame.

On a draft page where the overlay does not run (the toggle is Off and the page passes instantPreview={false}, or framedOnly outside the Live Preview), the markers are still removed from the text, every attribute, the title and the meta tags of <head>, also from content rendered later. There are no outlines and no instant preview there.

Handing the field to another admin component

Before the bridge expands collapsibles and focuses a field the editor clicked in the preview, it dispatches a cancelable payload:open-field event on window (OPEN_FIELD_EVENT). This happens only when the clicked field belongs to the document that is open in the admin:

window.addEventListener('payload:open-field', (event) => {
  const { path, collectionSlug, globalSlug, docId, locale } = (event as CustomEvent).detail
  // e.g. path: 'layout.0.items.1.title'
  event.preventDefault() // take over: the bridge does nothing else
})

Admin UI that shows nested fields its own way uses the event to open the field there. One example is @focus-reactive/payload-plugin-stacked-editing, which opens array and blocks rows in stacked panels. If no listener cancels the event, the bridge behaves as before. announceOpenField(detail) and the OpenFieldEventDetail type are exported for components that want to raise the same event.

What gets a marker

  • Fields of type text, textarea and email, at any depth: in groups, tabs, rows, collapsibles, array rows and blocks (declared inline or through blockReferences).
  • The name of a block (blockName), unless the block sets admin.disableBlockName. A click on a rendered block name focuses the name input in the block header.
  • Not: empty values, and values that match excludeValues (by default URLs, slugs like hello-world, #fragments and ISO dates). A range of numbers such as 8-10 and a text that starts with a hash, such as #1 in the ranking, are marked.
  • Not: fields named slug, folder, _status, apiKey or anything in excludeFieldNames.
  • Not: fields the editor cannot change in the admin, that is hidden: true, admin.hidden, admin.readOnly or admin.disabled, and everything inside a group, array or blocks field that has one of them.
  • Not: text fields with hasMany, numbers, selects, dates and other non-text fields.
  • With instantPreview only: every text node of a Lexical rich text field, see Markers in rich text.

A populated document (a relationship or an upload read with depth ≥ 1) is marked as itself: its text carries its own collection, id and paths, wherever it appears. A populated document of a collection listed in skipCollections gets no markers.

If you render a marked value into an attribute, the overlay removes the marker from it: alt, aria-label, an href, a style, an id, a data-* attribute. It also cleans document.title. An image whose alt carries the marker of a field becomes the edit target of that field, usually the alt of the media document, unless the image already names its field with withVisualEditingPath. An element whose whole text is one marked field, such as a heading, gets the data-ve-* attributes of that field while the overlay runs, so it stays the edit target when a script of your site splits its text into words or characters after the overlay found it. The overlay cleans the page in the browser, so a value the template transforms before the browser sees it (a slug, a hash, a number it parses) keeps the invisible characters inside the transform: clean it first with stripMarkers or keep the field away with excludeFieldNames.

Rich text, uploads and relationships

The text of a rich text field belongs to its renderer, and an image has no text node to carry a marker. For these values the plugin leaves a _meta object on the value that says which field of which document holds it. Spread withVisualEditingPath(value) on the element that should become the edit target. For a value that holds a document, such as an upload, it also writes the id of that document as data-ve-value-id, so a replaced image is refused as Changed elsewhere when the field was given other media after the page showed it:

import { withVisualEditingPath } from '@focus-reactive/payload-plugin-visual-editing/client'
import { RichText } from '@payloadcms/richtext-lexical/react'

<div {...withVisualEditingPath(page.content)}>
  <RichText data={page.content} />
</div>

<img src={page.image.url} alt={page.image.alt} {...withVisualEditingPath(page.image)} />

<article {...withVisualEditingPath(page.author)}>
  <h3>{page.author.name}</h3>
</article>

A click on such an element focuses the rich text, upload or relationship field in the document that holds it (image of the page), not the media or author document.

| Field | Where the _meta is | |---|---| | rich text | page.content | | upload or relationship | page.image, the populated document | | hasMany | every populated document: page.gallery[0], page.gallery[1]. Each addresses the field gallery | | several relationTo | page.image (the { relationTo, value } object) and page.image.value |

Uploads and relationships need depth ≥ 1. At depth: 0 the value of a field with one relationTo is an id and has no _meta. withVisualEditingPath returns {} for a value without _meta, so the spread is safe on published pages.

Text inside the populated document, such as page.image.alt or page.author.name, is a text field of that document. If its collection is not skipped it has its own marker, and a click on it opens the media or author document.

Instant preview

Without it the Live Preview shows an edit after Payload has saved it and the frontend has rendered again. With it, text typed in the admin form appears in the preview on the same keystroke. The save and the re-render still happen and stay the source of truth.

Turn it on in the plugin and regenerate the import map:

// payload.config.ts
visualEditingPlugin({ instantPreview: true })

The page half is on by default: VisualEditing.Provider and mountVisualEditing listen for the admin, and the admin sends nothing unless the plugin option is on. Pass instantPreview={false} (instantPreview: false without React) to a page that should not listen; with the toggle on Off the overlay then does not run at all and the page only loses its markers.

Requirements

  • Live Preview is configured for the collection or global: admin.livePreview on it, or its slug in the root admin.livePreview.collections / globals.
  • The frontend refreshes itself after a save, for example with RefreshRouteOnSave from @payloadcms/live-preview-react, see below.
  • The admin posts to the origin of the Live Preview URL. The preview posts to adminOrigin on VisualEditing.Provider, its own origin by default.
  • On a localized site, pass the locale of the page: <VisualEditing.Overlay locale={locale}>. The admin tags its messages with the locale it is editing, and the overlay can only ignore another locale when it knows its own.
  • The admin bundle and the frontend overlay come from the same version of the plugin. An overlay of 1.1.1 or earlier leaves the markers of rich text in the page, and an overlay of 1.2.0 or earlier cannot read the shorter markers this version writes and leaves every marker in the text.
  • Rich text is rendered inside an element that spreads withVisualEditingPath(value), see Rich text, uploads and relationships. Without that wrapper its text is not live.

A refresh after every save, with Payload's own component:

bun add @payloadcms/live-preview-react
// components/RefreshOnSave.tsx
'use client'

import { RefreshRouteOnSave } from '@payloadcms/live-preview-react'
import { useRouter } from 'next/navigation'

export const RefreshOnSave = () => {
  const router = useRouter()
  const adminOrigin = typeof window === 'undefined' ? '' : window.location.origin
  return <RefreshRouteOnSave refresh={() => router.refresh()} serverURL={adminOrigin} />
}
// app/(frontend)/layout.tsx
{isEnabled && <RefreshOnSave />}

RefreshRouteOnSave refreshes only on a message whose origin equals serverURL exactly, so with another value the page never refreshes and nothing reports it. The snippet is for an admin served from the same origin as the page, as in a Next.js app that hosts Payload; the component renders nothing, and its listener starts in the browser, where the origin is known. With the admin on another origin, pass that origin, without a trailing slash.

What updates instantly

  • text, textarea and email fields that have a marker on the page, the block name included.
  • Text typed, deleted or replaced inside existing text of a Lexical rich text field: in paragraphs, headings, list items, quotes, links and formatted text.
  • With LiveRichText: every edit that changes the structure of a Lexical rich text field, such as a new paragraph, a list, a heading, bold on a part of a text, a link, an upload or a new block, and the text typed after it.
  • Only where the page renders the stored value unchanged.
  • In an element whose whole text is one field after a script of your site split that text into words or characters, while the element still shows the value the field had. The overlay writes the new value as plain text into the element, so the split and its animation are gone from the preview until the page reloads.
  • In every toggle position, also Off. The toggle controls frames, badges and click-to-edit only.

What waits for the save

  • Every other field type: numbers, uploads, relationships, selects, checkboxes, dates, code, json, text with hasMany.
  • In rich text that is not wrapped in LiveRichText, an edit that changes the structure: a paragraph, list, link, block or upload added or removed, or formatting applied to a part of a text, which splits it. From that edit on the preview keeps the structure of the last save, with the text it showed when the structure changed, until the autosave has landed and the page has rendered the new structure; then its text is live again. Autosave is debounced, so that happens after a pause in typing. An edit that returns to the saved structure is live again at once.
  • Rich text whose stored tree Lexical normalises on the first edit, such as imported or seeded content with neighbouring texts of the same format, which Lexical merges on the first keystroke. That is an edit of the structure; the field is live after its first save from the editor.
  • In rich text, formatting that does not change the structure. Bold on a whole text, another heading level, list type or link URL shows after the save, or with the next structural edit of a field in LiveRichText; the text keeps updating meanwhile.
  • Text in the fields of a block inside rich text, Slate rich text, and a rich text field whose name contains #.
  • Rows and blocks that are added, removed, duplicated or moved. Text typed into a new row appears with the save that creates the row. A moved row keeps its text; the order changes with the next refresh.
  • A field that was empty in the last render. An empty value has no marker, so text typed into it appears with the next save.
  • Values the page transforms: uppercased in JavaScript, truncated, formatted, parsed into markup. The overlay rewrites a text node only while it shows a value the field recently had.
  • Localized fields, and all rich text, on a page that reads the document with locale: 'all'.

What is sent to the preview

The admin posts field values to the preview window with postMessage. Every script on the preview page can read them. A value is sent only when all of these hold:

  1. The field belongs to the document that is open in the admin form.
  2. The preview page has rendered that field, with a marker, at least once since it loaded. The page tells the admin which fields those are. From then on the admin sends the field's value on every change until the preview window loads another page, also while the field is not on screen.
  3. The field can carry a marker under the rules in What gets a marker, read from the collection or global config. Values that exist only in the form, such as a typed password, are never sent.
  4. The collection has no auth. Fields of auth collections are marked for click-to-edit but never sent.

Rule 3 is the boundary you control. The list in rule 2 comes from the preview page, so a script running there could ask for any field that passes rule 3. Keep a field away from the preview with excludeFieldNames, admin.readOnly, admin.hidden or hidden.

For a rich text field that passes these rules the admin sends the saved and the current text of single text nodes the page announced. It sends the editor state of the field only to a page that renders it in LiveRichText, and only when the structure changes. While the editor holds another structure than the saved one it sends, in place of the current text, the last text those nodes had under the saved structure while this preview page was listening, or else their saved text.

The editor state of a rich text field holds its text, the ids of uploads, relationships and linked documents, and the fields of link and upload nodes. The admin posts it when the structure of the field changes, and only for a field the page announced as rendered in LiveRichText. That announcement also comes from the page, so the boundary is again rule 3 for the rich text field itself. Blocks in the state are posted with their id and type and without the values of their fields. The page hands the state to your Server Action, which answers only to a signed-in user who may read the document. A page that renders rich text in the browser, with renderValue on LiveRichText or renderRichTextValue without React, also renders the posted state itself, with data Payload already gave that page, see Rendering on the page with renderValue and Rendered on the page first.

A page states the locale of its overlay when it reports its fields. The admin sends nothing to a page that states another locale than the one the form is in. A page whose overlay has no locale states none and is answered in every locale.

excludeValues is not applied in the admin. A value that matches it has no marker on the page and is not sent, unless the page rendered the same field with a marker earlier in this page load.

When the Live Preview iframe loads another page, the admin stops sending and waits for that page to report its fields. A page without the overlay is sent nothing. When the admin switches to another locale it stops sending as well, until the preview has loaded a page again; text typed in one locale is never sent to a page that was loaded for another, provided the overlay of that page was given its locale.

Unsaved rich text structure

Typing inside existing text needs nothing but the wrapper. A new paragraph, a list or a bold word changes the structure of the value, and the page cannot build that markup from text alone: it comes from your renderer. LiveRichText asks your app to render the unsaved editor state and shows the result until the saved render has the same structure. The reference setup uses a Server Action of the Next.js App Router.

Three pieces, all in your app. The component that renders rich text:

// components/RichText/Body.tsx
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'

import { withVisualEditingPath } from '@focus-reactive/payload-plugin-visual-editing/client'
import { RichText } from '@payloadcms/richtext-lexical/react'

export const RichTextBody = ({ content }: { content: SerializedEditorState }) => (
  <div {...withVisualEditingPath(content)}>
    <RichText data={content} />
  </div>
)

A Server Action that renders the unsaved state with that same component:

// components/RichText/renderUnsavedRichText.tsx
'use server'

import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'

import { readUnsavedRichText } from '@focus-reactive/payload-plugin-visual-editing'
import config from '@payload-config'
import { draftMode, headers } from 'next/headers'
import { getPayload } from 'payload'

import { RichTextBody } from './Body'

export async function renderUnsavedRichText(request: unknown) {
  const { isEnabled } = await draftMode()
  if (!isEnabled) return null

  const content = await readUnsavedRichText<SerializedEditorState>({
    headers: await headers(),
    payload: await getPayload({ config }),
    request,
  })
  return content && <RichTextBody content={content} />
}

And the component your pages use:

// components/RichText/index.tsx
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'

import { LiveRichText, liveRichTextOf } from '@focus-reactive/payload-plugin-visual-editing/client'

import { RichTextBody } from './Body'
import { renderUnsavedRichText } from './renderUnsavedRichText'

export const RichText = ({ content }: { content: SerializedEditorState }) => {
  const body = <RichTextBody content={content} />
  const liveRichText = liveRichTextOf(content)
  if (!liveRichText) return body

  return (
    <LiveRichText {...liveRichText} action={renderUnsavedRichText}>
      {body}
    </LiveRichText>
  )
}
  • liveRichTextOf(content) returns the identity of the field, the structure of the saved value, its _meta and whether it holds blocks, uploads, relationships or links to documents, about 300 bytes, or null for a value that is not a marked rich text: every published read, a read with locale: 'all', a row without an id. A published page therefore gets no client component and no extra payload, and the value itself is never passed to the client.
  • The action must render through the component the page uses, with the same wrapper element. React then swaps the two renders in place, and the text typed after the structural edit keeps updating through the markers.
  • Props the renderer needs (a variant, a class name) can be bound: action={renderUnsavedRichText.bind(null, { variant })}. They arrive as the first argument of the action.
  • LiveRichText renders no element of its own. Outside draft mode or with instantPreview off it only renders its children.
  • Put it inside VisualEditing.Overlay. The overlay passes its locale on, and LiveRichText ignores the admin while it edits another locale.

LiveRichText makes one call at a time and only the latest state waits. It starts a call 200 ms after the first new structure, so the structures of one edit (Enter, then the first character of the new paragraph) make one call. When a call fails, takes longer than ten seconds or returns null, and when the returned elements throw while rendering, the preview shows the saved render, as it does without LiveRichText, and asks again a few times per structure, for about half a minute. A call that hangs is never joined by a second one.

A Server Action shares a queue with router.refresh(). While a render call is out, the refresh that brings the saved render waits for it. readUnsavedRichText answers null after timeLimitMs (three seconds by default), which bounds that wait per call within one server process. A slow server delays the saved render by up to one call; it never shows a wrong frame.

Another transport. Pass render in place of action to make the call yourself: render(request, signal) returns a promise of React nodes and gets an AbortSignal that LiveRichText aborts when it stops waiting. A route handler can answer a fetch with that signal with readUnsavedRichText({ payload, request }) as JSON; that call stays off the router's queue and can be cancelled, but the page then renders the marked editor state in the browser, so your renderer and everything it renders for uploads, links and blocks must work as Client Components.

readUnsavedRichText is the only safe way to turn the posted state into something to render on the server. Hand it the argument of the action untouched. It guarantees:

  • Nothing from the request is trusted. It accepts a document of the config, a key that names a rich text field the plugin marks, a locale of the project and a Lexical editor state of at most maxStateLength characters of JSON (DEFAULT_MAX_UNSAVED_STATE_LENGTH, one million). The fields of blocks and uploads and the extra fields of links come from the saved document by node id, and related documents are reduced to their ids. The target of a link (doc, linkType, newTab, url) and the document a relationship or upload node refers to come from the posted state, and Payload populates them with the access of the user. Called from your Server Action, readUnsavedRichText therefore resolves a reference the editor has just added; the endpoint does not, see How the page is allowed to read the unsaved value.
  • It reads as the signed-in user. The user comes from the request headers through payload.auth. The argument of an action is checked before anyone is signed in; the body of a Request is read only for a signed-in user, with a size limit. The document is read as a draft, in the locale of the request, with overrideAccess: false, and Payload populates uploads, relationships and links with that user's access. Nothing is written.
  • The answer is the value of the field with the markers of a draft read, or null. null for a malformed argument, no user, a user who may not read the document or field, an auth collection, a value whose structure is not the posted one, a request a newer one for the same field replaced, and an answer that took longer than timeLimitMs. It does not throw: a read that throws, for example in a hook of your project that cannot handle the unsaved state, goes to payload.logger.error and answers null.

Two cases never reach it: Next.js answers 500 itself for an action body over its limit (1 MB by default, serverActions.bodySizeLimit) and for a body it cannot decode.

| readUnsavedRichText argument | Purpose | |---|---| | payload | The Payload instance. | | request | The argument LiveRichText passed to the action, or the Request a route handler received. Untrusted input: hand it over as it is. | | headers | The headers of the request, with the argument of an action. The user is read from them. A Request brings its own. | | depth | The depth your page reads the document with, so populated documents have the same shape: a number, or a function of the validated field ({ collectionSlug, kind, docId?, key }). Payload's default when omitted. | | maxStateLength | Longest accepted editor state, in characters of JSON. | | timeLimitMs | How long reading the body of a Request, signing in and reading may take before the answer is null. DEFAULT_UNSAVED_READ_TIME_LIMIT_MS, 3000. | | readWholeDocument | true reads every field of the document, as 1.2.0 did. By default only the top-level field that holds the rich text is read, see Upgrading from 1.2.0. |

During that read your own hooks and access functions see the unsaved state as if it were stored: collection and field afterRead hooks, anything that caches by document id inside the read. isUnsavedRichTextRead(req), exported from the main entry, tells such code that the read is one of these. The read selects only the top-level field that holds the rich text (layout for a rich text in a block of layout), so a hook that reads other fields of the document sees them missing; pass readWholeDocument: true for such a hook.

What this costs: one Server Action call per structural edit, never one per keystroke. Each call posts the editor state of that field and reads the top-level field that holds it once. The draft mode check stays in your action because it is specific to Next.js; readUnsavedRichText does not depend on Next.

Rendering on the page with renderValue

With a Server Action alone a structural edit shows one round trip after the admin posts it. When your rich text renderer can run as a Client Component, pass it as renderValue and the page shows the structure as it arrives: it builds the value Payload would answer from the posted editor state and data Payload already gave the page, with the same markers and _meta, and renders it with your function. A function cannot cross from a Server Component to a Client Component, so renderValue is set in a client module of your site:

// components/RichText/LiveBody.tsx
'use client'

import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { ReactNode } from 'react'

import {
  LiveRichText,
  type LiveRichTextIdentity,
} from '@focus-reactive/payload-plugin-visual-editing/client'

import { RichTextBody } from './Body'
import { renderUnsavedRichText } from './renderUnsavedRichText'

export const LiveBody = (props: LiveRichTextIdentity & { children: ReactNode }) => (
  <LiveRichText
    {...props}
    action={renderUnsavedRichText}
    renderValue={(value: SerializedEditorState) => <RichTextBody content={value} />}
  />
)
// components/RichText/index.tsx
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'

import { liveRichTextOf } from '@focus-reactive/payload-plugin-visual-editing/client'

import { RichTextBody } from './Body'
import { LiveBody } from './LiveBody'

export const RichText = ({ content }: { content: SerializedEditorState }) => {
  const body = <RichTextBody content={content} />
  const liveRichText = liveRichTextOf(content)
  return liveRichText ? <LiveBody {...liveRichText}>{body}</LiveBody> : body
}

Where the check with the server goes depends on payloadApi of VisualEditing.Provider:

| Setup | On the page | Check with the server | |---|---|---| | action | nothing | 200 ms after the first new structure, as above | | action, renderValue | at once | the action, 350 ms after the last structure; its result replaces the render on the page | | action, renderValue, payloadApi | at once | the unsaved-rich-text endpoint, 350 ms after the last structure, rendered with renderValue |

<VisualEditing.Provider available={isEnabled} payloadApi="https://cms.example.com/api">

A provider that is given adminOrigin finds the API at <adminOrigin>/api on its own.

  • With payloadApi the page asks the endpoint with the preview grant the admin posts, as a page without React does, see How the page is allowed to read the unsaved value. The answer goes through the same renderValue, so React updates the elements in place and nothing changes on screen when Payload agrees. The call is a fetch: it can be cancelled and does not hold router.refresh() back. While the page holds no grant, the action is called.
  • With the action alone its result replaces the render on the page after the pause. It renders on the server, so React mounts its elements anew: the page looks the same, but an iframe in a block loads again. An action that returns null leaves the render on the page.
  • A field with blocks, uploads, relationships or links to documents needs its saved value for the fields of saved blocks and the documents Payload populated. With payloadApi the page asks the endpoint for the saved value of that field once the editor types in it or changes its structure, and adds every answer Payload gives; when the saved value arrives, the structure the editor holds renders on the page. Without payloadApi, such a field waits for the action. A save forgets every saved value; the page asks again when a structure with blocks, uploads, relationships or links to documents needs it. A structure without them never needs one. A newly inserted upload or relationship appears with the answer of the server, a new link to a document links to its id until then, and a new block shows only its id and type.
  • The same renderer on the client and on the server. renderValue must render the same markup for the same value as the component your page and your action render with, best the very same component. Markup that differs swaps once the server answers.
  • renderValue runs in the browser with a value that did not pass through your Payload hooks. When it throws, or the elements it returns throw while rendering, that structure shows the saved render and waits for the server.
  • An identity printed by liveRichTextOf of 1.2.0, without meta and hasReferences, waits for the server.
  • After a save that renders the page again, the children you pass are the saved render. Until they change, for example in a popup preview that does not refresh, LiveRichText takes the render it showed for the structure the editor saved as the saved render.

Markers in rich text

With instantPreview on, a draft read puts a marker of roughly 50 to 60 zero-width characters into every non-empty text node of every Lexical rich text field the editor can change. excludeValues does not apply to them. Reads with locale: 'all' and rich text in a row without an id get none.

The overlay removes these markers from the text inside VisualEditing.Overlay. Code that derives something else from rich text on a draft read (heading ids, slugs, excerpts, reading time, plain text, JSON-LD) receives them. Clean the value first with stripMarkers. It takes a string or any JSON value and returns a copy of the same shape in which no string carries a marker; a value without markers comes back with the same content, so it is safe on published reads too. It copies plain objects and arrays only: a Map, a Set or a class instance is returned as it is.

import { stripMarkers } from '@focus-reactive/payload-plugin-visual-editing'

const minutes = readingTime(stripMarkers(post.content))
const excerpt = stripMarkers(post.excerpt)

vercelStegaClean from @vercel/stega gives the same result for a JSON value without _meta. It serialises the value through JSON, so it turns a Date into a string and drops undefined. Or keep the field out with excludeFieldNames, which also ends click-to-edit for it.

Opting out

A render can transform a value and still output the stored text for some inputs, such as a lowercase transform on a title that is already lowercase. Put data-ve-live="off" on the element or an ancestor to keep instant preview away from it. Click-to-edit keeps working there.

<h1 data-ve-live="off">{title.toLowerCase()}</h1>

Limitations

  • Markup that the page turns into elements shows as typed until the save: if a heading renders *accent* as <em>, the asterisks appear as characters while you type.
  • Payload's Lexical field passes its value to the form when the browser is idle, not on the keystroke itself, so rich text can reach the preview later than a text field. The plugin cannot shorten that.
  • A renderer that joins several text nodes of rich text into one DOM text node, or changes their text, leaves that text to the save.
  • Rich text that is not wrapped in LiveRichText:
    • While a structural edit is unsaved, the preview shows the structure of the last save, with the text its text nodes had when the structure changed. Whatever is typed after that edit appears once the autosave has landed and the page has rendered it. A preview page that loads during that time shows the saved text.
    • When a structural edit is undone before its save has landed (Enter, then Backspace, then more typing), the text typed after the undo is live at first. Then the save of the undone edit lands and the page renders it: the structure and the text of that save, which is older than what the editor holds. The preview shows that until the next autosave lands and is rendered, usually a few seconds. The plugin does not carry text from one structure of a field to another: a saved editor state identifies a text node by its position only, and matching nodes by position or by text could put text in the wrong place.
  • Rich text in LiveRichText:
    • With action, the setup needs the App Router and a Server Action. The Pages Router has none: pass render with a transport of your own, and with renderValue and adminOrigin (or payloadApi) the page renders a structure itself and checks it through the unsaved-rich-text endpoint. A frontend without React uses ./dom, see Pages without React.
    • While a Server Action call is out, router.refresh() waits for it, see Unsaved rich text structure.
    • A Server Action is called with the cookies of the preview page. A preview on another origin than the admin has no Payload session there; the answer of the action is null. Such a page passes renderValue and adminOrigin (or payloadApi): the endpoint is asked with the preview grant, which needs no session, see How the page is allowed to read the unsaved value. Without them the structure appears with the save.
    • Without renderValue, a structural edit is on screen one round trip after the admin sees it. Until then, and after a failed call, the preview shows the saved render. Text typed meanwhile is painted into the new render when it arrives.
    • The fields of a block inside rich text are never posted: the admin has no schema of the blocks of an editor, so it cannot tell which of their fields may leave the form. A block that is already saved is rendered with its saved fields, a new block with none, and an edit of a block's fields shows with the save.
    • The unsaved state is rendered as the editor holds it. Hooks that change a value on save (beforeValidate, beforeChange) have not run yet; their effect shows with the save. Hooks that run on read see the unsaved state, see isUnsavedRichTextRead above.
    • An editor state longer than maxStateLength is not rendered before the save.
    • A field the page renders twice makes two calls per structural edit, one per place.
  • After the admin switches to another locale, instant preview resumes when the preview has loaded a page again. Payload reloads the Live Preview for the new locale; a popup preview window that was opened before the switch is sent nothing.
  • After a client-side navigation inside the preview, fields of pages visited earlier stay on the admin's list until the preview does a full page load.
  • In the popup preview window the admin cannot see a navigation. It keeps sending the listed fields to the popup until a page there reports its fields again or the popup is closed.
  • The popup keeps unsaved text on screen after you leave the document without saving. It shows the saved content again when it reloads.
  • While the preview shows fields of the open document, every change in the form reads the whole form state before the admin paints. On a form with several thousand fields this costs a few milliseconds per keystroke. With Live Preview closed it costs nothing.

Editing on the page

With it the editor types into plain text on the page itself, writes and formats rich text in place and replaces an image from the page. The text, the rich text and the image go into the draft; the published document changes only on publish. It needs instant preview and is off by default.

Turn it on in the plugin, regenerate the import map, and offer it on the page:

// payload.config.ts
visualEditingPlugin({ instantPreview: true, inlineEditing: true })
<VisualEditing.Provider available={isEnabled} inlineEditing adminBasePath="/admin">

Without React pass inlineEditing: true to mountVisualEditing.

Rich text is edited on the page only when the site also hands the page its editor, from a Client Component or from the script that mounts the page:

<VisualEditing.Provider
  available={isEnabled}
  inlineEditing
  richTextEditor={() => import('@focus-reactive/payload-plugin-visual-editing/rich-text')}
>
mountVisualEditing({
  inlineEditing: true,
  richTextEditor: () => import('@focus-reactive/payload-plugin-visual-editing/rich-text'),
})

Without richTextEditor a click on rich text opens the field in the admin, and the page loads nothing of Lexical.

Editing on the page then runs whenever the toggle is on Hover or Always; there is nothing more to turn on. The toggle starts on Hover for an editor who has not picked a mode on the site yet, so the page can be edited at once. On Off the page shows no frames and edits nothing, as without visual editing; an editor who picked Off keeps it.

Using it

  • An edit on the page leaves the form of the admin where it is: it is not scrolled to the field and nothing in it takes the focus, so the Live Preview frame does not move under the pointer. A click that opens the field in the admin still shows it there.
  • A click on plain text puts the caret into it. Enter ends the edit, Escape brings back the text the edit began with, and a click elsewhere ends the edit. Escape saves that text only when a typed one was already sent; a typed text that still waited is dropped, and nothing is saved. In a textarea field Shift+Enter starts a new line in a browser that supports contenteditable="plaintext-only"; elsewhere it ends the edit. A text or email field stays one line on the page as it is saved: Shift+Enter ends the edit as Enter does, and a line break in pasted, dropped or dictated text shows as a space.
  • With richTextEditor set, a click into rich text is taken by the page at once. The page asks for the state of the field (it already does when the pointer moves over the rich text) and puts the caret at the text position that was clicked as soon as the state is there; a click beside the text, or on a block, puts it at the nearest text. While the page waits for the state, the rich text shows a dashed outline in the accent colour (data-ve-edit-starting). When the field cannot be edited on the page, or no answer comes within four seconds, the field opens in the admin instead; in a tab of its own a browser may block that late tab as a pop-up, and the Edit badge opens it. The text is edited in the styles of the site. Enter starts a paragraph, Escape brings back the state the edit began with, a click outside the rich text and its toolbar ends the edit, and Cmd/Ctrl+Z and Cmd/Ctrl+Shift+Z undo and redo inside the edit.
  • While rich text is edited, a toolbar sits above its top left corner, and at the top of the window once that corner is scrolled out of view. It holds the formats the field allows, out of Bold, Italic, Underline, Link, H2, H3, Bullet list and Numbered list. Each button shows whether the selection has the format and turns it on or off. Cmd/Ctrl+B, I and U do the same from the keyboard. Link, or Cmd/Ctrl+K, opens an address field in the toolbar: Enter links the selection, an empty address removes the link, Escape closes the field, and both leave the text selected that was selected when the field opened. An address must start with http:, https:, mailto: or tel: or be relative; anything else is refused, and the toolbar says so in words under the field. Without a selected range Link and Cmd/Ctrl+K do nothing. The toolbar is never wider than the window less 8 px on each side: its buttons wrap, the address field takes a row of its own, and it stays inside the window.
  • A paragraph that begins with # to ###### , - , * , + , 1. or > becomes a heading, a bullet list, a numbered list or a quote as soon as the space is typed, when the field allows that block.
  • An icon the site renders as the first element of a list item (an <svg> or an <img>) is drawn in the edited list as well, from the first item of each kind of list.
  • Spaces are shown as the site shows them. Where the first element the site rendered collapses white space (white-space: normal or nowrap), runs of spaces, spaces at the start and end of a line and spaces around a line break are dropped from the text when the edit begins, so the lines stay where they were; text formatted as code keeps its spaces. The first change you make saves the text that way. Where the site keeps white space (pre, pre-wrap, pre-line, break-spaces), nothing is dropped. A line break that ends a paragraph or a list item adds no empty line, as on the site, until the caret is put after it. The twin also takes the word-break, overflow-wrap and line-break of that element, which the editor and the browser would otherwise replace.
  • The text keeps the direction of the site. The edited elements carry no dir of their own, so direction, unicode-bidi and text-align come from the styles of the site, and a dir the site wrote on the element that holds the rich text is kept. The direction the state stores is saved as it is, as the admin saves it.
  • A paste keeps what the field allows. A heading of a size the field does not have, a quote or a list in a field without them becomes paragraphs, a format the field does not have is dropped, and a pasted link arrives as its text.
  • A block, an inline block, an upload, a relationship, a horizontal rule, a table and every other node the page cannot edit is fixed: its content is never changed on the page. At the top level it shows as a copy of what the site rendered for it, which takes no click and no focus; where the page cannot tell which element that is, and inside a paragraph, it shows as a dashed placeholder with the name of its type.
  • A fixed node can be deleted, in two steps. A click on it, or Backspace or Delete with the caret next to it, selects it, with an outline in the accent colour; Backspace or Delete then removes it. Cmd/Ctrl+Z and Escape bring it back. Nothing else removes it: a selection that spans it and is deleted, cut or typed over loses its text and keeps the node, and it cannot be cut, copied in, dragged or moved past another one. Backspace at the start of the paragraph after it never touches the text before it. Add and reorder blocks in the admin.
  • A line of text that is all its block holds, such as a <span> in a heading, is framed and edited as that block: a click anywhere in the block puts the caret at the nearest text, and the frame is one rectangle while the text wraps over several lines.
  • In a button or a link that holds more than the text, such as an accordion header with an icon, only a click on the text edits it. A click beside the text is left to the page, so the accordion still opens.
  • The lines of the text stay as the page broke them until the first key press, paste, cut, drop or typed text. A long word breaks where the page broke it for the whole edit. From the first change on the browser keeps every space and line break of the text, so a text with two spaces in a row, or with a line break the page does not show, can wrap at another place while it is edited.
  • The Edit badge still opens the field in the admin form.
  • A pasted text arrives without its formatting.
  • An image that names a single upload field shows a Replace image button while the pointer is over it, in its top left corner, or in the top left corner of the part of it in the window when the image is scrolled past its top or its left. The button opens a list of the media of that field's collection, where a new file can be uploaded too. The picked image shows on the page at once; when its save fails, the page shows the image it had again, and a Retry that saves shows the picked one. A click on the image itself still opens the field in the admin form, and so does the button when the field turns out to take no media from the page.
  • A status in the bottom right corner says Unsaved changes, Saving…, Saved or, with a Retry button, why a save was refused: Locked by another editor, This content has no drafts, This field cannot be edited here, Sign in to the admin to edit, or Not saved for anything else. The form of the admin gives the same reasons: This field cannot be edited here for an edit or a pick it cannot write, Not saved for a pick while its drawer is open or of an image it could not read. A refusal stays on screen while other fields are edited and saved, until a Retry saves the edit or a newer edit of the same field replaces it. Changed elsewhere, reload the page comes with a Reload button instead: the field was saved somewhere else after the page showed it, see Limits. Nothing more of that field is sent until the page is reloaded, and a newer edit of it does not clear the status.

Where an edit is saved

| The page is | The edit goes to | Saved by | |---|---|---| | in Live Preview, and the form of the document is open | the admin form, as if the editor had typed there or picked the image there | Payload: autosave, or the editor's own save | | in a tab of its own, in draft mode | POST <payloadApi>/visual-editing/field-edit with the editor's session | the endpoint, into the latest draft | | in a window the admin opened, such as the tab of Payload's Preview button | the endpoint, as in a tab of its own, until the admin sends that window the values of a form; the pop-up window of Live Preview gets them and writes into the form. An edit keeps the route it began with: one begun before the values arrived is saved through the endpoint to its end, and one begun in the form is saved through the endpoint once the window of the admin is closed | as in the row that applies |

In the pop-up window of Live Preview Replace image opens the list on the page, not the drawer of the admin behind it, and the admin writes the picked document into the form after it read it with the editor's access.

The endpoint takes { collectionSlug, kind, docId, key, locale, value } for text and for an image, and { …, state } with a serialised Lexical editor state for rich text. Text and rich text also carry base, the text or the state the edit began from, and an image the id of the media the page showed when its element carries data-ve-value-id. Text and rich text may carry sentBefore too, the value of an earlier save of the same edit that is still on the way when the tab is hidden or closed and may land first; the endpoint saves when the draft holds either. The endpoint saves the edits of one document one after the other, so two saves of rows of one list or blocks of one layout that arrive together keep both. It reads the latest draft with the user's access, changes the one field and saves a draft with overrideAccess: false. It answers { saved: true, autosave }, with autosave whether the drafts of the document autosave, and with value, what the field holds after the save, when the edit carried a base; or { saved: false, reason } with a status: 401 and signed-out without a user, 409 and no-drafts for a collection or global without versions.drafts, 412 and changed when the draft no longer holds the base of the edit, 422 and not-editable for a field the editor cannot reach (also 403 and 404), 423 and locked for a document another editor holds a lock on, 400 and unreadable for a body it cannot read (a state sent as a JSON string, or a body sent with another Content-Type than application/json, for example), and failed for everything else, also a read or save that throws. It never publishes. For an upload field the value is the id of a media document; the endpoint takes it only when the user can read that document in the collection of the field.

Rich text needs the stored state of the field before it can be edited, and where it comes from depends on the page as well:

| The page is | The state comes from | With | |---|---|---| | in Live Preview, and the form of the document is open | the form: the page posts ve:rich-text-state-request, the admin answers ve:rich-text-state | the fields of blocks left out, as in what is sent to the preview | | in a tab of its own, in draft mode | POST <payloadApi>/visual-editing/rich-text-value with the editor's session | the value of the draft, read with the user's access at depth 0 |

rich-text-value takes the document, the field and the locale, runs the checks of field-edit and answers { value, formats }, or { value: null, formats: null, reason } with the status and the reason field-edit would answer. formats are the formats the editor of the field allows (textFormats as Lexical's bit mask, headings, lists, hasLinks, hasQuotes), read from the field's Lexical editor config, plus every format the stored value already holds. The form answers the same formats: the admin asks rich-text-value for them when the page asks for the state, and adds every format the form holds. When the endpoint cannot answer, for a field of a row that is not saved yet for example, the form offers only the formats its state holds. A request the form cannot answer, also for a field whose access.update refuses the user, gets ve:rich-text-state-refused with reason: "not-editable".

Neither path trusts what the page sends back; the endpoint and the form apply the same rules, and an edit that breaks one is refused whole (422, or ve:field-edit-refused with reason: "not-editable"):

  • The state is valid JSON of at most 1,000,000 characters, holds a root and nothing beside it, and no key named __proto__, constructor or prototype.
  • The nodes the page cannot edit are fixed, and may only be left out. Their sequence in the posted state must be a part of their sequence in what the user was shown, in the same order: each posted node must equal a shown one that comes after the one matched before it, with the fields of blocks left out on both sides, and sit in a parent of the same type. Nodes are compared as the JSON they serialise to, so a key the admin holds with the value undefined counts as missing. The stored node of the matched one is then written, when its type, id and block type match: so the fields of a block, of an upload or of a relationship never come from the page, and no such node can be added, doubled, swapped, moved into another kind of parent or given another id, collection or document. A node that is not posted is removed.
  • A removed node comes back only inside the edit that removed it. In a tab of its own what is typed is saved after each pause, but from the moment a fixed node is removed nothing more is saved until the edit ends, so an undo or Escape still has the node to bring back. In Live Preview the admin keeps the state it answered when the edit began until the page posts ve:rich-text-edit-ended (on a commit and on Escape) or the document or the locale of the form changes; a posted state may hold any part of the fixed nodes of that state, and gets the node the form holds now, or else the one it held when the edit began, with its fields. After that a node the form no longer holds is refused.
  • Every other node is one the page can edit: a paragraph, heading, quote, list, list item, link, line break, text or tab, in a place Lexical allows it, with exactly the keys Lexical writes for it and values of their type and range. A text style and a node state ($) are taken only when the stored value already holds them.
  • Only formats of the field: a heading size, list type, quote, link or text format outside formats is refused.
  • Links: url is a string and, on a custom link, not empty. An address outside the kinds above is taken only on the link that already holds exactly that address in the stored value, by its id, and once. Fields of a link other than linkType, url, newTab and doc come from the stored link of that id.

The admin writes the state into the form as its value and its initial value, so Payload's editor shows it; the endpoint writes it only into a field the plugin lists as rich text, and tells a save Payload dropped from one that landed by comparing what the field stores, whatever order the database keeps its keys in.

After an edit in a tab of its own nothing renders the page again by itself. The page keeps what the editor typed on screen, as a read-only copy in place of the rich text the site rendered, until the site renders that rich text again. A click on that copy edits it again, or, on Off, does what a click on the rich text does. Pass onEdited to render it: it is called after every save of an edit made on the page in a tab of its own, of text, rich text or an image.

'use client'
const router = useRouter()
return (
  <VisualEditing.Provider
    available
    inlineEditing
    onEdited={() => router.refresh()}
    richTextEditor={() => import('@focus-reactive/payload-plugin-visual-editing/rich-text')}
  >
    {children}
  </VisualEditing.Provider>
)

In Live Preview onEdited is not called: the admin saves, and the page follows it as it does for an edit made in the form. There a new paragraph, list or format shows on the page before the save only for rich text rendered through LiveRichText or renderRichTextValue; other rich text shows the typed text and gets its new structure with the render after the save.

Where the image is picked depends on the page too:

| The page is | The media is picked in | Listed by | |---|---|---| | in Live Preview, and the form of the document is open | Payload's own list drawer of the collection, opened in the admin | Payload | | in a tab of its own, in draft mode | a picker the plugin draws on the page: thumbnails, a search by file name, Upload new | POST <payloadApi>/visual-editing/media-options with the editor's session |

In Live Prev