@abinnovision/payloadcms-viewfinder 1.0.0-beta.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 abi group GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # @abinnovision/payloadcms-viewfinder
2
+
3
+ Two-way block addressing between a rendered frontend and the [Payload CMS](https://payloadcms.com/)
4
+ admin form.
5
+
6
+ Viewfinder owns addressing and transport, and nothing else. It puts a stable identifier on each
7
+ rendered block, resolves that identifier back to a path in the admin's own form state, and carries
8
+ messages between the two windows. In the preview, hovering a block outlines and names it and
9
+ clicking anywhere inside it scrolls the matching form row into view. In the admin, hovering anywhere
10
+ in a block row outlines that block in the preview, and a button in the row header scrolls the
11
+ preview to it.
12
+
13
+ Inline editing is deliberately not part of it. A visual editor needs to know which DOM node belongs
14
+ to which field before it can do anything else, and that layer is useful on its own.
15
+ [`docs/concepts.md`](./docs/concepts.md) describes the addressing model;
16
+ [`docs/limitations.md`](./docs/limitations.md) states what is out of scope and why.
17
+
18
+ Viewfinder works in any Payload app. [`@abinnovision/payloadcms-montage`](../montage) is not
19
+ required, but when it is present its `wrapBlock` registry option makes the whole block tree
20
+ addressable in one hook. See [`docs/integration.md`](./docs/integration.md) for both paths.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ yarn add @abinnovision/payloadcms-viewfinder
26
+ ```
27
+
28
+ Peers: `payload >=3.88.0 <4`, `react ^19`, `react-dom ^19`. `@payloadcms/ui` is an optional peer,
29
+ needed only by the `./admin` entrypoint.
30
+
31
+ ## Setup
32
+
33
+ Add the plugin in `payload.config.ts`. It mounts the admin half of the bridge inside the document
34
+ form of the collections and globals you name, defaulting to all of them:
35
+
36
+ ```ts
37
+ // payload.config.ts
38
+ import { viewfinderPlugin } from "@abinnovision/payloadcms-viewfinder/config";
39
+ import { buildConfig } from "payload";
40
+
41
+ export default buildConfig({
42
+ // ...
43
+ plugins: [viewfinderPlugin({ collections: ["pages"] })],
44
+ });
45
+ ```
46
+
47
+ Then run `payload generate:importmap`, as for any plugin that contributes admin components. Payload
48
+ resolves the bridge by import path, so it has to be in the generated map.
49
+
50
+ Configure live preview on the collection. It must be server-side live preview, which is the shape
51
+ Payload gives you by setting `admin.livePreview.url`: the iframe loads the real route, and a
52
+ `RefreshRouteOnSave` in the frontend re-renders it on the server after each save:
53
+
54
+ ```ts
55
+ // collections/pages.ts
56
+ export const pages: CollectionConfig = {
57
+ slug: "pages",
58
+ admin: {
59
+ livePreview: {
60
+ url: ({ data }) => `/preview?path=/${String(data["slug"] ?? "")}`,
61
+ },
62
+ },
63
+ // ...
64
+ };
65
+ ```
66
+
67
+ Mount the frontend bridge once, near the root of the app. `adminOrigin` is required rather than
68
+ defaulting to `"*"`, because this window posts the ids of everything it renders:
69
+
70
+ ```tsx
71
+ // app/layout.tsx
72
+ import { ViewfinderBridge } from "@abinnovision/payloadcms-viewfinder/client";
73
+
74
+ const Layout = ({ children }: { children: React.ReactNode }) => (
75
+ <html lang="en">
76
+ <body>
77
+ {children}
78
+ <ViewfinderBridge adminOrigin="http://localhost:3000" />
79
+ </body>
80
+ </html>
81
+ );
82
+ ```
83
+
84
+ The bridge does nothing when the page is not framed, so the same tree can be served to real
85
+ visitors without a second code path. Inside the preview it outlines the block under the pointer and
86
+ names it, and a click anywhere inside that block selects it. The whole block is the target, so a
87
+ plain click on a link inside a marked block selects rather than navigates while the page is framed.
88
+ Modified and secondary clicks are left alone, so an editor can still open a link in a new tab.
89
+
90
+ Finally, mark the blocks. Wrap each one in `<Marked>`, passing the Payload row `id` and your own
91
+ preview flag:
92
+
93
+ ```tsx
94
+ import { Marked } from "@abinnovision/payloadcms-viewfinder/client";
95
+
96
+ <Marked id={block.id} blockType={block.blockType} enabled={isPreview}>
97
+ <HeroModule block={block} />
98
+ </Marked>;
99
+ ```
100
+
101
+ With `enabled={false}` the children render untouched, with no wrapper and no attributes, so
102
+ production output is unaffected by having viewfinder installed.
103
+
104
+ `Marked` adds nothing to the tree when its child is a DOM element: the attributes go onto that
105
+ element. Only a component element, a fragment, an array, text or a promise gets a
106
+ `display: contents` wrapper, since a component may not forward unknown props to any DOM node. A
107
+ block can settle it either way by spreading `markBlock()` onto its own element:
108
+
109
+ ```tsx
110
+ import {
111
+ markBlock,
112
+ markField,
113
+ } from "@abinnovision/payloadcms-viewfinder/client";
114
+
115
+ <section {...markBlock(block.id, block.blockType)}>
116
+ <h2 {...markField("heading")}>{block.heading}</h2>
117
+ </section>;
118
+ ```
119
+
120
+ `markField` is optional and opt-in. Its argument is relative to the enclosing block (`"heading"`,
121
+ or `"items.0.label"` for something nested), never an absolute document path, which is what lets the
122
+ address survive the block moving to a different index.
123
+
124
+ ## Entrypoints
125
+
126
+ ```
127
+ "." attributes, protocol, path resolution. Imports nothing.
128
+ "./client" ViewfinderBridge, Marked, markBlock, markField
129
+ "./config" viewfinderPlugin, loaded from payload.config.ts
130
+ "./admin" ViewfinderFormBridge, mounted by the plugin through the import map
131
+ ```
132
+
133
+ `.` is shared by the frontend bundle and the admin bundle, so it imports nothing at all: no React,
134
+ no Payload, no Next. `./config` is loaded by the CLI, by migrations and by `generate:types`, so it
135
+ must stay React-free. [`docs/concepts.md`](./docs/concepts.md) covers why each boundary is where it
136
+ is.
137
+
138
+ ## Documentation
139
+
140
+ - [`docs/concepts.md`](./docs/concepts.md): the addressing model, the entrypoint boundaries, and
141
+ the scope of the package.
142
+ - [`docs/integration.md`](./docs/integration.md): wiring it up, standalone and with montage,
143
+ including the live-preview requirement.
144
+ - [`docs/limitations.md`](./docs/limitations.md): what viewfinder does not do, and why.
145
+
146
+ ## License
147
+
148
+ Apache-2.0
@@ -0,0 +1,19 @@
1
+ import { ReactNode } from "react";
2
+ //#region src/admin/bridge.d.ts
3
+ /**
4
+ * Connects the admin form to the page it is previewing. Mounted inside the
5
+ * document form by `viewfinderPlugin`, and inert until a framed page
6
+ * announces itself.
7
+ *
8
+ * A `select` from the preview reveals the matching form row. In the other
9
+ * direction, hovering anywhere in a block row outlines that block in the
10
+ * preview without moving it, and the locate button in the row's controls
11
+ * scrolls the preview to it.
12
+ *
13
+ * Only the button scrolls. Driving the scroll from focus or from an ordinary
14
+ * click, as an earlier version did, moved the preview while an editor was
15
+ * merely placing a caret.
16
+ */
17
+ declare const ViewfinderFormBridge: () => ReactNode;
18
+ //#endregion
19
+ export { ViewfinderFormBridge };
@@ -0,0 +1,111 @@
1
+ "use client";
2
+ import { adminMessage, isPreviewMessage } from "../protocol.mjs";
3
+ import { resolveAddressForPath, resolveAddressPath } from "../resolve-path.mjs";
4
+ import { revealPath } from "./reveal.mjs";
5
+ import { RowButton } from "./row-button.mjs";
6
+ import { blockPaths, findRows, rowControls, rowPathAt, sameRows } from "./rows.mjs";
7
+ import { Fragment, jsx } from "react/jsx-runtime";
8
+ import { useEffect, useMemo, useRef, useState } from "react";
9
+ import { createPortal } from "react-dom";
10
+ import { useAllFormFields } from "@payloadcms/ui";
11
+ //#region src/admin/bridge.tsx
12
+ /** Payload renders exactly one live-preview iframe, with this id. */ const PREVIEW_IFRAME_ID = "live-preview-iframe";
13
+ /** Long enough to coalesce a burst of admin re-renders, short enough to feel instant. */ const RESCAN_MS = 50;
14
+ const previewIframe = () => document.getElementById(PREVIEW_IFRAME_ID);
15
+ /**
16
+ * Posts into the preview frame, addressed to the origin that frame is
17
+ * actually on. Resolves the iframe per call rather than holding a reference:
18
+ * the admin mounts and unmounts it as the editor toggles live preview.
19
+ */ const post = (message) => {
20
+ const iframe = previewIframe();
21
+ const target = iframe?.contentWindow;
22
+ if (!iframe || !target) return;
23
+ target.postMessage(message, new URL(iframe.src, location.href).origin);
24
+ };
25
+ /**
26
+ * Connects the admin form to the page it is previewing. Mounted inside the
27
+ * document form by `viewfinderPlugin`, and inert until a framed page
28
+ * announces itself.
29
+ *
30
+ * A `select` from the preview reveals the matching form row. In the other
31
+ * direction, hovering anywhere in a block row outlines that block in the
32
+ * preview without moving it, and the locate button in the row's controls
33
+ * scrolls the preview to it.
34
+ *
35
+ * Only the button scrolls. Driving the scroll from focus or from an ordinary
36
+ * click, as an earlier version did, moved the preview while an editor was
37
+ * merely placing a caret.
38
+ */ const ViewfinderFormBridge = () => {
39
+ const [fields] = useAllFormFields();
40
+ const [rows, setRows] = useState(/* @__PURE__ */ new Map());
41
+ const formState = useRef(fields);
42
+ formState.current = fields;
43
+ const rowPaths = useRef(/* @__PURE__ */ new Map());
44
+ rowPaths.current = useMemo(() => new Map([...rows].map(([path, row]) => [row, path])), [rows]);
45
+ const pathsKey = useMemo(() => blockPaths(fields).join("|"), [fields]);
46
+ useEffect(() => {
47
+ const onMessage = (event) => {
48
+ if (event.source !== previewIframe()?.contentWindow) return;
49
+ if (!isPreviewMessage(event.data) || event.data.type !== "select") return;
50
+ const path = resolveAddressPath(formState.current, event.data.address);
51
+ if (path !== void 0) revealPath(document, path);
52
+ };
53
+ window.addEventListener("message", onMessage);
54
+ return () => {
55
+ window.removeEventListener("message", onMessage);
56
+ };
57
+ }, []);
58
+ useEffect(() => {
59
+ let timer = 0;
60
+ const rescan = () => {
61
+ const next = previewIframe() ? findRows(document, formState.current) : /* @__PURE__ */ new Map();
62
+ setRows((previous) => sameRows(previous, next) ? previous : next);
63
+ };
64
+ rescan();
65
+ const observer = new MutationObserver(() => {
66
+ window.clearTimeout(timer);
67
+ timer = window.setTimeout(rescan, RESCAN_MS);
68
+ });
69
+ observer.observe(document.body, {
70
+ childList: true,
71
+ subtree: true
72
+ });
73
+ return () => {
74
+ observer.disconnect();
75
+ window.clearTimeout(timer);
76
+ };
77
+ }, [pathsKey]);
78
+ useEffect(() => {
79
+ let hovered;
80
+ const highlight = (path) => {
81
+ if (path === hovered) return;
82
+ hovered = path;
83
+ const address = path === void 0 ? void 0 : resolveAddressForPath(formState.current, path);
84
+ post(address ? adminMessage.highlight(address) : adminMessage.clear());
85
+ };
86
+ const onPointerOver = (event) => {
87
+ highlight(rowPathAt(rowPaths.current, event.target));
88
+ };
89
+ const onPointerLeave = () => {
90
+ highlight(void 0);
91
+ };
92
+ document.addEventListener("pointerover", onPointerOver, { passive: true });
93
+ document.addEventListener("pointerleave", onPointerLeave, { passive: true });
94
+ return () => {
95
+ document.removeEventListener("pointerover", onPointerOver);
96
+ document.removeEventListener("pointerleave", onPointerLeave);
97
+ };
98
+ }, []);
99
+ return /*#__PURE__*/ jsx(Fragment, { children: [...rows].map(([path, row]) => {
100
+ const controls = rowControls(row);
101
+ return controls === null ? null : /*#__PURE__*/ createPortal(/*#__PURE__*/ jsx(RowButton, {
102
+ label: "Scroll the preview to this block",
103
+ onSelect: () => {
104
+ const address = resolveAddressForPath(formState.current, path);
105
+ if (address) post(adminMessage.scrollTo(address));
106
+ }
107
+ }), controls, path);
108
+ }) });
109
+ };
110
+ //#endregion
111
+ export { ViewfinderFormBridge };
@@ -0,0 +1,48 @@
1
+ //#region src/admin/element-id.ts
2
+ /**
3
+ * The second place this package leans on Payload internals, kept separate
4
+ * from `resolve-path.ts` because these are DOM conventions of the admin
5
+ * bundle rather than form-state conventions.
6
+ *
7
+ * Payload renders a field wrapper as `id="field-<path with dots as __>"`
8
+ * (every module under `@payloadcms/ui/fields`) and a block row as
9
+ * `id="<parent path with dots as ->-row-<index>"` (`fields/Blocks/BlockRow`).
10
+ */ const FIELD_PREFIX = "field-";
11
+ /** DOM id of the wrapper Payload renders for a field path. */ const fieldElementId = (path) => `${FIELD_PREFIX}${path.split(".").join("__")}`;
12
+ /**
13
+ * DOM id of the block row at a path, or undefined for a path that is not
14
+ * shaped like a row (no trailing numeric index).
15
+ */ const blockRowElementId = (path) => {
16
+ const segments = path.split(".");
17
+ const index = segments.pop();
18
+ if (index === void 0 || !/^\d+$/.test(index) || segments.length === 0) return;
19
+ return `${segments.join("-")}-row-${index}`;
20
+ };
21
+ /**
22
+ * The DOM ids worth trying for a resolved path, most specific first.
23
+ *
24
+ * A block path resolves to a row, but a field path inside it resolves to the
25
+ * field wrapper — and a field that is itself a blocks or array field has
26
+ * both. Callers take the first that exists.
27
+ */ const candidateElementIds = (path) => {
28
+ const row = blockRowElementId(path);
29
+ return row === void 0 ? [fieldElementId(path)] : [row, fieldElementId(path)];
30
+ };
31
+ /**
32
+ * The block-row paths along a form path, outermost first.
33
+ *
34
+ * `layout.1.modules.0.title` yields `["layout.1", "layout.1.modules.0"]`: a
35
+ * row is any prefix ending in an index. Used to expand a path's ancestors in
36
+ * order, since a collapsed row renders none of its contents and the deeper
37
+ * rows therefore do not exist yet.
38
+ */ const rowPathsAlong = (path) => {
39
+ const segments = path.split(".");
40
+ const paths = [];
41
+ for (let end = 1; end <= segments.length; end++) {
42
+ const last = segments[end - 1];
43
+ if (last !== void 0 && /^\d+$/.test(last) && end > 1) paths.push(segments.slice(0, end).join("."));
44
+ }
45
+ return paths;
46
+ };
47
+ //#endregion
48
+ export { blockRowElementId, candidateElementIds, fieldElementId, rowPathsAlong };
@@ -0,0 +1,2 @@
1
+ import { ViewfinderFormBridge } from "./bridge.mjs";
2
+ export { ViewfinderFormBridge };
@@ -0,0 +1,3 @@
1
+ "use client";
2
+ import { ViewfinderFormBridge } from "./bridge.mjs";
3
+ export { ViewfinderFormBridge };
@@ -0,0 +1,108 @@
1
+ import { blockRowElementId, candidateElementIds, rowPathsAlong } from "./element-id.mjs";
2
+ //#region src/admin/reveal.ts
3
+ const COLLAPSED_TOGGLE = `button.collapsible__toggle--collapsed`;
4
+ const COLLAPSIBLE = ".collapsible";
5
+ const COLLAPSED = ".collapsible--collapsed";
6
+ const FLASH_MS = 1200;
7
+ const FLASH_COLOR = "var(--theme-elevation-800)";
8
+ const WAIT_ATTEMPTS = 60;
9
+ const POLL_MS = 16;
10
+ const wait = async (view, ms) => {
11
+ await new Promise((resolve) => {
12
+ view.setTimeout(resolve, ms);
13
+ });
14
+ };
15
+ /**
16
+ * Waits for one of `ids` to appear, since expanding a row re-renders and the
17
+ * element does not exist on the tick the click was dispatched. Gives it about
18
+ * a second: Payload's own lazy field rendering sits between the expand and
19
+ * the element showing up.
20
+ *
21
+ * Polls on a timer rather than on animation frames: the admin tab can be
22
+ * backgrounded (or throttled) while the editor works elsewhere, and
23
+ * `requestAnimationFrame` stops firing there, which would hang the reveal.
24
+ */ const waitForElement = async (doc, ids) => {
25
+ const view = doc.defaultView;
26
+ for (let attempt = 0; attempt < WAIT_ATTEMPTS; attempt++) {
27
+ for (const id of ids) {
28
+ const element = doc.getElementById(id);
29
+ if (element) return element;
30
+ }
31
+ if (!view) return null;
32
+ await wait(view, POLL_MS);
33
+ }
34
+ return null;
35
+ };
36
+ /**
37
+ * Clicks a row's own toggle if it is collapsed.
38
+ *
39
+ * Payload puts the row id on a bare wrapper whose only child is the
40
+ * collapsible, so the row element is not itself `.collapsible`. Resolving
41
+ * that child first is what keeps this from clicking a nested row's toggle:
42
+ * only a toggle whose own collapsible is this one counts.
43
+ */ const expandRow = (row) => {
44
+ const collapsible = row.querySelector(`:scope > ${COLLAPSIBLE}`);
45
+ if (!collapsible?.matches(COLLAPSED)) return;
46
+ for (const toggle of collapsible.querySelectorAll(COLLAPSED_TOGGLE)) if (toggle.closest(COLLAPSIBLE) === collapsible) {
47
+ toggle.click();
48
+ return;
49
+ }
50
+ };
51
+ /**
52
+ * Marks the target briefly so the eye can find it after the scroll.
53
+ *
54
+ * Darkens the row's own border rather than drawing an outline around it.
55
+ * Payload already gives a row a border, and an outline sits outside that, so
56
+ * it reads as a second box drawn around the row instead of as the row being
57
+ * picked out. The colour is Payload's, so it follows the theme.
58
+ *
59
+ * A field wrapper has no border to darken, so that case keeps an outline, in
60
+ * the same colour.
61
+ */ const flash = (element) => {
62
+ const view = element.ownerDocument.defaultView;
63
+ if (!view) return;
64
+ const bordered = element.querySelector(`:scope > ${COLLAPSIBLE}`) ?? element;
65
+ if (view.getComputedStyle(bordered).borderTopWidth === "0px") {
66
+ const previous = element.style.outline;
67
+ element.style.outline = `2px solid ${FLASH_COLOR}`;
68
+ view.setTimeout(() => {
69
+ element.style.outline = previous;
70
+ }, FLASH_MS);
71
+ return;
72
+ }
73
+ const previous = bordered.style.borderColor;
74
+ bordered.style.borderColor = FLASH_COLOR;
75
+ view.setTimeout(() => {
76
+ bordered.style.borderColor = previous;
77
+ }, FLASH_MS);
78
+ };
79
+ /**
80
+ * Brings the field or block row at `path` into view: expands whatever is
81
+ * collapsed around it, scrolls to it, and marks it briefly so the eye can
82
+ * find it after the scroll.
83
+ *
84
+ * Driven by the path rather than by walking up from the target, because a
85
+ * collapsed row renders none of its contents: until its ancestors are open,
86
+ * the element this is meant to reveal is not in the document to walk up from.
87
+ * Each ancestor is expanded in turn and awaited before the next is looked up.
88
+ */ const revealPath = async (doc, path) => {
89
+ for (const rowPath of rowPathsAlong(path)) {
90
+ const id = blockRowElementId(rowPath);
91
+ if (id === void 0) continue;
92
+ const row = await waitForElement(doc, [id]);
93
+ if (row) {
94
+ expandRow(row);
95
+ row.scrollIntoView({ block: "center" });
96
+ }
97
+ }
98
+ const target = await waitForElement(doc, candidateElementIds(path));
99
+ if (!target) return null;
100
+ target.scrollIntoView({
101
+ behavior: "smooth",
102
+ block: "center"
103
+ });
104
+ flash(target);
105
+ return target;
106
+ };
107
+ //#endregion
108
+ export { revealPath };