focusreactive

payload plugin visual editing

by focusreactive
payload-plugins
Admin customization
v3
^3.90.0
MIT

Overview

Summary generated from the README

Writes invisible stega markers into text values on draft reads, and a frontend overlay frames marked elements with an Edit badge. A click focuses the field in the Payload admin through a postMessage bridge. It offers optional instant preview and inline editing. It requires Payload 3.90 or later, the guard plugin and a config wrapped in withAccessPolicy.

Features

  • Invisible markers added to text values on draft reads and removed from every write
  • React overlay and toggle with Off, Hover and Always modes
  • Plain DOM entry for frontends without React
  • Optional instant preview of unsaved admin form text in Live Preview
  • Optional inline editing of text, rich text and images that saves drafts
  • Preview and editInline capabilities granted through an access policy

Use cases

  • Let editors click a heading on a Next.js page to jump to its field in the admin
  • Preview unsaved changes in Live Preview as editors type
  • Enable on-page editing of text and images for selected editor roles

From the author

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

Installation

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

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

849

Weekly Downloads

v2.0.2

npm Version

2.6 MB

Unpacked Size

2

Dependencies

Repository stars

37+22 since Sep 6

Show data
Repository stars by day (UTC)
DateStars
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615
Sep 6, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

826+572 since Oct 8

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026826
Dec 4, 2026809
Dec 3, 20261,063
Dec 2, 2026866
Dec 1, 2026828
Nov 30, 2026827
Nov 29, 2026663
Nov 28, 2026640
Nov 27, 2026912
Nov 26, 2026874
Nov 25, 2026880
Nov 24, 2026892
Nov 23, 2026898
Nov 22, 2026902
Nov 21, 20261,154
Nov 20, 2026843
Nov 19, 2026577
Nov 18, 2026672
Nov 17, 2026662
Nov 16, 2026645
Nov 15, 2026625
Nov 14, 2026421
Nov 13, 2026409
Nov 12, 2026382
Nov 11, 2026263
Nov 10, 2026263
Nov 9, 2026261
Nov 8, 2026254
Nov 7, 2026162
Nov 6, 2026130
Nov 5, 2026171
Nov 4, 2026160
Nov 3, 2026161
Nov 2, 2026164
Nov 1, 2026190
Oct 31, 2026179
Oct 30, 2026179
Oct 29, 2026104
Oct 28, 202693
Oct 27, 202695
Oct 26, 202698
Oct 25, 202660
Oct 24, 202650
Oct 23, 202636
Oct 22, 202689
Oct 21, 202690
Oct 20, 202685
Oct 19, 202678
Oct 18, 202672
Oct 17, 202671
Oct 16, 2026166
Oct 15, 2026135
Oct 14, 2026388
Oct 13, 2026385
Oct 12, 2026383
Oct 11, 2026380
Oct 10, 2026371
Oct 9, 2026276
Oct 8, 2026254

Each point is npm's rolling 7-day download count.

Health Score

73/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1177993877-payload-plugin-visual-editing.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-visual-editing)
HTML
<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-visual-editing"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-visual-editing.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

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.

The plugin is built on @focus-reactive/payload-plugin-guard. Who may preview drafts and who may edit on the page are two capabilities the project grants in its access policy, see Access.

Requirements: Payload ^3.90.0, @focus-reactive/payload-plugin-guard, and a config wrapped in withAccessPolicy.

AI Integration Prompt

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

I want to add click-to-edit to my Payload CMS v3 project using
@focus-reactive/payload-plugin-visual-editing. Follow these steps in order, and stop to ask me where a step says so.

## Rules you must follow

- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
  no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles get each capability.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
  collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
  `overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere. Every draft read of the site passes `overrideAccess: false`
  and the user it reads for.
- Never enable draft mode, and never read a draft, for a request that is not from a signed-in user of
  the admin collection or does not carry a secret only the CMS knows.
- A secret goes only into the server's environment, never into a `NEXT_PUBLIC_` variable.

## How it works

Draft reads that ask for it 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.
The plugin declares two capabilities that the project grants in its access policy, none with a default:
- `preview`: get a preview grant, so the Live Preview page can read unsaved rich text of a document.
- `editInline`: edit text, rich text and images on the page, which saves drafts.
Every read and save also needs the user's own read or update access to the document and the field.
The plugin owns no collections.
First find out how my frontend renders: React / Next.js (step 6a) or no React, such as a static site
generator, server templates, Vue or Svelte (step 6b).

## Step 1: install

pnpm add @focus-reactive/payload-plugin-visual-editing @focus-reactive/payload-plugin-guard

Check that `payload` and `@payloadcms/ui` are 3.90 or later; if they are not, upgrade them first.
A React frontend needs react 18.2+, a frontend without React needs nothing more.

## Step 2: ask me about roles

Look at the auth collection named in `admin.user` and the roles it has.
Ask me, one question per capability: "Which roles may preview unsaved drafts?" and "Which roles may
edit content directly on the page?". Wait for my answers. Write each answer as a gate in step 3.

## Step 3: the access policy file

Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add this entry for the plugin:

plugins: {
  "visual-editing": {
    preview: <gate from my first answer>,
    editInline: <gate from my second answer>,
  },
},

## Step 4: register the plugin and wrap the config

// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { visualEditingPlugin } from '@focus-reactive/payload-plugin-visual-editing'
import { accessPolicy } from './access.policy'

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...the existing config
    plugins: [
      visualEditingPlugin({
        access: accessPolicy.plugins['visual-editing'],
        // optionally: instantPreview: true, inlineEditing: true
      }),
    ],
  })
)

Editable collections and globals need versions: { drafts: true } and admin.livePreview.url pointing
at the preview route of the page. Run `payload generate:importmap`, then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.

## Step 5: the preview route

On Next.js add /next/preview?path=/<slug> and /next/exit-preview as in the plugin README, setup step 3.
The preview route must check, before it calls draftMode().enable(), that the request comes from a signed-in
user of the admin collection (payload.auth({ headers: req.headers })), or, when the site runs on
another origin than Payload, that it carries a secret compared with timingSafeEqual.
It accepts only paths that start with one "/".

## Step 6a: React / Next.js frontend

- Read drafts only for the signed-in user, with their access:
    const { isEnabled } = await draftMode()
    const { user } = isEnabled ? await payload.auth({ headers: await headers() }) : { user: null }
    const draft = Boolean(user)
    payload.find({ collection: 'pages', draft, overrideAccess: false, user,
                   context: { visualEditing: draft }, depth: 1, 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)} />

## Step 6b: frontend without React

- Read drafts over REST or GraphQL with draft=true, the x-visual-editing header and the session of a
  Payload 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.

## Step 7: verify, and show me the output

With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the setup is wrong: stop and tell me.

1. Draft mode without a session, expect 401 and no `__prerender_bypass` cookie:
   curl -i 'http://localhost:3000/next/preview?path=/'
2. With instantPreview on, an anonymous preview grant, expect 401:
   curl -i -X POST http://localhost:3000/api/visual-editing/preview-grant -H 'Content-Type: application/json' -d '{}'
3. The same with the session cookie of a user whose role may not preview, expect 403.
4. With inlineEditing on, an edit with the session cookie of a user whose role may not edit on the page, expect 403:
   curl -i -X POST http://localhost:3000/api/visual-editing/field-edit -H 'Content-Type: application/json' -H 'Cookie: <cookie>' -d '{"collectionSlug":"pages","kind":"collection","docId":"1","key":"title","value":"x"}'
5. An edit sent as text/plain with an admin's cookie, expect 415:
   curl -i -X POST http://localhost:3000/api/visual-editing/field-edit -H 'Content-Type: text/plain' -H 'Cookie: <admin cookie>' -d '{}'

Then 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.

Installation

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

Peer dependencies, all optional: payload ^3.90.0, @payloadcms/ui ^3.90.0, 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, and @focus-reactive/payload-plugin-guard with a config wrapped in withAccessPolicy.
  • 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. 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 that pass context: { visualEditing: true }, 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 instant preview and LiveRichText, and is the working reference.

1. Register the plugin

Grant the two capabilities in your access policy, see Access:

// src/access.policy.ts
export const accessPolicy = defineAccessPolicy({
  collections: {
    // ...your collections
  },
  globals: {
    // ...your globals
  },
  plugins: {
    "visual-editing": {
      preview: isEditor,
      editInline: isEditor,
    },
  },
}) satisfies AccessPolicy<Config>;

isEditor stands for a gate of your own that names a role, such as gate(({ req }) => req.user?.role === "editor"). Never pass a gate that admits every signed-in user.

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

import { accessPolicy } from './access.policy'

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...
    plugins: [visualEditingPlugin({ access: accessPolicy.plugins['visual-editing'] })],
  })
)

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

Draft mode shows unpublished content, so the route that turns it on must know who asks. This one turns it on only for a signed-in user of the admin collection, whose session cookie reaches it because the site and Payload share an origin:

// app/(frontend)/next/preview/route.ts
import config from '@payload-config'
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'

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 })
  }
  const payload = await getPayload({ config })
  const { user } = await payload.auth({ headers: req.headers })
  if (user?.collection !== payload.config.admin.user) {
    return new Response('Sign in to the admin to preview drafts', { status: 401 })
  }
  ;(await draftMode()).enable()
  redirect(path)
}

When the site runs on another origin than Payload, the cookie of the admin does not reach it. Put a secret into the Live Preview URL instead, in the server-side url function of admin.livePreview, and compare it in the route with timingSafeEqual of node:crypto before you call enable(). Keep the secret in the server's environment only, never in a NEXT_PUBLIC_ variable, and read drafts on that site as a user that may read drafts and nothing else.

// 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 config from '@payload-config'
import { draftMode, headers } from 'next/headers'
import { getPayload } from 'payload'

export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const { isEnabled } = await draftMode()
  const payload = await getPayload({ config })
  const { user } = isEnabled ? await payload.auth({ headers: await headers() }) : { user: null }
  const draft = Boolean(user)

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

The Local API skips access control unless it is told otherwise, so pass overrideAccess: false and the user: a draft is then read only for a user who may read it, and a draft mode cookie without a session gets the published content. A global is read the same way, payload.findGlobal({ slug: 'header', draft, overrideAccess: false, user, context: { visualEditing: draft } }), and is marked at every depth. context: { visualEditing: draft } asks for the markers, see Enrichment modes.

A global or another document that the site reads on its own and renders into the page, such as a header or a list of partners, gets markers only when the site reads it in the same preview as a draft read that asks for markers: with draft (and context: { visualEditing: draft } under 'explicit') in the Local API, or with the x-visual-editing header over REST or GraphQL. Read in another way, for example published, cached for every visitor or by a layout that does not know the preview is on, it shows no frames and cannot be edited from the page.

The plugin marks only draft reads, also of a collection or global without versions.drafts (in the Local API, context: { visualEditing: true } marks any read). Read such a document with draft: true as well, payload.findGlobal({ slug: 'footer', draft: true }) in the Local API or ?draft=true over REST, and Payload answers it as it is stored, since it keeps no drafts. Its targets are framed, and a click or Edit opens the field in the admin, as for a document the editor may only read.

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. It stays in view all the time, also while the editor hovers editable text. In a window too narrow for it, such as a very narrow preview, it moves in from the right edge and wraps its modes onto more lines.
  • 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 and its text, also when its text wraps or its letters are taller than its line height, 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. The frame and the badge stay while the pointer moves from the frame onto the badge, across the gap between them or over another target on the way, also along a path that bows a little off the straight line, and while it rests on the badge or its Replace image button; another target on the way takes them only once the pointer rests on it for a quarter of a second; the pointer over the toggle, the status or the toolbar of rich text changes no frame, and a click there opens no field. A click with a modifier key and a text selection keep the page's own behaviour; a double click does nothing. Text or an image beneath an empty layer of the page, such as a decorative layer over an image, or inside a container with pointer-events: none, is found where it is drawn: the frame, the badge and a click work as over the text or the image itself, but not over a layer that holds text, an icon or other media and is stacked above the text or the image. A layer stacked below a target, such as the background image of a section under text the page raises with position and z-index, never hides it. Over a control of the page, such as a link, a button, a form control, a video or an element with role="button", role="link" or a tabindex, the frame and the badge of what is drawn beneath still show where the control draws none of its own text or media, and over none of a control that paints itself, or its ::before or ::after, with a background-image, a mask-image, a background colour that is not fully transparent, a visible border or a box-shadow, or that shows text in ::before or ::after, such as the icon font of a carousel arrow, so a link laid over a whole card still offers Replace image for the card's image, while the text or logo of a link in a header shows nothing beneath it. A click goes where the frame is: where the control draws nothing of its own, the click opens or edits what is drawn beneath and the page does not follow the link; on its own text, icon or media the click goes to the control. A click the keyboard makes, such as Enter on a focused link, always goes to the page. Text the page renders for screen readers only, hidden with clip, clip-path: inset(50%), a box of one pixel, opacity: 0, visibility: hidden or a font size of 0, gets no frame, so a link over a whole card that names the card only in such text still offers the image beneath it, and a click there opens the image. This is checked while the pointer is over the text, not once when the page loads, so text the page shows later, such as text that fades in on scroll or the panel of a tab or an accordion, can be edited as soon as it is shown. Where targets are drawn over each other, the one painted on top is taken; a target the browser does not hit, such as one with pointer-events: none, is taken over one it hits when its position and z-index stack it higher, and left below it when they are stacked alike; of two targets the browser does not hit, the later one in the page is taken. The frame and the hit area hold only the text an element shows: text cut off by overflow, an ellipsis or a line clamp is left out. Where a text is drawn over another target, only its letters and 4 pixels around them take the pointer from the target beneath: over the empty part of a wide card title laid over an image, the frame, the badge and a click are the image's; where nothing is beneath, the whole block of the text is the text's. 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 that lies under it is hidden. The badge always stays in sight: it sits on the top right corner of the frame like a tab, and when a cover pinned to the top of the window or the top of the window itself takes that room (a heading right under a sticky header, a tall image scrolled half out of view), it hangs inside the top of the visible part of the frame, or below a frame too short for that:

<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. A layer that is position: fixed or sticky and draws over a field (a text, an icon, media or a background colour that is not fully transparent), such as a full-screen mobile menu, hides the frame of that field without the mark; a pinned layer that draws nothing there hides nothing, and the fields the layer holds keep their frames. This is judged at the middle and near both ends of the frame, so a layer that covers only a corner needs the mark.

Inside the admin, visual editing runs only in the Live Preview iframe. A page shown in any other iframe of the admin, such as a card that previews the document in a custom field, shows no toggle, no outlines, no instant preview and no editing on the page. The data-visual-editing attribute of the iframe decides instead, when it is there: "on" turns visual editing on in another iframe, "off" turns it off in the Live Preview:

<iframe src={previewUrl} data-visual-editing="on" />

A page of the admin's origin reads its iframe before it shows anything. A page of another origin asks the admin when it loads and turns off when the answer comes.

On a draft page where the overlay does not run (the toggle is Off and the page passes instantPreview={false}, framedOnly outside the Live Preview, or an iframe of the admin other than 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.

Following the form

The link also goes the other way. When the editor focuses a field in the admin form, the Live Preview (the iframe or the window it opens) scrolls smoothly to that field and shows its frame for a moment, in the colour the field gets on hover (violet, amber or teal), then fades it. The field is found by its key with the ids of its rows, not their indexes: blocks.<rowId>.title, blocks.<rowId>.cards.<cardId>.description, hero.heading.eyebrow. A field inside a rich text editor, an upload, a relationship or a select counts as its field. When several elements carry the field, the first one that is shown is taken; when it is hidden at the moment (in a closed accordion or tab), the page falls back to the elements of its row, and then to the row that holds that. The frame is drawn once the scroll has come to rest, however long the page takes to get there, and it moves with the field if the page shifts while it shows. A field in a drawer that edits the open document, such as a row opened in a drawer of its own, is followed like a field of the form; a field in the drawer of another document, such as one that creates a related document, or in a drawer with a form of its own, such as the link drawer of rich text, is not followed, and the preview stays where it is.

A click on the header of a row of a blocks or array field, with no field focused, scrolls to the row and frames each of its elements with its normal frame. The page scrolls only when the target is out of view, and shows the frame also when it is in view already. It makes room for a data-ve-cover header, and for a position: fixed or sticky bar pinned to the top or the bottom edge that spans most of the width and is lower than 40% of the window, found without a mark. A target is framed only where a visitor sees it: not when it is display: none, visibility: hidden, transparent, clipped away by an overflow ancestor or covered by a bar or another element of the page; the frame is cut where a bar lies over it, and a hidden field falls back to its row, and nothing visible to no frame, though the page still scrolls. With prefers-reduced-motion the scroll is instant and the frame is shown for a moment without a fade. The page scrolls in every mode, as navigation; the frame shows in Hover and Always, not in Off. The only focus that does not scroll the page is the one the admin itself causes when it opens the field a click on the page asked for; a page being edited inline is left alone.

Turn it off with syncScroll: false on the plugin (default true). The admin then sends nothing, so the page has nothing to follow:

visualEditingPlugin({ instantPreview: true, syncScroll: false })

The admin sends { type: 've:focus-block', collectionSlug, kind, docId?, locale?, key, scope: 'field' | 'row' } to the preview window, after a pause of 150 ms. It works on the page with VisualEditing.Provider and with mountVisualEditing. Limits: the page scrolls through window, not through a scrolling container of its own; an element of the page that carries no data-ve-key (a field outside a row the page marks without a key) is not followed.

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 URL has no white space, so an eyebrow such as New: Insights 2.0 is marked). 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. One exception: the description of the media document of an upload field that holds one document of one collection, alt by default (imageDescriptionField names another field), carries the marker of that upload field instead, with the id of the media, so an image rendered with alt alone is found as the image of the field. A click on such an image, or on a caption that a template renders from the same alt, opens that upload field of the page, not the alt of the media document; edit the description in the media document itself. An empty or missing description gets no marker, since a marker would make it a non-empty string and change checks such as alt || filename or {alt && <figcaption>} in drafts: an image with an empty description is found only when the page marks it with withVisualEditingPath or the data-ve-* attributes. A description left out by excludeFieldNames or matched by excludeValues stays as the media document has it.

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 upload field that shows it, unless the image already names its field with withVisualEditingPath or sits in an element marked with it that holds no other image. 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.

FieldWhere the _meta is
rich textpage.content
upload or relationshippage.image, the populated document
hasManyevery populated document: page.gallery[0], page.gallery[1]. Each addresses the field gallery
several relationTopage.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, and must be a user of the admin collection, signed in with a session (not an API key), whom the preview capability admits; for anyone else it answers null. 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 of another auth collection or without the preview capability, 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 argumentPurpose
payloadThe Payload instance.
requestThe argument LiveRichText passed to the action, or the Request a route handler received. Untrusted input: hand it over as it is.
headersThe headers of the request, with the argument of an action. The user is read from them. A Request brings its own.
depthThe 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.
maxStateLengthLongest accepted editor state, in characters of JSON.
timeLimitMsHow 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.
readWholeDocumenttrue 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:

SetupOn the pageCheck with the server
actionnothing200 ms after the first new structure, as above
action, renderValueat oncethe action, 350 ms after the last structure; its result replaces the render on the page
action, renderValue, payloadApiat oncethe 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 inpu

README truncated — read the full version on GitHub

Similar plugins