@focus-reactive/payload-plugin-visual-editing 1.0.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.
Files changed (119) hide show
  1. package/README.md +264 -0
  2. package/dist/admin/VisualEditingBridgeProvider.d.ts +4 -0
  3. package/dist/admin/VisualEditingBridgeProvider.js +144 -0
  4. package/dist/admin/VisualEditingBridgeProvider.js.map +1 -0
  5. package/dist/admin/expandAndFocus.d.ts +6 -0
  6. package/dist/admin/expandAndFocus.js +356 -0
  7. package/dist/admin/expandAndFocus.js.map +1 -0
  8. package/dist/admin/index.d.ts +1 -0
  9. package/dist/admin/index.js +3 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/admin/parseFieldPath.d.ts +4 -0
  12. package/dist/admin/parseFieldPath.js +25 -0
  13. package/dist/admin/parseFieldPath.js.map +1 -0
  14. package/dist/admin/resolveContainerChain.d.ts +30 -0
  15. package/dist/admin/resolveContainerChain.js +171 -0
  16. package/dist/admin/resolveContainerChain.js.map +1 -0
  17. package/dist/client/VisualEditingOverlay.d.ts +4 -0
  18. package/dist/client/VisualEditingOverlay.js +30 -0
  19. package/dist/client/VisualEditingOverlay.js.map +1 -0
  20. package/dist/client/VisualEditingProvider.d.ts +23 -0
  21. package/dist/client/VisualEditingProvider.js +68 -0
  22. package/dist/client/VisualEditingProvider.js.map +1 -0
  23. package/dist/client/VisualEditingToggle.d.ts +1 -0
  24. package/dist/client/VisualEditingToggle.js +163 -0
  25. package/dist/client/VisualEditingToggle.js.map +1 -0
  26. package/dist/client/buildAdminEditUrl.d.ts +7 -0
  27. package/dist/client/buildAdminEditUrl.js +9 -0
  28. package/dist/client/buildAdminEditUrl.js.map +1 -0
  29. package/dist/client/index.d.ts +11 -0
  30. package/dist/client/index.js +13 -0
  31. package/dist/client/index.js.map +1 -0
  32. package/dist/client/overlay/constants.d.ts +9 -0
  33. package/dist/client/overlay/constants.js +49 -0
  34. package/dist/client/overlay/constants.js.map +1 -0
  35. package/dist/client/overlay/createOverlay.d.ts +11 -0
  36. package/dist/client/overlay/createOverlay.js +80 -0
  37. package/dist/client/overlay/createOverlay.js.map +1 -0
  38. package/dist/client/overlay/editBadge.d.ts +21 -0
  39. package/dist/client/overlay/editBadge.js +99 -0
  40. package/dist/client/overlay/editBadge.js.map +1 -0
  41. package/dist/client/overlay/hoverController.d.ts +14 -0
  42. package/dist/client/overlay/hoverController.js +137 -0
  43. package/dist/client/overlay/hoverController.js.map +1 -0
  44. package/dist/client/overlay/markerExtractor.d.ts +8 -0
  45. package/dist/client/overlay/markerExtractor.js +47 -0
  46. package/dist/client/overlay/markerExtractor.js.map +1 -0
  47. package/dist/client/overlay/mutationPipeline.d.ts +10 -0
  48. package/dist/client/overlay/mutationPipeline.js +78 -0
  49. package/dist/client/overlay/mutationPipeline.js.map +1 -0
  50. package/dist/client/overlay/stegaBookkeeper.d.ts +11 -0
  51. package/dist/client/overlay/stegaBookkeeper.js +36 -0
  52. package/dist/client/overlay/stegaBookkeeper.js.map +1 -0
  53. package/dist/client/overlay/stegaScanner.d.ts +11 -0
  54. package/dist/client/overlay/stegaScanner.js +54 -0
  55. package/dist/client/overlay/stegaScanner.js.map +1 -0
  56. package/dist/client/overlay/targetRegistry.d.ts +34 -0
  57. package/dist/client/overlay/targetRegistry.js +70 -0
  58. package/dist/client/overlay/targetRegistry.js.map +1 -0
  59. package/dist/client/overlay/targetSelector.d.ts +2 -0
  60. package/dist/client/overlay/targetSelector.js +67 -0
  61. package/dist/client/overlay/targetSelector.js.map +1 -0
  62. package/dist/client/overlayClickHandler.d.ts +7 -0
  63. package/dist/client/overlayClickHandler.js +24 -0
  64. package/dist/client/overlayClickHandler.js.map +1 -0
  65. package/dist/client/useVisualEditingOverlay.d.ts +4 -0
  66. package/dist/client/useVisualEditingOverlay.js +21 -0
  67. package/dist/client/useVisualEditingOverlay.js.map +1 -0
  68. package/dist/client/withVisualEditingPath.d.ts +9 -0
  69. package/dist/client/withVisualEditingPath.js +17 -0
  70. package/dist/client/withVisualEditingPath.js.map +1 -0
  71. package/dist/constants.d.ts +16 -0
  72. package/dist/constants.js +15 -0
  73. package/dist/constants.js.map +1 -0
  74. package/dist/excludeValues.d.ts +6 -0
  75. package/dist/excludeValues.js +24 -0
  76. package/dist/excludeValues.js.map +1 -0
  77. package/dist/index.d.ts +13 -0
  78. package/dist/index.js +107 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/internal/afterOperationHook.d.ts +10 -0
  81. package/dist/internal/afterOperationHook.js +28 -0
  82. package/dist/internal/afterOperationHook.js.map +1 -0
  83. package/dist/internal/afterReadHook.d.ts +2 -0
  84. package/dist/internal/afterReadHook.js +16 -0
  85. package/dist/internal/afterReadHook.js.map +1 -0
  86. package/dist/internal/beforeOperationHook.d.ts +4 -0
  87. package/dist/internal/beforeOperationHook.js +16 -0
  88. package/dist/internal/beforeOperationHook.js.map +1 -0
  89. package/dist/internal/buildFieldSchema.d.ts +3 -0
  90. package/dist/internal/buildFieldSchema.js +67 -0
  91. package/dist/internal/buildFieldSchema.js.map +1 -0
  92. package/dist/internal/encodeStega.d.ts +7 -0
  93. package/dist/internal/encodeStega.js +171 -0
  94. package/dist/internal/encodeStega.js.map +1 -0
  95. package/dist/internal/enrichWithPathMeta.d.ts +4 -0
  96. package/dist/internal/enrichWithPathMeta.js +76 -0
  97. package/dist/internal/enrichWithPathMeta.js.map +1 -0
  98. package/dist/internal/filterEditableFields.d.ts +2 -0
  99. package/dist/internal/filterEditableFields.js +88 -0
  100. package/dist/internal/filterEditableFields.js.map +1 -0
  101. package/dist/internal/gate.d.ts +2 -0
  102. package/dist/internal/gate.js +15 -0
  103. package/dist/internal/gate.js.map +1 -0
  104. package/dist/internal/globalAfterReadHook.d.ts +10 -0
  105. package/dist/internal/globalAfterReadHook.js +19 -0
  106. package/dist/internal/globalAfterReadHook.js.map +1 -0
  107. package/dist/internal/markTerminalUploads.d.ts +13 -0
  108. package/dist/internal/markTerminalUploads.js +79 -0
  109. package/dist/internal/markTerminalUploads.js.map +1 -0
  110. package/dist/internal/schemaCache.d.ts +10 -0
  111. package/dist/internal/schemaCache.js +29 -0
  112. package/dist/internal/schemaCache.js.map +1 -0
  113. package/dist/internal/shared.d.ts +32 -0
  114. package/dist/internal/shared.js +55 -0
  115. package/dist/internal/shared.js.map +1 -0
  116. package/dist/internal/stripStegaHook.d.ts +2 -0
  117. package/dist/internal/stripStegaHook.js +29 -0
  118. package/dist/internal/stripStegaHook.js.map +1 -0
  119. package/package.json +105 -0
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # @focus-reactive/payload-plugin-visual-editing
2
+
3
+ Visual editing plugin for Payload CMS. Embeds field-path markers into draft content via Vercel stega, then renders in-place edit overlays on the frontend that deep-link back into Payload admin via a postMessage bridge.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @focus-reactive/payload-plugin-visual-editing
9
+ ```
10
+
11
+ Peer dependencies: `payload ^3.79`, `@payloadcms/ui ^3.79`, `react ^18 || ^19`. `next` is optional.
12
+
13
+ ## Compatibility
14
+
15
+ Requires Payload **3.79 or newer** (within the 3.x line), supplied by the host app. `@payloadcms/ui`, `payload`, and `react` are peer dependencies, so the plugin shares the host's single copy rather than bundling its own. Built and tested against Payload `3.84.1`.
16
+
17
+ ## Setup
18
+
19
+ The plugin has two halves: a **server half** (Payload hooks that embed stega path-markers into draft reads, register the admin bridge, and strip stega back out on write) and a **client half** (the frontend overlay that turns those markers into click-to-edit badges). Enrichment only happens for **draft** content served to the **frontend** — never the admin form or published reads — so the flow below wires Next.js draft mode end to end.
20
+
21
+ Steps 1–2 set up the server, steps 3–5 connect draft preview, steps 6–8 finish the client. The `apps/dev` app in this repo is a complete working reference.
22
+
23
+ ### 1. Register the plugin — `payload.config.ts`
24
+
25
+ ```ts
26
+ import { buildConfig } from 'payload'
27
+ import { visualEditingPlugin } from '@focus-reactive/payload-plugin-visual-editing'
28
+
29
+ export default buildConfig({
30
+ // ...
31
+ plugins: [
32
+ visualEditingPlugin({
33
+ // all optional:
34
+ skipCollections: ['media'], // collection slugs to exclude from enrichment
35
+ skipGlobals: [], // global slugs to exclude
36
+ excludeFieldNames: ['tenant'], // extra field names to strip (merged with '_status', 'folder', 'slug')
37
+ adminBasePath: '/admin', // Payload admin base path (default '/admin')
38
+ }),
39
+ ],
40
+ })
41
+ ```
42
+
43
+ This adds enrichment hooks to every non-skipped collection and global, registers the `VisualEditingBridgeProvider` admin component, and adds a `beforeChange` hook that strips stega from writes so markers can never be persisted to the database.
44
+
45
+ ### 2. Enable drafts on editable collections
46
+
47
+ The plugin only enriches **draft** reads, so each collection you want to edit visually needs Payload drafts turned on:
48
+
49
+ ```ts
50
+ export const Pages: CollectionConfig = {
51
+ slug: 'pages',
52
+ versions: { drafts: true },
53
+ // fields...
54
+ }
55
+ ```
56
+
57
+ ### 3. Add draft-mode preview routes
58
+
59
+ Next.js draft mode is what flips a frontend read into a draft read. Add a route that enables it (and one that exits):
60
+
61
+ ```ts
62
+ // app/(frontend)/next/preview/route.ts
63
+ import { draftMode } from 'next/headers'
64
+ import { redirect } from 'next/navigation'
65
+
66
+ export async function GET(req: Request) {
67
+ const path = new URL(req.url).searchParams.get('path')
68
+ // same-origin relative paths only — block open redirects
69
+ if (!path || !path.startsWith('/') || path.startsWith('//')) {
70
+ return new Response('Invalid path', { status: 400 })
71
+ }
72
+ ;(await draftMode()).enable()
73
+ redirect(path)
74
+ }
75
+ ```
76
+
77
+ ```ts
78
+ // app/(frontend)/next/exit-preview/route.ts
79
+ import { draftMode } from 'next/headers'
80
+ import { redirect } from 'next/navigation'
81
+
82
+ export async function GET(req: Request) {
83
+ const path = new URL(req.url).searchParams.get('path')
84
+ ;(await draftMode()).disable()
85
+ redirect(path && path.startsWith('/') && !path.startsWith('//') ? path : '/')
86
+ }
87
+ ```
88
+
89
+ ### 4. Point Live Preview at the preview route
90
+
91
+ So the CMS side-by-side preview opens the frontend already in draft mode, set the collection's `admin.livePreview.url` to go through `/next/preview`:
92
+
93
+ ```ts
94
+ export const Pages: CollectionConfig = {
95
+ slug: 'pages',
96
+ admin: {
97
+ livePreview: {
98
+ url: ({ data }) => {
99
+ const slug = typeof data?.slug === 'string' ? data.slug : ''
100
+ return `${process.env.NEXT_PUBLIC_SERVER_URL}/next/preview?path=${encodeURIComponent(`/${slug}`)}`
101
+ },
102
+ },
103
+ },
104
+ versions: { drafts: true },
105
+ // fields...
106
+ }
107
+ ```
108
+
109
+ ### 5. Fetch drafts in the frontend page
110
+
111
+ Read the document with `draft` tied to draft mode — stega is only embedded on draft reads:
112
+
113
+ ```tsx
114
+ // app/(frontend)/[slug]/page.tsx
115
+ import { draftMode } from 'next/headers'
116
+ import { getPayload } from 'payload'
117
+ import config from '@payload-config'
118
+
119
+ export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
120
+ const { slug } = await params
121
+ const { isEnabled: draft } = await draftMode()
122
+ const payload = await getPayload({ config })
123
+
124
+ const { docs } = await payload.find({
125
+ collection: 'pages',
126
+ draft,
127
+ depth: 1, // ≥ 1 so uploads/relationships populate (see "Editable richText and upload fields")
128
+ where: { slug: { equals: slug } },
129
+ })
130
+ // render docs[0]
131
+ }
132
+ ```
133
+
134
+ ### 6. Wrap the frontend layout
135
+
136
+ Mount the provider (gated on draft mode), the toggle, and the overlay:
137
+
138
+ ```tsx
139
+ // app/(frontend)/layout.tsx
140
+ import { VisualEditing } from '@focus-reactive/payload-plugin-visual-editing/client'
141
+ import { draftMode } from 'next/headers'
142
+
143
+ export default async function Layout({ children }: { children: React.ReactNode }) {
144
+ const { isEnabled } = await draftMode()
145
+
146
+ return (
147
+ <html>
148
+ <body>
149
+ <VisualEditing.Provider available={isEnabled} framedOnly adminBasePath="/admin">
150
+ <VisualEditing.Toggle />
151
+ <VisualEditing.Overlay>{children}</VisualEditing.Overlay>
152
+ </VisualEditing.Provider>
153
+ </body>
154
+ </html>
155
+ )
156
+ }
157
+ ```
158
+
159
+ - `available` enables the overlay only when draft mode is on; a user-level toggle (stored in `localStorage`) then gates whether badges actually render.
160
+ - `framedOnly` (optional) restricts the overlay to the CMS preview iframe — omit it to also allow editing when the frontend is opened in a standalone tab.
161
+ - `VisualEditing.Toggle` renders the floating off/hover/always control; `VisualEditing.Overlay` scans the DOM for markers and draws the edit badges.
162
+
163
+ ### 7. Mark richText and upload fields
164
+
165
+ `text` / `textarea` / `email` fields are picked up automatically. `richText` and `upload` values opt out of inline stega and need one line in your renderer — see [Editable richText and upload fields](#editable-richtext-and-upload-fields).
166
+
167
+ ### 8. Regenerate the admin import map
168
+
169
+ The bridge is registered as an admin component, so refresh Payload's import map (re-run after config changes):
170
+
171
+ ```bash
172
+ bunx payload generate:importmap
173
+ ```
174
+
175
+ ### Using it
176
+
177
+ Open a document in the admin, open the **Live Preview** side panel (it loads the frontend in draft mode), then flip the floating toggle to **Always** or **Hover**. Editable text shows an outline and an **Edit** badge; clicking it focuses that field in the admin form. To leave draft mode when viewing the frontend directly, hit `/next/exit-preview`.
178
+
179
+ ## Editable richText and upload fields
180
+
181
+ Most fields (`text`, `textarea`, `email`, …) are edit-overlayable automatically — the plugin weaves zero-width stega characters into their rendered text and the client overlay picks them up. Two kinds of values opt out of stega and need one line in your renderer:
182
+
183
+ - **`richText`** — treated as a leaf-renderer black box; no stega is embedded into its rendered paragraphs.
184
+ - **`upload:<slug>`** — its populated value is a different document whose `_meta` is preserved for wrapper-attr consumption instead of being re-encoded.
185
+
186
+ For both, spread `withVisualEditingPath(value)` onto the element you want to receive the Edit badge.
187
+
188
+ ```tsx
189
+ import { withVisualEditingPath } from '@focus-reactive/payload-plugin-visual-editing/client'
190
+ ```
191
+
192
+ ### RichText
193
+
194
+ ```tsx
195
+ import { RichText } from '@payloadcms/richtext-lexical/react'
196
+
197
+ <div {...withVisualEditingPath(page.content)}>
198
+ <RichText data={page.content} />
199
+ </div>
200
+ ```
201
+
202
+ ### Upload — single relationTo
203
+
204
+ ```tsx
205
+ <img
206
+ src={page.image.url}
207
+ alt={page.image.alt}
208
+ {...withVisualEditingPath(page.image)}
209
+ />
210
+ ```
211
+
212
+ ### Upload — polymorphic (`relationTo: ['media', 'videos']`)
213
+
214
+ Spread on `value`, not the wrapper:
215
+
216
+ ```tsx
217
+ <img
218
+ src={page.image.value.url}
219
+ alt={page.image.value.alt}
220
+ {...withVisualEditingPath(page.image.value)}
221
+ />
222
+ ```
223
+
224
+ Clicking the Edit badge on an upload opens the media document's admin page (not a field on the host doc).
225
+
226
+ **Uploads require `depth ≥ 1`** so Payload returns the populated media document alongside its `_meta`. At `depth: 0` the value is a bare id string and no overlay is drawn.
227
+
228
+ ## How it works
229
+
230
+ ### Server pipeline
231
+
232
+ 1. `beforeOperation` stamps `req.context` with the draft flag.
233
+ 2. `afterRead` (gated to draft reads served to the frontend Local API — admin-panel reads, identified by their admin pathname, and REST reads are skipped) walks the returned document, attaches `_meta.path` markers to leaf-ish objects, and for rich-text / primitive-terminal types sets `_meta.terminal = true` so outer collection walks don't clobber them.
234
+ 3. `afterOperation` uses the collection's schema to embed Vercel stega into text fields, carrying the field path all the way through SSR into the client DOM.
235
+ 4. Before stega is embedded, a small pre-pass walks each enriched doc's schema against its data. Populated `upload:<slug>` values are flipped to `_meta.terminal = true` so their identity is preserved for wrapper-attr consumption on the client (`<img {...withVisualEditingPath(upload)} />`), without embedding zero-width stega into `alt` or `filename`.
236
+ 5. `beforeChange` strips stega from every write as a safety net, so markers can never be persisted even if a read is ever mis-classified.
237
+
238
+ The schema cache (per slug, memoized) resolves relationship targets lazily so you don't pay for unused collections.
239
+
240
+ ### Client overlay
241
+
242
+ `VisualEditing.Overlay` mounts a MutationObserver inside its effect, scans existing DOM for stega-bearing text, and redraws edit badges on mount, lazy-mount, and DOM mutations. Clicking a badge reaches `VisualEditingBridgeProvider` (via `postMessage` to the parent admin when framed, or `window.opener` when opened from an admin tab) → schema walk → field focus.
243
+
244
+ ## Options
245
+
246
+ | Option | Type | Default | Purpose |
247
+ |---|---|---|---|
248
+ | `skipCollections` | `string[]` | `[]` | Exclude these collection slugs from enrichment. Payload internal collections are always skipped. |
249
+ | `skipGlobals` | `string[]` | `[]` | Exclude these global slugs from enrichment. |
250
+ | `excludeFieldNames` | `string[]` | `[]` | Extra field names to strip from the serialized schema. Always merged with `_status`, `folder`, `slug`. |
251
+ | `adminBasePath` | `string` | `/admin` | Payload admin base path. Used to exclude admin reads from enrichment and by the bridge for URL parsing and admin-tab navigation. |
252
+
253
+ The `VisualEditing.Provider` (client) also accepts `framedOnly` (restrict the overlay to the CMS preview iframe) and `adminBasePath` (must match the server option).
254
+
255
+ ## Caveats
256
+
257
+ - **`target="_blank"` must not carry `noopener`.** The postMessage bridge requires `window.opener` to be non-null. If you open the frontend from the admin tab with a plain anchor, browsers default `window.opener` to `null` on `target="_blank"` unless you explicitly opt out. Use `window.open(url, '_blank', 'noopener=no')` or cross-tab messaging will fail silently. (Not a concern in the side-by-side Live Preview, which messages the parent frame.)
258
+ - **The overlay hook intentionally collapses effect deps to `[enabled]`** via `ctxRef`. Do not "fix" this — parent re-renders would teardown the MutationObserver and lazy-mounted content (React.lazy / Suspense) would stop getting outlined.
259
+ - **`_meta.terminal = true` on rich-text is load-bearing** — prevents outer `afterRead` walks from clobbering inner markers when collections relate to other collections.
260
+ - **`slug` is excluded from stega** — zero-width chars inside a slug corrupt URLs (become noisy `%E2%80%8B` sequences).
261
+
262
+ ## License
263
+
264
+ MIT
@@ -0,0 +1,4 @@
1
+ export declare function VisualEditingBridgeProvider({ adminBasePath, children, }: {
2
+ adminBasePath?: string;
3
+ children: React.ReactNode;
4
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,144 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useConfig } from "@payloadcms/ui";
4
+ import { useEffect } from "react";
5
+ import { VE_MESSAGE_TYPE } from "../constants.js";
6
+ import { expandAndFocus } from "./expandAndFocus.js";
7
+ import { parseFieldPath } from "./parseFieldPath.js";
8
+ import { resolveContainerChain } from "./resolveContainerChain.js";
9
+ const VE_FOCUS_PARAM = "veFocus";
10
+ const escapeRegex = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11
+ const isSameOrigin = (eventOrigin)=>{
12
+ if (typeof window === "undefined") return false;
13
+ return eventOrigin === window.location.origin;
14
+ };
15
+ const makeLocators = (adminBasePath)=>{
16
+ const base = escapeRegex(adminBasePath);
17
+ const collectionRe = new RegExp(`^${base}/collections/([^/]+)/([^/?#]+)`);
18
+ const globalRe = new RegExp(`^${base}/globals/([^/?#]+)`);
19
+ const currentCollectionLocation = ()=>{
20
+ const match = window.location.pathname.match(collectionRe);
21
+ if (!match) return null;
22
+ const [, slug, id] = match;
23
+ if (!slug || !id) return null;
24
+ return {
25
+ slug,
26
+ id
27
+ };
28
+ };
29
+ const currentGlobalSlug = ()=>{
30
+ const match = window.location.pathname.match(globalRe);
31
+ return match?.[1] ?? null;
32
+ };
33
+ const navigateAndFocus = (message)=>{
34
+ const target = message.kind === "global" ? `${adminBasePath}/globals/${message.collectionSlug}` : `${adminBasePath}/collections/${message.collectionSlug}/${message.docId}`;
35
+ const params = new URLSearchParams();
36
+ if (message.path) params.set(VE_FOCUS_PARAM, message.path);
37
+ if (message.locale) params.set("locale", message.locale);
38
+ const qs = params.toString();
39
+ const url = qs ? `${target}?${qs}` : target;
40
+ // Different doc => new tab so the current admin context is preserved.
41
+ // Same-doc field focus goes through `focusFieldPath`, not this helper.
42
+ // `noopener` here would force the return value to null, defeating the
43
+ // popup-block detection below. We're same-origin (admin -> admin), so
44
+ // the retained opener reference isn't a security concern.
45
+ const opened = window.open(url, "_blank");
46
+ if (!opened) window.location.assign(url);
47
+ };
48
+ return {
49
+ currentCollectionLocation,
50
+ currentGlobalSlug,
51
+ navigateAndFocus
52
+ };
53
+ };
54
+ // If the schema walk fails (drift, malformed path), reconstruct a row-only
55
+ // chain from numeric segments in the path — matches the pre-resolver behavior.
56
+ const fallbackResolution = (path)=>{
57
+ const { rowIds, fieldId } = parseFieldPath(path);
58
+ return {
59
+ chain: rowIds.map((rowContainerId)=>({
60
+ kind: "row",
61
+ rowContainerId
62
+ })),
63
+ fieldId
64
+ };
65
+ };
66
+ const focusFieldPath = async (path, kind, slug, getFields)=>{
67
+ const fields = getFields(kind, slug);
68
+ const chainResult = fields !== null ? resolveContainerChain(path, fields) : null;
69
+ const resolved = chainResult ?? fallbackResolution(path);
70
+ await expandAndFocus(resolved.chain, resolved.fieldId);
71
+ };
72
+ export function VisualEditingBridgeProvider({ adminBasePath = "/admin", children }) {
73
+ const { getEntityConfig } = useConfig();
74
+ useEffect(()=>{
75
+ const { currentCollectionLocation, currentGlobalSlug, navigateAndFocus } = makeLocators(adminBasePath);
76
+ const getFields = (kind, slug)=>{
77
+ try {
78
+ const entity = kind === "collection" ? getEntityConfig({
79
+ collectionSlug: slug
80
+ }) : getEntityConfig({
81
+ globalSlug: slug
82
+ });
83
+ return entity?.fields ?? null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ };
88
+ // URL-param activation: strip `veFocus` from URL, then defer to give the
89
+ // admin form time to paint.
90
+ const url = new URL(window.location.href);
91
+ const focusPath = url.searchParams.get(VE_FOCUS_PARAM);
92
+ if (focusPath) {
93
+ url.searchParams.delete(VE_FOCUS_PARAM);
94
+ window.history.replaceState(null, "", url.toString());
95
+ const collection = currentCollectionLocation();
96
+ const globalSlug = currentGlobalSlug();
97
+ setTimeout(()=>{
98
+ if (collection) {
99
+ void focusFieldPath(focusPath, "collection", collection.slug, getFields);
100
+ } else if (globalSlug) {
101
+ void focusFieldPath(focusPath, "global", globalSlug, getFields);
102
+ }
103
+ }, 500);
104
+ }
105
+ const handle = (event)=>{
106
+ if (!isSameOrigin(event.origin)) return;
107
+ const data = event.data;
108
+ if (!data || data.type !== VE_MESSAGE_TYPE) return;
109
+ // Collection mismatch: navigate to the correct (collection, doc) pair —
110
+ // compare BOTH slug and id. Two collections can share an id (pages/1 vs
111
+ // forms/1), so matching on id alone would leave the user on the wrong
112
+ // edit view and every field lookup would fail.
113
+ if (data.kind === "collection") {
114
+ const current = currentCollectionLocation();
115
+ const wrongCollection = current?.slug !== data.collectionSlug;
116
+ const wrongDoc = data.docId !== undefined && current?.id !== data.docId;
117
+ if (!current || wrongCollection || wrongDoc) {
118
+ navigateAndFocus(data);
119
+ return;
120
+ }
121
+ void focusFieldPath(data.path, "collection", data.collectionSlug, getFields);
122
+ return;
123
+ }
124
+ if (data.kind === "global") {
125
+ const slug = currentGlobalSlug();
126
+ if (slug !== data.collectionSlug) {
127
+ navigateAndFocus(data);
128
+ return;
129
+ }
130
+ void focusFieldPath(data.path, "global", data.collectionSlug, getFields);
131
+ }
132
+ };
133
+ window.addEventListener("message", handle);
134
+ return ()=>window.removeEventListener("message", handle);
135
+ }, [
136
+ getEntityConfig,
137
+ adminBasePath
138
+ ]);
139
+ return /*#__PURE__*/ _jsx(_Fragment, {
140
+ children: children
141
+ });
142
+ }
143
+
144
+ //# sourceMappingURL=VisualEditingBridgeProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/admin/VisualEditingBridgeProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useConfig } from \"@payloadcms/ui\";\nimport { useEffect } from \"react\";\n\nimport { VE_MESSAGE_TYPE } from \"../constants.js\";\nimport type { VeOpenFieldMessage } from \"../constants.js\";\nimport { expandAndFocus } from \"./expandAndFocus.js\";\nimport { parseFieldPath } from \"./parseFieldPath.js\";\nimport { resolveContainerChain } from \"./resolveContainerChain.js\";\nimport type { ContainerInstruction, ResolverField } from \"./resolveContainerChain.js\";\n\nconst VE_FOCUS_PARAM = \"veFocus\";\n\nconst escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst isSameOrigin = (eventOrigin: string): boolean => {\n if (typeof window === \"undefined\") return false;\n return eventOrigin === window.location.origin;\n};\n\nconst makeLocators = (adminBasePath: string) => {\n const base = escapeRegex(adminBasePath);\n const collectionRe = new RegExp(`^${base}/collections/([^/]+)/([^/?#]+)`);\n const globalRe = new RegExp(`^${base}/globals/([^/?#]+)`);\n\n const currentCollectionLocation = (): { slug: string; id: string } | null => {\n const match = window.location.pathname.match(collectionRe);\n if (!match) return null;\n const [, slug, id] = match;\n if (!slug || !id) return null;\n return { slug, id };\n };\n\n const currentGlobalSlug = (): string | null => {\n const match = window.location.pathname.match(globalRe);\n return match?.[1] ?? null;\n };\n\n const navigateAndFocus = (message: VeOpenFieldMessage): void => {\n const target =\n message.kind === \"global\"\n ? `${adminBasePath}/globals/${message.collectionSlug}`\n : `${adminBasePath}/collections/${message.collectionSlug}/${message.docId}`;\n const params = new URLSearchParams();\n if (message.path) params.set(VE_FOCUS_PARAM, message.path);\n if (message.locale) params.set(\"locale\", message.locale);\n const qs = params.toString();\n const url = qs ? `${target}?${qs}` : target;\n // Different doc => new tab so the current admin context is preserved.\n // Same-doc field focus goes through `focusFieldPath`, not this helper.\n // `noopener` here would force the return value to null, defeating the\n // popup-block detection below. We're same-origin (admin -> admin), so\n // the retained opener reference isn't a security concern.\n const opened = window.open(url, \"_blank\");\n if (!opened) window.location.assign(url);\n };\n\n return { currentCollectionLocation, currentGlobalSlug, navigateAndFocus };\n};\n\n// If the schema walk fails (drift, malformed path), reconstruct a row-only\n// chain from numeric segments in the path — matches the pre-resolver behavior.\nconst fallbackResolution = (\n path: string\n): { chain: ContainerInstruction[]; fieldId: string | null } => {\n const { rowIds, fieldId } = parseFieldPath(path);\n return {\n chain: rowIds.map((rowContainerId) => ({ kind: \"row\", rowContainerId }) as const),\n fieldId,\n };\n};\n\ntype EntityFieldsLookup = (kind: \"collection\" | \"global\", slug: string) => ResolverField[] | null;\n\nconst focusFieldPath = async (\n path: string,\n kind: \"collection\" | \"global\",\n slug: string,\n getFields: EntityFieldsLookup\n): Promise<void> => {\n const fields = getFields(kind, slug);\n const chainResult = fields !== null ? resolveContainerChain(path, fields) : null;\n const resolved = chainResult ?? fallbackResolution(path);\n await expandAndFocus(resolved.chain, resolved.fieldId);\n};\n\nexport function VisualEditingBridgeProvider({\n adminBasePath = \"/admin\",\n children,\n}: {\n adminBasePath?: string;\n children: React.ReactNode;\n}) {\n const { getEntityConfig } = useConfig();\n\n useEffect(() => {\n const { currentCollectionLocation, currentGlobalSlug, navigateAndFocus } =\n makeLocators(adminBasePath);\n\n const getFields: EntityFieldsLookup = (kind, slug) => {\n try {\n const entity =\n kind === \"collection\"\n ? getEntityConfig({ collectionSlug: slug })\n : getEntityConfig({ globalSlug: slug });\n return (entity?.fields ?? null) as ResolverField[] | null;\n } catch {\n return null;\n }\n };\n\n // URL-param activation: strip `veFocus` from URL, then defer to give the\n // admin form time to paint.\n const url = new URL(window.location.href);\n const focusPath = url.searchParams.get(VE_FOCUS_PARAM);\n if (focusPath) {\n url.searchParams.delete(VE_FOCUS_PARAM);\n window.history.replaceState(null, \"\", url.toString());\n const collection = currentCollectionLocation();\n const globalSlug = currentGlobalSlug();\n setTimeout(() => {\n if (collection) {\n void focusFieldPath(focusPath, \"collection\", collection.slug, getFields);\n } else if (globalSlug) {\n void focusFieldPath(focusPath, \"global\", globalSlug, getFields);\n }\n }, 500);\n }\n\n const handle = (event: MessageEvent) => {\n if (!isSameOrigin(event.origin)) return;\n const data = event.data as VeOpenFieldMessage | undefined;\n if (!data || data.type !== VE_MESSAGE_TYPE) return;\n\n // Collection mismatch: navigate to the correct (collection, doc) pair —\n // compare BOTH slug and id. Two collections can share an id (pages/1 vs\n // forms/1), so matching on id alone would leave the user on the wrong\n // edit view and every field lookup would fail.\n if (data.kind === \"collection\") {\n const current = currentCollectionLocation();\n const wrongCollection = current?.slug !== data.collectionSlug;\n const wrongDoc = data.docId !== undefined && current?.id !== data.docId;\n if (!current || wrongCollection || wrongDoc) {\n navigateAndFocus(data);\n return;\n }\n void focusFieldPath(data.path, \"collection\", data.collectionSlug, getFields);\n return;\n }\n\n if (data.kind === \"global\") {\n const slug = currentGlobalSlug();\n if (slug !== data.collectionSlug) {\n navigateAndFocus(data);\n return;\n }\n void focusFieldPath(data.path, \"global\", data.collectionSlug, getFields);\n }\n };\n\n window.addEventListener(\"message\", handle);\n return () => window.removeEventListener(\"message\", handle);\n }, [getEntityConfig, adminBasePath]);\n\n return <>{children}</>;\n}\n"],"names":["useConfig","useEffect","VE_MESSAGE_TYPE","expandAndFocus","parseFieldPath","resolveContainerChain","VE_FOCUS_PARAM","escapeRegex","value","replace","isSameOrigin","eventOrigin","window","location","origin","makeLocators","adminBasePath","base","collectionRe","RegExp","globalRe","currentCollectionLocation","match","pathname","slug","id","currentGlobalSlug","navigateAndFocus","message","target","kind","collectionSlug","docId","params","URLSearchParams","path","set","locale","qs","toString","url","opened","open","assign","fallbackResolution","rowIds","fieldId","chain","map","rowContainerId","focusFieldPath","getFields","fields","chainResult","resolved","VisualEditingBridgeProvider","children","getEntityConfig","entity","globalSlug","URL","href","focusPath","searchParams","get","delete","history","replaceState","collection","setTimeout","handle","event","data","type","current","wrongCollection","wrongDoc","undefined","addEventListener","removeEventListener"],"mappings":"AAAA;;AAEA,SAASA,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,SAAS,QAAQ,QAAQ;AAElC,SAASC,eAAe,QAAQ,kBAAkB;AAElD,SAASC,cAAc,QAAQ,sBAAsB;AACrD,SAASC,cAAc,QAAQ,sBAAsB;AACrD,SAASC,qBAAqB,QAAQ,6BAA6B;AAGnE,MAAMC,iBAAiB;AAEvB,MAAMC,cAAc,CAACC,QAA0BA,MAAMC,OAAO,CAAC,uBAAuB;AAEpF,MAAMC,eAAe,CAACC;IACpB,IAAI,OAAOC,WAAW,aAAa,OAAO;IAC1C,OAAOD,gBAAgBC,OAAOC,QAAQ,CAACC,MAAM;AAC/C;AAEA,MAAMC,eAAe,CAACC;IACpB,MAAMC,OAAOV,YAAYS;IACzB,MAAME,eAAe,IAAIC,OAAO,CAAC,CAAC,EAAEF,KAAK,8BAA8B,CAAC;IACxE,MAAMG,WAAW,IAAID,OAAO,CAAC,CAAC,EAAEF,KAAK,kBAAkB,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,IAAI,EAAE2B;gBAChE,OAAO,IAAIQ,YAAY;oBACrB,KAAKT,eAAeY,WAAW,UAAUH,YAAYR;gBACvD;YACF,GAAG;QACL;QAEA,MAAMmB,SAAS,CAACC;YACd,IAAI,CAAC7D,aAAa6D,MAAMzD,MAAM,GAAG;YACjC,MAAM0D,OAAOD,MAAMC,IAAI;YACvB,IAAI,CAACA,QAAQA,KAAKC,IAAI,KAAKvE,iBAAiB;YAE5C,wEAAwE;YACxE,wEAAwE;YACxE,sEAAsE;YACtE,+CAA+C;YAC/C,IAAIsE,KAAK1C,IAAI,KAAK,cAAc;gBAC9B,MAAM4C,UAAUrD;gBAChB,MAAMsD,kBAAkBD,SAASlD,SAASgD,KAAKzC,cAAc;gBAC7D,MAAM6C,WAAWJ,KAAKxC,KAAK,KAAK6C,aAAaH,SAASjD,OAAO+C,KAAKxC,KAAK;gBACvE,IAAI,CAAC0C,WAAWC,mBAAmBC,UAAU;oBAC3CjD,iBAAiB6C;oBACjB;gBACF;gBACA,KAAKtB,eAAesB,KAAKrC,IAAI,EAAE,cAAcqC,KAAKzC,cAAc,EAAEoB;gBAClE;YACF;YAEA,IAAIqB,KAAK1C,IAAI,KAAK,UAAU;gBAC1B,MAAMN,OAAOE;gBACb,IAAIF,SAASgD,KAAKzC,cAAc,EAAE;oBAChCJ,iBAAiB6C;oBACjB;gBACF;gBACA,KAAKtB,eAAesB,KAAKrC,IAAI,EAAE,UAAUqC,KAAKzC,cAAc,EAAEoB;YAChE;QACF;QAEAvC,OAAOkE,gBAAgB,CAAC,WAAWR;QACnC,OAAO,IAAM1D,OAAOmE,mBAAmB,CAAC,WAAWT;IACrD,GAAG;QAACb;QAAiBzC;KAAc;IAEnC,qBAAO;kBAAGwC;;AACZ"}
@@ -0,0 +1,6 @@
1
+ import type { ContainerInstruction } from "./resolveContainerChain.js";
2
+ export declare const playSweep: (el: HTMLElement) => void;
3
+ export declare const findFieldElement: (fieldId: string) => HTMLElement | null;
4
+ export declare const scrollNearestAncestorIntoView: (fieldId: string) => void;
5
+ export declare const applyContainerChain: (chain: readonly ContainerInstruction[]) => Promise<boolean>;
6
+ export declare const expandAndFocus: (chain: readonly ContainerInstruction[], fieldId: string | null) => Promise<void>;