@derweili/payload-visual-editing 0.0.0-stage → 0.1.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 (52) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +142 -2
  4. package/dist/client/VisualEditingAdmin.d.ts +9 -0
  5. package/dist/client/VisualEditingAdmin.d.ts.map +1 -0
  6. package/dist/client/VisualEditingAdmin.js +109 -0
  7. package/dist/client/VisualEditingAdmin.js.map +1 -0
  8. package/dist/client/dom-adapter.d.ts +61 -0
  9. package/dist/client/dom-adapter.d.ts.map +1 -0
  10. package/dist/client/dom-adapter.js +177 -0
  11. package/dist/client/dom-adapter.js.map +1 -0
  12. package/dist/client/focus.d.ts +36 -0
  13. package/dist/client/focus.d.ts.map +1 -0
  14. package/dist/client/focus.js +61 -0
  15. package/dist/client/focus.js.map +1 -0
  16. package/dist/client/index.d.ts +6 -0
  17. package/dist/client/index.d.ts.map +1 -0
  18. package/dist/client/index.js +7 -0
  19. package/dist/client/index.js.map +1 -0
  20. package/dist/client/keep-in-view.d.ts +6 -0
  21. package/dist/client/keep-in-view.d.ts.map +1 -0
  22. package/dist/client/keep-in-view.js +78 -0
  23. package/dist/client/keep-in-view.js.map +1 -0
  24. package/dist/client/resolve-focus.d.ts +56 -0
  25. package/dist/client/resolve-focus.d.ts.map +1 -0
  26. package/dist/client/resolve-focus.js +138 -0
  27. package/dist/client/resolve-focus.js.map +1 -0
  28. package/dist/server/encode-document.d.ts +23 -0
  29. package/dist/server/encode-document.d.ts.map +1 -0
  30. package/dist/server/encode-document.js +147 -0
  31. package/dist/server/encode-document.js.map +1 -0
  32. package/dist/server/hooks.d.ts +17 -0
  33. package/dist/server/hooks.d.ts.map +1 -0
  34. package/dist/server/hooks.js +79 -0
  35. package/dist/server/hooks.js.map +1 -0
  36. package/dist/server/index.d.ts +10 -0
  37. package/dist/server/index.d.ts.map +1 -0
  38. package/dist/server/index.js +10 -0
  39. package/dist/server/index.js.map +1 -0
  40. package/dist/server/options.d.ts +58 -0
  41. package/dist/server/options.d.ts.map +1 -0
  42. package/dist/server/options.js +18 -0
  43. package/dist/server/options.js.map +1 -0
  44. package/dist/server/path-matcher.d.ts +8 -0
  45. package/dist/server/path-matcher.d.ts.map +1 -0
  46. package/dist/server/path-matcher.js +32 -0
  47. package/dist/server/path-matcher.js.map +1 -0
  48. package/dist/server/plugin.d.ts +13 -0
  49. package/dist/server/plugin.d.ts.map +1 -0
  50. package/dist/server/plugin.js +102 -0
  51. package/dist/server/plugin.js.map +1 -0
  52. package/package.json +74 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @derweili/payload-visual-editing
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Julian Weiland
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # @derweili/payload-visual-editing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Payload 3 plugin for visual editing:
4
+
5
+ - **`/server`:** encodes an invisible source map into every text value of draft reads (text,
6
+ textarea, Lexical), and tags images, numbers and other values that can't hold hidden text.
7
+ - **`/client`:** an admin component that focuses a field from a `?field=` link or from a click in
8
+ the Live Preview. It opens the tab, expands the row, scrolls the field to the centre, focuses it
9
+ and highlights it.
10
+
11
+ Use it with [`@derweili/payload-visual-editing-overlay`](../visual-editing-overlay) on the
12
+ frontend. Overview: [README](../../README.md).
13
+
14
+ ## Setup
15
+
16
+ ```ts
17
+ // payload.config.ts
18
+ import { visualEditingPlugin } from '@derweili/payload-visual-editing/server'
19
+
20
+ export default buildConfig({
21
+ // …
22
+ plugins: [
23
+ visualEditingPlugin({
24
+ collections: ['pages', 'posts'],
25
+ globals: ['header'],
26
+ }),
27
+ ],
28
+ })
29
+ ```
30
+
31
+ Then run `payload generate:importmap`, so the admin can load the component.
32
+
33
+ ### Reading with source maps
34
+
35
+ Encoding is off unless a request asks for it, and only draft/preview reads should ask:
36
+
37
+ ```ts
38
+ // Local API (server code: always allowed)
39
+ const page = await payload.findByID({
40
+ collection: 'pages',
41
+ id,
42
+ draft: true,
43
+ context: { encodeSourceMaps: true },
44
+ })
45
+ ```
46
+
47
+ ```http
48
+ GET /api/pages/1?draft=true&encodeSourceMaps=true
49
+ ```
50
+
51
+ The REST parameter only works for GET requests, and by default only for logged-in users (see
52
+ `canEncode`).
53
+
54
+ **Never cache encoded reads.** A cache entry with hidden characters could later be served on the
55
+ live site. Skip `unstable_cache`/`"use cache"` in Draft Mode, or include the draft state in the
56
+ cache key.
57
+
58
+ Writes are safe: the plugin strips encoded characters before validation, so text copied from the
59
+ preview back into the admin is saved clean.
60
+
61
+ ## Options
62
+
63
+ ```ts
64
+ visualEditingPlugin({
65
+ enabled?: boolean // default true; false leaves the config untouched
66
+ collections?: string[] // collections with source maps and field focusing (default: none)
67
+ globals?: string[] // globals with source maps and field focusing (default: none)
68
+ focusFields?: boolean // default true; adds the admin component to their edit views
69
+ sourceMaps?: {
70
+ enabled?: boolean // default true; false removes the encoding hooks
71
+ canEncode?: ({ req }) => boolean | Promise<boolean>
72
+ // who may use ?encodeSourceMaps=true (default: logged-in users);
73
+ // the Local API context flag is always trusted
74
+ skip?: 'auto' | boolean // default 'auto': leaves URL- and date-like strings unencoded;
75
+ // false encodes every string, true none
76
+ include?: string[] // only encode these paths (default: all)
77
+ exclude?: string[] // never encode these paths (default: ['slug', 'url'])
78
+ },
79
+ })
80
+ ```
81
+
82
+ Path patterns match the data path without array indices (`team.links.label`). `*` is one segment
83
+ and `**` any number of segments; a pattern without a dot matches a field name at any depth
84
+ (`'url'` matches `links.url`). Setting `exclude` replaces the defaults, so add `...DEFAULT_EXCLUDE`
85
+ if you still want them. Fields named `id` are never encoded.
86
+
87
+ Exclude every text field that feeds logic rather than display: slugs, URLs, link targets, CSS
88
+ values, enum-like text, anything compared or parsed. Excluded and skipped fields still get a source
89
+ tag, so they stay clickable through `fieldAttrs`.
90
+
91
+ ## What gets encoded
92
+
93
+ | Field | In the data |
94
+ | --- | --- |
95
+ | text, textarea | hidden ref appended to the string |
96
+ | richText (Lexical) | every text node; the ref points at the field (`body`), not the node |
97
+ | upload, relationship (populated) | the related document is tagged (`sourceOf(doc.image)`). Its own fields are encoded with its own ref if its collection is in scope |
98
+ | number, date, select, radio, checkbox, point, excluded/skipped text | tagged on the parent (`fieldSourceOf(doc, 'year')`) |
99
+ | arrays, blocks, groups, named tabs | walked; paths include indices (`team.1.links.0.label`) |
100
+ | ids, `blockType`, virtual fields | untouched |
101
+
102
+ With `locale: 'all'`, each locale's value gets a ref with its own locale.
103
+
104
+ Source tags use symbol keys. They are invisible to JSON and REST, and lost on serialization, so
105
+ read them on the server; see the overlay README.
106
+
107
+ ## Admin: focusing fields
108
+
109
+ - **Deep link:** `/admin/collections/pages/1?field=team.1.links.0.label&locale=en`. The overlay
110
+ builds these links. `locale` is Payload's own locale switch.
111
+ - **Live Preview:** the overlay inside the preview iframe asks the admin (`pve:ready`). If the admin
112
+ answers, a click sends `pve:focus` and the admin focuses the field in the same tab. A field of
113
+ another document or locale navigates there. Without an answer within 500 ms, the overlay opens
114
+ the link in a new tab. Messages are accepted only from the view's own preview iframe or popup.
115
+ - Focus waits until Payload has loaded the form. It opens tabs by clicking the tab button and
116
+ expands collapsed array/block rows through Payload's form state, the same way an editor would.
117
+ It keeps the field centred while lazy content above it still loads, and stops at the first
118
+ scroll, click or key press.
119
+
120
+ All access to Payload's admin markup sits in one module (`src/client/dom-adapter.ts`).
121
+ `test/payload-markup.test.ts` fails when an installed Payload version no longer renders what it
122
+ relies on. When markup does change, focusing stops working silently; it never throws.
123
+
124
+ ## Known limitations
125
+
126
+ - **Long forms: fields far down are reached by scrolling (workaround).** Payload renders each list
127
+ of fields only once it comes within 1000 px of the viewport, and has no API to force it. When the
128
+ target field doesn't exist yet, the admin first scrolls the nearest rendered parent field into
129
+ view. If that isn't enough, it scrolls down one screen at a time until the field appears (each
130
+ step waits for the DOM to change; it gives up after 3 s or at the end of the page). On very
131
+ long forms this shows as a short jump before the smooth scroll to the field. It relies on
132
+ Payload's current rendering behaviour; if Payload adds an API to render a field on demand,
133
+ replace it. See [ADR 0001](../../docs/adr/0001-payload-visual-editing.md), section 12.
134
+ - **Tabs inside array/block rows** can't be located (rows have React-generated ids). The field is
135
+ focused only if its tab is already open.
136
+ - **Collapsibles that start collapsed** (`admin.initCollapsed`) aren't opened. Payload reads their
137
+ state once, on mount.
138
+ - **Uploads** have no input; the field's edit button gets the focus.
139
+
140
+ ## Cloudflare Workers
141
+
142
+ The server entry uses no Node-only APIs (fs, path, child_process). The test suite runs on Payload's
143
+ D1 adapter with an in-memory Miniflare D1.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Mounted in every edit view of the plugin's collections and globals (`beforeDocumentControls`).
3
+ * - Deep link: `?field=<path>` focuses that field (`&locale=` is Payload's own locale switch).
4
+ * - Live Preview: answers the overlay's `pve:ready`, and on `pve:focus` focuses the field, or
5
+ * opens the other document. Only messages from this view's preview iframe/popup are accepted.
6
+ * Renders nothing.
7
+ */
8
+ export declare function VisualEditingAdmin(): null;
9
+ //# sourceMappingURL=VisualEditingAdmin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VisualEditingAdmin.d.ts","sourceRoot":"","sources":["../../src/client/VisualEditingAdmin.tsx"],"names":[],"mappings":"AAiCA;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAkEzC"}
@@ -0,0 +1,109 @@
1
+ 'use client';
2
+ import { buildAdminUrl, createReadyMessage, decodeRef, FIELD_PARAM, isFocusMessage, isReadyMessage } from '@derweili/payload-visual-editing-core';
3
+ import { useConfig, useDocumentInfo, useForm, useFormInitializing, useLivePreviewContext, useLocale } from '@payloadcms/ui';
4
+ import { useRouter, useSearchParams } from 'next/navigation';
5
+ import { useCallback, useEffect, useRef } from 'react';
6
+ import { blockTypeOf, runFocusPlan } from "./focus.js";
7
+ import { resolveFocus } from "./resolve-focus.js";
8
+ /** Origin of a window's URL, or null when it can't be read. */ const originOf = (url)=>{
9
+ try {
10
+ return url ? new URL(url, window.location.href).origin : null;
11
+ } catch {
12
+ return null;
13
+ }
14
+ };
15
+ /**
16
+ * Mounted in every edit view of the plugin's collections and globals (`beforeDocumentControls`).
17
+ * - Deep link: `?field=<path>` focuses that field (`&locale=` is Payload's own locale switch).
18
+ * - Live Preview: answers the overlay's `pve:ready`, and on `pve:focus` focuses the field, or
19
+ * opens the other document. Only messages from this view's preview iframe/popup are accepted.
20
+ * Renders nothing.
21
+ */ export function VisualEditingAdmin() {
22
+ const { config, getEntityConfig } = useConfig();
23
+ const { collectionSlug, globalSlug, id, setDocFieldPreferences } = useDocumentInfo();
24
+ const { getField, dispatchFields } = useForm();
25
+ // Payload renders the fields disabled until the form state has loaded; focus() is ignored then
26
+ const initializing = useFormInitializing();
27
+ const { iframeRef, popupRef } = useLivePreviewContext();
28
+ const locale = useLocale();
29
+ const router = useRouter();
30
+ const searchParams = useSearchParams();
31
+ const adminRoute = config.routes.admin;
32
+ const focus = useCallback(async (path)=>{
33
+ const entity = collectionSlug ? getEntityConfig({
34
+ collectionSlug
35
+ }) : getEntityConfig({
36
+ globalSlug
37
+ });
38
+ if (!entity) return false;
39
+ const api = {
40
+ getField,
41
+ dispatchFields,
42
+ setDocFieldPreferences
43
+ };
44
+ const plan = resolveFocus(entity.fields, path, {
45
+ blocksMap: config.blocksMap,
46
+ getBlockType: (rowPath)=>blockTypeOf(api, rowPath)
47
+ });
48
+ return plan ? runFocusPlan(plan, api) : false;
49
+ }, [
50
+ collectionSlug,
51
+ globalSlug,
52
+ getEntityConfig,
53
+ getField,
54
+ dispatchFields,
55
+ setDocFieldPreferences,
56
+ config.blocksMap
57
+ ]);
58
+ // Deep link: once per `?field=` value (not again on every re-render), once the form is ready
59
+ const field = searchParams?.get(FIELD_PARAM);
60
+ const focusedFor = useRef(null);
61
+ useEffect(()=>{
62
+ if (!field || initializing || focusedFor.current === field) return;
63
+ focusedFor.current = field;
64
+ void focus(field);
65
+ }, [
66
+ field,
67
+ initializing,
68
+ focus
69
+ ]);
70
+ // Live Preview
71
+ useEffect(()=>{
72
+ const onMessage = (event)=>{
73
+ const iframe = iframeRef?.current;
74
+ const preview = iframe?.contentWindow ?? null;
75
+ const popup = popupRef?.current ?? null;
76
+ if (!event.source || event.source !== preview && event.source !== popup) return;
77
+ if (event.source === preview && event.origin !== originOf(iframe?.src)) return;
78
+ const source = event.source;
79
+ if (isReadyMessage(event.data)) {
80
+ source.postMessage(createReadyMessage(), event.origin);
81
+ return;
82
+ }
83
+ if (!isFocusMessage(event.data)) return;
84
+ const target = decodeRef(event.data.ref);
85
+ if (!target) return;
86
+ const sameDocument = 'global' in target && target.global ? target.global === globalSlug : target.collection === collectionSlug && String(target.id) === String(id);
87
+ const sameLocale = !target.locale || target.locale === locale?.code;
88
+ if (sameDocument && sameLocale) void focus(target.path);
89
+ else router.push(buildAdminUrl(target, {
90
+ adminRoute
91
+ }));
92
+ };
93
+ window.addEventListener('message', onMessage);
94
+ return ()=>window.removeEventListener('message', onMessage);
95
+ }, [
96
+ iframeRef,
97
+ popupRef,
98
+ collectionSlug,
99
+ globalSlug,
100
+ id,
101
+ locale?.code,
102
+ focus,
103
+ router,
104
+ adminRoute
105
+ ]);
106
+ return null;
107
+ }
108
+
109
+ //# sourceMappingURL=VisualEditingAdmin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/VisualEditingAdmin.tsx"],"sourcesContent":["'use client'\n\nimport {\n buildAdminUrl,\n createReadyMessage,\n decodeRef,\n FIELD_PARAM,\n isFocusMessage,\n isReadyMessage,\n} from '@derweili/payload-visual-editing-core'\nimport {\n useConfig,\n useDocumentInfo,\n useForm,\n useFormInitializing,\n useLivePreviewContext,\n useLocale,\n} from '@payloadcms/ui'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useCallback, useEffect, useRef } from 'react'\n\nimport { blockTypeOf, runFocusPlan, type FocusApi } from './focus.ts'\nimport { resolveFocus, type FieldLike } from './resolve-focus.ts'\n\n/** Origin of a window's URL, or null when it can't be read. */\nconst originOf = (url: string | undefined) => {\n try {\n return url ? new URL(url, window.location.href).origin : null\n } catch {\n return null\n }\n}\n\n/**\n * Mounted in every edit view of the plugin's collections and globals (`beforeDocumentControls`).\n * - Deep link: `?field=<path>` focuses that field (`&locale=` is Payload's own locale switch).\n * - Live Preview: answers the overlay's `pve:ready`, and on `pve:focus` focuses the field, or\n * opens the other document. Only messages from this view's preview iframe/popup are accepted.\n * Renders nothing.\n */\nexport function VisualEditingAdmin(): null {\n const { config, getEntityConfig } = useConfig()\n const { collectionSlug, globalSlug, id, setDocFieldPreferences } = useDocumentInfo()\n const { getField, dispatchFields } = useForm()\n // Payload renders the fields disabled until the form state has loaded; focus() is ignored then\n const initializing = useFormInitializing()\n const { iframeRef, popupRef } = useLivePreviewContext()\n const locale = useLocale()\n const router = useRouter()\n const searchParams = useSearchParams()\n const adminRoute = config.routes.admin\n\n const focus = useCallback(\n async (path: string) => {\n const entity = collectionSlug ? getEntityConfig({ collectionSlug }) : getEntityConfig({ globalSlug })\n if (!entity) return false\n const api: FocusApi = { getField, dispatchFields, setDocFieldPreferences } as unknown as FocusApi\n const plan = resolveFocus(entity.fields as unknown as FieldLike[], path, {\n blocksMap: config.blocksMap as unknown as Record<string, { slug: string; fields: FieldLike[] }>,\n getBlockType: (rowPath) => blockTypeOf(api, rowPath),\n })\n return plan ? runFocusPlan(plan, api) : false\n },\n [collectionSlug, globalSlug, getEntityConfig, getField, dispatchFields, setDocFieldPreferences, config.blocksMap],\n )\n\n // Deep link: once per `?field=` value (not again on every re-render), once the form is ready\n const field = searchParams?.get(FIELD_PARAM)\n const focusedFor = useRef<string | null>(null)\n useEffect(() => {\n if (!field || initializing || focusedFor.current === field) return\n focusedFor.current = field\n void focus(field)\n }, [field, initializing, focus])\n\n // Live Preview\n useEffect(() => {\n const onMessage = (event: MessageEvent) => {\n const iframe = iframeRef?.current\n const preview = iframe?.contentWindow ?? null\n const popup = popupRef?.current ?? null\n if (!event.source || (event.source !== preview && event.source !== popup)) return\n if (event.source === preview && event.origin !== originOf(iframe?.src)) return\n\n const source = event.source as Window\n if (isReadyMessage(event.data)) {\n source.postMessage(createReadyMessage(), event.origin)\n return\n }\n if (!isFocusMessage(event.data)) return\n const target = decodeRef(event.data.ref)\n if (!target) return\n\n const sameDocument =\n 'global' in target && target.global\n ? target.global === globalSlug\n : target.collection === collectionSlug && String(target.id) === String(id)\n const sameLocale = !target.locale || target.locale === locale?.code\n if (sameDocument && sameLocale) void focus(target.path)\n else router.push(buildAdminUrl(target, { adminRoute }))\n }\n window.addEventListener('message', onMessage)\n return () => window.removeEventListener('message', onMessage)\n }, [iframeRef, popupRef, collectionSlug, globalSlug, id, locale?.code, focus, router, adminRoute])\n\n return null\n}\n"],"names":["buildAdminUrl","createReadyMessage","decodeRef","FIELD_PARAM","isFocusMessage","isReadyMessage","useConfig","useDocumentInfo","useForm","useFormInitializing","useLivePreviewContext","useLocale","useRouter","useSearchParams","useCallback","useEffect","useRef","blockTypeOf","runFocusPlan","resolveFocus","originOf","url","URL","window","location","href","origin","VisualEditingAdmin","config","getEntityConfig","collectionSlug","globalSlug","id","setDocFieldPreferences","getField","dispatchFields","initializing","iframeRef","popupRef","locale","router","searchParams","adminRoute","routes","admin","focus","path","entity","api","plan","fields","blocksMap","getBlockType","rowPath","field","get","focusedFor","current","onMessage","event","iframe","preview","contentWindow","popup","source","src","data","postMessage","target","ref","sameDocument","global","collection","String","sameLocale","code","push","addEventListener","removeEventListener"],"mappings":"AAAA;AAEA,SACEA,aAAa,EACbC,kBAAkB,EAClBC,SAAS,EACTC,WAAW,EACXC,cAAc,EACdC,cAAc,QACT,wCAAuC;AAC9C,SACEC,SAAS,EACTC,eAAe,EACfC,OAAO,EACPC,mBAAmB,EACnBC,qBAAqB,EACrBC,SAAS,QACJ,iBAAgB;AACvB,SAASC,SAAS,EAAEC,eAAe,QAAQ,kBAAiB;AAC5D,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,QAAQ,QAAO;AAEtD,SAASC,WAAW,EAAEC,YAAY,QAAuB,aAAY;AACrE,SAASC,YAAY,QAAwB,qBAAoB;AAEjE,6DAA6D,GAC7D,MAAMC,WAAW,CAACC;IAChB,IAAI;QACF,OAAOA,MAAM,IAAIC,IAAID,KAAKE,OAAOC,QAAQ,CAACC,IAAI,EAAEC,MAAM,GAAG;IAC3D,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC;IACd,MAAM,EAAEC,MAAM,EAAEC,eAAe,EAAE,GAAGvB;IACpC,MAAM,EAAEwB,cAAc,EAAEC,UAAU,EAAEC,EAAE,EAAEC,sBAAsB,EAAE,GA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Q;YAC3E,IAAIJ,MAAMK,MAAM,KAAKH,WAAWF,MAAMjC,MAAM,KAAKN,SAASwC,QAAQK,MAAM;YAExE,MAAMD,SAASL,MAAMK,MAAM;YAC3B,IAAI3D,eAAesD,MAAMO,IAAI,GAAG;gBAC9BF,OAAOG,WAAW,CAAClE,sBAAsB0D,MAAMjC,MAAM;gBACrD;YACF;YACA,IAAI,CAACtB,eAAeuD,MAAMO,IAAI,GAAG;YACjC,MAAME,SAASlE,UAAUyD,MAAMO,IAAI,CAACG,GAAG;YACvC,IAAI,CAACD,QAAQ;YAEb,MAAME,eACJ,YAAYF,UAAUA,OAAOG,MAAM,GAC/BH,OAAOG,MAAM,KAAKxC,aAClBqC,OAAOI,UAAU,KAAK1C,kBAAkB2C,OAAOL,OAAOpC,EAAE,MAAMyC,OAAOzC;YAC3E,MAAM0C,aAAa,CAACN,OAAO7B,MAAM,IAAI6B,OAAO7B,MAAM,KAAKA,QAAQoC;YAC/D,IAAIL,gBAAgBI,YAAY,KAAK7B,MAAMuB,OAAOtB,IAAI;iBACjDN,OAAOoC,IAAI,CAAC5E,cAAcoE,QAAQ;gBAAE1B;YAAW;QACtD;QACAnB,OAAOsD,gBAAgB,CAAC,WAAWnB;QACnC,OAAO,IAAMnC,OAAOuD,mBAAmB,CAAC,WAAWpB;IACrD,GAAG;QAACrB;QAAWC;QAAUR;QAAgBC;QAAYC;QAAIO,QAAQoC;QAAM9B;QAAOL;QAAQE;KAAW;IAEjG,OAAO;AACT"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The ONLY module that knows Payload's admin markup (ADR 0001, M3). Everything else goes through
3
+ * Payload's public API. Every function fails silently: when Payload's markup changes, focusing
4
+ * stops working, but nothing throws and the document still opens.
5
+ *
6
+ * test/payload-markup.test.ts checks that the installed @payloadcms/ui still renders these.
7
+ */
8
+ /** Field inputs/wrappers: `id="field-<path with . replaced by __>"` (Payload uses it for label links). */
9
+ export declare const fieldElementId: (path: string) => string;
10
+ /** The Lexical rich text field marks its wrapper with the path instead. */
11
+ export declare const FIELD_PATH_ATTR = "data-field-path";
12
+ /** Wrapper of every field (label, input, description): what gets highlighted. */
13
+ export declare const FIELD_CLASS = "field-type";
14
+ /** The rendered element of the field at `path`, or null. */
15
+ export declare function findFieldElement(path: string, root?: Element): Element | null;
16
+ /** Tabs field container and its tab buttons. No public API switches a tab after mount. */
17
+ export declare const TABS_CLASS = "tabs-field";
18
+ export declare const TAB_BUTTON_CLASS = "tabs-field__tab-button";
19
+ export declare const TAB_BUTTON_ACTIVE_CLASS = "tabs-field__tab-button--active";
20
+ /** Array and blocks fields: tabs inside their rows are out of scope. */
21
+ export declare const ROW_CONTAINER_CLASSES: string[];
22
+ /**
23
+ * Tabs fields directly in `scope`, in render order: not inside another tabs field or an
24
+ * array/blocks row within the scope.
25
+ */
26
+ export declare function tabsInScope(scope: Element): Element[];
27
+ /**
28
+ * Opens tab `index` of the `ordinal`-th tabs field in `scope` by clicking its button, as an editor
29
+ * would: Payload's own handler switches the tab and saves the preference.
30
+ * Returns the tabs field (the scope for nested tabs), or null when it can't be found.
31
+ */
32
+ export declare function selectTab(scope: Element, ordinal: number, index: number): Element | null;
33
+ /**
34
+ * Resolves once `find()` returns an element: right away, or when Payload has rendered it.
35
+ * Waits for a DOM change, not for a fixed time; null after `timeout`.
36
+ */
37
+ export declare function waitForElement(find: () => Element | null, root?: Node, timeout?: number): Promise<Element | null>;
38
+ export interface RevealOptions {
39
+ root?: Element;
40
+ /** Field paths that contain the element, deepest first: scrolled to before searching. */
41
+ ancestors?: string[];
42
+ timeout?: number;
43
+ }
44
+ /**
45
+ * Like `waitForElement`, for elements Payload hasn't rendered because they are far below the
46
+ * viewport (it renders each list of fields only within 1000 px of it). Decided with the user:
47
+ * 1. scroll the nearest rendered ancestor field into view and look again (deeper ancestors may
48
+ * appear on the way); 2. then scroll down one screen at a time until it appears or the page ends.
49
+ * Each step waits for a DOM change, up to STEP_WAIT; the whole search ends after `timeout`.
50
+ * Fields above the viewport are always rendered, so the search only goes down.
51
+ */
52
+ export declare function revealElement(find: () => Element | null, { root, ancestors, timeout }?: RevealOptions): Promise<Element | null>;
53
+ /** `a.b.c` → `['a.b', 'a']` */
54
+ export declare const ancestorPaths: (path: string) => string[];
55
+ /**
56
+ * Scrolls the field to the window's centre, focuses its input, keeps it centred while lazy-loaded
57
+ * content still changes the layout (see keep-in-view.ts), then highlights it briefly. The
58
+ * highlight waits until the page stopped moving, so it doesn't slide across the screen.
59
+ */
60
+ export declare function focusFieldElement(element: Element, highlightColor?: string): void;
61
+ //# sourceMappingURL=dom-adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dom-adapter.d.ts","sourceRoot":"","sources":["../../src/client/dom-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,0GAA0G;AAC1G,eAAO,MAAM,cAAc,SAAU,MAAM,WAAyC,CAAA;AACpF,2EAA2E;AAC3E,eAAO,MAAM,eAAe,oBAAoB,CAAA;AAChD,iFAAiF;AACjF,eAAO,MAAM,WAAW,eAAe,CAAA;AAEvC,4DAA4D;AAC5D,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,OAAuB,GAAG,OAAO,GAAG,IAAI,CAQ5F;AAED,0FAA0F;AAC1F,eAAO,MAAM,UAAU,eAAe,CAAA;AACtC,eAAO,MAAM,gBAAgB,2BAA2B,CAAA;AACxD,eAAO,MAAM,uBAAuB,mCAAmC,CAAA;AACvE,wEAAwE;AACxE,eAAO,MAAM,qBAAqB,UAAkC,CAAA;AAKpE;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,EAAE,CAMrD;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAUxF;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,OAAO,GAAG,IAAI,EAC1B,IAAI,GAAE,IAAoB,EAC1B,OAAO,SAAiB,GACvB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAgBzB;AAKD,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;IACpB,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,OAAO,GAAG,IAAI,EAC1B,EAAE,IAAoB,EAAE,SAAc,EAAE,OAAwB,EAAE,GAAE,aAAkB,GACrF,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAyBzB;AAED,+BAA+B;AAC/B,eAAO,MAAM,aAAa,SAAU,MAAM,aAI2B,CAAA;AAiBrE;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,cAAc,SAAY,GAAG,IAAI,CAuBpF"}
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The ONLY module that knows Payload's admin markup (ADR 0001, M3). Everything else goes through
3
+ * Payload's public API. Every function fails silently: when Payload's markup changes, focusing
4
+ * stops working, but nothing throws and the document still opens.
5
+ *
6
+ * test/payload-markup.test.ts checks that the installed @payloadcms/ui still renders these.
7
+ */ import { keepInView } from "./keep-in-view.js";
8
+ /** Field inputs/wrappers: `id="field-<path with . replaced by __>"` (Payload uses it for label links). */ export const fieldElementId = (path)=>`field-${path.replace(/\./g, '__')}`;
9
+ /** The Lexical rich text field marks its wrapper with the path instead. */ export const FIELD_PATH_ATTR = 'data-field-path';
10
+ /** Wrapper of every field (label, input, description): what gets highlighted. */ export const FIELD_CLASS = 'field-type';
11
+ /** The rendered element of the field at `path`, or null. */ export function findFieldElement(path, root = document.body) {
12
+ const byId = root.ownerDocument.getElementById(fieldElementId(path));
13
+ if (byId && root.contains(byId)) return byId;
14
+ // Compare the attribute instead of building a selector from the path
15
+ for (const element of root.querySelectorAll(`[${FIELD_PATH_ATTR}]`)){
16
+ if (element.getAttribute(FIELD_PATH_ATTR) === path) return element;
17
+ }
18
+ return null;
19
+ }
20
+ /** Tabs field container and its tab buttons. No public API switches a tab after mount. */ export const TABS_CLASS = 'tabs-field';
21
+ export const TAB_BUTTON_CLASS = 'tabs-field__tab-button';
22
+ export const TAB_BUTTON_ACTIVE_CLASS = 'tabs-field__tab-button--active';
23
+ /** Array and blocks fields: tabs inside their rows are out of scope. */ export const ROW_CONTAINER_CLASSES = [
24
+ 'array-field',
25
+ 'blocks-field'
26
+ ];
27
+ /** How long to wait for Payload to render a tab or row before giving up. */ const RENDER_TIMEOUT = 3000;
28
+ /**
29
+ * Tabs fields directly in `scope`, in render order: not inside another tabs field or an
30
+ * array/blocks row within the scope.
31
+ */ export function tabsInScope(scope) {
32
+ const nested = [
33
+ TABS_CLASS,
34
+ ...ROW_CONTAINER_CLASSES
35
+ ].map((name)=>`.${name}`).join(',');
36
+ return [
37
+ ...scope.querySelectorAll(`.${TABS_CLASS}`)
38
+ ].filter((tabs)=>{
39
+ const outer = tabs.parentElement?.closest(nested);
40
+ return !outer || outer === scope || !scope.contains(outer);
41
+ });
42
+ }
43
+ /**
44
+ * Opens tab `index` of the `ordinal`-th tabs field in `scope` by clicking its button, as an editor
45
+ * would: Payload's own handler switches the tab and saves the preference.
46
+ * Returns the tabs field (the scope for nested tabs), or null when it can't be found.
47
+ */ export function selectTab(scope, ordinal, index) {
48
+ const tabs = tabsInScope(scope)[ordinal];
49
+ if (!tabs) return null;
50
+ const buttons = [
51
+ ...tabs.querySelectorAll(`.${TAB_BUTTON_CLASS}`)
52
+ ].filter((button)=>button.closest(`.${TABS_CLASS}`) === tabs);
53
+ const button = buttons[index];
54
+ if (!(button instanceof HTMLElement)) return null;
55
+ if (!button.classList.contains(TAB_BUTTON_ACTIVE_CLASS)) button.click();
56
+ return tabs;
57
+ }
58
+ /**
59
+ * Resolves once `find()` returns an element: right away, or when Payload has rendered it.
60
+ * Waits for a DOM change, not for a fixed time; null after `timeout`.
61
+ */ export function waitForElement(find, root = document.body, timeout = RENDER_TIMEOUT) {
62
+ const found = find();
63
+ if (found) return Promise.resolve(found);
64
+ return new Promise((resolve)=>{
65
+ const done = (element)=>{
66
+ observer.disconnect();
67
+ clearTimeout(timer);
68
+ resolve(element);
69
+ };
70
+ const observer = new MutationObserver(()=>{
71
+ const element = find();
72
+ if (element) done(element);
73
+ });
74
+ const timer = setTimeout(()=>done(null), timeout);
75
+ observer.observe(root, {
76
+ childList: true,
77
+ subtree: true,
78
+ attributes: true
79
+ });
80
+ });
81
+ }
82
+ /** How long one reveal step waits for Payload to render (a ceiling: it resolves on the DOM change). */ const STEP_WAIT = 300;
83
+ /**
84
+ * Like `waitForElement`, for elements Payload hasn't rendered because they are far below the
85
+ * viewport (it renders each list of fields only within 1000 px of it). Decided with the user:
86
+ * 1. scroll the nearest rendered ancestor field into view and look again (deeper ancestors may
87
+ * appear on the way); 2. then scroll down one screen at a time until it appears or the page ends.
88
+ * Each step waits for a DOM change, up to STEP_WAIT; the whole search ends after `timeout`.
89
+ * Fields above the viewport are always rendered, so the search only goes down.
90
+ */ export async function revealElement(find, { root = document.body, ancestors = [], timeout = RENDER_TIMEOUT } = {}) {
91
+ const deadline = Date.now() + timeout;
92
+ const step = ()=>waitForElement(find, root, Math.max(0, Math.min(STEP_WAIT, deadline - Date.now())));
93
+ // Rendering may simply be in progress (a tab just opened, a row just expanded)
94
+ let found = await step();
95
+ if (found) return found;
96
+ let scrolledTo = null;
97
+ while(Date.now() < deadline){
98
+ const ancestor = ancestors.map((path)=>findFieldElement(path, root)).find(Boolean) ?? null;
99
+ if (!ancestor || ancestor === scrolledTo) break;
100
+ scrolledTo = ancestor;
101
+ ancestor.scrollIntoView?.({
102
+ block: 'start'
103
+ });
104
+ if (found = await step()) return found;
105
+ }
106
+ const view = root.ownerDocument.defaultView;
107
+ const scroller = root.ownerDocument.scrollingElement;
108
+ while(view && scroller && Date.now() < deadline){
109
+ const before = scroller.scrollTop;
110
+ view.scrollBy(0, view.innerHeight);
111
+ if (scroller.scrollTop === before) break; // end of the page
112
+ if (found = await step()) return found;
113
+ }
114
+ return waitForElement(find, root, Math.max(0, deadline - Date.now()));
115
+ }
116
+ /** `a.b.c` → `['a.b', 'a']` */ export const ancestorPaths = (path)=>path.split('.').slice(0, -1).map((_, i, parts)=>parts.slice(0, parts.length - i).join('.'));
117
+ /** What to focus in a field: where the editor types first, else a control (e.g. an upload's edit button). */ const INPUTS = 'input:not([type=hidden]), textarea, select, [contenteditable=true]';
118
+ /** The element to focus for a field: the field itself if it is an input, else an input or control
119
+ * inside it, else in its wrapper (upload fields render their buttons next to the id element). */ function focusTarget(element, wrapper) {
120
+ // In this order: an input, a button (e.g. an upload's edit button), a link
121
+ for (const selector of [
122
+ INPUTS,
123
+ 'button:not([disabled])',
124
+ 'a[href]'
125
+ ]){
126
+ if (element.matches(selector)) return element;
127
+ const found = element.querySelector(selector) ?? wrapper.querySelector(selector);
128
+ if (found instanceof HTMLElement) return found;
129
+ }
130
+ return null;
131
+ }
132
+ /**
133
+ * Scrolls the field to the window's centre, focuses its input, keeps it centred while lazy-loaded
134
+ * content still changes the layout (see keep-in-view.ts), then highlights it briefly. The
135
+ * highlight waits until the page stopped moving, so it doesn't slide across the screen.
136
+ */ export function focusFieldElement(element, highlightColor = '#2563eb') {
137
+ element.scrollIntoView?.({
138
+ block: 'center',
139
+ behavior: 'smooth'
140
+ });
141
+ const wrapper = element.closest(`.${FIELD_CLASS}`) ?? element;
142
+ const target = focusTarget(element, wrapper);
143
+ if (target) target.focus({
144
+ preventScroll: true
145
+ });
146
+ else {
147
+ // Some fields render their controls later (an upload loads its file details first). Focus them
148
+ // when they appear, unless the editor has moved the focus in the meantime (focus is still where
149
+ // it was now: the page, or the Live Preview iframe that was clicked).
150
+ const before = element.ownerDocument.activeElement;
151
+ void waitForElement(()=>focusTarget(element, wrapper), wrapper).then((late)=>{
152
+ if (late instanceof HTMLElement && element.ownerDocument.activeElement === before) {
153
+ late.focus({
154
+ preventScroll: true
155
+ });
156
+ }
157
+ });
158
+ }
159
+ keepInView(element, {
160
+ onDone: ()=>wrapper.animate?.([
161
+ {
162
+ boxShadow: `0 0 0 3px ${highlightColor}`
163
+ },
164
+ {
165
+ boxShadow: `0 0 0 3px ${highlightColor}`
166
+ },
167
+ {
168
+ boxShadow: 'none'
169
+ }
170
+ ], {
171
+ duration: 1600,
172
+ easing: 'ease-out'
173
+ })
174
+ });
175
+ }
176
+
177
+ //# sourceMappingURL=dom-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/dom-adapter.ts"],"sourcesContent":["/**\n * The ONLY module that knows Payload's admin markup (ADR 0001, M3). Everything else goes through\n * Payload's public API. Every function fails silently: when Payload's markup changes, focusing\n * stops working, but nothing throws and the document still opens.\n *\n * test/payload-markup.test.ts checks that the installed @payloadcms/ui still renders these.\n */\n\nimport { keepInView } from './keep-in-view.ts'\n\n/** Field inputs/wrappers: `id=\"field-<path with . replaced by __>\"` (Payload uses it for label links). */\nexport const fieldElementId = (path: string) => `field-${path.replace(/\\./g, '__')}`\n/** The Lexical rich text field marks its wrapper with the path instead. */\nexport const FIELD_PATH_ATTR = 'data-field-path'\n/** Wrapper of every field (label, input, description): what gets highlighted. */\nexport const FIELD_CLASS = 'field-type'\n\n/** The rendered element of the field at `path`, or null. */\nexport function findFieldElement(path: string, root: Element = document.body): Element | null {\n const byId = root.ownerDocument.getElementById(fieldElementId(path))\n if (byId && root.contains(byId)) return byId\n // Compare the attribute instead of building a selector from the path\n for (const element of root.querySelectorAll(`[${FIELD_PATH_ATTR}]`)) {\n if (element.getAttribute(FIELD_PATH_ATTR) === path) return element\n }\n return null\n}\n\n/** Tabs field container and its tab buttons. No public API switches a tab after mount. */\nexport const TABS_CLASS = 'tabs-field'\nexport const TAB_BUTTON_CLASS = 'tabs-field__tab-button'\nexport const TAB_BUTTON_ACTIVE_CLASS = 'tabs-field__tab-button--active'\n/** Array and blocks fields: tabs inside their rows are out of scope. */\nexport const ROW_CONTAINER_CLASSES = ['array-field', 'blocks-field']\n\n/** How long to wait for Payload to render a tab or row before giving up. */\nconst RENDER_TIMEOUT = 3000\n\n/**\n * Tabs fields directly in `scope`, in render order: not inside another tabs field or an\n * array/blocks row within the scope.\n */\nexport function tabsInScope(scope: Element): Element[] {\n const nested = [TABS_CLASS, ...ROW_CONTAINER_CLASSES].map((name) => `.${name}`).join(',')\n return [...scope.querySelectorAll(`.${TABS_CLASS}`)].filter((tabs) => {\n const outer = tabs.parentElement?.closest(nested)\n return !outer || outer === scope || !scope.contains(outer)\n })\n}\n\n/**\n * Opens tab `index` of the `ordinal`-th tabs field in `scope` by clicking its button, as an editor\n * would: Payload's own handler switches the tab and saves the preference.\n * Returns the tabs field (the scope for nested tabs), or null when it can't be found.\n */\nexport function selectTab(scope: Element, ordinal: number, index: number): Element | null {\n const tabs = tabsInScope(scope)[ordinal]\n if (!tabs) return null\n const buttons = [...tabs.querySelectorAll(`.${TAB_BUTTON_CLASS}`)].filter(\n (button) => button.closest(`.${TABS_CLASS}`) === tabs,\n )\n const button = buttons[index]\n if (!(button instanceof HTMLElement)) return null\n if (!button.classList.contains(TAB_BUTTON_ACTIVE_CLASS)) button.click()\n return tabs\n}\n\n/**\n * Resolves once `find()` returns an element: right away, or when Payload has rendered it.\n * Waits for a DOM change, not for a fixed time; null after `timeout`.\n */\nexport function waitForElement(\n find: () => Element | null,\n root: Node = document.body,\n timeout = RENDER_TIMEOUT,\n): Promise<Element | null> {\n const found = find()\n if (found) return Promise.resolve(found)\n return new Promise((resolve) => {\n const done = (element: Element | null) => {\n observer.disconnect()\n clearTimeout(timer)\n resolve(element)\n }\n const observer = new MutationObserver(() => {\n const element = find()\n if (element) done(element)\n })\n const timer = setTimeout(() => done(null), timeout)\n observer.observe(root, { childList: true, subtree: true, attributes: true })\n })\n}\n\n/** How long one reveal step waits for Payload to render (a ceiling: it resolves on the DOM change). */\nconst STEP_WAIT = 300\n\nexport interface RevealOptions {\n root?: Element\n /** Field paths that contain the element, deepest first: scrolled to before searching. */\n ancestors?: string[]\n timeout?: number\n}\n\n/**\n * Like `waitForElement`, for elements Payload hasn't rendered because they are far below the\n * viewport (it renders each list of fields only within 1000 px of it). Decided with the user:\n * 1. scroll the nearest rendered ancestor field into view and look again (deeper ancestors may\n * appear on the way); 2. then scroll down one screen at a time until it appears or the page ends.\n * Each step waits for a DOM change, up to STEP_WAIT; the whole search ends after `timeout`.\n * Fields above the viewport are always rendered, so the search only goes down.\n */\nexport async function revealElement(\n find: () => Element | null,\n { root = document.body, ancestors = [], timeout = RENDER_TIMEOUT }: RevealOptions = {},\n): Promise<Element | null> {\n const deadline = Date.now() + timeout\n const step = () => waitForElement(find, root, Math.max(0, Math.min(STEP_WAIT, deadline - Date.now())))\n // Rendering may simply be in progress (a tab just opened, a row just expanded)\n let found = await step()\n if (found) return found\n\n let scrolledTo: Element | null = null\n while (Date.now() < deadline) {\n const ancestor = ancestors.map((path) => findFieldElement(path, root)).find(Boolean) ?? null\n if (!ancestor || ancestor === scrolledTo) break\n scrolledTo = ancestor\n ancestor.scrollIntoView?.({ block: 'start' })\n if ((found = await step())) return found\n }\n\n const view = root.ownerDocument.defaultView\n const scroller = root.ownerDocument.scrollingElement\n while (view && scroller && Date.now() < deadline) {\n const before = scroller.scrollTop\n view.scrollBy(0, view.innerHeight)\n if (scroller.scrollTop === before) break // end of the page\n if ((found = await step())) return found\n }\n return waitForElement(find, root, Math.max(0, deadline - Date.now()))\n}\n\n/** `a.b.c` → `['a.b', 'a']` */\nexport const ancestorPaths = (path: string) =>\n path\n .split('.')\n .slice(0, -1)\n .map((_, i, parts) => parts.slice(0, parts.length - i).join('.'))\n\n/** What to focus in a field: where the editor types first, else a control (e.g. an upload's edit button). */\nconst INPUTS = 'input:not([type=hidden]), textarea, select, [contenteditable=true]'\n\n/** The element to focus for a field: the field itself if it is an input, else an input or control\n * inside it, else in its wrapper (upload fields render their buttons next to the id element). */\nfunction focusTarget(element: Element, wrapper: Element): HTMLElement | null {\n // In this order: an input, a button (e.g. an upload's edit button), a link\n for (const selector of [INPUTS, 'button:not([disabled])', 'a[href]']) {\n if (element.matches(selector)) return element as HTMLElement\n const found = element.querySelector(selector) ?? wrapper.querySelector(selector)\n if (found instanceof HTMLElement) return found\n }\n return null\n}\n\n/**\n * Scrolls the field to the window's centre, focuses its input, keeps it centred while lazy-loaded\n * content still changes the layout (see keep-in-view.ts), then highlights it briefly. The\n * highlight waits until the page stopped moving, so it doesn't slide across the screen.\n */\nexport function focusFieldElement(element: Element, highlightColor = '#2563eb'): void {\n element.scrollIntoView?.({ block: 'center', behavior: 'smooth' })\n const wrapper = element.closest(`.${FIELD_CLASS}`) ?? element\n const target = focusTarget(element, wrapper)\n if (target) target.focus({ preventScroll: true })\n else {\n // Some fields render their controls later (an upload loads its file details first). Focus them\n // when they appear, unless the editor has moved the focus in the meantime (focus is still where\n // it was now: the page, or the Live Preview iframe that was clicked).\n const before = element.ownerDocument.activeElement\n void waitForElement(() => focusTarget(element, wrapper), wrapper).then((late) => {\n if (late instanceof HTMLElement && element.ownerDocument.activeElement === before) {\n late.focus({ preventScroll: true })\n }\n })\n }\n keepInView(element, {\n onDone: () =>\n wrapper.animate?.(\n [{ boxShadow: `0 0 0 3px ${highlightColor}` }, { boxShadow: `0 0 0 3px ${highlightColor}` }, { boxShadow: 'none' }],\n { duration: 1600, easing: 'ease-out' },\n ),\n })\n}\n"],"names":["keepInView","fieldElementId","path","replace","FIELD_PATH_ATTR","FIELD_CLASS","findFieldElement","root","document","body","byId","ownerDocument","getElementById","contains","element","querySelectorAll","getAttribute","TABS_CLASS","TAB_BUTTON_CLASS","TAB_BUTTON_ACTIVE_CLASS","ROW_CONTAINER_CLASSES","RENDER_TIMEOUT","tabsInScope","scope","nested","map","name","join","filter","tabs","outer","parentElement","closest","selectTab","ordinal","index","buttons","button","HTMLElement","classList","click","waitForElement","find","timeout","found","Promise","resolve","done","observer","disconnect","clearTimeout","timer","MutationObserver","setTimeout","observe","childList","subtree","attributes","STEP_WAIT","revealElement","ancestors","deadline","Date","now","step","Math","max","min","scrolledTo","ancestor","Boolean","scrollIntoView","block","view","defaultView","scroller","scrollingElement","before","scrollTop","scrollBy","innerHeight","ancestorPaths","split","slice","_","i","parts","length","INPUTS","focusTarget","wrapper","selector","matches","querySelector","focusFieldElement","highlightColor","behavior","target","focus","preventScroll","activeElement","then","late","onDone","animate","boxShadow","duration","easing"],"mappings":"AAAA;;;;;;CAMC,GAED,SAASA,UAAU,QAAQ,oBAAmB;AAE9C,wGAAwG,GACxG,OAAO,MAAMC,iBAAiB,CAACC,OAAiB,CAAC,MAAM,EAAEA,KAAKC,OAAO,CAAC,OAAO,OAAO,CAAA;AACpF,yEAAyE,GACzE,OAAO,MAAMC,kBAAkB,kBAAiB;AAChD,+EAA+E,GAC/E,OAAO,MAAMC,cAAc,aAAY;AAEvC,0DAA0D,GAC1D,OAAO,SAASC,iBAAiBJ,IAAY,EAAEK,OAAgBC,SAASC,IAAI;IAC1E,MAAMC,OAAOH,KAAKI,aAAa,CAACC,cAAc,CAACX,eAAeC;IAC9D,IAAIQ,QAAQH,KAAKM,QAAQ,CAACH,OAAO,OAAOA;IACxC,qEAAqE;IACrE,KAAK,MAAMI,WAAWP,KAAKQ,gBAAgB,CAAC,CAAC,CAAC,EAAEX,gBAAgB,CAAC,CAAC,EAAG;QACnE,IAAIU,QAAQE,YAAY,CAACZ,qBAAqBF,MAAM,OAAOY;IAC7D;IACA,OAAO;AACT;AAEA,wFAAwF,GACxF,OAAO,MAAMG,aAAa,aAAY;AACtC,OAAO,MAAMC,mBAAmB,yBAAwB;AACxD,OAAO,MAAMC,0BAA0B,iCAAgC;AACvE,sEAAsE,GACtE,OAAO,MAAMC,wBAAwB;IAAC;IAAe;CAAe,CAAA;AAEpE,0EAA0E,GAC1E,MAAMC,iBAAiB;AAEvB;;;CAGC,GACD,OAAO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AQ;gBACjFyB,KAAKJ,KAAK,CAAC;oBAAEC,eAAe;gBAAK;YACnC;QACF;IACF;IACAnG,WAAWc,SAAS;QAClByF,QAAQ,IACNb,QAAQc,OAAO,GACb;gBAAC;oBAAEC,WAAW,CAAC,UAAU,EAAEV,gBAAgB;gBAAC;gBAAG;oBAAEU,WAAW,CAAC,UAAU,EAAEV,gBAAgB;gBAAC;gBAAG;oBAAEU,WAAW;gBAAO;aAAE,EACnH;gBAAEC,UAAU;gBAAMC,QAAQ;YAAW;IAE3C;AACF"}
@@ -0,0 +1,36 @@
1
+ import type { FocusPlan } from './resolve-focus.ts';
2
+ /** The parts of Payload's form and document APIs that focusing needs (all public). */
3
+ export interface FocusApi {
4
+ /** `useForm().getField` */
5
+ getField: (path: string) => {
6
+ rows?: {
7
+ id: string;
8
+ collapsed?: boolean;
9
+ blockType?: string;
10
+ }[];
11
+ value?: unknown;
12
+ } | undefined;
13
+ /** `useForm().dispatchFields` */
14
+ dispatchFields: (action: {
15
+ type: 'SET_ROW_COLLAPSED';
16
+ path: string;
17
+ updatedRows: never[];
18
+ }) => void;
19
+ /** `useDocumentInfo().setDocFieldPreferences` */
20
+ setDocFieldPreferences: (path: string, preferences: {
21
+ collapsed: string[];
22
+ }) => void;
23
+ }
24
+ /**
25
+ * Expands a collapsed array/blocks row the way Payload's array field does: form state through
26
+ * `SET_ROW_COLLAPSED`, and the user's collapsed rows saved in the document preferences.
27
+ */
28
+ export declare function expandRow(api: FocusApi, path: string, index: number): void;
29
+ /** blockType of the block row at `rowPath` (e.g. `layout.2`), from form state. */
30
+ export declare function blockTypeOf(api: FocusApi, rowPath: string): string | undefined;
31
+ /**
32
+ * Runs a focus plan: opens tabs, expands rows, then focuses the field once Payload rendered it.
33
+ * True when the field was focused. Never throws.
34
+ */
35
+ export declare function runFocusPlan(plan: FocusPlan, api: FocusApi, root?: Element): Promise<boolean>;
36
+ //# sourceMappingURL=focus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.d.ts","sourceRoot":"","sources":["../../src/client/focus.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAEnD,sFAAsF;AACtF,MAAM,WAAW,QAAQ;IACvB,2BAA2B;IAC3B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK;QAAE,IAAI,CAAC,EAAE;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,SAAS,CAAC,EAAE,OAAO,CAAC;YAAC,SAAS,CAAC,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,SAAS,CAAA;IAC7H,iCAAiC;IACjC,cAAc,EAAE,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,mBAAmB,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,KAAK,EAAE,CAAA;KAAE,KAAK,IAAI,CAAA;IACnG,iDAAiD;IACjD,sBAAsB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE;QAAE,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,KAAK,IAAI,CAAA;CACrF;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAM1E;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAM9E;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,GAAE,OAAuB,GAAG,OAAO,CAAC,OAAO,CAAC,CA0BlH"}