@focus-reactive/payload-plugin-visual-editing 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +265 -31
- package/dist/admin/InstantPreviewBroadcaster.js +44 -3
- package/dist/admin/InstantPreviewBroadcaster.js.map +1 -1
- package/dist/admin/PreviewPageBridge.d.ts +1 -0
- package/dist/admin/PreviewPageBridge.js +50 -0
- package/dist/admin/PreviewPageBridge.js.map +1 -0
- package/dist/admin/VisualEditingBridgeProvider.js +60 -35
- package/dist/admin/VisualEditingBridgeProvider.js.map +1 -1
- package/dist/admin/expandAndFocus.d.ts +1 -0
- package/dist/admin/expandAndFocus.js +122 -99
- package/dist/admin/expandAndFocus.js.map +1 -1
- package/dist/admin/index.d.ts +1 -0
- package/dist/admin/index.js +1 -0
- package/dist/admin/index.js.map +1 -1
- package/dist/admin/instantPreview/previewGrants.d.ts +14 -0
- package/dist/admin/instantPreview/previewGrants.js +62 -0
- package/dist/admin/instantPreview/previewGrants.js.map +1 -0
- package/dist/admin/instantPreview/usePreviewPage.d.ts +2 -1
- package/dist/admin/instantPreview/usePreviewPage.js +12 -3
- package/dist/admin/instantPreview/usePreviewPage.js.map +1 -1
- package/dist/admin/openField/openForms.d.ts +7 -0
- package/dist/admin/openField/openForms.js +40 -0
- package/dist/admin/openField/openForms.js.map +1 -1
- package/dist/admin/previewPages.d.ts +7 -0
- package/dist/admin/previewPages.js +13 -0
- package/dist/admin/previewPages.js.map +1 -0
- package/dist/client/createOverlay.js +3 -0
- package/dist/client/createOverlay.js.map +1 -1
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +5 -5
- package/dist/client/index.js.map +1 -1
- package/dist/client/instantPreview/instantPreview.js +1 -1
- package/dist/client/instantPreview/instantPreview.js.map +1 -1
- package/dist/client/instantPreview/liveFields.d.ts +2 -1
- package/dist/client/instantPreview/liveFields.js +32 -5
- package/dist/client/instantPreview/liveFields.js.map +1 -1
- package/dist/client/instantPreview/liveRichTextOf.d.ts +3 -0
- package/dist/client/instantPreview/liveRichTextOf.js +3 -0
- package/dist/client/instantPreview/liveRichTextOf.js.map +1 -1
- package/dist/client/instantPreview/unsavedRender/baseValues.d.ts +12 -0
- package/dist/client/instantPreview/unsavedRender/baseValues.js +130 -0
- package/dist/client/instantPreview/unsavedRender/baseValues.js.map +1 -0
- package/dist/client/instantPreview/unsavedRender/liveRichText.d.ts +29 -0
- package/dist/client/instantPreview/unsavedRender/liveRichText.js +117 -0
- package/dist/client/instantPreview/unsavedRender/liveRichText.js.map +1 -0
- package/dist/client/instantPreview/unsavedRender/optimisticValue.d.ts +6 -0
- package/dist/client/instantPreview/unsavedRender/optimisticValue.js +20 -0
- package/dist/client/instantPreview/unsavedRender/optimisticValue.js.map +1 -0
- package/dist/client/instantPreview/unsavedRender/renderSources.d.ts +26 -0
- package/dist/client/instantPreview/unsavedRender/renderSources.js +77 -0
- package/dist/client/instantPreview/unsavedRender/renderSources.js.map +1 -0
- package/dist/client/instantPreview/unsavedRender/unsavedRender.d.ts +6 -1
- package/dist/client/instantPreview/unsavedRender/unsavedRender.js +116 -17
- package/dist/client/instantPreview/unsavedRender/unsavedRender.js.map +1 -1
- package/dist/client/instantPreview/unsavedRender/valueSource.d.ts +17 -0
- package/dist/client/instantPreview/unsavedRender/valueSource.js +38 -0
- package/dist/client/instantPreview/unsavedRender/valueSource.js.map +1 -0
- package/dist/client/overlay/constants.d.ts +1 -2
- package/dist/client/overlay/constants.js +1 -7
- package/dist/client/overlay/constants.js.map +1 -1
- package/dist/client/overlay/fieldTracker.d.ts +2 -0
- package/dist/client/overlay/fieldTracker.js +140 -42
- package/dist/client/overlay/fieldTracker.js.map +1 -1
- package/dist/client/overlay/hoverController.js +3 -3
- package/dist/client/overlay/hoverController.js.map +1 -1
- package/dist/client/overlay/markerCleaner.d.ts +5 -0
- package/dist/client/overlay/markerCleaner.js +94 -0
- package/dist/client/overlay/markerCleaner.js.map +1 -0
- package/dist/client/overlay/markerExtractor.js +1 -1
- package/dist/client/overlay/markerExtractor.js.map +1 -1
- package/dist/client/overlay/mutationPipeline.d.ts +3 -0
- package/dist/client/overlay/mutationPipeline.js +15 -9
- package/dist/client/overlay/mutationPipeline.js.map +1 -1
- package/dist/client/overlay/pageNodes.d.ts +3 -0
- package/dist/client/overlay/pageNodes.js +34 -0
- package/dist/client/overlay/pageNodes.js.map +1 -0
- package/dist/client/overlayClickHandler.js +3 -2
- package/dist/client/overlayClickHandler.js.map +1 -1
- package/dist/client/overlayScope.d.ts +14 -0
- package/dist/client/overlayScope.js +23 -0
- package/dist/client/overlayScope.js.map +1 -0
- package/dist/client/previewGrant.d.ts +5 -0
- package/dist/client/previewGrant.js +34 -0
- package/dist/client/previewGrant.js.map +1 -0
- package/dist/client/react/LiveRichText.d.ts +17 -0
- package/dist/client/react/LiveRichText.js +32 -0
- package/dist/client/react/LiveRichText.js.map +1 -0
- package/dist/client/react/UnsavedRenderBoundary.js.map +1 -0
- package/dist/client/react/VisualEditingOverlay.js +60 -0
- package/dist/client/react/VisualEditingOverlay.js.map +1 -0
- package/dist/client/react/VisualEditingProvider.d.ts +21 -0
- package/dist/client/react/VisualEditingProvider.js +83 -0
- package/dist/client/react/VisualEditingProvider.js.map +1 -0
- package/dist/client/react/VisualEditingToggle.d.ts +1 -0
- package/dist/client/react/VisualEditingToggle.js +32 -0
- package/dist/client/react/VisualEditingToggle.js.map +1 -0
- package/dist/client/react/overlayContext.d.ts +2 -0
- package/dist/client/react/overlayContext.js +4 -0
- package/dist/client/react/overlayContext.js.map +1 -0
- package/dist/client/react/useIsomorphicLayoutEffect.js.map +1 -0
- package/dist/client/react/useUnsavedRender.d.ts +16 -0
- package/dist/client/react/useUnsavedRender.js +89 -0
- package/dist/client/react/useUnsavedRender.js.map +1 -0
- package/dist/client/saveEvents.d.ts +3 -0
- package/dist/client/saveEvents.js +27 -0
- package/dist/client/saveEvents.js.map +1 -0
- package/dist/client/session.d.ts +40 -0
- package/dist/client/session.js +100 -0
- package/dist/client/session.js.map +1 -0
- package/dist/client/sessionOverlay.d.ts +9 -0
- package/dist/client/sessionOverlay.js +74 -0
- package/dist/client/sessionOverlay.js.map +1 -0
- package/dist/client/toggle.d.ts +7 -0
- package/dist/client/toggle.js +158 -0
- package/dist/client/toggle.js.map +1 -0
- package/dist/client/withVisualEditingPath.d.ts +2 -0
- package/dist/client/withVisualEditingPath.js +5 -6
- package/dist/client/withVisualEditingPath.js.map +1 -1
- package/dist/dom/index.d.ts +6 -0
- package/dist/dom/index.js +7 -0
- package/dist/dom/index.js.map +1 -0
- package/dist/dom/liveRichTextElements.d.ts +8 -0
- package/dist/dom/liveRichTextElements.js +69 -0
- package/dist/dom/liveRichTextElements.js.map +1 -0
- package/dist/dom/mountVisualEditing.d.ts +16 -0
- package/dist/dom/mountVisualEditing.js +52 -0
- package/dist/dom/mountVisualEditing.js.map +1 -0
- package/dist/excludeValues.d.ts +0 -4
- package/dist/excludeValues.js +4 -4
- package/dist/excludeValues.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/readUnsavedRichText.d.ts +16 -2
- package/dist/readUnsavedRichText.js +26 -7
- package/dist/readUnsavedRichText.js.map +1 -1
- package/dist/server/endpoints.d.ts +16 -0
- package/dist/server/endpoints.js +136 -0
- package/dist/server/endpoints.js.map +1 -0
- package/dist/server/markRead.js +3 -3
- package/dist/server/markRead.js.map +1 -1
- package/dist/server/markedReads.d.ts +1 -1
- package/dist/server/markedReads.js +4 -2
- package/dist/server/markedReads.js.map +1 -1
- package/dist/server/previewGrant.d.ts +9 -0
- package/dist/server/previewGrant.js +31 -0
- package/dist/server/previewGrant.js.map +1 -0
- package/dist/server/unsavedRichText/hooks.js +24 -9
- package/dist/server/unsavedRichText/hooks.js.map +1 -1
- package/dist/server/unsavedRichText/placeUnsavedState.js +1 -1
- package/dist/server/unsavedRichText/placeUnsavedState.js.map +1 -1
- package/dist/server/unsavedRichText/postedEditorState.js +3 -31
- package/dist/server/unsavedRichText/postedEditorState.js.map +1 -1
- package/dist/server/unsavedRichText/postedRequest.d.ts +2 -1
- package/dist/server/unsavedRichText/postedRequest.js +14 -4
- package/dist/server/unsavedRichText/postedRequest.js.map +1 -1
- package/dist/server/unsavedRichText/readAsUser.d.ts +7 -2
- package/dist/server/unsavedRichText/readAsUser.js +47 -16
- package/dist/server/unsavedRichText/readAsUser.js.map +1 -1
- package/dist/server/unsavedRichText/readContext.d.ts +6 -0
- package/dist/server/unsavedRichText/readContext.js +5 -0
- package/dist/server/unsavedRichText/readContext.js.map +1 -1
- package/dist/server/unsavedRichText/savedReferences.d.ts +5 -0
- package/dist/server/unsavedRichText/savedReferences.js +61 -0
- package/dist/server/unsavedRichText/savedReferences.js.map +1 -0
- package/dist/server/withDocumentControls.d.ts +10 -0
- package/dist/server/{withInstantPreview.js → withDocumentControls.js} +17 -7
- package/dist/server/withDocumentControls.js.map +1 -0
- package/dist/shared/buildAdminEditUrl.d.ts +1 -0
- package/dist/shared/buildAdminEditUrl.js +5 -1
- package/dist/shared/buildAdminEditUrl.js.map +1 -1
- package/dist/shared/protocol.d.ts +18 -0
- package/dist/shared/protocol.js +6 -0
- package/dist/shared/protocol.js.map +1 -1
- package/dist/shared/richText/editorStateTree.d.ts +2 -0
- package/dist/shared/richText/editorStateTree.js +34 -0
- package/dist/shared/richText/editorStateTree.js.map +1 -0
- package/dist/{server → shared}/richText/markTextLeaves.js +5 -5
- package/dist/shared/richText/markTextLeaves.js.map +1 -0
- package/dist/shared/richText/nodeKey.d.ts +3 -2
- package/dist/shared/richText/nodeKey.js +15 -6
- package/dist/shared/richText/nodeKey.js.map +1 -1
- package/dist/shared/richText/references.d.ts +16 -0
- package/dist/shared/richText/references.js +85 -0
- package/dist/shared/richText/references.js.map +1 -0
- package/dist/{server/unsavedRichText → shared/richText}/relatedIds.d.ts +1 -1
- package/dist/{server/unsavedRichText → shared/richText}/relatedIds.js +4 -4
- package/dist/shared/richText/relatedIds.js.map +1 -0
- package/dist/shared/richText/savedNodeFields.d.ts +3 -0
- package/dist/{server/unsavedRichText → shared/richText}/savedNodeFields.js +4 -4
- package/dist/shared/richText/savedNodeFields.js.map +1 -0
- package/dist/shared/shared.d.ts +14 -3
- package/dist/shared/shared.js +46 -1
- package/dist/shared/shared.js.map +1 -1
- package/dist/shared/stegaText.d.ts +2 -1
- package/dist/shared/stegaText.js +3 -1
- package/dist/shared/stegaText.js.map +1 -1
- package/package.json +26 -4
- package/dist/client/VisualEditingOverlay.js +0 -39
- package/dist/client/VisualEditingOverlay.js.map +0 -1
- package/dist/client/VisualEditingProvider.d.ts +0 -25
- package/dist/client/VisualEditingProvider.js +0 -68
- package/dist/client/VisualEditingProvider.js.map +0 -1
- package/dist/client/VisualEditingToggle.d.ts +0 -1
- package/dist/client/VisualEditingToggle.js +0 -153
- package/dist/client/VisualEditingToggle.js.map +0 -1
- package/dist/client/instantPreview/LiveRichText.d.ts +0 -16
- package/dist/client/instantPreview/LiveRichText.js +0 -18
- package/dist/client/instantPreview/LiveRichText.js.map +0 -1
- package/dist/client/instantPreview/unsavedRender/UnsavedRenderBoundary.js.map +0 -1
- package/dist/client/instantPreview/unsavedRender/useUnsavedRender.d.ts +0 -10
- package/dist/client/instantPreview/unsavedRender/useUnsavedRender.js +0 -118
- package/dist/client/instantPreview/unsavedRender/useUnsavedRender.js.map +0 -1
- package/dist/client/overlayContext.d.ts +0 -3
- package/dist/client/overlayContext.js +0 -5
- package/dist/client/overlayContext.js.map +0 -1
- package/dist/client/useIsomorphicLayoutEffect.js.map +0 -1
- package/dist/client/useVisualEditingOverlay.d.ts +0 -4
- package/dist/client/useVisualEditingOverlay.js +0 -33
- package/dist/client/useVisualEditingOverlay.js.map +0 -1
- package/dist/server/richText/markTextLeaves.js.map +0 -1
- package/dist/server/unsavedRichText/relatedIds.js.map +0 -1
- package/dist/server/unsavedRichText/savedNodeFields.d.ts +0 -2
- package/dist/server/unsavedRichText/savedNodeFields.js.map +0 -1
- package/dist/server/withInstantPreview.d.ts +0 -9
- package/dist/server/withInstantPreview.js.map +0 -1
- /package/dist/client/{instantPreview/unsavedRender → react}/UnsavedRenderBoundary.d.ts +0 -0
- /package/dist/client/{instantPreview/unsavedRender → react}/UnsavedRenderBoundary.js +0 -0
- /package/dist/client/{VisualEditingOverlay.d.ts → react/VisualEditingOverlay.d.ts} +0 -0
- /package/dist/client/{useIsomorphicLayoutEffect.d.ts → react/useIsomorphicLayoutEffect.d.ts} +0 -0
- /package/dist/client/{useIsomorphicLayoutEffect.js → react/useIsomorphicLayoutEffect.js} +0 -0
- /package/dist/{server → shared}/richText/markTextLeaves.d.ts +0 -0
package/README.md
CHANGED
|
@@ -8,11 +8,17 @@ Click-to-edit for Payload CMS. On draft reads the plugin writes an invisible mar
|
|
|
8
8
|
bun add @focus-reactive/payload-plugin-visual-editing
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Peer dependencies: `payload ^3.79`, `@payloadcms/ui ^3.79`, `react
|
|
11
|
+
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:
|
|
12
|
+
|
|
13
|
+
- The Payload app (the plugin and its admin components) needs `payload`, `@payloadcms/ui` and React 19, which Payload 3 requires anyway.
|
|
14
|
+
- A React frontend that imports `./client` needs `react` and `react-dom` 18.2 or newer.
|
|
15
|
+
- A site that imports only `./dom` needs none of them.
|
|
16
|
+
|
|
17
|
+
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`.
|
|
12
18
|
|
|
13
19
|
## Setup
|
|
14
20
|
|
|
15
|
-
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 made with the **Local API
|
|
21
|
+
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](#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.
|
|
16
22
|
|
|
17
23
|
### 1. Register the plugin
|
|
18
24
|
|
|
@@ -136,7 +142,7 @@ export default async function Layout({ children }: { children: React.ReactNode }
|
|
|
136
142
|
}
|
|
137
143
|
```
|
|
138
144
|
|
|
139
|
-
- `VisualEditing.Toggle` is the floating Off / Hover / Always control. The chosen mode is kept in `localStorage
|
|
145
|
+
- `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**. The chosen mode is kept in `localStorage` under the key `visual-editing`, per origin of the page.
|
|
140
146
|
- `VisualEditing.Overlay` scans its children for markers. Content outside it is not touched.
|
|
141
147
|
|
|
142
148
|
### 7. Mark rich text, uploads and relationships
|
|
@@ -155,11 +161,13 @@ Open a document in the admin, open **Live Preview** and set the toggle to **Alwa
|
|
|
155
161
|
|
|
156
162
|
To leave draft mode in a normal browser tab, open `/next/exit-preview`.
|
|
157
163
|
|
|
164
|
+
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.
|
|
165
|
+
|
|
158
166
|
## What gets a marker
|
|
159
167
|
|
|
160
168
|
- Fields of type `text`, `textarea` and `email`, at any depth: in groups, tabs, rows, collapsibles, array rows and blocks (declared inline or through `blockReferences`).
|
|
161
169
|
- 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.
|
|
162
|
-
- Not: empty values, and values that match `excludeValues` (by default URLs, slugs like `hello-world`, `#fragments` and ISO dates).
|
|
170
|
+
- 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.
|
|
163
171
|
- Not: fields named `slug`, `folder`, `_status`, `apiKey` or anything in `excludeFieldNames`.
|
|
164
172
|
- 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.
|
|
165
173
|
- Not: `text` fields with `hasMany`, numbers, selects, dates and other non-text fields.
|
|
@@ -167,7 +175,7 @@ To leave draft mode in a normal browser tab, open `/next/exit-preview`.
|
|
|
167
175
|
|
|
168
176
|
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.
|
|
169
177
|
|
|
170
|
-
If you render a marked value into an attribute, the overlay removes the marker from `alt`, `
|
|
178
|
+
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`.
|
|
171
179
|
|
|
172
180
|
## Rich text, uploads and relationships
|
|
173
181
|
|
|
@@ -205,17 +213,14 @@ Text inside the populated document, such as `page.image.alt` or `page.author.nam
|
|
|
205
213
|
|
|
206
214
|
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.
|
|
207
215
|
|
|
208
|
-
Turn it on in
|
|
216
|
+
Turn it on in the plugin and regenerate the import map:
|
|
209
217
|
|
|
210
218
|
```ts
|
|
211
219
|
// payload.config.ts
|
|
212
220
|
visualEditingPlugin({ instantPreview: true })
|
|
213
221
|
```
|
|
214
222
|
|
|
215
|
-
|
|
216
|
-
// app/(frontend)/layout.tsx
|
|
217
|
-
<VisualEditing.Provider available={isEnabled} instantPreview adminBasePath="/admin">
|
|
218
|
-
```
|
|
223
|
+
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.
|
|
219
224
|
|
|
220
225
|
### Requirements
|
|
221
226
|
|
|
@@ -223,7 +228,7 @@ visualEditingPlugin({ instantPreview: true })
|
|
|
223
228
|
- The frontend refreshes itself after a save, for example with `RefreshRouteOnSave` from `@payloadcms/live-preview-react`, see below.
|
|
224
229
|
- The admin posts to the origin of the Live Preview URL. The preview posts to `adminOrigin` on `VisualEditing.Provider`, its own origin by default.
|
|
225
230
|
- 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.
|
|
226
|
-
- 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.
|
|
231
|
+
- 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.
|
|
227
232
|
- Rich text is rendered inside an element that spreads `withVisualEditingPath(value)`, see [Rich text, uploads and relationships](#rich-text-uploads-and-relationships). Without that wrapper its text is not live.
|
|
228
233
|
|
|
229
234
|
A refresh after every save, with Payload's own component:
|
|
@@ -259,6 +264,7 @@ export const RefreshOnSave = () => {
|
|
|
259
264
|
- Text typed, deleted or replaced inside existing text of a Lexical rich text field: in paragraphs, headings, list items, quotes, links and formatted text.
|
|
260
265
|
- With [`LiveRichText`](#unsaved-rich-text-structure): 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.
|
|
261
266
|
- Only where the page renders the stored value unchanged.
|
|
267
|
+
- 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.
|
|
262
268
|
- In every toggle position, also **Off**. The toggle controls outlines, badges and click-to-edit only.
|
|
263
269
|
|
|
264
270
|
### What waits for the save
|
|
@@ -286,7 +292,7 @@ Rule 3 is the boundary you control. The list in rule 2 comes from the preview pa
|
|
|
286
292
|
|
|
287
293
|
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`](#unsaved-rich-text-structure), 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.
|
|
288
294
|
|
|
289
|
-
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.
|
|
295
|
+
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`](#rendering-on-the-page-with-rendervalue) and [Rendered on the page first](#rendered-on-the-page-first).
|
|
290
296
|
|
|
291
297
|
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.
|
|
292
298
|
|
|
@@ -366,21 +372,21 @@ export const RichText = ({ content }: { content: SerializedEditorState }) => {
|
|
|
366
372
|
}
|
|
367
373
|
```
|
|
368
374
|
|
|
369
|
-
- `liveRichTextOf(content)` returns the identity of the field
|
|
375
|
+
- `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.
|
|
370
376
|
- 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.
|
|
371
377
|
- 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.
|
|
372
378
|
- `LiveRichText` renders no element of its own. Outside draft mode or with `instantPreview` off it only renders its children.
|
|
373
379
|
- Put it inside `VisualEditing.Overlay`. The overlay passes its `locale` on, and `LiveRichText` ignores the admin while it edits another locale.
|
|
374
380
|
|
|
375
|
-
`LiveRichText` makes one call at a time and only the latest state waits. 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.
|
|
381
|
+
`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.
|
|
376
382
|
|
|
377
383
|
**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.
|
|
378
384
|
|
|
379
385
|
**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.
|
|
380
386
|
|
|
381
|
-
`readUnsavedRichText` is the only safe way to turn the posted state into something to render. Hand it the argument of the action untouched. It guarantees:
|
|
387
|
+
`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:
|
|
382
388
|
|
|
383
|
-
- **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
|
|
389
|
+
- **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](#how-the-page-is-allowed-to-read-the-unsaved-value).
|
|
384
390
|
- **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.
|
|
385
391
|
- **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`.
|
|
386
392
|
|
|
@@ -394,14 +400,81 @@ Two cases never reach it: Next.js answers 500 itself for an action body over its
|
|
|
394
400
|
| `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. |
|
|
395
401
|
| `maxStateLength` | Longest accepted editor state, in characters of JSON. |
|
|
396
402
|
| `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. |
|
|
403
|
+
| `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](#upgrading-from-120). |
|
|
404
|
+
|
|
405
|
+
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.
|
|
406
|
+
|
|
407
|
+
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.
|
|
408
|
+
|
|
409
|
+
#### Rendering on the page with `renderValue`
|
|
410
|
+
|
|
411
|
+
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:
|
|
412
|
+
|
|
413
|
+
```tsx
|
|
414
|
+
// components/RichText/LiveBody.tsx
|
|
415
|
+
'use client'
|
|
397
416
|
|
|
398
|
-
|
|
417
|
+
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
|
|
418
|
+
import type { ReactNode } from 'react'
|
|
419
|
+
|
|
420
|
+
import {
|
|
421
|
+
LiveRichText,
|
|
422
|
+
type LiveRichTextIdentity,
|
|
423
|
+
} from '@focus-reactive/payload-plugin-visual-editing/client'
|
|
424
|
+
|
|
425
|
+
import { RichTextBody } from './Body'
|
|
426
|
+
import { renderUnsavedRichText } from './renderUnsavedRichText'
|
|
427
|
+
|
|
428
|
+
export const LiveBody = (props: LiveRichTextIdentity & { children: ReactNode }) => (
|
|
429
|
+
<LiveRichText
|
|
430
|
+
{...props}
|
|
431
|
+
action={renderUnsavedRichText}
|
|
432
|
+
renderValue={(value: SerializedEditorState) => <RichTextBody content={value} />}
|
|
433
|
+
/>
|
|
434
|
+
)
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
```tsx
|
|
438
|
+
// components/RichText/index.tsx
|
|
439
|
+
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
|
|
399
440
|
|
|
400
|
-
|
|
441
|
+
import { liveRichTextOf } from '@focus-reactive/payload-plugin-visual-editing/client'
|
|
442
|
+
|
|
443
|
+
import { RichTextBody } from './Body'
|
|
444
|
+
import { LiveBody } from './LiveBody'
|
|
445
|
+
|
|
446
|
+
export const RichText = ({ content }: { content: SerializedEditorState }) => {
|
|
447
|
+
const body = <RichTextBody content={content} />
|
|
448
|
+
const liveRichText = liveRichTextOf(content)
|
|
449
|
+
return liveRichText ? <LiveBody {...liveRichText}>{body}</LiveBody> : body
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
Where the check with the server goes depends on `payloadApi` of `VisualEditing.Provider`:
|
|
454
|
+
|
|
455
|
+
| Setup | On the page | Check with the server |
|
|
456
|
+
|---|---|---|
|
|
457
|
+
| `action` | nothing | 200 ms after the first new structure, as above |
|
|
458
|
+
| `action`, `renderValue` | at once | the action, 350 ms after the last structure; its result replaces the render on the page |
|
|
459
|
+
| `action`, `renderValue`, `payloadApi` | at once | the `unsaved-rich-text` endpoint, 350 ms after the last structure, rendered with `renderValue` |
|
|
460
|
+
|
|
461
|
+
```tsx
|
|
462
|
+
<VisualEditing.Provider available={isEnabled} payloadApi="https://cms.example.com/api">
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
A provider that is given `adminOrigin` finds the API at `<adminOrigin>/api` on its own.
|
|
466
|
+
|
|
467
|
+
- **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](#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.
|
|
468
|
+
- **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.
|
|
469
|
+
- **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.
|
|
470
|
+
- **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.
|
|
471
|
+
- **`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.
|
|
472
|
+
- An identity printed by `liveRichTextOf` of 1.2.0, without `meta` and `hasReferences`, waits for the server.
|
|
473
|
+
- **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.
|
|
401
474
|
|
|
402
475
|
### Markers in rich text
|
|
403
476
|
|
|
404
|
-
With `instantPreview` on, a draft read puts a marker of roughly
|
|
477
|
+
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.
|
|
405
478
|
|
|
406
479
|
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.
|
|
407
480
|
|
|
@@ -431,10 +504,10 @@ A render can transform a value and still output the stored text for some inputs,
|
|
|
431
504
|
- 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.
|
|
432
505
|
- 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.
|
|
433
506
|
- Rich text in `LiveRichText`:
|
|
434
|
-
-
|
|
507
|
+
- 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](#pages-without-react).
|
|
435
508
|
- While a Server Action call is out, `router.refresh()` waits for it, see [Unsaved rich text structure](#unsaved-rich-text-structure).
|
|
436
|
-
-
|
|
437
|
-
-
|
|
509
|
+
- 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](#how-the-page-is-allowed-to-read-the-unsaved-value). Without them the structure appears with the save.
|
|
510
|
+
- 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.
|
|
438
511
|
- 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.
|
|
439
512
|
- 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.
|
|
440
513
|
- An editor state longer than `maxStateLength` is not rendered before the save.
|
|
@@ -445,6 +518,139 @@ A render can transform a value and still output the stored text for some inputs,
|
|
|
445
518
|
- The popup keeps unsaved text on screen after you leave the document without saving. It shows the saved content again when it reloads.
|
|
446
519
|
- 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.
|
|
447
520
|
|
|
521
|
+
## Pages without React
|
|
522
|
+
|
|
523
|
+
`./dom` runs the same overlay, mode toggle and instant preview on a page that has no React: a static site generator, server templates, Vue, Svelte. It does not import React. The server half and the admin are the same as above.
|
|
524
|
+
|
|
525
|
+
### 1. Read drafts over HTTP with the header
|
|
526
|
+
|
|
527
|
+
A page that reads Payload through REST or GraphQL asks for markers with the `x-visual-editing` header on a draft read (`draft=true`). Only the presence of the header counts, its value does not. The read is marked only for a signed-in user, so send the session of a Payload user with it.
|
|
528
|
+
|
|
529
|
+
```ts
|
|
530
|
+
const response = await fetch(`${CMS_URL}/api/pages?where[slug][equals]=home&draft=true`, {
|
|
531
|
+
headers: { Cookie: session, 'x-visual-editing': '1' },
|
|
532
|
+
})
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
A published read, a read without the header and an anonymous read get no markers. Leave the header out of production builds.
|
|
536
|
+
|
|
537
|
+
A build or a preview function has no browser session, so it signs in as a user of its own, best a service user that may read drafts and nothing else. Any way Payload authenticates a request works:
|
|
538
|
+
|
|
539
|
+
- Log in once with `POST /api/users/login` (`{ email, password }`) and send the `token` of the answer as `Authorization: JWT <token>` or `Authorization: Bearer <token>`, or as the `payload-token` cookie.
|
|
540
|
+
- With `auth.useAPIKey` on the users collection, send `Authorization: users API-Key <key>`.
|
|
541
|
+
|
|
542
|
+
`enrichment: 'explicit'` does not turn these reads off: it is about Local API reads, and the header is already an explicit request.
|
|
543
|
+
|
|
544
|
+
### 2. Mount it on the page
|
|
545
|
+
|
|
546
|
+
Load this only in the preview, after the page has rendered:
|
|
547
|
+
|
|
548
|
+
```ts
|
|
549
|
+
import { mountVisualEditing } from '@focus-reactive/payload-plugin-visual-editing/dom'
|
|
550
|
+
|
|
551
|
+
mountVisualEditing({
|
|
552
|
+
adminOrigin: 'https://cms.example.com',
|
|
553
|
+
framedOnly: true,
|
|
554
|
+
locale: 'en',
|
|
555
|
+
onSave: () => location.reload(),
|
|
556
|
+
})
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
| Option | Default | Purpose |
|
|
560
|
+
|---|---|---|
|
|
561
|
+
| `root` | `document.body` | Element the overlay scans for markers. |
|
|
562
|
+
| `available` | `true` | `false` leaves the page alone, for a page read without drafts. |
|
|
563
|
+
| `adminOrigin` | the page's origin | Origin of the admin window, with its scheme: `https://cms.example.com`. Required when the admin runs on another origin. A value that is no `http` or `https` URL, such as `cms.example.com`, is ignored: the page then talks to its own origin and asks no `payloadApi`. |
|
|
564
|
+
| `framedOnly` | `false` | Only run inside the Live Preview: its iframe or the window it opens. Elsewhere it only removes the markers from `root` and `<head>`. |
|
|
565
|
+
| `instantPreview` | `true` | Text typed in the admin appears on the page, once the plugin option is on. `false` keeps the page from listening. |
|
|
566
|
+
| `locale` | none | Locale of the page, see [Requirements](#requirements). |
|
|
567
|
+
| `toggle` | `true` | Shows the Off / Hover / Always toggle. |
|
|
568
|
+
| `onSave` | none | Called after the admin saves the document, autosave included. |
|
|
569
|
+
| `payloadApi` | `<adminOrigin>/api` when `adminOrigin` is set | URL of the Payload REST API, where the page asks the `unsaved-rich-text` endpoint for unsaved rich text. Set it when `routes.api` of your Payload config is not `/api` or the API is served from another origin than the admin; an empty string keeps the page from asking. |
|
|
570
|
+
| `renderRichTextValue`, `renderRichText` | none | Unsaved rich text structure, see below. |
|
|
571
|
+
| `optimistic` | `true` | With `renderRichTextValue`, render a new structure on the page before the server answers, see [Rendered on the page first](#rendered-on-the-page-first). `false` waits for the server. |
|
|
572
|
+
| `adminBasePath`, `buildAdminEditUrl` | as for `VisualEditing.Provider` | |
|
|
573
|
+
|
|
574
|
+
It returns `{ destroy }`.
|
|
575
|
+
|
|
576
|
+
What to pass depends on what the page should do:
|
|
577
|
+
|
|
578
|
+
| Goal | Plugin | `mountVisualEditing` and templates |
|
|
579
|
+
|---|---|---|
|
|
580
|
+
| Click-to-edit | nothing | `adminOrigin`, when the admin runs on another origin |
|
|
581
|
+
| Text shows while it is typed | `instantPreview: true` | `adminOrigin`; `onSave`, or a reload of your own after a save |
|
|
582
|
+
| Paragraphs, lists and formatting show before the save | `instantPreview: true` | also `richTextAttributes(value)` on the wrapper of the rich text and `renderRichTextValue`, see [Unsaved rich text on a page without React](#unsaved-rich-text-on-a-page-without-react) |
|
|
583
|
+
|
|
584
|
+
The toggle starts on **Off**, as on a React page: the mode is kept in `localStorage` under `visual-editing`, per origin, so an editor picks **Hover** or **Always** once on each site.
|
|
585
|
+
|
|
586
|
+
Nothing reloads the page after a save unless you say so. `onSave` is called each time the editor saves the document, autosave included, and never when the page loads; `() => location.reload()` is the usual value. Without `onSave` and without a reload of your own, the page keeps the content it loaded with: typed text stays on screen through instant preview, and everything that waits for the save never appears. A site that already reloads its preview after a save should leave `onSave` out, or it reloads twice.
|
|
587
|
+
|
|
588
|
+
`onSave` follows `ve:document-saved`, a message the plugin's admin posts after Payload reports a save. The message names the saved document (`collectionSlug`, `kind`, `docId`) and the locale of the admin; `onSave` is called for every one of them, also for a document saved in a drawer. Do not use Payload's own `payload-document-event` for this: Payload also sends it once right after the page reports that it is ready, without a save, and a page that reloads on it reloads once for nothing.
|
|
589
|
+
|
|
590
|
+
### 3. Mark rich text, uploads and relationships
|
|
591
|
+
|
|
592
|
+
`withVisualEditingPath(value)` returns the attributes as an object. Print them on the element in your template. For a rich text field that should update its structure before the save, print `richTextAttributes(value)` instead: it adds `data-ve-live-rich-text`, the identity and shape of the saved value. Both functions run in Node, at build time.
|
|
593
|
+
|
|
594
|
+
A marked text carries invisible characters. Where a template turns text into an `id`, an anchor, a CSS selector or a value it compares, clean it first with `stripMarkers(value)`, also exported from `./dom`: `{{ service.title | stripMarkers | slugify }}`.
|
|
595
|
+
|
|
596
|
+
```njk
|
|
597
|
+
<div {% for name, value in richTextAttributes(page.content) %}{{ name }}="{{ value }}" {% endfor %}>
|
|
598
|
+
{{ page.content | richTextHtml | safe }}
|
|
599
|
+
</div>
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
The example relies on Nunjucks escaping what it prints (`autoescape`, on by default and in Eleventy): the value of `data-ve-live-rich-text` is JSON and must reach the page with its quotes escaped. With autoescape off, or in a template language that does not escape, print the value through its escape filter, here `{{ value | escape }}`.
|
|
603
|
+
|
|
604
|
+
### Unsaved rich text on a page without React
|
|
605
|
+
|
|
606
|
+
Text typed inside existing text of a rich text field updates through the markers, as on a React page. A new paragraph, a list or a bold word needs your renderer. `./dom` replaces the content of the element that carries `data-ve-live-rich-text` with the HTML of the unsaved value, and puts the saved HTML back when the editor returns to the saved structure. After a save without a reload, the HTML it shows for the structure the editor saved becomes the saved HTML, so the page shows what was saved when the editor returns to it and renders the structure it loaded with as unsaved. Choose where that HTML is made:
|
|
607
|
+
|
|
608
|
+
| | Where the HTML is made | Plugin | `mountVisualEditing` |
|
|
609
|
+
|---|---|---|---|
|
|
610
|
+
| In Payload | `renderHtml` in the plugin config | `instantPreview: true, renderHtml` | `adminOrigin` (or `payloadApi`) |
|
|
611
|
+
| On the site | your function, from the value Payload reads | `instantPreview: true` | `adminOrigin` (or `payloadApi`), `renderRichTextValue` |
|
|
612
|
+
| Anywhere | your own call | as you need | `renderRichText` |
|
|
613
|
+
|
|
614
|
+
```ts
|
|
615
|
+
visualEditingPlugin({
|
|
616
|
+
instantPreview: true,
|
|
617
|
+
renderHtml: ({ value }) => toSiteHtml(value),
|
|
618
|
+
})
|
|
619
|
+
|
|
620
|
+
mountVisualEditing({ adminOrigin: 'https://cms.example.com' })
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
`renderHtml` gets the value with the markers of a draft read, the field, the locale and the request. Render it with the same converter the site uses: the HTML replaces the saved HTML in place, and markup that differs flickers when the saved render comes back. There is no default converter for that reason.
|
|
624
|
+
|
|
625
|
+
`renderRichTextValue(value, signal)` gets the same value on the page and returns HTML, or a promise of it. `renderRichText(request, signal)` gets the request itself; hand it to `readUnsavedRichText` on your own server.
|
|
626
|
+
|
|
627
|
+
The HTML of `renderHtml`, `renderRichTextValue` and `renderRichText` is written into the element with `innerHTML`, as it is. The value holds what an editor typed and has not passed the validation of a save, so the renderer must escape every text it prints and check every URL it writes into an `href` or `src` (allow `http:`, `https:`, `mailto:` and relative addresses, refuse `javascript:`), as the renderer of the built site must. `convertLexicalToHTML` of Payload 3.90 escapes text and sanitizes the URL of a link; a converter of your own for a link, an upload or a block has to do both.
|
|
628
|
+
|
|
629
|
+
`./dom` finds the elements that carry `data-ve-live-rich-text` when `mountVisualEditing` runs. An element added later, by a client-side navigation or a script, is not live: call `destroy()` and `mountVisualEditing` again after the page has replaced its content. Text typed into existing text needs no new mount, the overlay follows the page.
|
|
630
|
+
|
|
631
|
+
#### Rendered on the page first
|
|
632
|
+
|
|
633
|
+
With `renderRichTextValue`, the page does not wait for Payload. When the admin posts a new structure, the page builds the value Payload would answer from the posted editor state and data Payload already gave this page, with the same markers and `_meta`, renders it with `renderRichTextValue` and shows it at once. Payload is asked once the editor pauses, 350 ms after the last structure, and its answer replaces the HTML only when it renders differently. Enter followed by the first letter of a new paragraph renders twice on the page and asks Payload once.
|
|
634
|
+
|
|
635
|
+
- **A field of paragraphs, headings, lists and links to URLs** needs nothing else: no request until the pause, and no `payloadApi` to render on the page.
|
|
636
|
+
- **A field with blocks, uploads, relationships or links to documents** needs the saved value of the field, the base, for the fields of saved blocks, uploads and links and for the documents Payload populated. The page asks the `unsaved-rich-text` endpoint for it, without a state, once the editor types in that field or changes its structure, and adds every answer Payload gives for a structure to it. Until the base arrives, a structure of that field goes through Payload as without this option; when it arrives, the structure renders on the page. Without `payloadApi` there is no base, and such a field waits for `renderRichText`. A base that did not arrive is asked for again. A save forgets every base; the page asks again when a structure with blocks, uploads, relationships or links to documents needs it. A structure without them renders on the page without a base, also after a save.
|
|
637
|
+
- **What only Payload knows appears with its answer.** A newly inserted upload or relationship is left out until then, a new link to a document links to its id, and a new block shows only its id and type, as it does in Payload's answer before the save.
|
|
638
|
+
- **`renderRichTextValue` runs in the browser**, so the converter ships in the bundle of the preview page. `convertLexicalToHTML` from `@payloadcms/richtext-lexical/html` bundles for the browser as it is: `renderRichTextValue: (data) => convertLexicalToHTML({ data })`. It gets a value that did not pass through your Payload hooks. It must render the same markup for the same value as the build of the site does, or the page swaps the HTML once Payload answers. When it throws for a structure, that structure goes through Payload. It may return a promise; the HTML is shown when it resolves.
|
|
639
|
+
- **Pass `optimistic: false`** to wait for Payload for every structure, as 1.2.0 did. A page whose `data-ve-live-rich-text` was printed by `richTextAttributes` of 1.2.0 has no `_meta` in it and waits for Payload too; build it again.
|
|
640
|
+
|
|
641
|
+
`renderHtml` in Payload and your own `renderRichText` cannot render on the page. They start a call 200 ms after the first new structure, as `LiveRichText` does, and gain from the read of one field described in [Upgrading from 1.2.0](#upgrading-from-120).
|
|
642
|
+
|
|
643
|
+
With both `renderRichTextValue` and `renderRichText`, the page renders a structure itself and checks it as `LiveRichText` does with `renderValue` and an action: through the `unsaved-rich-text` endpoint while it holds a grant, rendered with `renderRichTextValue`, and through `renderRichText` otherwise. Pass `payloadApi: ''` to check through `renderRichText` alone.
|
|
644
|
+
|
|
645
|
+
#### How the page is allowed to read the unsaved value
|
|
646
|
+
|
|
647
|
+
The admin and the page often run on different origins, so the page cannot send the admin's session cookie. With `instantPreview` on, the plugin adds two endpoints:
|
|
648
|
+
|
|
649
|
+
- `POST /api/visual-editing/preview-grant`. The admin asks it, with the editor's session, for a grant of the document open in the form. The grant names the user and the document, expires after ten minutes and is signed with a key derived from the Payload secret. The admin posts it to the preview window, only to the origin of the Live Preview URL: once to every page that loads there or asks for it, and again when it has renewed the grant, which it checks every four minutes while the form is open.
|
|
650
|
+
- `POST /api/visual-editing/unsaved-rich-text`. The page posts the grant and the request as `text/plain`, which needs no CORS preflight. The endpoint reads the posted state as `readUnsavedRichText` does, with the access of the user in the grant and only for the document in the grant, and answers the origin of the request. A request without `state` gets the saved value of the field, read the same way. In both answers a relationship, upload or internal link node is populated only when the saved value of the same field refers to the same document (the same `relationTo` and id), and never when it refers to an auth collection or a collection whose slug starts with `payload-`; every other reference stays an id. A reference the editor adds therefore shows on the page after the save. `renderHtml` gets a request whose `user` is the user of the grant. It waits up to eight seconds for the read, longer than the three seconds `readUnsavedRichText` allows by default, because no router queue waits behind a `fetch`. It writes nothing.
|
|
651
|
+
|
|
652
|
+
A grant is a bearer token: a script on the preview page can read it, as it can read every value the admin posts there. For ten minutes it lets the holder read the rich text fields of one document, saved or with a posted structure, with the access of the user who opened it, together with the documents the saved rich text of that field already refers to, populated as that user may read them. It reads no other field of the document and no document the posted state names on its own. The blocks of a posted state get their fields from the saved document, so what they populate is what the saved document refers to.
|
|
653
|
+
|
|
448
654
|
## Enrichment modes
|
|
449
655
|
|
|
450
656
|
`enrichment` decides which reads get markers.
|
|
@@ -463,7 +669,9 @@ await payload.find({
|
|
|
463
669
|
})
|
|
464
670
|
```
|
|
465
671
|
|
|
466
|
-
In both modes `context.visualEditing` wins when it is set: `true` marks the read, `false` leaves it clean.
|
|
672
|
+
In both modes `context.visualEditing` wins when it is set: `true` marks the read, `false` leaves it clean. `true` marks any read it is passed to, also a published one, so pass the draft flag as above and never a constant `true`.
|
|
673
|
+
|
|
674
|
+
`enrichment` is about Local API reads. A REST or GraphQL draft read that sends the `x-visual-editing` header with a signed-in user is marked in both modes.
|
|
467
675
|
|
|
468
676
|
A `beforeChange` hook removes intact markers from every write. It cannot recognise a marker that a transformation damaged. If server code reads drafts, changes the text (a translation, a truncation) and writes it back, use `'explicit'` or pass `context: { visualEditing: false }` on those reads.
|
|
469
677
|
|
|
@@ -475,17 +683,20 @@ A `beforeChange` hook removes intact markers from every write. It cannot recogni
|
|
|
475
683
|
| `skipGlobals` | `string[]` | `[]` | Globals the plugin does not mark. |
|
|
476
684
|
| `excludeFieldNames` | `string[]` | `[]` | Field names that are never marked and never sent to the preview, in addition to `_status`, `folder`, `slug` and `apiKey`. |
|
|
477
685
|
| `excludeValues` | `((value: string) => boolean)[]` | `defaultExcludeValues` | Values that are not marked. Replaces the defaults (`isUrl`, `isSlug`, `isHash`, `isIsoDate`, all exported). |
|
|
478
|
-
| `adminBasePath` | `string` | `/admin` | Admin base path. Reads from below it are not marked; the bridge uses it to recognise the open document. |
|
|
686
|
+
| `adminBasePath` | `string` | `/admin` | Admin base path. Reads from below it are not marked; the bridge uses it to recognise the open document. A slash at its end is ignored. |
|
|
479
687
|
| `enrichment` | `'auto' \| 'explicit'` | `'auto'` | See [Enrichment modes](#enrichment-modes). |
|
|
480
688
|
| `instantPreview` | `boolean` | `false` | See [Instant preview](#instant-preview). |
|
|
689
|
+
| `renderHtml` | `({ value, field, locale, req }) => string \| Promise<string>` | none | Renders unsaved rich text to HTML for a page without React, see [Pages without React](#unsaved-rich-text-on-a-page-without-react). |
|
|
690
|
+
| `readWholeDocument` | `boolean` | `false` | The `unsaved-rich-text` endpoint reads every field of the document instead of the top-level field that holds the rich text. For `afterRead` hooks that need other fields, see [Upgrading from 1.2.0](#upgrading-from-120). |
|
|
481
691
|
|
|
482
692
|
`LiveRichText` props:
|
|
483
693
|
|
|
484
694
|
| Prop | Purpose |
|
|
485
695
|
|---|---|
|
|
486
|
-
| `field`, `shape` | From `liveRichTextOf(value)`: spread its result. |
|
|
696
|
+
| `field`, `shape`, `meta`, `hasReferences` | From `liveRichTextOf(value)`: spread its whole result. `field` and `shape` identify the saved value; `meta` and `hasReferences` are what a render on the page with `renderValue` needs, and without them the field waits for the server. |
|
|
487
697
|
| `action` | A Server Action that renders the unsaved state. It is called with the request only. |
|
|
488
698
|
| `render` | In place of `action`: `(request, signal) => Promise<ReactNode>`, a call you make yourself. |
|
|
699
|
+
| `renderValue` | `(value) => ReactNode`, your rich text renderer as a Client Component. Renders a structure on the page as it arrives, see [Rendering on the page with `renderValue`](#rendering-on-the-page-with-rendervalue). |
|
|
489
700
|
| `children` | The saved render. |
|
|
490
701
|
|
|
491
702
|
`VisualEditing.Provider` props:
|
|
@@ -493,11 +704,12 @@ A `beforeChange` hook removes intact markers from every write. It cannot recogni
|
|
|
493
704
|
| Prop | Default | Purpose |
|
|
494
705
|
|---|---|---|
|
|
495
706
|
| `available` | `false` | Turns the overlay on. Pass the draft mode flag. |
|
|
496
|
-
| `framedOnly` | `false` | Only run inside
|
|
707
|
+
| `framedOnly` | `false` | Only run inside the Live Preview: its iframe or the window it opens. Elsewhere a draft page only loses its markers. |
|
|
497
708
|
| `adminBasePath` | `/admin` | Must match the plugin option. |
|
|
498
|
-
| `adminOrigin` | the page's origin | Origin of the admin window. |
|
|
499
|
-
| `instantPreview` | `
|
|
500
|
-
| `buildAdminEditUrl` | built in | Builds the link used when the page was not opened from the admin. |
|
|
709
|
+
| `adminOrigin` | the page's origin | Origin of the admin window, with its scheme: `https://cms.example.com`. A value that is no `http` or `https` URL is ignored: the page then talks to its own origin and asks no `payloadApi`. |
|
|
710
|
+
| `instantPreview` | `true` | See [Instant preview](#instant-preview). `false` keeps the page from listening to the admin. |
|
|
711
|
+
| `buildAdminEditUrl` | built in | Builds the link used when the page was not opened from the admin. A link without an origin opens on `adminOrigin`. |
|
|
712
|
+
| `payloadApi` | `<adminOrigin>/api` when `adminOrigin` is set | URL of the Payload REST API, such as `https://cms.example.com/api`. With `renderValue` on `LiveRichText`, unsaved rich text is checked through the `unsaved-rich-text` endpoint instead of the action. |
|
|
501
713
|
|
|
502
714
|
## Reads with every locale
|
|
503
715
|
|
|
@@ -505,6 +717,28 @@ A draft read with `locale: 'all'` returns localized values keyed by locale (`tit
|
|
|
505
717
|
|
|
506
718
|
When the clicked document is already open in the admin, the bridge focuses the field in the locale the admin is showing. It does not switch the admin locale.
|
|
507
719
|
|
|
720
|
+
## Upgrading from 1.2.0
|
|
721
|
+
|
|
722
|
+
Regenerate the import map. The plugin adds `PreviewPageBridge` to every collection and global with Live Preview, and `OpenFormAnnouncer` to every collection and global it marks, both also with `instantPreview` off. Without `OpenFormAnnouncer` in the import map a link with `?veFocus` waits 15 seconds before it focuses the field.
|
|
723
|
+
|
|
724
|
+
- **A click on a page served from another origin than the admin opens the field.** The admin used to accept clicks only from its own origin. It now also accepts them from the Live Preview window, on the origin of its URL.
|
|
725
|
+
- **The page no longer posts a click to any origin.** Without `adminOrigin` it posts to its own origin, as instant preview already did.
|
|
726
|
+
- **Draft reads over REST and GraphQL can be marked.** Only with the `x-visual-editing` header and a signed-in user, see [Pages without React](#pages-without-react). Reads that do not send the header are unchanged.
|
|
727
|
+
- **With `instantPreview` on, the plugin adds two endpoints** under `/api/visual-editing/`, see [How the page is allowed to read the unsaved value](#how-the-page-is-allowed-to-read-the-unsaved-value). A grant issued before a deploy that changes how it is signed is refused once; the admin asks for a new one when the page asks again or within four minutes.
|
|
728
|
+
- **A draft page without the overlay loses its markers.** With the toggle on **Off** and instant preview off, or with `framedOnly` in a normal tab, the page used to keep every marker, and a script that splits text into characters rendered them as empty boxes. `VisualEditing.Overlay` and `mountVisualEditing` now remove them from the text, every attribute, the title and `<head>`, and put them back when they unmount. A script that reads marked text from the page after that sees clean text.
|
|
729
|
+
- **The meta tags of `<head>` lose their markers while the overlay runs**, like the title already did.
|
|
730
|
+
- **A structural rich text edit makes one render call, not one per structure.** `LiveRichText` and the rich text of `mountVisualEditing` wait 200 ms after a new structure before they start a call. Enter followed by typing used to start two calls in a row and showed the new text only after both.
|
|
731
|
+
- **A page without React renders a structural edit itself.** With `renderRichTextValue`, `mountVisualEditing` shows the new structure as the admin posts it and asks Payload 350 ms after the last one, see [Rendered on the page first](#rendered-on-the-page-first). Your `renderRichTextValue` now also runs on every structure, in the browser. A page that also passes `renderRichText` is checked through the `unsaved-rich-text` endpoint while it holds a grant, and through `renderRichText` otherwise. Print `richTextAttributes` again: its attribute now carries the `_meta` of the value and whether it holds references. Pass `optimistic: false` to keep the old behaviour.
|
|
732
|
+
- **An unsaved rich text read reads one field, not the whole document.** `readUnsavedRichText` and the `unsaved-rich-text` endpoint pass `select` with the top-level field that holds the rich text, so Payload no longer reads and populates every other field of the document for each structural edit. Collection and field `afterRead` hooks of your project see only that field during the read. A hook that needs another field (a slug, a sibling value) should pass `readWholeDocument: true` to `readUnsavedRichText` and set the plugin option `readWholeDocument: true` for the endpoint.
|
|
733
|
+
- **`LiveRichText` can render a structural edit on the page.** Pass your renderer as `renderValue` from a client module, and `payloadApi` to `VisualEditing.Provider` to check it through the endpoint instead of the action, see [Rendering on the page with `renderValue`](#rendering-on-the-page-with-rendervalue). Without `renderValue` nothing changes. `liveRichTextOf` now also returns the `_meta` of the value and whether it holds references; spread its whole result into `LiveRichText`.
|
|
734
|
+
- **An element whose whole text is one marked field gets that field's `data-ve-*` attributes while the overlay runs.** A heading that a script of your site splits into words after the overlay found it stays an edit target and keeps its instant text; the overlay then writes the new value as plain text into it, which resets the split until the page reloads. The attributes are removed when the overlay unmounts. A CSS selector of your site on `[data-ve-path]` now also matches these elements.
|
|
735
|
+
- **Markers are about half as long.** A marker used to spell out the names of its properties and state the path of a row twice, about 1.6 KB of UTF-8 for a field in a row; it now holds the same identity as a short list. Upgrade the server and the frontend together: the overlay of this version reads both forms, an overlay of 1.2.0 does not read the new one and leaves it in the text. Code of your own that decodes a marker with `vercelStegaDecode` gets the list; `stripMarkers` and `vercelStegaClean` work as before. A block name the page never shows still costs a marker in every block: add `blockName` to `excludeFieldNames` to leave it out.
|
|
736
|
+
- **The page half of instant preview is on by default.** `instantPreview` of `VisualEditing.Provider` and `mountVisualEditing` used to be `false`. The admin still sends nothing unless the plugin option is on, so a site without the plugin option sees one difference: with the toggle on **Off** the overlay runs instead of the marker cleaner, which costs a few milliseconds more on a page with some hundred marked texts. Pass `instantPreview={false}` to keep the old behaviour.
|
|
737
|
+
- **`payloadApi` is `<adminOrigin>/api` when `adminOrigin` is set.** A page that names its admin origin and prints `richTextAttributes` or passes `renderValue` now asks the `unsaved-rich-text` endpoint without being given `payloadApi`. Pass `payloadApi` when your API is elsewhere, or an empty string to keep the page from asking.
|
|
738
|
+
- **The mode toggle lives in a shadow root.** Its element is `[data-ve-toggle]` on `<body>`, and its buttons and styles are inside its shadow root, so styles of the site no longer reach them and the toggle no longer inherits fonts or resets. `[data-ve-toggle-root]`, `[data-ve-toggle-btn]` and the `<style id="ve-toggle-styles">` element are gone: a selector or a test of your own that used them finds nothing. Reach a button through `document.querySelector('[data-ve-toggle]').shadowRoot`; the buttons are `button[data-mode]` with `role="radio"`.
|
|
739
|
+
- **`isSlug` and `isHash` exclude less, so more values are marked.** `isSlug` now needs a letter: `8-10` and `10-20-30` are marked, `top-10` and `a-1` still are not. `isHash` now needs a value without white space: `#1 in the ranking` is marked, `#demo` and `#` still are not. A project that passes its own `excludeValues` with these two gets the new behaviour; write your own predicate to keep the old one.
|
|
740
|
+
- **All peers are optional, and `react` and `react-dom` accept `^18.2.0` again.** The Payload app still needs `payload`, `@payloadcms/ui` and React 19. A site that installs the package only for `./dom` gets none of them, and a site that keeps React 18 for something else can install it.
|
|
741
|
+
|
|
508
742
|
## Upgrading from 1.1.1
|
|
509
743
|
|
|
510
744
|
No config change is needed. Regenerate the import map when you turn `instantPreview` on: it adds `InstantPreviewBroadcaster` and `OpenFormAnnouncer`.
|
|
@@ -541,11 +775,11 @@ Markers:
|
|
|
541
775
|
Overlay:
|
|
542
776
|
|
|
543
777
|
- **Edit targets follow the page.** A target is bound again when React renders another field or document into the same element. An element that leaves the overlay, or a wrapper that loses its `data-ve-*` attributes, loses its outline and badge.
|
|
544
|
-
- **Click-to-edit after a row move** (with `instantPreview`): between a move in the form and the refresh, a click opens the row that was clicked, not the row that now has its index. A rich text wrapper does the same through its `data-ve-key`. For this the plugin adds an `OpenFormAnnouncer` to the document controls of every collection and global it marks, with or without Live Preview; it renders nothing and tells the bridge which row ids the open form has.
|
|
778
|
+
- **Click-to-edit after a row move** (with `instantPreview`): between a move in the form and the refresh, a click opens the row that was clicked, not the row that now has its index. A rich text wrapper does the same through its `data-ve-key`. For this the plugin adds an `OpenFormAnnouncer` to the document controls of every collection and global it marks, with or without Live Preview; it renders nothing and tells the bridge which row ids the open form has. It is now added with `instantPreview` off as well, because a link with `?veFocus` waits for it.
|
|
545
779
|
|
|
546
780
|
## Caveats
|
|
547
781
|
|
|
548
|
-
- **Click-to-edit
|
|
782
|
+
- **Click-to-edit works across origins only from the Live Preview.** The admin accepts a click from its own origin, and from the Live Preview iframe or the window it opens, on the origin of the Live Preview URL; pass `adminOrigin` to the page. A page on another origin that has no admin window behind it, such as one opened from a bookmark, opens the field in a new admin tab; a click posted from any other window on another origin is ignored.
|
|
549
783
|
- **`target="_blank"` must not carry `noopener`** when you open the frontend from the admin in a new tab. The overlay talks to `window.opener`. The Live Preview iframe is not affected.
|
|
550
784
|
- **`slug` is never marked.** Zero-width characters in a slug end up in URLs.
|
|
551
785
|
- **A value that starts to match `excludeValues`** (a heading that becomes `hello-world`) is rendered without a marker. The overlay stops patching that text node and does not write an earlier value back. Click-to-edit and instant preview return with the next marked render.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { useAllFormFields, useDocumentInfo, useLocale } from "@payloadcms/ui";
|
|
3
|
-
import { useLayoutEffect, useMemo, useState } from "react";
|
|
2
|
+
import { useAllFormFields, useConfig, useDocumentInfo, useLocale } from "@payloadcms/ui";
|
|
3
|
+
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
4
|
+
import { createPreviewGrants, fetchGrantFrom, GRANT_RENEWAL_INTERVAL_MS } from "./instantPreview/previewGrants.js";
|
|
4
5
|
import { createPreviewSession } from "./instantPreview/previewSession.js";
|
|
5
6
|
import { useEditableSchema } from "./instantPreview/useEditableSchema.js";
|
|
6
7
|
import { usePreviewPage } from "./instantPreview/usePreviewPage.js";
|
|
@@ -17,6 +18,33 @@ export function InstantPreviewBroadcaster({ excludeFieldNames }) {
|
|
|
17
18
|
const preview = usePreviewWindow();
|
|
18
19
|
const { getWindow: getPreviewWindow, post: postToPreview } = preview;
|
|
19
20
|
const [session] = useState(createPreviewSession);
|
|
21
|
+
const { config } = useConfig();
|
|
22
|
+
const [grants] = useState(()=>createPreviewGrants(fetchGrantFrom(`${config.serverURL}${config.routes.api}`)));
|
|
23
|
+
const latestPageId = useRef(null);
|
|
24
|
+
const openDocument = useMemo(()=>openDocumentOf({
|
|
25
|
+
collectionSlug,
|
|
26
|
+
globalSlug,
|
|
27
|
+
id
|
|
28
|
+
}), [
|
|
29
|
+
collectionSlug,
|
|
30
|
+
globalSlug,
|
|
31
|
+
id
|
|
32
|
+
]);
|
|
33
|
+
const postGrantToPage = useCallback((page)=>{
|
|
34
|
+
if (!openDocument) return;
|
|
35
|
+
latestPageId.current = page.pageId;
|
|
36
|
+
const sendGrant = async ()=>{
|
|
37
|
+
const message = await grants.forPage(openDocument, page);
|
|
38
|
+
if (message) postToPreview([
|
|
39
|
+
message
|
|
40
|
+
]);
|
|
41
|
+
};
|
|
42
|
+
void sendGrant();
|
|
43
|
+
}, [
|
|
44
|
+
grants,
|
|
45
|
+
openDocument,
|
|
46
|
+
postToPreview
|
|
47
|
+
]);
|
|
20
48
|
const admin = useMemo(()=>{
|
|
21
49
|
const document = openDocumentOf({
|
|
22
50
|
collectionSlug,
|
|
@@ -42,7 +70,20 @@ export function InstantPreviewBroadcaster({ excludeFieldNames }) {
|
|
|
42
70
|
locale,
|
|
43
71
|
savedDocument
|
|
44
72
|
]);
|
|
45
|
-
usePreviewPage(preview, session);
|
|
73
|
+
usePreviewPage(preview, session, postGrantToPage);
|
|
74
|
+
useEffect(()=>{
|
|
75
|
+
const postRenewedGrant = ()=>{
|
|
76
|
+
const pageId = latestPageId.current;
|
|
77
|
+
if (pageId !== null) postGrantToPage({
|
|
78
|
+
asksForGrant: false,
|
|
79
|
+
pageId
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
const timer = setInterval(postRenewedGrant, GRANT_RENEWAL_INTERVAL_MS);
|
|
83
|
+
return ()=>clearInterval(timer);
|
|
84
|
+
}, [
|
|
85
|
+
postGrantToPage
|
|
86
|
+
]);
|
|
46
87
|
useLayoutEffect(()=>{
|
|
47
88
|
session.localeChanged(locale);
|
|
48
89
|
}, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/admin/InstantPreviewBroadcaster.tsx"],"sourcesContent":["\"use client\";\n\nimport { useAllFormFields, useDocumentInfo, useLocale } from \"@payloadcms/ui\";\nimport { useLayoutEffect, useMemo, useState } from \"react\";\n\nimport type { AdminState } from \"./instantPreview/previewSession.js\";\n\nimport { createPreviewSession } from \"./instantPreview/previewSession.js\";\nimport { useEditableSchema } from \"./instantPreview/useEditableSchema.js\";\nimport { usePreviewPage } from \"./instantPreview/usePreviewPage.js\";\nimport { usePreviewWindow } from \"./instantPreview/usePreviewWindow.js\";\nimport { openDocumentOf } from \"./openField/openDocument.js\";\n\nexport function InstantPreviewBroadcaster({ excludeFieldNames }: { excludeFieldNames?: string[] }) {\n const [formState] = useAllFormFields();\n const { id, collectionSlug, globalSlug, data: savedDocument } = useDocumentInfo();\n const editableSchema = useEditableSchema({ collectionSlug, globalSlug }, excludeFieldNames);\n const { code: locale } = useLocale();\n const preview = usePreviewWindow();\n const { getWindow: getPreviewWindow, post: postToPreview } = preview;\n const [session] = useState(createPreviewSession);\n\n const admin = useMemo((): AdminState | null => {\n const document = openDocumentOf({ collectionSlug, globalSlug, id });\n if (!document) return null;\n return { document: { ...document, locale }, editableSchema, formState, savedDocument };\n }, [collectionSlug, editableSchema, formState, globalSlug, id, locale, savedDocument]);\n\n usePreviewPage(preview, session);\n\n useLayoutEffect(() => {\n session.localeChanged(locale);\n }, [locale, session]);\n\n useLayoutEffect(() => {\n if (!getPreviewWindow()) session.pageLeft();\n postToPreview(session.formChanged(admin));\n }, [admin, getPreviewWindow, postToPreview, session]);\n\n return null;\n}\n"],"names":["useAllFormFields","useDocumentInfo","useLocale","useLayoutEffect","useMemo","useState","createPreviewSession","useEditableSchema","usePreviewPage","usePreviewWindow","openDocumentOf","InstantPreviewBroadcaster","excludeFieldNames","formState","id","collectionSlug","globalSlug","data","savedDocument","editableSchema","code","locale","preview","getWindow","getPreviewWindow","post","postToPreview","session","admin","document","localeChanged","pageLeft","formChanged"],"mappings":"AAAA;AAEA,SAASA,gBAAgB,EAAEC,eAAe,EAAEC,SAAS,QAAQ,iBAAiB;
|
|
1
|
+
{"version":3,"sources":["../../src/admin/InstantPreviewBroadcaster.tsx"],"sourcesContent":["\"use client\";\n\nimport { useAllFormFields, useConfig, useDocumentInfo, useLocale } from \"@payloadcms/ui\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nimport type { GrantedPage } from \"./instantPreview/previewGrants.js\";\nimport type { AdminState } from \"./instantPreview/previewSession.js\";\n\nimport {\n createPreviewGrants,\n fetchGrantFrom,\n GRANT_RENEWAL_INTERVAL_MS,\n} from \"./instantPreview/previewGrants.js\";\nimport { createPreviewSession } from \"./instantPreview/previewSession.js\";\nimport { useEditableSchema } from \"./instantPreview/useEditableSchema.js\";\nimport { usePreviewPage } from \"./instantPreview/usePreviewPage.js\";\nimport { usePreviewWindow } from \"./instantPreview/usePreviewWindow.js\";\nimport { openDocumentOf } from \"./openField/openDocument.js\";\n\nexport function InstantPreviewBroadcaster({ excludeFieldNames }: { excludeFieldNames?: string[] }) {\n const [formState] = useAllFormFields();\n const { id, collectionSlug, globalSlug, data: savedDocument } = useDocumentInfo();\n const editableSchema = useEditableSchema({ collectionSlug, globalSlug }, excludeFieldNames);\n const { code: locale } = useLocale();\n const preview = usePreviewWindow();\n const { getWindow: getPreviewWindow, post: postToPreview } = preview;\n const [session] = useState(createPreviewSession);\n const { config } = useConfig();\n const [grants] = useState(() =>\n createPreviewGrants(fetchGrantFrom(`${config.serverURL}${config.routes.api}`))\n );\n const latestPageId = useRef<string | null>(null);\n const openDocument = useMemo(\n () => openDocumentOf({ collectionSlug, globalSlug, id }),\n [collectionSlug, globalSlug, id]\n );\n\n const postGrantToPage = useCallback(\n (page: GrantedPage) => {\n if (!openDocument) return;\n latestPageId.current = page.pageId;\n const sendGrant = async () => {\n const message = await grants.forPage(openDocument, page);\n if (message) postToPreview([message]);\n };\n void sendGrant();\n },\n [grants, openDocument, postToPreview]\n );\n\n const admin = useMemo((): AdminState | null => {\n const document = openDocumentOf({ collectionSlug, globalSlug, id });\n if (!document) return null;\n return { document: { ...document, locale }, editableSchema, formState, savedDocument };\n }, [collectionSlug, editableSchema, formState, globalSlug, id, locale, savedDocument]);\n\n usePreviewPage(preview, session, postGrantToPage);\n\n useEffect(() => {\n const postRenewedGrant = () => {\n const pageId = latestPageId.current;\n if (pageId !== null) postGrantToPage({ asksForGrant: false, pageId });\n };\n const timer = setInterval(postRenewedGrant, GRANT_RENEWAL_INTERVAL_MS);\n return () => clearInterval(timer);\n }, [postGrantToPage]);\n\n useLayoutEffect(() => {\n session.localeChanged(locale);\n }, [locale, session]);\n\n useLayoutEffect(() => {\n if (!getPreviewWindow()) session.pageLeft();\n postToPreview(session.formChanged(admin));\n }, [admin, getPreviewWindow, postToPreview, session]);\n\n return null;\n}\n"],"names":["useAllFormFields","useConfig","useDocumentInfo","useLocale","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","createPreviewGrants","fetchGrantFrom","GRANT_RENEWAL_INTERVAL_MS","createPreviewSession","useEditableSchema","usePreviewPage","usePreviewWindow","openDocumentOf","InstantPreviewBroadcaster","excludeFieldNames","formState","id","collectionSlug","globalSlug","data","savedDocument","editableSchema","code","locale","preview","getWindow","getPreviewWindow","post","postToPreview","session","config","grants","serverURL","routes","api","latestPageId","openDocument","postGrantToPage","page","current","pageId","sendGrant","message","forPage","admin","document","postRenewedGrant","asksForGrant","timer","setInterval","clearInterval","localeChanged","pageLeft","formChanged"],"mappings":"AAAA;AAEA,SAASA,gBAAgB,EAAEC,SAAS,EAAEC,eAAe,EAAEC,SAAS,QAAQ,iBAAiB;AACzF,SAASC,WAAW,EAAEC,SAAS,EAAEC,eAAe,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAK3F,SACEC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,oCAAoC;AAC3C,SAASC,oBAAoB,QAAQ,qCAAqC;AAC1E,SAASC,iBAAiB,QAAQ,wCAAwC;AAC1E,SAASC,cAAc,QAAQ,qCAAqC;AACpE,SAASC,gBAAgB,QAAQ,uCAAuC;AACxE,SAASC,cAAc,QAAQ,8BAA8B;AAE7D,OAAO,SAASC,0BAA0B,EAAEC,iBAAiB,EAAoC;IAC/F,MAAM,CAACC,UAAU,GAAGpB;IACpB,MAAM,EAAEqB,EAAE,EAAEC,cAAc,EAAEC,UAAU,EAAEC,MAAMC,aAAa,EAAE,GAAGvB;IAChE,MAAMwB,iBAAiBZ,kBAAkB;QAAEQ;QAAgBC;IAAW,GAAGJ;IACzE,MAAM,EAAEQ,MAAMC,MAAM,EAAE,GAAGzB;IACzB,MAAM0B,UAAUb;IAChB,MAAM,EAAEc,WAAWC,gBAAgB,EAAEC,MAAMC,aAAa,EAAE,GAAGJ;IAC7D,MAAM,CAACK,QAAQ,GAAGzB,SAASI;IAC3B,MAAM,EAAEsB,MAAM,EAAE,GAAGlC;IACnB,MAAM,CAACmC,OAAO,GAAG3B,SAAS,IACxBC,oBAAoBC,eAAe,CAAC,EAAEwB,OAAOE,SAAS,CAAC,EAAEF,OAAOG,MAAM,CAACC,GAAG,CAAC,CAAC;IAE9E,MAAMC,eAAehC,OAAsB;IAC3C,MAAMiC,eAAelC,QACnB,IAAMU,eAAe;YAAEK;YAAgBC;YAAYF;QAAG,IACtD;QAACC;QAAgBC;QAAYF;KAAG;IAGlC,MAAMqB,kBAAkBtC,YACtB,CAACuC;QACC,IAAI,CAACF,cAAc;QACnBD,aAAaI,OAAO,GAAGD,KAAKE,MAAM;QAClC,MAAMC,YAAY;YAChB,MAAMC,UAAU,MAAMX,OAAOY,OAAO,CAACP,cAAcE;YACnD,IAAII,SAASd,cAAc;gBAACc;aAAQ;QACtC;QACA,KAAKD;IACP,GACA;QAACV;QAAQK;QAAcR;KAAc;IAGvC,MAAMgB,QAAQ1C,QAAQ;QACpB,MAAM2C,WAAWjC,eAAe;YAAEK;YAAgBC;YAAYF;QAAG;QACjE,IAAI,CAAC6B,UAAU,OAAO;QACtB,OAAO;YAAEA,UAAU;gBAAE,GAAGA,QAAQ;gBAAEtB;YAAO;YAAGF;YAAgBN;YAAWK;QAAc;IACvF,GAAG;QAACH;QAAgBI;QAAgBN;QAAWG;QAAYF;QAAIO;QAAQH;KAAc;IAErFV,eAAec,SAASK,SAASQ;IAEjCrC,UAAU;QACR,MAAM8C,mBAAmB;YACvB,MAAMN,SAASL,aAAaI,OAAO;YACnC,IAAIC,WAAW,MAAMH,gBAAgB;gBAAEU,cAAc;gBAAOP;YAAO;QACrE;QACA,MAAMQ,QAAQC,YAAYH,kBAAkBvC;QAC5C,OAAO,IAAM2C,cAAcF;IAC7B,GAAG;QAACX;KAAgB;IAEpBpC,gBAAgB;QACd4B,QAAQsB,aAAa,CAAC5B;IACxB,GAAG;QAACA;QAAQM;KAAQ;IAEpB5B,gBAAgB;QACd,IAAI,CAACyB,oBAAoBG,QAAQuB,QAAQ;QACzCxB,cAAcC,QAAQwB,WAAW,CAACT;IACpC,GAAG;QAACA;QAAOlB;QAAkBE;QAAeC;KAAQ;IAEpD,OAAO;AACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function PreviewPageBridge(): null;
|