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
@@ -6,6 +6,8 @@ import { defaultBlocks } from '../blocks/index.js';
6
6
  import { richTextFieldName } from '../core/blocks.js';
7
7
  import { DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, TEMPLATE_TARGET_FIELD } from '../core/bindings.js';
8
8
  import { localeSettingsOf } from '../core/locale.js';
9
+ import { resolveRegions } from '../core/regions.js';
10
+ import { decodePayloadBlocks, payloadBlocksProblems, payloadBlocksStorage } from '../core/payloadBlocks.js';
9
11
  import { EMPTY_LAYOUT, } from '../core/types.js';
10
12
  import { applyFontFamilies, getCanvasCssInput, getStyleTokens } from '../css/index.js';
11
13
  import { DEFAULT_THEME_SLUG, THEME_CONFIG_KEY, THEME_PATH } from '../theme/config.js';
@@ -14,7 +16,9 @@ import { themeGlobal } from '../theme/global.js';
14
16
  import { BUILDER_CONFIG_KEY, defaultLiveRuntime, documentEndpoints, installShutdownFlush, LIVE_PATH, LIVE_RUNTIME_KEY, liveEndpoints, } from '../live/index.js';
15
17
  import { captureFieldSemantics } from '../core/fieldSemantics.js';
16
18
  import { FIELD_REGISTRY_KEY } from '../live/fieldChecks.js';
17
- import { keepLockBeforeOperation, layoutAfterChange, layoutAfterRead, layoutBeforeChange, recordOverrideAccess, } from './hook.js';
19
+ import { regionEndpoints } from '../live/regions.js';
20
+ import { defaultWriteGate, installLocalApiBoundary, installTransactionSignals, withGateSignals } from '../live/writeGate.js';
21
+ import { keepLockBeforeOperation, layoutAfterChange, payloadBlocksAfterChange, payloadBlocksBeforeChange, layoutAfterRead, layoutBeforeChange, recordOverrideAccess, } from './hook.js';
18
22
  import { DEFAULT_SAVED_SECTIONS_SLUG, SAVED_SECTIONS_CONFIG_KEY, savedSectionsCollection, SECTION_LAYOUT_FIELD, } from './sections.js';
19
23
  import { syncSectionBlocks } from './sectionsBuilder.js';
20
24
  import { toJsonSafe } from './jsonSafe.js';
@@ -62,9 +66,15 @@ export function websiteBuilder(options) {
62
66
  const canvasPath = options.canvasPath ?? '/builder-canvas';
63
67
  const sourceCollections = config.collections ?? [];
64
68
  const live = defaultLiveRuntime();
69
+ const writeGate = defaultWriteGate();
65
70
  // Payload's locales. Each builder collection uses them unless it sets `localization: false`.
66
71
  const locales = localeSettingsOf(config.localization);
72
+ // Collections whose builder field is their own Payload blocks field (filled below).
73
+ const blocksStorageOf = {};
67
74
  const localizationOf = (slug) => {
75
+ // A Payload blocks field: the builder edits the default locale; Payload's editor the others.
76
+ if (blocksStorageOf[slug])
77
+ return null;
68
78
  const option = builderOptions[slug]?.localization;
69
79
  if (option !== undefined && option !== false && option !== 'props') {
70
80
  throw new Error(`[websiteBuilder] \`localization\` of "${slug}" must be 'props' or false. A separate layout per locale is not supported yet.`);
@@ -138,6 +148,22 @@ export function websiteBuilder(options) {
138
148
  }
139
149
  }
140
150
  }
151
+ // A builder field that is the collection's own Payload blocks field stays the source of truth.
152
+ for (const [slug, o] of Object.entries(options.collections)) {
153
+ const source = sourceCollections.find((c) => c.slug === slug);
154
+ const field = o.field ?? 'layout';
155
+ const found = source ? takeField(source.fields, field).found : undefined;
156
+ if (found?.type !== 'blocks')
157
+ continue;
158
+ if (o.templates) {
159
+ throw new Error(`[websiteBuilder] "${slug}.${field}" is a Payload blocks field, and templates hold builder JSON layouts. Leave out \`templates\` for "${slug}", or use a json field.`);
160
+ }
161
+ const slugs = [
162
+ ...(found.blocks ?? []).map((b) => (typeof b === 'string' ? b : b.slug)),
163
+ ...(found.blockReferences ?? []).map((b) => (typeof b === 'string' ? b : b.slug)),
164
+ ];
165
+ blocksStorageOf[slug] = payloadBlocksStorage([...new Set(slugs)], blocks, `"${slug}.${field}"`);
166
+ }
141
167
  // Saved sections: a collection of sections people saved from the editor.
142
168
  const savedSections = options.savedSections === false ? null : { slug: options.savedSections?.slug ?? DEFAULT_SAVED_SECTIONS_SLUG };
143
169
  if (savedSections) {
@@ -157,10 +183,34 @@ export function websiteBuilder(options) {
157
183
  collections,
158
184
  blocks,
159
185
  sources: {
160
- ...Object.fromEntries(Object.entries(builderOptions).map(([slug, o]) => [slug, { layout: o.field ?? 'layout' }])),
186
+ ...Object.fromEntries(Object.entries(builderOptions).map(([slug, o]) => {
187
+ const storage = blocksStorageOf[slug];
188
+ if (!storage)
189
+ return [slug, { layout: o.field ?? 'layout' }];
190
+ // The references index follows the blocks field itself (no copy of the content).
191
+ const decode = (value) => {
192
+ const result = decodePayloadBlocks(value, storage);
193
+ return result.ok ? result.layout : undefined;
194
+ };
195
+ return [slug, { layout: o.field ?? 'layout', decode }];
196
+ })),
161
197
  ...(savedSections ? { [savedSections.slug]: { layout: 'blocks', blocksOnly: true } } : {}),
162
198
  },
163
199
  });
200
+ // Page regions: document fields outside the layout that the builder shows and edits.
201
+ const regionsOf = {};
202
+ for (const [slug, o] of Object.entries(options.collections)) {
203
+ if (!o.regions)
204
+ continue;
205
+ if (!Array.isArray(o.regions))
206
+ throw new Error(`[websiteBuilder] \`regions\` of "${slug}" must be a list.`);
207
+ if (o.regions.length === 0)
208
+ continue;
209
+ const source = sourceCollections.find((c) => c.slug === slug);
210
+ const field = o.field ?? 'layout';
211
+ const own = [field, cssFieldName(field), richTextFieldName(field), DOCUMENT_TEMPLATE_FIELD, ...(references ? [references.field] : [])];
212
+ regionsOf[slug] = resolveRegions(slug, source?.fields ?? [], o.regions, { fields: new Set(own), legacy: new Set(o.legacyFields ?? []) });
213
+ }
164
214
  const clientBlocks = toJsonSafe(blocks);
165
215
  const css = {
166
216
  entry: path.resolve(process.cwd(), options.css.entry),
@@ -173,6 +223,8 @@ export function websiteBuilder(options) {
173
223
  ...(o.url ? { url: o.url } : {}),
174
224
  ...(o.legacyFields?.length ? { legacyFields: o.legacyFields } : {}),
175
225
  localization: localizationOf(slug),
226
+ ...(regionsOf[slug] ? { regions: regionsOf[slug] } : {}),
227
+ ...(blocksStorageOf[slug] ? { payloadBlocks: blocksStorageOf[slug] } : {}),
176
228
  },
177
229
  ]));
178
230
  const serverConfig = { collections: liveCollections, templates: targets.length > 0 ? templatesSlug : null };
@@ -215,6 +267,9 @@ export function websiteBuilder(options) {
215
267
  const imageService = options.ai ? createImageService(options.ai) : null;
216
268
  return {
217
269
  ...config,
270
+ // The write gate hears of every commit, rollback and failed Local API save from the first one
271
+ // on, also without onInit (`payload migrate`) and in migrations on connect (live/writeGate.ts).
272
+ ...(config.db ? { db: withGateSignals(config.db, writeGate) } : {}),
218
273
  admin: {
219
274
  ...config.admin,
220
275
  components: {
@@ -232,14 +287,21 @@ export function websiteBuilder(options) {
232
287
  return references ? addReferences(collection, references) : collection;
233
288
  const field = collectionOptions.field ?? 'layout';
234
289
  fieldNames[collection.slug] = field;
290
+ const storage = blocksStorageOf[collection.slug];
235
291
  const clientConfig = {
236
292
  collection: collection.slug,
237
293
  field,
238
- blocks: clientBlocks,
294
+ // A Payload blocks field offers its own block types only.
295
+ // Its blocks have no style controls there: a Payload block stores no classes or animations,
296
+ // also when the definition turns styles on for the builder's JSON layouts.
297
+ blocks: storage ? toJsonSafe(storage.blocks.map(withoutStyles)) : clientBlocks,
239
298
  canvasPath,
240
299
  cssEndpoint: `${apiRoute}${CANVAS_CSS_PATH}`,
241
300
  tokensEndpoint: `${apiRoute}${STYLE_TOKENS_PATH}`,
242
- sections: options.sections ?? [],
301
+ // Only sections the field can store as they are.
302
+ sections: storage
303
+ ? (options.sections ?? []).filter((section) => payloadBlocksProblems({ version: 1, blocks: section.blocks }, storage).length === 0)
304
+ : (options.sections ?? []),
243
305
  liveEndpoint: `${apiRoute}${LIVE_PATH}`,
244
306
  templates: clientTemplates,
245
307
  ai: options.ai ? aiClientConfig(options.ai, `${apiRoute}${AI_PATH}`) : null,
@@ -248,6 +310,8 @@ export function websiteBuilder(options) {
248
310
  editor: { dragMode: options.editor?.dragMode ?? 'indicator' },
249
311
  validateTypes: [...fieldRegistry.types('validate')],
250
312
  localization: localizationOf(collection.slug),
313
+ ...(regionsOf[collection.slug] ? { regions: toJsonSafe(regionsOf[collection.slug]) } : {}),
314
+ ...(storage ? { storage: 'payload-blocks', payloadRootTypes: [...storage.rootTypes] } : {}),
251
315
  };
252
316
  const isSections = collection.slug === savedSections?.slug;
253
317
  const built = addBuilder(collection, {
@@ -263,6 +327,8 @@ export function websiteBuilder(options) {
263
327
  ownFields: [...(references ? [references.field] : []), ...(isSections ? ['blocks'] : [])],
264
328
  fieldRegistry,
265
329
  localization: localizationOf(collection.slug),
330
+ writeGate,
331
+ payloadBlocks: storage,
266
332
  });
267
333
  // After the layout hook, so the references follow the layout the session guard put in.
268
334
  return references ? addReferences(built, references) : built;
@@ -281,9 +347,16 @@ export function websiteBuilder(options) {
281
347
  ...(imageService ? { [AI_IMAGES_KEY]: imageService } : {}),
282
348
  },
283
349
  globals: themeOptions ? [...(config.globals ?? []), themeGlobal(themeOptions)] : config.globals,
350
+ // A failed GraphQL or REST request ends its builder saves without a transaction (live/writeGate.ts).
351
+ hooks: {
352
+ ...config.hooks,
353
+ afterError: [...(config.hooks?.afterError ?? []), ({ req }) => writeGate.failRequest(req)],
354
+ },
284
355
  endpoints: [
285
356
  ...(config.endpoints ?? []),
286
357
  ...liveEndpoints({ collections: liveCollections, blocks, runtime: live, heartbeatMs: options.live?.heartbeatMs, fieldRegistry }),
358
+ // Region fields: only when a collection has regions.
359
+ ...(Object.keys(regionsOf).length > 0 ? regionEndpoints({ collections: liveCollections, runtime: live, gate: writeGate }) : []),
287
360
  ...documentEndpoints({
288
361
  collections: liveCollections,
289
362
  templates: serverConfig.templates,
@@ -345,10 +418,19 @@ export function websiteBuilder(options) {
345
418
  : []),
346
419
  ],
347
420
  onInit: async (payload) => {
421
+ // The adapter's init already did this (withGateSignals); again here for a `db` that came
422
+ // in some other way. Before the app's own onInit saves anything: the write gate learns
423
+ // from the adapter itself when a transaction committed or rolled back…
424
+ installTransactionSignals(payload.db, writeGate);
425
+ // …and when a Local API update ended, also a failed one without a transaction.
426
+ installLocalApiBoundary(payload, writeGate);
348
427
  await config.onInit?.(payload);
349
428
  // Save unsaved live edits when the server stops.
350
429
  installShutdownFlush(live.sessions);
351
430
  for (const [slug, field] of Object.entries(fieldNames)) {
431
+ // A Payload blocks field stays where the collection put it.
432
+ if (blocksStorageOf[slug])
433
+ continue;
352
434
  const collection = payload.config.collections.find((c) => c.slug === slug);
353
435
  const topLevel = collection?.fields.some((f) => 'name' in f && f.name === field);
354
436
  if (topLevel)
@@ -360,14 +442,18 @@ export function websiteBuilder(options) {
360
442
  };
361
443
  }
362
444
  function addBuilder(collection, args) {
445
+ if (args.payloadBlocks)
446
+ return addPayloadBlocksBuilder(collection, args, args.payloadBlocks);
363
447
  const { field, clientConfig, blocks, css, sessions, bindings, afterLayout = [], ownFields, fieldRegistry, localization } = args;
364
448
  const cssField = cssFieldName(field);
449
+ const gate = args.writeGate.hooks(collection.slug);
365
450
  // An existing field with this name (also inside rows, collapsibles or unnamed tabs) is reused
366
451
  // and moved to the top level.
367
452
  const { fields, found } = takeField(collection.fields, field);
368
453
  if (found && found.type !== 'json') {
369
454
  throw new Error(wrongFieldTypeMessage(collection.slug, field, found.type));
370
455
  }
456
+ // (A `blocks` field never gets here: addPayloadBlocksBuilder edits it in place.)
371
457
  if (fields.some((f) => 'name' in f && f.name === cssField)) {
372
458
  throw new Error(`[websiteBuilder] Collection "${collection.slug}" already has a field named "${cssField}". The plugin needs this name for the generated CSS.`);
373
459
  }
@@ -415,12 +501,18 @@ function addBuilder(collection, args) {
415
501
  };
416
502
  return {
417
503
  ...collection,
504
+ // The write gate refuses bulk updates (live/writeGate.ts): the list view does not offer them.
505
+ disableBulkEdit: true,
418
506
  fields: [...fields, layoutField, generatedCssField, ...(richText ? [richText] : [])],
419
507
  // Payload's document lock stays on: it protects the other fields in the Edit view and the
420
508
  // settings drawer. The builder view never takes it; the plugin's own saves keep it.
421
509
  hooks: {
422
510
  ...collection.hooks,
423
- beforeOperation: [...(collection.hooks?.beforeOperation ?? []), keepLockBeforeOperation({ collection: collection.slug })],
511
+ // One save at a time per document (live/writeGate.ts): the session's layout saves, the
512
+ // settings drawer's autosave and the region fields endpoint never overwrite each other.
513
+ beforeOperation: [...(collection.hooks?.beforeOperation ?? []), gate.beforeOperation, keepLockBeforeOperation({ collection: collection.slug })],
514
+ afterOperation: [...(collection.hooks?.afterOperation ?? []), gate.afterOperation],
515
+ afterError: [...(collection.hooks?.afterError ?? []), gate.afterError],
424
516
  beforeChange: [
425
517
  ...(collection.hooks?.beforeChange ?? []),
426
518
  layoutBeforeChange({ collection: collection.slug, field, cssField, blocks, css, sessions, bindings, ownFields, fieldRegistry, localization }),
@@ -428,7 +520,7 @@ function addBuilder(collection, args) {
428
520
  ],
429
521
  afterChange: [
430
522
  ...(collection.hooks?.afterChange ?? []),
431
- layoutAfterChange({ collection: collection.slug, sessions, props: { field, blocks, registry: fieldRegistry, localization } }),
523
+ layoutAfterChange({ collection: collection.slug, sessions, writeGate: args.writeGate, props: { field, blocks, registry: fieldRegistry, localization } }),
432
524
  ],
433
525
  },
434
526
  admin: {
@@ -450,15 +542,85 @@ function addBuilder(collection, args) {
450
542
  },
451
543
  };
452
544
  }
545
+ /**
546
+ * The builder on a collection whose builder field is its own Payload `blocks` field: the field
547
+ * stays exactly as the collection declares it (place, editor, hooks, validation, access, versions),
548
+ * and no other field holds the content. The builder adds the Builder tab and view, the write gate,
549
+ * the stale-save check and the handover of saves from elsewhere to the live session.
550
+ */
551
+ function addPayloadBlocksBuilder(collection, args, storage) {
552
+ const { field, clientConfig, sessions, ownFields = [] } = args;
553
+ const gate = args.writeGate.hooks(collection.slug);
554
+ // The inspector edits rich text props with Payload's editor through a virtual field (no column).
555
+ const richText = richTextSupportField(storage.blocks, field);
556
+ if (richText && collection.fields.some((f) => 'name' in f && f.name === richText.name)) {
557
+ throw new Error(`[websiteBuilder] Collection "${collection.slug}" already has a field named "${richText.name}". The plugin needs this name for rich text block props.`);
558
+ }
559
+ const views = collection.admin?.components?.views;
560
+ if (views?.edit?.root) {
561
+ throw new Error(`[websiteBuilder] Collection "${collection.slug}" replaces the whole document view (admin.components.views.edit.root). The Builder tab cannot be added.`);
562
+ }
563
+ const edit = {
564
+ ...views?.edit,
565
+ builder: { Component: BUILDER_REDIRECT_COMPONENT, path: '/builder', tab: { Component: BUILDER_TAB_COMPONENT } },
566
+ };
567
+ // The builder view reads its config from here: a hidden virtual field, so the blocks field stays untouched.
568
+ const configField = {
569
+ name: builderConfigFieldName(field),
570
+ type: 'json',
571
+ virtual: true,
572
+ admin: { hidden: true, disableListColumn: true, disableListFilter: true, custom: { builder: clientConfig } },
573
+ };
574
+ const skip = [builderConfigFieldName(field), ...(richText ? [richText.name] : []), ...ownFields];
575
+ return {
576
+ ...collection,
577
+ // The write gate refuses bulk updates (live/writeGate.ts): the list view does not offer them.
578
+ disableBulkEdit: true,
579
+ fields: [...collection.fields, configField, ...(richText ? [richText] : [])],
580
+ hooks: {
581
+ ...collection.hooks,
582
+ beforeOperation: [...(collection.hooks?.beforeOperation ?? []), gate.beforeOperation, keepLockBeforeOperation({ collection: collection.slug })],
583
+ afterOperation: [...(collection.hooks?.afterOperation ?? []), gate.afterOperation],
584
+ afterError: [...(collection.hooks?.afterError ?? []), gate.afterError],
585
+ beforeChange: [...(collection.hooks?.beforeChange ?? []), payloadBlocksBeforeChange({ collection: collection.slug, field, skip })],
586
+ afterChange: [
587
+ ...(collection.hooks?.afterChange ?? []),
588
+ payloadBlocksAfterChange({ collection: collection.slug, field, sessions, writeGate: args.writeGate }),
589
+ ],
590
+ },
591
+ admin: {
592
+ ...collection.admin,
593
+ ...(collection.versions && typeof collection.versions === 'object' && collection.versions.drafts && !collection.admin?.defaultColumns
594
+ ? { defaultColumns: [collection.admin?.useAsTitle ?? 'id', '_status', 'updatedAt'] }
595
+ : {}),
596
+ components: {
597
+ ...collection.admin?.components,
598
+ edit: {
599
+ ...collection.admin?.components?.edit,
600
+ PublishButton: collection.admin?.components?.edit?.PublishButton ?? PUBLISH_BUTTON_COMPONENT,
601
+ },
602
+ views: { ...views, edit },
603
+ },
604
+ },
605
+ };
606
+ }
607
+ /** A block definition without style controls (classes, animations, default classes). */
608
+ function withoutStyles(def) {
609
+ const { defaultClassName: _defaultClassName, ...rest } = def;
610
+ return { ...rest, styles: false };
611
+ }
612
+ /** Name of the hidden virtual field that carries the builder's config for a Payload blocks field. */
613
+ export function builderConfigFieldName(field) {
614
+ return `${field}Builder`;
615
+ }
453
616
  /** The error for a layout field name that a field of another type already uses. */
454
617
  function wrongFieldTypeMessage(collection, field, type) {
455
618
  const suggestion = field === 'builderLayout' ? 'builder' : 'builderLayout';
456
619
  const intro = `[websiteBuilder] Collection "${collection}" already has a "${type}" field named "${field}". The builder stores its layout in a "json" field.`;
457
620
  if (type === 'blocks') {
458
- return (`${intro} Keep your blocks field and give the builder a field of its own: ` +
459
- `websiteBuilder({ collections: { ${collection}: { field: '${suggestion}' } } }). ` +
460
- 'Your block configs work as builder blocks with fromPayloadBlocks(), and migrateBlocksField() copies the content over. ' +
461
- 'See "Using existing Payload blocks" in the payload-canvas README.');
621
+ // The builder edits a top-level blocks field itself. Here the field is somewhere it cannot reach.
622
+ return (`[websiteBuilder] Collection "${collection}" has a "blocks" field named "${field}" that is not at the top level (or in rows, collapsibles or unnamed tabs). ` +
623
+ 'Move it there, and the builder edits that field itself. See "Using existing Payload blocks" in the payload-canvas README.');
462
624
  }
463
625
  return `${intro} Pick another name: websiteBuilder({ collections: { ${collection}: { field: '${suggestion}' } } }).`;
464
626
  }
@@ -1,6 +1,6 @@
1
1
  import { type CollectionBeforeChangeHook, type CollectionBeforeDeleteHook, type CollectionConfig, type Field, type Payload, type PayloadRequest, type RelationshipField } from 'payload';
2
2
  import { type Reference } from '../core/references.js';
3
- import type { BlockDefinition } from '../core/types.js';
3
+ import type { BlockDefinition, Layout } from '../core/types.js';
4
4
  export type ReferencesOptions = {
5
5
  /** Name of the hidden references field on builder collections. Default "builderRefs". */
6
6
  field?: string;
@@ -29,6 +29,8 @@ export type ReferenceSource = {
29
29
  layout: string;
30
30
  /** The field holds a list of blocks (saved sections), not a whole layout. */
31
31
  blocksOnly?: boolean;
32
+ /** The field is the collection's own Payload blocks field: its stored value as a layout (or undefined). */
33
+ decode?: (value: unknown) => Layout | undefined;
32
34
  drafts: boolean;
33
35
  /** Field shown as the document's name in messages. */
34
36
  title: string;
@@ -58,7 +60,7 @@ export declare function referencesConfigOf(payload: {
58
60
  export declare function resolveReferences(args: {
59
61
  options: ReferencesOptions | false | undefined;
60
62
  collections: CollectionConfig[];
61
- sources: Record<string, Pick<ReferenceSource, 'layout' | 'blocksOnly'>>;
63
+ sources: Record<string, Pick<ReferenceSource, 'layout' | 'blocksOnly' | 'decode'>>;
62
64
  blocks: BlockDefinition[];
63
65
  }): ReferencesServerConfig | null;
64
66
  type Id = string | number;
@@ -115,6 +115,8 @@ function layoutOf(source, data) {
115
115
  const value = data[source.layout];
116
116
  if (value === undefined)
117
117
  return undefined;
118
+ if (source.decode)
119
+ return source.decode(value);
118
120
  return source.blocksOnly ? normalizeLayout({ version: 1, blocks: value }) : normalizeLayout(value);
119
121
  }
120
122
  /** The references of one document's layout, checked against the database. */
@@ -2,7 +2,7 @@
2
2
  // layout as the section's `blocks`. See SECTION_LAYOUT_FIELD in ./sections.ts.
3
3
  import { sameJson } from '../core/fieldSemantics.js';
4
4
  import { isPlainObject, normalizeLayout } from '../core/tree.js';
5
- import { GUARD_SEQ_CONTEXT, SESSION_SAVE_CONTEXT } from './hook.js';
5
+ import { guardSeqOf, SESSION_SAVE_CONTEXT } from './hook.js';
6
6
  import { SECTION_LAYOUT_FIELD } from './sections.js';
7
7
  /**
8
8
  * Collection `beforeChange` hook, after the builder's layout hook: the layout the builder saved
@@ -11,11 +11,11 @@ import { SECTION_LAYOUT_FIELD } from './sections.js';
11
11
  * guard put the session's layout in (the session owns the blocks while it is open), and when it
12
12
  * differs from the stored blocks. Otherwise the incoming `blocks` stay (REST, MCP, the library).
13
13
  */
14
- export const syncSectionBlocks = ({ context, data, originalDoc }) => {
14
+ export const syncSectionBlocks = ({ collection, context, data, originalDoc }) => {
15
15
  const layout = data?.[SECTION_LAYOUT_FIELD];
16
16
  if (!isPlainObject(layout) || !Array.isArray(layout.blocks))
17
17
  return data;
18
- const session = Boolean(context?.[SESSION_SAVE_CONTEXT] || context?.[GUARD_SEQ_CONTEXT] !== undefined);
18
+ const session = Boolean(context?.[SESSION_SAVE_CONTEXT] || guardSeqOf(context, collection.slug, originalDoc?.id) !== undefined);
19
19
  const stored = normalizeLayout({ version: 1, blocks: isPlainObject(originalDoc) ? originalDoc.blocks : [] }).blocks;
20
20
  if (session || !sameJson(normalizeLayout({ version: 1, blocks: layout.blocks }).blocks, stored))
21
21
  data.blocks = layout.blocks;
@@ -1,4 +1,4 @@
1
- import type { Block, BlockDefinition, CanvasMeasurement, Layout, Point, Rect, TemplateContext } from '../core/types.js';
1
+ import type { Block, BlockDefinition, CanvasMeasurement, Layout, Point, Rect, RegionConfig, TemplateContext } from '../core/types.js';
2
2
  export * from './motion.js';
3
3
  export declare const CHANNEL: 'payload-builder';
4
4
  /** What the iframe needs besides the layout. Sent by the admin before the first layout. */
@@ -16,6 +16,12 @@ export type CanvasInit = {
16
16
  collection: string;
17
17
  id: string | number;
18
18
  } | null;
19
+ /**
20
+ * The document's fixed regions (the collection's `regions` option). With regions, the canvas
21
+ * asks the app's canvas server action for the page frame and shows the whole page. Left out:
22
+ * the layout alone.
23
+ */
24
+ regions?: RegionConfig[];
19
25
  };
20
26
  export type PointerKind = 'move' | 'leave' | 'click';
21
27
  /** One section to picture. The iframe answers with a `thumbnail` message with the same `key`. */
@@ -87,7 +93,10 @@ export type CanvasImageSpot = {
87
93
  * under it (a video's poster under the video, a background under a photo).
88
94
  */
89
95
  export type CanvasImageTarget = {
96
+ /** The block. Empty for a region. */
90
97
  id: string;
98
+ /** The region, when the image shows a region's field. `spots` then hold document paths. */
99
+ region?: string;
91
100
  spots: CanvasImageSpot[];
92
101
  };
93
102
  export type CanvasToAdmin =
@@ -137,20 +146,28 @@ export type CanvasToAdmin =
137
146
  id: string;
138
147
  path: string;
139
148
  kind: InlineKind;
149
+ region?: string;
150
+ /** A region's plain text as the canvas shows it at the start: the base of the save when editing ends. */
151
+ base?: unknown;
140
152
  }
141
- /** The new value of the edited prop (a string, or Lexical JSON for rich text). Sent about every 150 ms while typing. */
153
+ /**
154
+ * The new value of the edited prop (a string, or Lexical JSON for rich text). Sent about every
155
+ * 150 ms while typing. With `region`, `id` is empty and `path` is a document path of the region.
156
+ */
142
157
  | {
143
158
  type: 'inlineChange';
144
159
  session: string;
145
160
  id: string;
146
161
  path: string;
147
162
  value: unknown;
163
+ region?: string;
148
164
  }
149
165
  /** Editing ended. Any last change was sent before this message. */
150
166
  | {
151
167
  type: 'inlineEnd';
152
168
  session: string;
153
169
  id: string;
170
+ region?: string;
154
171
  }
155
172
  /**
156
173
  * Enter in a list item. Editing of it has ended (with the text before the caret); `after` is the
@@ -192,6 +209,7 @@ export type CanvasToAdmin =
192
209
  path: string;
193
210
  reason: 'bound' | 'unsupported';
194
211
  field?: string;
212
+ region?: string;
195
213
  }
196
214
  /** Thumbnail mode: the picture of a requested section as a data URL, or null with the error. */
197
215
  | {
@@ -268,6 +286,7 @@ export type AdminToCanvas = {
268
286
  type: 'inlineStart';
269
287
  id: string;
270
288
  offset?: number;
289
+ region?: string;
271
290
  }
272
291
  /** Ends inline editing (a click outside the canvas, another block selected). */
273
292
  | {
@@ -282,6 +301,13 @@ export type AdminToCanvas = {
282
301
  collection: string;
283
302
  id: string | number;
284
303
  }
304
+ /**
305
+ * The open document's other fields changed (a region edit, the settings drawer, someone else's
306
+ * save): the canvas asks for the page frame again. Ignored without regions.
307
+ */
308
+ | {
309
+ type: 'frameRefresh';
310
+ }
285
311
  /** Rich text: a toolbar command for the current session. */
286
312
  | {
287
313
  type: 'inlineCommand';