payload-canvas 0.1.1 → 0.2.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 (124) hide show
  1. package/README.md +187 -26
  2. package/dist/admin/editor/Canvas.js +30 -8
  3. package/dist/admin/editor/Editor.js +2 -0
  4. package/dist/admin/editor/Inspector.js +14 -7
  5. package/dist/admin/editor/Outline.js +15 -9
  6. package/dist/admin/editor/Overlay.js +2 -1
  7. package/dist/admin/editor/actions.d.ts +5 -0
  8. package/dist/admin/editor/actions.js +23 -1
  9. package/dist/admin/editor/counts.d.ts +6 -0
  10. package/dist/admin/editor/counts.js +10 -0
  11. package/dist/admin/editor/dnd/displace.js +3 -1
  12. package/dist/admin/editor/editor.scss +53 -0
  13. package/dist/admin/editor/inline.d.ts +12 -0
  14. package/dist/admin/editor/inline.js +48 -3
  15. package/dist/admin/editor/insert/spots.js +4 -2
  16. package/dist/admin/editor/live/useMultiplayer.js +8 -2
  17. package/dist/admin/editor/media/ImageEditor.js +21 -15
  18. package/dist/admin/editor/media/actions.d.ts +13 -9
  19. package/dist/admin/editor/media/actions.js +67 -28
  20. package/dist/admin/editor/media/model.d.ts +8 -0
  21. package/dist/admin/editor/media/model.js +14 -6
  22. package/dist/admin/editor/menu/blockMenu.js +13 -8
  23. package/dist/admin/editor/regions/RegionOverlay.d.ts +18 -0
  24. package/dist/admin/editor/regions/RegionOverlay.js +44 -0
  25. package/dist/admin/editor/regions/RegionPane.d.ts +5 -0
  26. package/dist/admin/editor/regions/RegionPane.js +26 -0
  27. package/dist/admin/editor/regions/RegionRows.d.ts +1 -0
  28. package/dist/admin/editor/regions/RegionRows.js +23 -0
  29. package/dist/admin/editor/regions/controller.d.ts +73 -0
  30. package/dist/admin/editor/regions/controller.js +231 -0
  31. package/dist/admin/editor/regions/select.d.ts +17 -0
  32. package/dist/admin/editor/regions/select.js +31 -0
  33. package/dist/admin/editor/runtime.d.ts +6 -0
  34. package/dist/admin/editor/runtime.js +49 -4
  35. package/dist/admin/editor/sections/controller.d.ts +6 -2
  36. package/dist/admin/editor/sections/controller.js +9 -3
  37. package/dist/admin/editor/shortcuts.js +11 -4
  38. package/dist/admin/editor/storage.d.ts +7 -0
  39. package/dist/admin/editor/storage.js +15 -0
  40. package/dist/admin/editor/store.d.ts +39 -0
  41. package/dist/admin/editor/store.js +106 -2
  42. package/dist/admin/editor/templates/Bindable.js +1 -1
  43. package/dist/admin/editor/templates/SamplePicker.js +1 -1
  44. package/dist/admin/editor/topbar/DocumentActions.js +38 -5
  45. package/dist/admin/editor/topbar/closeSave.d.ts +50 -0
  46. package/dist/admin/editor/topbar/closeSave.js +90 -0
  47. package/dist/admin/editor/topbar/document.d.ts +10 -2
  48. package/dist/admin/editor/topbar/document.js +9 -1
  49. package/dist/admin/editor/topbar/drawerLabels.d.ts +22 -0
  50. package/dist/admin/editor/topbar/drawerLabels.js +69 -0
  51. package/dist/admin/editor/topbar/problems.d.ts +9 -0
  52. package/dist/admin/editor/topbar/problems.js +15 -1
  53. package/dist/admin/editor/topbar/settingsDrawer.js +88 -4
  54. package/dist/admin/editor/topbar/settingsFocus.d.ts +11 -0
  55. package/dist/admin/editor/topbar/settingsFocus.js +46 -0
  56. package/dist/admin/editor/ui/payloadA11y.d.ts +17 -0
  57. package/dist/admin/editor/ui/payloadA11y.js +12 -5
  58. package/dist/admin/editor/valueStore.d.ts +2 -0
  59. package/dist/admin/editor/valueStore.js +6 -0
  60. package/dist/core/dropTarget.js +3 -1
  61. package/dist/core/index.d.ts +2 -0
  62. package/dist/core/index.js +2 -0
  63. package/dist/core/payloadBlocks.d.ts +53 -0
  64. package/dist/core/payloadBlocks.js +391 -0
  65. package/dist/core/regions.d.ts +63 -0
  66. package/dist/core/regions.js +239 -0
  67. package/dist/core/types.d.ts +53 -0
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.js +1 -0
  70. package/dist/live/document.d.ts +9 -1
  71. package/dist/live/document.js +57 -17
  72. package/dist/live/draftAccess.d.ts +36 -0
  73. package/dist/live/draftAccess.js +146 -0
  74. package/dist/live/endpoints.d.ts +11 -2
  75. package/dist/live/endpoints.js +120 -10
  76. package/dist/live/fieldChecks.d.ts +3 -3
  77. package/dist/live/fieldsGuard.d.ts +56 -2
  78. package/dist/live/fieldsGuard.js +107 -11
  79. package/dist/live/index.d.ts +2 -0
  80. package/dist/live/index.js +2 -0
  81. package/dist/live/regions.d.ts +89 -0
  82. package/dist/live/regions.js +401 -0
  83. package/dist/live/runtime.d.ts +1 -1
  84. package/dist/live/runtime.js +5 -2
  85. package/dist/live/session.d.ts +74 -9
  86. package/dist/live/session.js +655 -123
  87. package/dist/live/storage.d.ts +97 -0
  88. package/dist/live/storage.js +269 -0
  89. package/dist/live/types.d.ts +64 -0
  90. package/dist/live/writeGate.d.ts +72 -0
  91. package/dist/live/writeGate.js +478 -0
  92. package/dist/mcp/index.js +56 -12
  93. package/dist/plugin/hook.d.ts +44 -6
  94. package/dist/plugin/hook.js +176 -20
  95. package/dist/plugin/index.d.ts +23 -1
  96. package/dist/plugin/index.js +172 -10
  97. package/dist/plugin/references.d.ts +4 -2
  98. package/dist/plugin/references.js +2 -0
  99. package/dist/plugin/sectionsBuilder.js +3 -3
  100. package/dist/protocol/index.d.ts +28 -2
  101. package/dist/react/canvas/BuilderCanvas.js +198 -8
  102. package/dist/react/canvas/frame.d.ts +70 -0
  103. package/dist/react/canvas/frame.js +66 -0
  104. package/dist/react/canvas/inline/dom.d.ts +7 -1
  105. package/dist/react/canvas/inline/dom.js +19 -9
  106. package/dist/react/canvas/inline/mapper.d.ts +26 -0
  107. package/dist/react/canvas/inline/mapper.js +59 -32
  108. package/dist/react/canvas/inline/session.d.ts +7 -1
  109. package/dist/react/canvas/inline/session.js +6 -2
  110. package/dist/react/canvas/measure.js +26 -1
  111. package/dist/react/index.d.ts +2 -0
  112. package/dist/react/index.js +2 -0
  113. package/dist/react/render/LayoutOutlet.d.ts +11 -0
  114. package/dist/react/render/LayoutOutlet.js +16 -0
  115. package/dist/react/render/canvasFrame.d.ts +46 -0
  116. package/dist/react/render/canvasFrame.js +59 -0
  117. package/dist/react/render/canvasServer.d.ts +13 -0
  118. package/dist/react/render/canvasServer.js +3 -0
  119. package/dist/react/render/canvasServerTypes.d.ts +17 -0
  120. package/dist/react/render/regions.d.ts +13 -0
  121. package/dist/react/render/regions.js +8 -0
  122. package/dist/react/server.d.ts +2 -1
  123. package/dist/react/server.js +1 -0
  124. package/package.json +1 -1
@@ -6,7 +6,7 @@
6
6
  // other users) replace the layout without entering the history, so undo never
7
7
  // reverts someone else's edit. Undo applies the inverse as NEW local operations, so it syncs like
8
8
  // any edit. Parts of it that no longer apply (someone else changed or deleted the block) are skipped.
9
- import { applyOperation, BASE_VARIANT, createLocaleView, findBlock, knownLocale, localizeOperations, stampLocale } from '../../core/index.js';
9
+ import { applyOperation, applyOperations, BASE_VARIANT, createLocaleView, findBlock, knownLocale, localizeOperations, stampLocale } from '../../core/index.js';
10
10
  import { ACCESS_DENIED_PREFIX } from '../../core/fieldAccess.js';
11
11
  import { createSyncEngine } from './live/sync.js';
12
12
  import { useSelector } from './valueStore.js';
@@ -83,6 +83,60 @@ export function createEditorStore(initial, options = {}) {
83
83
  const sharedEdits = new Set();
84
84
  let tagCounter = 0;
85
85
  const nextTag = () => `t${++tagCounter}`;
86
+ let fieldWriter = null;
87
+ let historyBusy = false;
88
+ let historyGeneration = 0;
89
+ let editGeneration = 0;
90
+ const historyQueue = [];
91
+ /**
92
+ * Field saves run in order. A temporary failure restores the step for a later retry.
93
+ */
94
+ const fieldStep = (entry, direction) => {
95
+ historyBusy = true;
96
+ const source = direction === 'undo' ? 'undoStack' : 'redoStack';
97
+ const destination = direction === 'undo' ? 'redoStack' : 'undoStack';
98
+ const earlier = new Set(state[source]);
99
+ const generation = historyGeneration;
100
+ const edits = editGeneration;
101
+ set({ [source]: state[source].filter((e) => e !== entry), [destination]: [...state[destination], entry], lastError: null });
102
+ const drop = () => set({ undoStack: state.undoStack.filter((e) => e !== entry), redoStack: state.redoStack.filter((e) => e !== entry) });
103
+ void (async () => {
104
+ let result = 'retry';
105
+ try {
106
+ if (entry.fieldsReady && !(await entry.fieldsReady))
107
+ result = false;
108
+ else if (!fieldWriter)
109
+ warn(UNDO_NONE);
110
+ else {
111
+ const changes = (entry.fields ?? []).map((e) => direction === 'undo'
112
+ ? { path: e.path, value: e.before, base: 'afterShown' in e ? e.afterShown : e.after }
113
+ : { path: e.path, value: e.after, base: 'beforeShown' in e ? e.beforeShown : e.before });
114
+ result = await fieldWriter(changes, entry.fieldLocale ?? null);
115
+ }
116
+ }
117
+ catch {
118
+ warn('Not saved. Try undo or redo again when the connection returns.');
119
+ }
120
+ if (result === false)
121
+ drop();
122
+ if (result === 'retry') {
123
+ drop();
124
+ // New edits clear redo, but an undo that failed still belongs before those edits.
125
+ if (generation === historyGeneration && (direction === 'undo' || edits === editGeneration)) {
126
+ const newerIndex = state[source].findIndex((e) => !earlier.has(e));
127
+ const index = newerIndex < 0 ? state[source].length : newerIndex;
128
+ set({ [source]: [...state[source].slice(0, index), entry, ...state[source].slice(index)].slice(-HISTORY_LIMIT) });
129
+ }
130
+ historyQueue.length = 0;
131
+ }
132
+ historyBusy = false;
133
+ while (historyQueue.length > 0) {
134
+ if (historyBusy)
135
+ break;
136
+ historyQueue.shift()?.();
137
+ }
138
+ })();
139
+ };
86
140
  const warn = (text) => {
87
141
  for (const listener of warnings)
88
142
  listener(text);
@@ -107,6 +161,8 @@ export function createEditorStore(initial, options = {}) {
107
161
  const selectedBefore = state.selectedId;
108
162
  if (update.reset) {
109
163
  // The layout was replaced as a whole: the history no longer applies to it.
164
+ historyGeneration++;
165
+ historyQueue.length = 0;
110
166
  set({ layout: update.layout, undoStack: [], redoStack: [] });
111
167
  return;
112
168
  }
@@ -147,7 +203,7 @@ export function createEditorStore(initial, options = {}) {
147
203
  reverse: { ops: result.inverse, selectedId: state.selectedId, tags: [tag], at: Date.now() },
148
204
  };
149
205
  };
150
- return {
206
+ const store = {
151
207
  /** The sync engine. The live hook connects it to the server. */
152
208
  sync,
153
209
  getState: () => state,
@@ -187,6 +243,14 @@ export function createEditorStore(initial, options = {}) {
187
243
  }
188
244
  list = localized.ops;
189
245
  }
246
+ if (options.storageProblem) {
247
+ const next = applyOperations(state.layout, list);
248
+ const problem = next.ok ? options.storageProblem(next.layout) : null;
249
+ if (problem) {
250
+ set({ lastError: problem });
251
+ return false;
252
+ }
253
+ }
190
254
  const tag = nextTag();
191
255
  const result = sync.local(list, tag);
192
256
  if (!result.ok) {
@@ -235,6 +299,7 @@ export function createEditorStore(initial, options = {}) {
235
299
  at: now,
236
300
  },
237
301
  ].slice(-HISTORY_LIMIT);
302
+ editGeneration++;
238
303
  set({
239
304
  layout: result.layout,
240
305
  undoStack,
@@ -245,9 +310,17 @@ export function createEditorStore(initial, options = {}) {
245
310
  return true;
246
311
  },
247
312
  undo() {
313
+ if (historyBusy) {
314
+ historyQueue.push(store.undo);
315
+ return;
316
+ }
248
317
  const entry = state.undoStack.at(-1);
249
318
  if (!entry)
250
319
  return;
320
+ if (entry.fields) {
321
+ fieldStep(entry, 'undo');
322
+ return;
323
+ }
251
324
  const done = replay(entry);
252
325
  if (!done) {
253
326
  set({ undoStack: state.undoStack.slice(0, -1) });
@@ -262,9 +335,17 @@ export function createEditorStore(initial, options = {}) {
262
335
  });
263
336
  },
264
337
  redo() {
338
+ if (historyBusy) {
339
+ historyQueue.push(store.redo);
340
+ return;
341
+ }
265
342
  const entry = state.redoStack.at(-1);
266
343
  if (!entry)
267
344
  return;
345
+ if (entry.fields) {
346
+ fieldStep(entry, 'redo');
347
+ return;
348
+ }
268
349
  const done = replay(entry);
269
350
  if (!done) {
270
351
  set({ redoStack: state.redoStack.slice(0, -1) });
@@ -278,6 +359,28 @@ export function createEditorStore(initial, options = {}) {
278
359
  lastError: null,
279
360
  });
280
361
  },
362
+ /**
363
+ * Records the action immediately. `saved` replaces its values after hooks, or removes a failed save.
364
+ */
365
+ recordFields(edits, locale = null, saved) {
366
+ if (edits.length === 0)
367
+ return;
368
+ editGeneration++;
369
+ const entry = { ops: [], fields: edits, fieldLocale: locale, selectedId: state.selectedId, tags: [], at: Date.now() };
370
+ if (saved)
371
+ entry.fieldsReady = saved.then((fields) => {
372
+ if (fields)
373
+ entry.fields = fields;
374
+ else
375
+ set({ undoStack: state.undoStack.filter((e) => e !== entry), redoStack: state.redoStack.filter((e) => e !== entry) });
376
+ return fields !== null;
377
+ });
378
+ set({ undoStack: [...state.undoStack, entry].slice(-HISTORY_LIMIT), redoStack: [] });
379
+ },
380
+ /** Saves the field changes of undo and redo. Without one, field steps cannot be undone. */
381
+ setFieldWriter(writer) {
382
+ fieldWriter = writer;
383
+ },
281
384
  /**
282
385
  * Ends the current merge run: the next edit starts a new undo step even with the same
283
386
  * `mergeKey` (a text field lost the focus). Groups are not affected.
@@ -320,6 +423,7 @@ export function createEditorStore(initial, options = {}) {
320
423
  /** The locales, or null without localization. */
321
424
  localization: localization?.settings ?? null,
322
425
  };
426
+ return store;
323
427
  }
324
428
  /**
325
429
  * Subscribes to one slice of the editor state. The component renders only when the slice changes.
@@ -225,7 +225,7 @@ function ScopeBanner({ block, scope }) {
225
225
  if (!def || !hasBindableField(def.fields))
226
226
  return null;
227
227
  if (scope.kind === 'template' && !scope.collection) {
228
- return (_jsxs("div", { className: "builder-bind__banner builder-bind__banner--warn", children: [_jsx(Icon, { name: "warning", size: 14 }), _jsxs("div", { children: [_jsx("p", { children: "Choose which collection this template is for. Then you can bind this block to its fields." }), _jsx("button", { type: "button", className: "builder-bind__link", onClick: runtime.doc.openSettings, children: "Open the template settings" })] })] }));
228
+ return (_jsxs("div", { className: "builder-bind__banner builder-bind__banner--warn", children: [_jsx(Icon, { name: "warning", size: 14 }), _jsxs("div", { children: [_jsx("p", { children: "Choose which collection this template is for. Then you can bind this block to its fields." }), _jsx("button", { type: "button", className: "builder-bind__link", onClick: () => runtime.doc.openSettings(), children: "Open the template settings" })] })] }));
229
229
  }
230
230
  if (scope.kind === 'list' && !scope.collection) {
231
231
  return (_jsxs("div", { className: "builder-bind__banner builder-bind__banner--warn", children: [_jsx(Icon, { name: "collectionList", size: 14 }), _jsx("p", { children: "This block is inside a collection list. Choose the list\u2019s collection to bind fields of each item." })] }));
@@ -20,7 +20,7 @@ export function TemplateControl() {
20
20
  if (!state.isTemplate)
21
21
  return null;
22
22
  if (!state.target) {
23
- return (_jsxs("button", { type: "button", className: "builder-template__control builder-template__control--warn", "data-tooltip": "Pick the collection in the page settings", onClick: runtime.doc.openSettings, children: [_jsx(Icon, { name: "warning", size: 14 }), _jsx("span", { className: "builder-template__mode", children: "Template" }), _jsx("span", { className: "builder-template__text", children: "Choose which collection this template is for" })] }));
23
+ return (_jsxs("button", { type: "button", className: "builder-template__control builder-template__control--warn", "data-tooltip": "Pick the collection in the page settings", onClick: () => runtime.doc.openSettings(), children: [_jsx(Icon, { name: "warning", size: 14 }), _jsx("span", { className: "builder-template__mode", children: "Template" }), _jsx("span", { className: "builder-template__text", children: "Choose which collection this template is for" })] }));
24
24
  }
25
25
  const text = state.status === 'loading' && !state.sample
26
26
  ? 'loading a sample…'
@@ -20,6 +20,8 @@ import { formatSaveTime } from './saveTime.js';
20
20
  import { RouterIntercept } from './screens/DrawerRouter.js';
21
21
  import { DrawerWidth } from './screens/DrawerWidth.js';
22
22
  import { SettingsDrawerReload, SettingsDrawerSlug } from './settingsDrawer.js';
23
+ import { useDrawerLabels } from './drawerLabels.js';
24
+ import { focusDrawerField } from './settingsFocus.js';
23
25
  /**
24
26
  * "Saving…" while this editor has unconfirmed changes or the session has unsaved commits, then
25
27
  * "Saved · 12:04" (with the day when it is not today). Errors win: "Offline" while commits cannot reach the server, "Not saved" (with
@@ -89,17 +91,29 @@ export function PageSettings() {
89
91
  const { collection, id } = useValue(runtime.doc.meta);
90
92
  const request = useValue(runtime.doc.settingsRequest);
91
93
  const singular = useCollectionLabel(collection, 'singular');
92
- const { config: { routes }, } = useConfig();
94
+ const { config: { routes }, getEntityConfig, } = useConfig();
95
+ const lockDocuments = getEntityConfig({ collectionSlug: collection })?.lockDocuments;
96
+ const lockDuration = typeof lockDocuments === 'object' ? lockDocuments.duration : undefined;
97
+ const renewLockMs = Math.min(60_000, (lockDuration && Number.isFinite(lockDuration) && lockDuration > 0 ? lockDuration : 300) * 500);
93
98
  // Numeric ids go to Payload as numbers (the app's ID type can be `number`).
94
99
  const docId = (/^\d+$/.test(id) ? Number(id) : id);
95
100
  const [DocumentDrawer, , { drawerSlug, openDrawer, closeDrawer, isDrawerOpen }] = useDocumentDrawer({ collectionSlug: collection, id: docId });
101
+ // Payload's labels in a drawer point at ids its inputs do not have: point them at the inputs.
102
+ useDrawerLabels(drawerSlug, isDrawerOpen);
96
103
  // A new key mounts the drawer's form again: Payload loads the document again.
97
104
  const [formKey, setFormKey] = useState(0);
98
105
  // The drawer takes Payload's document lock first, so a second person gets Payload's "Document
99
106
  // locked" dialog when the form loads (see live/fieldsGuard.ts).
100
107
  const open = useEffectEvent(async () => {
101
108
  await runtime.doc.settingsLock(true);
109
+ const focus = runtime.doc.settingsFocus.get();
110
+ if (focus && isDrawerOpen) {
111
+ focusDrawerField(drawerSlug, focus);
112
+ return;
113
+ }
102
114
  openDrawer();
115
+ if (focus)
116
+ focusDrawerField(drawerSlug, focus);
103
117
  });
104
118
  const reload = useCallback(async () => {
105
119
  await runtime.doc.settingsLock(true);
@@ -120,15 +134,22 @@ export function PageSettings() {
120
134
  return;
121
135
  void runtime.doc.settingsLock(false);
122
136
  void runtime.doc.refresh();
137
+ // The drawer's saves may have changed a region's fields: the canvas shows them again.
138
+ runtime.regions?.reload();
123
139
  }, [isDrawerOpen, runtime]);
124
140
  // Leaving the builder (or closing the tab) with the drawer open gives the lock back too.
125
141
  useEffect(() => {
126
142
  if (!isDrawerOpen)
127
143
  return;
128
144
  const release = () => void runtime.doc.settingsLock(false);
145
+ // A crashed tab expires on the server; an open drawer renews before that expiry.
146
+ const timer = window.setInterval(() => void runtime.doc.settingsLock(true), renewLockMs);
129
147
  window.addEventListener('pagehide', release);
130
- return () => window.removeEventListener('pagehide', release);
131
- }, [isDrawerOpen, runtime]);
148
+ return () => {
149
+ window.clearInterval(timer);
150
+ window.removeEventListener('pagehide', release);
151
+ };
152
+ }, [isDrawerOpen, runtime, renewLockMs]);
132
153
  useEffect(() => () => {
133
154
  if (!runtime.doc.settingsOpen.get())
134
155
  return;
@@ -145,7 +166,10 @@ export function PageSettings() {
145
166
  closeDrawer();
146
167
  return true;
147
168
  }, [admin, collection, closeDrawer]);
148
- return (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", className: "builder-bar__button", "aria-label": `${singular} settings`, "data-tooltip": `Title and other ${singular.toLowerCase()} settings`, onClick: runtime.doc.openSettings, children: [_jsx(Icon, { name: "settings", size: 14 }), _jsxs("span", { className: "builder-bar__label", children: [singular, " settings"] })] }), _jsx(DrawerWidth, { slug: drawerSlug, width: "min(720px, calc(100% - var(--gutter-h)))" }), _jsx(SettingsDrawerSlug, { value: drawerSlug, children: _jsx(SettingsDrawerReload, { value: reload, children: _jsx(RouterIntercept, { intercept: intercept, children: _jsx(DocumentDrawer, { disableActions: true, onSave: () => void runtime.doc.refresh() }, formKey) }) }) })] }));
169
+ return (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", className: "builder-bar__button", "aria-label": `${singular} settings`, "data-tooltip": `Title and other ${singular.toLowerCase()} settings`, onClick: () => runtime.doc.openSettings(), children: [_jsx(Icon, { name: "settings", size: 14 }), _jsxs("span", { className: "builder-bar__label", children: [singular, " settings"] })] }), _jsx(DrawerWidth, { slug: drawerSlug, width: "min(720px, calc(100% - var(--gutter-h)))" }), _jsx(SettingsDrawerSlug, { value: drawerSlug, children: _jsx(SettingsDrawerReload, { value: reload, children: _jsx(RouterIntercept, { intercept: intercept, children: _jsx(DocumentDrawer, { disableActions: true, onSave: () => {
170
+ void runtime.doc.refresh();
171
+ runtime.regions?.reload();
172
+ } }, formKey) }) }) })] }));
149
173
  }
150
174
  /**
151
175
  * "Publish changes" (disabled when nothing changed since the last publish) with a menu: Unpublish,
@@ -233,11 +257,20 @@ function PublishProblems() {
233
257
  runtime.store.select(problem.blockId);
234
258
  return;
235
259
  }
260
+ // A field of a page region: select the region on the canvas and open the drawer at the field.
261
+ const found = problem.path ? runtime.regions?.fieldOf(problem.path) : null;
262
+ if (found && runtime.regions) {
263
+ runtime.inspectorTab.set('block');
264
+ runtime.regions.selected.set(found.region.name);
265
+ runtime.doc.openSettings({ path: found.field.path, tabs: found.field.tabs });
266
+ return;
267
+ }
236
268
  runtime.doc.openSettings();
237
269
  };
238
270
  return (_jsxs(_Fragment, { children: [_jsxs("button", { ref: buttonRef, type: "button", className: "builder-bar__problems", "aria-haspopup": "dialog", "aria-expanded": list.open, "aria-label": `${count} ${count === 1 ? 'problem stops' : 'problems stop'} publishing. Show the list.`, "data-tooltip": "Fix these to publish", onClick: (e) => list.toggle(e.currentTarget), children: [_jsx(Icon, { name: "warning", size: 14 }), count] }), _jsxs(Popover, { ...list.props, className: "builder-bar__problems-popover", label: "Fix these to publish", children: [_jsx("p", { className: "builder-bar__problems-title", children: "Fix these to publish" }), _jsx("ul", { className: "builder-bar__problems-list", children: problems.map((problem, index) => {
239
271
  const block = problem.blockId ? findBlock(layout, problem.blockId) : null;
240
- const where = block ? blockSummary(block, runtime.blockLabel(block.type)) : `${singular} settings`;
272
+ const region = !block && problem.path ? runtime.regions?.fieldOf(problem.path)?.region : null;
273
+ const where = block ? blockSummary(block, runtime.blockLabel(block.type)) : region ? region.label : `${singular} settings`;
241
274
  return (_jsx("li", { children: _jsxs("button", { type: "button", className: "builder-bar__problem", onClick: () => go(problem), children: [_jsx("span", { className: "builder-bar__problem-icon", children: block ? _jsx(BlockIcon, { name: runtime.blockIcon(block.type), size: 14 }) : _jsx(Icon, { name: "settings", size: 14 }) }), _jsxs("span", { className: "builder-bar__problem-text", children: [_jsx("span", { className: "builder-bar__problem-where", children: where }), _jsx("span", { className: "builder-bar__problem-message", children: problem.message })] }), _jsx("span", { className: "builder-bar__problem-action", children: block ? 'Show' : 'Open' })] }) }, index));
242
275
  }) })] })] }));
243
276
  }
@@ -0,0 +1,50 @@
1
+ /** The URL of the drawer's autosave, with the parameters Payload's autosave sends. */
2
+ export declare function autosaveAction(input: {
3
+ api: string;
4
+ collection: string;
5
+ id: string | number;
6
+ locale?: string | null;
7
+ }): string;
8
+ /** The part of an element this file reads (tests pass fakes). */
9
+ export type CloseTarget = {
10
+ closest(selector: string): unknown;
11
+ };
12
+ /**
13
+ * Where an Escape in the topmost drawer goes: `popup` when the focus is in a popup inside it (see
14
+ * `OWN_ESCAPE`), `close` when it closes the drawer. `none`: not an Escape for this drawer.
15
+ */
16
+ export declare function escapeRoute(event: {
17
+ type: string;
18
+ key?: string;
19
+ target: CloseTarget | null;
20
+ }, topmost: boolean,
21
+ /** The drawer's element: it is a dialog itself, so it never counts as a popup in it. */
22
+ drawer?: unknown, popupOpen?: boolean): 'popup' | 'close' | 'none';
23
+ /**
24
+ * True when the event closes the drawer `slug` at once, without Payload asking first: a click on
25
+ * its "Close" button (the blurred area beside it), or Escape while it is the topmost drawer and
26
+ * no popup inside it has the focus.
27
+ */
28
+ export declare function closesDrawerAtOnce(event: {
29
+ type: string;
30
+ key?: string;
31
+ target: CloseTarget | null;
32
+ }, slug: string, topmost: boolean, drawer?: unknown): boolean;
33
+ /**
34
+ * Payload's focus trap reads Escape during capture; its modal provider reads keyCode during
35
+ * bubbling. Keep both from closing the drawer, but let the popup read Escape at the target and
36
+ * during bubbling. Replaying an Escape would run the focus trap again and release its focus.
37
+ */
38
+ export declare function keepEscapeInPopup(event: KeyboardEvent): void;
39
+ /** Payload portals have no owner ID, so remember which trigger opened them. */
40
+ export declare function trackDrawerPopups(drawer: Element): (event: {
41
+ type: string;
42
+ key?: string;
43
+ target: Element | null;
44
+ }) => boolean;
45
+ /** True when closing must wait for a save: an unsaved edit in a form that autosaves. */
46
+ export declare function closeMustSave(state: {
47
+ modified: boolean;
48
+ autosave: boolean;
49
+ saving: boolean;
50
+ }): boolean;
@@ -0,0 +1,90 @@
1
+ // Closing the builder's settings drawer with an edit that autosave has not saved yet. Payload's
2
+ // autosave waits for its interval, and the drawer's "Close" button (`#close-drawer__<slug>`) and
3
+ // Escape close it at once: the form unmounts and the edit was lost without a word. (Payload's own
4
+ // header X asks "Leave without saving?" instead, and is left alone.)
5
+ //
6
+ // So, while the form still holds the edit, the close waits: the form saves the draft as Payload's
7
+ // autosave would (the form's own `submit`, so access, hooks, validation, the document lock and the
8
+ // builder's write gate and stale-form checks apply), and the drawer closes when that worked. When
9
+ // it fails (a conflict, a validation error, offline), the drawer stays open with the typed values
10
+ // and Payload's errors. Only collections with draft autosave: without autosave, "Save draft" stays
11
+ // the user's choice, as in Payload. Never publishes.
12
+ /** The URL of the drawer's autosave, with the parameters Payload's autosave sends. */
13
+ export function autosaveAction(input) {
14
+ const params = new URLSearchParams({ autosave: 'true', depth: '0', draft: 'true', 'fallback-locale': 'null' });
15
+ if (input.locale)
16
+ params.set('locale', input.locale);
17
+ return `${input.api}/${encodeURIComponent(input.collection)}/${encodeURIComponent(String(input.id))}?${params}`;
18
+ }
19
+ /**
20
+ * Popups inside the drawer that handle Escape themselves: an expanded control (a select's or a
21
+ * relationship's open menu, a disclosure), a listbox or menu, a dialog inside the drawer, an open
22
+ * Payload popup. Their Escape closes them, never the drawer.
23
+ */
24
+ const OWN_ESCAPE = '[aria-expanded="true"], [role="listbox"], [role="menu"], [role="dialog"], .popup__content';
25
+ /**
26
+ * Where an Escape in the topmost drawer goes: `popup` when the focus is in a popup inside it (see
27
+ * `OWN_ESCAPE`), `close` when it closes the drawer. `none`: not an Escape for this drawer.
28
+ */
29
+ export function escapeRoute(event, topmost,
30
+ /** The drawer's element: it is a dialog itself, so it never counts as a popup in it. */
31
+ drawer, popupOpen = false) {
32
+ if (event.type !== 'keydown' || event.key !== 'Escape' || !topmost)
33
+ return 'none';
34
+ if (popupOpen)
35
+ return 'popup';
36
+ const popup = event.target?.closest(OWN_ESCAPE) ?? null;
37
+ return popup === null || popup === drawer ? 'close' : 'popup';
38
+ }
39
+ /**
40
+ * True when the event closes the drawer `slug` at once, without Payload asking first: a click on
41
+ * its "Close" button (the blurred area beside it), or Escape while it is the topmost drawer and
42
+ * no popup inside it has the focus.
43
+ */
44
+ export function closesDrawerAtOnce(event, slug, topmost, drawer) {
45
+ if (event.type === 'keydown')
46
+ return escapeRoute(event, topmost, drawer) === 'close';
47
+ if (event.type !== 'click' || !event.target)
48
+ return false;
49
+ return event.target.closest(`[id="close-drawer__${slug}"].drawer__close`) !== null;
50
+ }
51
+ /**
52
+ * Payload's focus trap reads Escape during capture; its modal provider reads keyCode during
53
+ * bubbling. Keep both from closing the drawer, but let the popup read Escape at the target and
54
+ * during bubbling. Replaying an Escape would run the focus trap again and release its focus.
55
+ */
56
+ export function keepEscapeInPopup(event) {
57
+ Object.defineProperties(event, {
58
+ key: { configurable: true, get: () => event.eventPhase === event.CAPTURING_PHASE ? 'Unidentified' : 'Escape' },
59
+ keyCode: { configurable: true, value: 0 },
60
+ });
61
+ }
62
+ /** Payload portals have no owner ID, so remember which trigger opened them. */
63
+ export function trackDrawerPopups(drawer) {
64
+ const document = drawer.ownerDocument;
65
+ let previous = new Set(document.querySelectorAll('.popup__content'));
66
+ let openedHere = false;
67
+ const owned = new Set();
68
+ return (event) => {
69
+ const current = new Set(document.querySelectorAll('.popup__content'));
70
+ for (const popup of current) {
71
+ if (openedHere && !previous.has(popup))
72
+ owned.add(popup);
73
+ }
74
+ for (const popup of owned) {
75
+ if (!current.has(popup))
76
+ owned.delete(popup);
77
+ }
78
+ previous = current;
79
+ openedHere = false;
80
+ if (event.type === 'click' || event.type === 'mouseover' || (event.type === 'keydown' && (event.key === 'Enter' || event.key === ' '))) {
81
+ const trigger = event.target?.closest('.popup__trigger-wrap');
82
+ openedHere = Boolean(trigger && (drawer.contains(trigger) || [...owned].some((popup) => popup.contains(trigger))));
83
+ }
84
+ return owned.size > 0;
85
+ };
86
+ }
87
+ /** True when closing must wait for a save: an unsaved edit in a form that autosaves. */
88
+ export function closeMustSave(state) {
89
+ return state.autosave && (state.modified || state.saving);
90
+ }
@@ -2,6 +2,7 @@ import type { BuilderClientConfig } from '../../../core/types.js';
2
2
  import type { BuilderDocMeta, DocStatus, LivePublishedEvent, LiveSavedEvent, PublishAction } from '../../../live/types.js';
3
3
  import { type ValueStore } from '../valueStore.js';
4
4
  import type { PublishFailure } from './problems.js';
5
+ import type { SettingsFocus } from './settingsFocus.js';
5
6
  export type DocumentBusy = PublishAction | 'rename' | null;
6
7
  /** Payload's document screens the builder opens in a drawer. */
7
8
  export type DocumentScreen = 'versions' | 'api';
@@ -11,8 +12,13 @@ export type DocumentController = {
11
12
  busy: ValueStore<DocumentBusy>;
12
13
  /** Set to the current time to open the settings drawer. */
13
14
  settingsRequest: ValueStore<number>;
14
- /** Opens the document's settings drawer (title, slug, SEO, a template's collection, …). */
15
- openSettings: () => void;
15
+ /**
16
+ * Opens the document's settings drawer (title, slug, SEO, a template's collection, …). With
17
+ * `focus`, the drawer opens the tabs that hold that field and focuses it.
18
+ */
19
+ openSettings: (focus?: SettingsFocus) => void;
20
+ /** The field the drawer opens at, set by `openSettings`. */
21
+ settingsFocus: ValueStore<SettingsFocus | null>;
16
22
  /** True while the settings drawer is open: its saves (autosave too) reload the header. */
17
23
  settingsOpen: ValueStore<boolean>;
18
24
  /**
@@ -75,6 +81,8 @@ type DocumentContext = {
75
81
  onPublishFailed?: (failure: PublishFailure) => string | null;
76
82
  /** A publish worked: old problems are gone. */
77
83
  onPublished?: () => void;
84
+ /** A save changed these top-level document fields (not the layout): their old problems are gone. */
85
+ onFieldsSaved?: (fields: readonly string[]) => void;
78
86
  };
79
87
  export declare function createDocumentController(context: DocumentContext, initial: BuilderDocMeta): DocumentController;
80
88
  export {};
@@ -48,6 +48,7 @@ export function createDocumentController(context, initial) {
48
48
  const busy = createValueStore(null);
49
49
  const settingsRequest = createValueStore(0);
50
50
  const settingsOpen = createValueStore(false);
51
+ const settingsFocus = createValueStore(null);
51
52
  const screenRequest = createValueStore(null);
52
53
  const path = `${encodeURIComponent(initial.collection)}/${encodeURIComponent(initial.id)}`;
53
54
  const endpoint = `${config.liveEndpoint}/${path}`;
@@ -101,7 +102,11 @@ export function createDocumentController(context, initial) {
101
102
  meta,
102
103
  busy,
103
104
  settingsRequest,
104
- openSettings: () => settingsRequest.set(Date.now()),
105
+ openSettings: (focus) => {
106
+ settingsFocus.set(focus ?? null);
107
+ settingsRequest.set(Date.now());
108
+ },
109
+ settingsFocus,
105
110
  settingsOpen,
106
111
  async settingsLock(take) {
107
112
  try {
@@ -121,6 +126,7 @@ export function createDocumentController(context, initial) {
121
126
  try {
122
127
  if (!(await patch({ [name]: value }, 'saved')))
123
128
  return false;
129
+ context.onFieldsSaved?.([name]);
124
130
  refreshSoon();
125
131
  return true;
126
132
  }
@@ -231,6 +237,8 @@ export function createDocumentController(context, initial) {
231
237
  updatedAt: event.updatedAt ?? current.updatedAt,
232
238
  publishedAt: status === 'published' ? (event.updatedAt ?? current.publishedAt) : current.publishedAt,
233
239
  });
240
+ if (event.fields?.length)
241
+ context.onFieldsSaved?.(event.fields);
234
242
  // A save from the settings drawer may change the title, the slug (preview URL), …
235
243
  if (settingsOpen.get())
236
244
  refreshSoon();
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The id a label should point at instead of `forId`: `forId` without its edit-depth suffix, when
3
+ * `forId` points at nothing in the drawer and the field holds an element with the shorter id.
4
+ * Null: keep the label as it is.
5
+ */
6
+ export declare function labelTarget(forId: string, inDrawer: (id: string) => boolean, inField: (id: string) => boolean): string | null;
7
+ /** The part of the DOM `relinkDrawerLabels` reads (tests pass small fakes). */
8
+ export type LabelScope = {
9
+ querySelector(selector: string): unknown;
10
+ querySelectorAll(selector: string): Iterable<DrawerLabel>;
11
+ };
12
+ export type DrawerLabel = {
13
+ htmlFor: string;
14
+ closest(selector: string): LabelScope | null;
15
+ };
16
+ /** Points the labels of `drawer` at their fields' inputs (see the top of this file). Returns how many changed. */
17
+ export declare function relinkDrawerLabels(drawer: LabelScope): number;
18
+ /**
19
+ * Keeps the labels of the document drawer `slug` pointed at their inputs while it is open: once
20
+ * after each change of the drawer's markup (Payload renders its fields, tabs and rows later).
21
+ */
22
+ export declare function useDrawerLabels(slug: string, open: boolean): void;
@@ -0,0 +1,69 @@
1
+ 'use client';
2
+ // Field labels in the builder's settings drawer. Payload's FieldLabel points a drawer field's label
3
+ // at `field-<path>-<depth>` (edit depth 2 and up), but several of Payload's inputs (text, email,
4
+ // number, select, …) keep the id `field-<path>`. In a drawer such a label points at nothing:
5
+ // screen readers announce an unnamed input, and a click on the label does not focus it. This
6
+ // points each such label at the input of its own field. Labels that already point at an element
7
+ // are left alone. Selects and relationships (react-select) get their field's label as their name
8
+ // (ui/payloadA11y.ts, as in the inspector). Nothing else in the form changes.
9
+ import { useEffect } from 'react';
10
+ import { nameComboboxes } from '../ui/payloadA11y.js';
11
+ /**
12
+ * The id a label should point at instead of `forId`: `forId` without its edit-depth suffix, when
13
+ * `forId` points at nothing in the drawer and the field holds an element with the shorter id.
14
+ * Null: keep the label as it is.
15
+ */
16
+ export function labelTarget(forId, inDrawer, inField) {
17
+ if (!forId || inDrawer(forId))
18
+ return null;
19
+ const match = /^(field-.+)-\d+$/.exec(forId);
20
+ if (!match)
21
+ return null;
22
+ return inField(match[1]) ? match[1] : null;
23
+ }
24
+ const byId = (id) => `[id="${id.replace(/["\\]/g, '\\$&')}"]`;
25
+ /** Points the labels of `drawer` at their fields' inputs (see the top of this file). Returns how many changed. */
26
+ export function relinkDrawerLabels(drawer) {
27
+ let changed = 0;
28
+ for (const label of drawer.querySelectorAll('label[for^="field-"]')) {
29
+ const field = label.closest('.field-type') ?? drawer;
30
+ const target = labelTarget(label.htmlFor, (id) => drawer.querySelector(byId(id)) !== null, (id) => field.querySelector(byId(id)) !== null);
31
+ if (target === null)
32
+ continue;
33
+ label.htmlFor = target;
34
+ changed += 1;
35
+ }
36
+ return changed;
37
+ }
38
+ /**
39
+ * Keeps the labels of the document drawer `slug` pointed at their inputs while it is open: once
40
+ * after each change of the drawer's markup (Payload renders its fields, tabs and rows later).
41
+ */
42
+ export function useDrawerLabels(slug, open) {
43
+ useEffect(() => {
44
+ if (!open || typeof MutationObserver === 'undefined')
45
+ return;
46
+ let frame = 0;
47
+ const run = () => {
48
+ frame = 0;
49
+ const drawer = document.getElementById(`close-drawer__${slug}`)?.closest('.drawer');
50
+ if (!drawer)
51
+ return;
52
+ relinkDrawerLabels(drawer);
53
+ // Selects and relationships (react-select) have no element with the field's id at all.
54
+ nameComboboxes(drawer);
55
+ };
56
+ const schedule = () => {
57
+ if (frame === 0)
58
+ frame = window.requestAnimationFrame(run);
59
+ };
60
+ const observer = new MutationObserver(schedule);
61
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['for', 'id'] });
62
+ schedule();
63
+ return () => {
64
+ observer.disconnect();
65
+ if (frame !== 0)
66
+ window.cancelAnimationFrame(frame);
67
+ };
68
+ }, [slug, open]);
69
+ }
@@ -4,6 +4,8 @@ export type PublishProblem = {
4
4
  blockId: string | null;
5
5
  /** The document field for a document-level problem ("title", "slug"). */
6
6
  field: string | null;
7
+ /** The whole path of a document field's problem ("header.title"): a page region may show it. */
8
+ path?: string;
7
9
  message: string;
8
10
  };
9
11
  /** The error shape of a failed publish. `errors` comes from the server when it can name the blocks. */
@@ -27,4 +29,11 @@ export declare function dedupeSentences(text: string): string;
27
29
  */
28
30
  export declare function publishProblems(layout: Layout, failure: PublishFailure): PublishProblem[];
29
31
  /** "2 blocks need attention" / "1 setting needs attention". */
32
+ /**
33
+ * The problems left after a save changed the top-level document fields `fields`: a problem of
34
+ * such a field is gone (its value changed, so the old message no longer says anything about it;
35
+ * the next publish checks it again). Problems of blocks and of other fields stay. Returns `list`
36
+ * itself when nothing goes.
37
+ */
38
+ export declare function withoutSavedFields(list: PublishProblem[], fields: readonly string[]): PublishProblem[];
30
39
  export declare function problemSummary(problems: PublishProblem[]): string;