payload-canvas 0.1.0 → 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 +202 -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
@@ -4,8 +4,9 @@ import { type FieldRegistry } from '../core/fieldSemantics.js';
4
4
  import type { BindingField, BlockDefinition, Layout, LocaleSettings } from '../core/types.js';
5
5
  import { type LayoutError } from '../core/validate.js';
6
6
  import { type CssOptions } from '../css/index.js';
7
- import { type FieldClock, type SettingsLocks } from '../live/fieldsGuard.js';
7
+ import { type FieldClock, type FieldHistory, type SettingsLocks } from '../live/fieldsGuard.js';
8
8
  import type { SessionManager } from '../live/session.js';
9
+ import { type WriteGate } from '../live/writeGate.js';
9
10
  /** Value of the generated CSS field. */
10
11
  export type GeneratedCss = {
11
12
  hash: string;
@@ -43,14 +44,25 @@ export declare const SESSION_SAVE_CONTEXT = "builderSession";
43
44
  * plugin clears another template's "Default" flag). The session guard leaves them alone.
44
45
  */
45
46
  export declare const KEEP_LAYOUT_CONTEXT = "builderKeepLayout";
46
- /** `context` key where the guard records the session seq it wrote. */
47
+ /**
48
+ * `context` key where the guard records the session seq it wrote, per document (`docEntry`).
49
+ * Saves that a hook runs with the same `req` (another template's "Default" flag) share the
50
+ * request's `context`: one document's seq must never mark another document's session as saved.
51
+ */
47
52
  export declare const GUARD_SEQ_CONTEXT = "builderSessionSeq";
53
+ /** `context` key where the guard records the id of the session it read, per document (`docEntry`). */
54
+ export declare const GUARD_SESSION_CONTEXT = "builderSessionId";
48
55
  /**
49
56
  * `context` key where the save hook puts the layout before and after the prop hooks
50
- * (`{ input, output }`), when the hooks changed a value. The live session reads it after its save
51
- * and sends the changed values to every editor (session.ts, `adoptSaved`).
57
+ * (`{ input, output }`), when the hooks changed a value, per document (`docEntry`). The live
58
+ * session reads it after its save and sends the changed values to every editor (session.ts,
59
+ * `adoptSaved`).
52
60
  */
53
61
  export declare const HOOK_CHANGES_CONTEXT = "builderHookChanges";
62
+ /** The entry of `collection`/`id` in a per-document `context` value (GUARD_SEQ_CONTEXT, HOOK_CHANGES_CONTEXT). */
63
+ export declare function docEntry(context: Record<string, unknown> | undefined, name: string, collection: string, id: unknown): unknown;
64
+ /** The session seq the guard wrote into this save of `collection`/`id`, or undefined. */
65
+ export declare function guardSeqOf(context: Record<string, unknown> | undefined, collection: string, id: unknown): number | undefined;
54
66
  /**
55
67
  * `context` flag for the plugin's own reads that feed a save (Revert, Restore): the layout field's
56
68
  * `afterRead` hook returns the stored layout, without prop hooks and without removing props the
@@ -79,8 +91,8 @@ export type HookChanges = {
79
91
  input: Layout;
80
92
  output: Layout;
81
93
  };
82
- /** The prop hook changes a save recorded in its `context`, or null. */
83
- export declare function hookChangesOf(context: Record<string, unknown> | undefined): HookChanges | null;
94
+ /** The prop hook changes a save of `collection`/`id` recorded in its `context`, or null. */
95
+ export declare function hookChangesOf(context: Record<string, unknown> | undefined, collection: string, id: unknown): HookChanges | null;
84
96
  /**
85
97
  * Before a plugin save, remembers Payload's lock on the document, so `layoutAfterChange` can put
86
98
  * it back (Payload deletes the lock on every update). Also before a save by someone who has the
@@ -138,6 +150,8 @@ export declare function layoutBeforeChange(options: HookOptions): CollectionBefo
138
150
  export declare function layoutAfterChange(options: {
139
151
  collection: string;
140
152
  sessions: SessionManager;
153
+ /** Events and records wait for the commit of the save. Default: the process-wide gate. */
154
+ writeGate?: WriteGate;
141
155
  fieldClock?: FieldClock;
142
156
  /** For the props' `afterChange` hooks: the layout field, the blocks, the field registry and the locales. */
143
157
  props?: {
@@ -165,4 +179,28 @@ export declare function layoutAfterRead(options: {
165
179
  /** The locales of localized props. A read in one locale gets that locale's view. */
166
180
  localization?: LocaleSettings | null;
167
181
  }): FieldHook;
182
+ /**
183
+ * The stale-save check for a Payload blocks collection: a form loaded before someone else changed
184
+ * a field (the page's blocks included) must not undo that change. See live/fieldsGuard.ts.
185
+ */
186
+ export declare function payloadBlocksBeforeChange(options: {
187
+ collection: string;
188
+ field: string;
189
+ skip: readonly string[];
190
+ fieldClock?: FieldClock;
191
+ fieldHistory?: FieldHistory;
192
+ }): CollectionBeforeChangeHook;
193
+ /**
194
+ * After a save of a Payload blocks collection committed: open editors hear of it, and when it
195
+ * came from outside the live session (the Edit view, REST, the Local API) and changed the blocks,
196
+ * the session takes the stored blocks before its next save. Records the changed fields for the
197
+ * stale-save check, and keeps Payload's document lock across the plugin's own saves.
198
+ */
199
+ export declare function payloadBlocksAfterChange(options: {
200
+ collection: string;
201
+ field: string;
202
+ sessions: SessionManager;
203
+ writeGate?: WriteGate;
204
+ fieldClock?: FieldClock;
205
+ }): CollectionAfterChangeHook;
168
206
  export {};
@@ -13,7 +13,8 @@ import { hasLocaleValues, knownLocale, mergeLocaleView, resolveLayoutLocale } fr
13
13
  import { isPlainObject, normalizeLayout } from '../core/tree.js';
14
14
  import { isBlockingError, isLayoutWarning, validateLayout } from '../core/validate.js';
15
15
  import { compileClasses } from '../css/index.js';
16
- import { checkStaleSave, defaultFieldClock, defaultSettingsLocks, KEEP_LOCK_CONTEXT, recordFieldChanges, rememberLocks, restoreLocks, staleSaveErrors, staleSaveMessage, topFieldLabel, } from '../live/fieldsGuard.js';
16
+ import { changedFieldsOf, checkStaleSave, defaultFieldClock, defaultFieldHistory, defaultSettingsLocks, KEEP_LOCK_CONTEXT, keepNewerField, recordFieldChanges, rememberLocks, restoreLocks, staleSaveErrors, staleSaveMessage, topFieldLabel, } from '../live/fieldsGuard.js';
17
+ import { defaultWriteGate, writeKey } from '../live/writeGate.js';
17
18
  /** `context` flag of the session's own draft saves. */
18
19
  export const SESSION_SAVE_CONTEXT = 'builderSession';
19
20
  /**
@@ -21,14 +22,45 @@ export const SESSION_SAVE_CONTEXT = 'builderSession';
21
22
  * plugin clears another template's "Default" flag). The session guard leaves them alone.
22
23
  */
23
24
  export const KEEP_LAYOUT_CONTEXT = 'builderKeepLayout';
24
- /** `context` key where the guard records the session seq it wrote. */
25
+ /**
26
+ * `context` key where the guard records the session seq it wrote, per document (`docEntry`).
27
+ * Saves that a hook runs with the same `req` (another template's "Default" flag) share the
28
+ * request's `context`: one document's seq must never mark another document's session as saved.
29
+ */
25
30
  export const GUARD_SEQ_CONTEXT = 'builderSessionSeq';
31
+ /** `context` key where the guard records the id of the session it read, per document (`docEntry`). */
32
+ export const GUARD_SESSION_CONTEXT = 'builderSessionId';
26
33
  /**
27
34
  * `context` key where the save hook puts the layout before and after the prop hooks
28
- * (`{ input, output }`), when the hooks changed a value. The live session reads it after its save
29
- * and sends the changed values to every editor (session.ts, `adoptSaved`).
35
+ * (`{ input, output }`), when the hooks changed a value, per document (`docEntry`). The live
36
+ * session reads it after its save and sends the changed values to every editor (session.ts,
37
+ * `adoptSaved`).
30
38
  */
31
39
  export const HOOK_CHANGES_CONTEXT = 'builderHookChanges';
40
+ /** The entry of `collection`/`id` in a per-document `context` value (GUARD_SEQ_CONTEXT, HOOK_CHANGES_CONTEXT). */
41
+ export function docEntry(context, name, collection, id) {
42
+ const entries = context?.[name];
43
+ return isPlainObject(entries) && (typeof id === 'string' || typeof id === 'number') ? entries[writeKey(collection, id)] : undefined;
44
+ }
45
+ /**
46
+ * Sets (or with `undefined`, removes) the entry of `collection`/`id`. A new object each time: the
47
+ * copies of the context that nested saves made keep their own entries.
48
+ */
49
+ function setDocEntry(context, name, collection, id, value) {
50
+ if (!context)
51
+ return;
52
+ const entries = isPlainObject(context[name]) ? context[name] : {};
53
+ const key = writeKey(collection, id);
54
+ if (value === undefined && !(key in entries))
55
+ return;
56
+ const { [key]: _old, ...rest } = entries;
57
+ context[name] = value === undefined ? rest : { ...rest, [key]: value };
58
+ }
59
+ /** The session seq the guard wrote into this save of `collection`/`id`, or undefined. */
60
+ export function guardSeqOf(context, collection, id) {
61
+ const seq = docEntry(context, GUARD_SEQ_CONTEXT, collection, id);
62
+ return typeof seq === 'number' ? seq : undefined;
63
+ }
32
64
  /**
33
65
  * `context` key where the layout field's `beforeValidate` hook records the operation's
34
66
  * `overrideAccess` (collection hooks do not get it). Field access applies only when it is false.
@@ -83,15 +115,19 @@ function requestLocale(req, settings) {
83
115
  fallback: typeof fallback === 'string' || Array.isArray(fallback) || fallback === false ? fallback : undefined,
84
116
  };
85
117
  }
86
- /** The prop hook changes a save recorded in its `context`, or null. */
87
- export function hookChangesOf(context) {
88
- const value = context?.[HOOK_CHANGES_CONTEXT];
118
+ /** The prop hook changes a save of `collection`/`id` recorded in its `context`, or null. */
119
+ export function hookChangesOf(context, collection, id) {
120
+ const value = docEntry(context, HOOK_CHANGES_CONTEXT, collection, id);
89
121
  return isPlainObject(value) && isPlainObject(value.input) && isPlainObject(value.output) ? value : null;
90
122
  }
91
123
  /**
92
124
  * A save by the plugin itself: the session's draft, publish / unpublish / revert, or the template
93
125
  * "Default" flag. It keeps Payload's document lock and skips the stale-save check.
94
126
  */
127
+ /** Payload's Restore of a version (its operation sets this flag): the version's values are the truth. */
128
+ function isRestore(context) {
129
+ return Boolean(context?.isRestoringVersion);
130
+ }
95
131
  function isPluginSave(context) {
96
132
  return Boolean(context?.[SESSION_SAVE_CONTEXT] || context?.[KEEP_LAYOUT_CONTEXT] || context?.[KEEP_LOCK_CONTEXT]);
97
133
  }
@@ -116,6 +152,8 @@ export function keepLockBeforeOperation(options) {
116
152
  }
117
153
  const userId = req.user?.id;
118
154
  if ((typeof userId === 'string' || typeof userId === 'number') && holders.has(options.collection, id, userId)) {
155
+ // A save from the open drawer: it is still open.
156
+ holders.renew(options.collection, id, userId);
119
157
  await rememberLocks({ payload, req, collection: options.collection, id, context, owner: userId });
120
158
  }
121
159
  return args;
@@ -197,15 +235,29 @@ export function layoutBeforeChange(options) {
197
235
  const docId = originalDoc?.id;
198
236
  const own = context?.[SESSION_SAVE_CONTEXT] || context?.[KEEP_LAYOUT_CONTEXT];
199
237
  let guarded = false;
200
- if (sessions && operation === 'update' && docId !== undefined && !own) {
238
+ // Payload's Restore writes the version: its layout is the truth (the session takes it after the commit).
239
+ if (sessions && operation === 'update' && docId !== undefined && !own && !isRestore(context)) {
201
240
  const open = sessions.peek(slug, docId);
202
241
  if (open) {
242
+ // A Restore or Revert runs: its layout may still be rolled back. Refused at once, never
243
+ // waiting while this save holds the write gate (the action's save needs it).
244
+ if (open.resetting)
245
+ throw new APIError('Not saved: this document is being restored or reverted. Try again in a moment.', 409, undefined, true);
246
+ // The hook changes of a committed save are not in the session's layout yet: copying it now
247
+ // would store the layout without them. Refused at once for the same reason.
248
+ if (open.adopting)
249
+ throw new APIError('Not saved: the live editor is still taking in the last save. Try again in a moment.', 409, undefined, true);
203
250
  data[field] = structuredClone(open.layout);
204
251
  guarded = true;
205
- if (context)
206
- context[GUARD_SEQ_CONTEXT] = open.seq;
252
+ setDocEntry(context, GUARD_SEQ_CONTEXT, slug, docId, open.seq);
253
+ setDocEntry(context, GUARD_SESSION_CONTEXT, slug, docId, open.sessionId);
207
254
  }
208
255
  }
256
+ // An earlier guarded save of this document in the same request does not make this one guarded.
257
+ if (!guarded && docId !== undefined) {
258
+ setDocEntry(context, GUARD_SEQ_CONTEXT, slug, docId, undefined);
259
+ setDocEntry(context, GUARD_SESSION_CONTEXT, slug, docId, undefined);
260
+ }
209
261
  // Stale-save check for the other fields (title, slug, SEO, …): a form loaded before someone
210
262
  // else changed a field must not undo that change. See live/fieldsGuard.ts.
211
263
  if (operation === 'update' && docId !== undefined) {
@@ -218,7 +270,8 @@ export function layoutBeforeChange(options) {
218
270
  skip: pluginFields,
219
271
  user: req.user,
220
272
  context,
221
- pluginSave: isPluginSave(context),
273
+ // A restore writes a version's values with that version's `updatedAt`: not a stale form.
274
+ pluginSave: isPluginSave(context) || isRestore(context),
222
275
  });
223
276
  if (conflicts.length > 0) {
224
277
  throw new APIError(staleSaveMessage(conflicts, (name) => topFieldLabel(collection.fields, name)), 409, staleSaveErrors(conflicts), true);
@@ -288,8 +341,10 @@ export function layoutBeforeChange(options) {
288
341
  const input = structuredClone(layout);
289
342
  await runPropHooks('beforeValidate', layout, { blocks, registry, previous: savedLayout, ctx, localization });
290
343
  await runPropHooks('beforeChange', layout, { blocks, registry, previous: savedLayout, ctx, localization });
291
- if (context && !sameJson(input, layout))
292
- context[HOOK_CHANGES_CONTEXT] = { input, output: structuredClone(layout) };
344
+ if (docId !== undefined) {
345
+ const changes = sameJson(input, layout) ? undefined : { input, output: structuredClone(layout) };
346
+ setDocEntry(context, HOOK_CHANGES_CONTEXT, slug, docId, changes);
347
+ }
293
348
  }
294
349
  }
295
350
  const { blocking, warnings } = await checkLayout(layout, { blocks, publishing, bindings, doc: merged, fields: fieldCheck(savedLayout), localization });
@@ -333,17 +388,37 @@ export function layoutBeforeChange(options) {
333
388
  */
334
389
  export function layoutAfterChange(options) {
335
390
  const clock = options.fieldClock ?? defaultFieldClock();
391
+ const gate = options.writeGate ?? defaultWriteGate();
336
392
  const props = options.props;
337
393
  return async ({ collection, context, data, doc, operation, previousDoc, req }) => {
338
394
  if (doc?.id === undefined)
339
395
  return doc;
340
- const seq = context?.[GUARD_SEQ_CONTEXT];
341
- if (typeof seq === 'number') {
342
- options.sessions.markSaved(options.collection, doc.id, seq, { updatedAt: doc.updatedAt, status: doc._status });
396
+ // This document's own entry: a save another document's hook ran with the same `req` never counts.
397
+ const seq = guardSeqOf(context, options.collection, doc.id);
398
+ // Only after the save committed (never after a rollback): editors that hear of it reload the
399
+ // values, and must find them stored.
400
+ const afterCommit = (fn) => gate.afterCommit(req, writeKey(options.collection, doc.id), fn);
401
+ if (seq !== undefined) {
402
+ // Editors show the page frame again when this save changed a region's field.
403
+ const fields = operation === 'update' ? changedFieldsOf(context, options.collection, doc.id) : [];
404
+ const guarded = docEntry(context, GUARD_SESSION_CONTEXT, options.collection, doc.id);
405
+ const source = typeof guarded === 'string' ? { sessionId: guarded } : {};
406
+ const info = { updatedAt: doc.updatedAt, status: doc._status, fields, ...source };
343
407
  // The save ran the prop hooks on the session's layout. Every editor gets the changed values.
344
- const changes = hookChangesOf(context);
345
- if (changes)
346
- options.sessions.adoptSaved(options.collection, doc.id, { ...changes, seq });
408
+ const changes = hookChangesOf(context, options.collection, doc.id);
409
+ const docId = doc.id;
410
+ afterCommit(() => {
411
+ options.sessions.markSaved(options.collection, docId, seq, info);
412
+ if (changes)
413
+ options.sessions.adoptSaved(options.collection, docId, { ...changes, seq, ...source });
414
+ });
415
+ }
416
+ else if (operation === 'update' && context?.[KEEP_LAYOUT_CONTEXT] && !context?.[SESSION_SAVE_CONTEXT]) {
417
+ // A plugin save that left the layout alone (another template's "Default" flag): editors hear
418
+ // of it, and an open session reads the other fields again (field access reads them).
419
+ const docId = doc.id;
420
+ const info = { updatedAt: doc.updatedAt, status: doc._status, fields: changedFieldsOf(context, options.collection, docId) };
421
+ afterCommit(() => options.sessions.externalSaved(options.collection, docId, info));
347
422
  }
348
423
  // The props' afterChange hooks. As in Payload, what they return changes only the returned document.
349
424
  let result = doc;
@@ -362,7 +437,19 @@ export function layoutAfterChange(options) {
362
437
  }
363
438
  if (operation !== 'update')
364
439
  return result;
365
- recordFieldChanges({ clock, collection: options.collection, doc, user: req.user, context });
440
+ // The work keeps no reference to `req`: the gate ends a hold when its request is collected.
441
+ const recorded = { ...doc };
442
+ const user = req.user;
443
+ // A restore of a version, after its commit. Payload's Restore: editors take the restored layout.
444
+ // The builder's Restore (STORED_LAYOUT) reset the session to that layout itself, so it stays:
445
+ // the session only reads the other fields again (they are the version's now).
446
+ if (isRestore(context)) {
447
+ const docId = doc.id;
448
+ const layoutChanged = !context?.[STORED_LAYOUT_CONTEXT];
449
+ const info = { updatedAt: doc.updatedAt, status: doc._status, fields: changedFieldsOf(context, options.collection, docId), layoutChanged };
450
+ afterCommit(() => options.sessions.externalSaved(options.collection, docId, info));
451
+ }
452
+ afterCommit(() => recordFieldChanges({ clock, collection: options.collection, doc: recorded, user, context }));
366
453
  // Same transaction as Payload's delete of the lock, so nobody sees the document unlocked.
367
454
  await restoreLocks({ payload: req.payload, req, collection: options.collection, id: doc.id, context });
368
455
  return result;
@@ -428,3 +515,72 @@ export function layoutAfterRead(options) {
428
515
  return layout;
429
516
  };
430
517
  }
518
+ // ---------------------------------------------------------------------------
519
+ // Collections whose layout field is their own Payload `blocks` field
520
+ // ---------------------------------------------------------------------------
521
+ //
522
+ // The field is the one source of truth, and Payload owns it: its own validation, hooks and access
523
+ // run on every save, exactly once, and no save gets another layout put in. The builder's live
524
+ // session reads the field and writes it with its codec (live/storage.ts). These hooks only keep
525
+ // saves from overwriting each other and tell open editors about saves from elsewhere.
526
+ /**
527
+ * The stale-save check for a Payload blocks collection: a form loaded before someone else changed
528
+ * a field (the page's blocks included) must not undo that change. See live/fieldsGuard.ts.
529
+ */
530
+ export function payloadBlocksBeforeChange(options) {
531
+ const clock = options.fieldClock ?? defaultFieldClock();
532
+ const history = options.fieldHistory ?? defaultFieldHistory();
533
+ const skip = new Set(options.skip);
534
+ return ({ collection, context, data, operation, originalDoc, req }) => {
535
+ if (!data)
536
+ return data;
537
+ const docId = originalDoc?.id;
538
+ if (operation !== 'update' || docId === undefined)
539
+ return data;
540
+ // A form loaded before the blocks last changed (the settings drawer while the canvas saves):
541
+ // blocks it left as loaded keep the newer blocks, changed ones are a conflict.
542
+ history.remember(options.collection, docId, options.field, originalDoc?.updatedAt, originalDoc?.[options.field]);
543
+ const blocks = isPluginSave(context) || isRestore(context)
544
+ ? []
545
+ : keepNewerField({ history, clock, collection: options.collection, id: docId, field: options.field, data, originalDoc });
546
+ if (blocks.length > 0) {
547
+ throw new APIError(staleSaveMessage(blocks, (name) => topFieldLabel(collection.fields, name)), 409, staleSaveErrors(blocks), true);
548
+ }
549
+ const conflicts = checkStaleSave({ clock, collection: options.collection, id: docId, data, originalDoc, skip, user: req.user, context, pluginSave: isPluginSave(context) || isRestore(context) });
550
+ if (conflicts.length > 0) {
551
+ throw new APIError(staleSaveMessage(conflicts, (name) => topFieldLabel(collection.fields, name)), 409, staleSaveErrors(conflicts), true);
552
+ }
553
+ return data;
554
+ };
555
+ }
556
+ /**
557
+ * After a save of a Payload blocks collection committed: open editors hear of it, and when it
558
+ * came from outside the live session (the Edit view, REST, the Local API) and changed the blocks,
559
+ * the session takes the stored blocks before its next save. Records the changed fields for the
560
+ * stale-save check, and keeps Payload's document lock across the plugin's own saves.
561
+ */
562
+ export function payloadBlocksAfterChange(options) {
563
+ const clock = options.fieldClock ?? defaultFieldClock();
564
+ const gate = options.writeGate ?? defaultWriteGate();
565
+ return async ({ context, doc, operation, req }) => {
566
+ if (doc?.id === undefined || operation !== 'update')
567
+ return doc;
568
+ const docId = doc.id;
569
+ const fields = changedFieldsOf(context, options.collection, docId);
570
+ // The session's own save tells editors itself; Revert and Restore reset the session themselves.
571
+ const own = Boolean(context?.[SESSION_SAVE_CONTEXT]);
572
+ const resets = Boolean(context?.[STORED_LAYOUT_CONTEXT]);
573
+ const info = { updatedAt: doc.updatedAt, status: doc._status, fields, layoutChanged: !own && !resets && (fields.includes(options.field) || isRestore(context)) };
574
+ // The work keeps no reference to `req`: the gate ends a hold when its request is collected.
575
+ const recorded = { ...doc };
576
+ const user = req.user;
577
+ gate.afterCommit(req, writeKey(options.collection, docId), () => {
578
+ if (!own)
579
+ options.sessions.externalSaved(options.collection, docId, info);
580
+ recordFieldChanges({ clock, collection: options.collection, doc: recorded, user, context });
581
+ });
582
+ // Same transaction as Payload's delete of the lock, so nobody sees the document unlocked.
583
+ await restoreLocks({ payload: req.payload, req, collection: options.collection, id: docId, context });
584
+ return doc;
585
+ };
586
+ }
@@ -1,5 +1,6 @@
1
1
  import type { CollectionConfig, Payload, Plugin } from 'payload';
2
2
  import type { AiOptions } from '../ai/types.js';
3
+ import { type RegionOption } from '../core/regions.js';
3
4
  import { type BlockDefinition, type EditorOptions, type SectionDefinition } from '../core/types.js';
4
5
  import { type CssOptions, type FontFamilies, type TailwindPlugins } from '../css/index.js';
5
6
  import { type ThemeOptions } from '../theme/config.js';
@@ -25,7 +26,16 @@ export declare function siteCssConfigOf(payload: {
25
26
  };
26
27
  }): SiteCssConfig | null;
27
28
  export type BuilderCollectionOptions = {
28
- /** Name of the layout JSON field. Default "layout". */
29
+ /**
30
+ * Name of the builder's field. Default "layout". The field's own type says how the layout is
31
+ * stored:
32
+ * - a Payload `blocks` field of the collection: the builder edits that field itself, the one
33
+ * source of truth. Payload's editor, hooks, validation, access and versions keep working on it;
34
+ * the builder offers only its block types (from `fromPayloadBlocks`) and keeps nothing the field
35
+ * cannot hold (no Tailwind classes, animations, bindings, hidden blocks; translations in
36
+ * Payload's editor).
37
+ * - a `json` field, or no field with that name: the builder's own JSON layout, with every feature.
38
+ */
29
39
  field?: string;
30
40
  /**
31
41
  * Frontend path of a document. Used for preview. Collections with a `url` can be shown by the
@@ -45,6 +55,16 @@ export type BuilderCollectionOptions = {
45
55
  * draft too. Remove the names when you remove the fields.
46
56
  */
47
57
  legacyFields?: string[];
58
+ /**
59
+ * Fixed parts of the page that show ordinary document fields outside the layout, for example a
60
+ * header made of `title`, `subtitle` and `coverImage`. The fields stay where they are; the
61
+ * builder shows the whole page through the app's page frame (`createCanvasServer({ frame })`)
62
+ * and lets editors edit these fields on the canvas and in the settings drawer. A region is
63
+ * never dragged, duplicated or deleted. Paths go through groups and named tabs ("header.title");
64
+ * fields in rows, collapsibles and unnamed tabs are named directly. Left out: the builder shows
65
+ * the layout alone. See the README's "Whole-page editing" section.
66
+ */
67
+ regions?: RegionOption[];
48
68
  /**
49
69
  * How the layout is translated when Payload's `localization` is on. `'props'` (the default):
50
70
  * one layout structure for every locale; props whose field says `localized: true` hold a value
@@ -139,3 +159,5 @@ export declare function cssFieldName(field: string): string;
139
159
  * without Payload's nav and header). The document's "Builder" tab and the layout field link there.
140
160
  */
141
161
  export declare function websiteBuilder(options: WebsiteBuilderOptions): Plugin;
162
+ /** Name of the hidden virtual field that carries the builder's config for a Payload blocks field. */
163
+ export declare function builderConfigFieldName(field: string): string;