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
@@ -12,11 +12,27 @@
12
12
  // map lookup per pass. DOM-only changes map at most once a second per block. A block being edited
13
13
  // inline is skipped until editing ends.
14
14
  import { EDITABLE_IMAGE_ATTRIBUTE, EDITABLE_TEXT_ATTRIBUTE } from '../../render/editable.js';
15
+ import { LAYOUT_ROOT_ATTRIBUTE, REGION_ATTRIBUTE } from '../../render/regions.js';
15
16
  import { blockCandidates, compactText, cssUrls, normalizeText, srcsetUrls, urlKey } from './candidates.js';
16
17
  /** The attribute the mapping puts on an element that shows a text prop. Its value is the prop path. */
17
18
  export const AUTO_TEXT_ATTRIBUTE = 'data-builder-text-auto';
18
19
  /** Explicit or automatic text marks. */
19
20
  export const TEXT_MARK_SELECTOR = `[${EDITABLE_TEXT_ATTRIBUTE}], [${AUTO_TEXT_ATTRIBUTE}]`;
21
+ /** Elements that own props: blocks and the page frame's regions. */
22
+ export const OWNER_SELECTOR = `[data-block-id], [${REGION_ATTRIBUTE}]`;
23
+ /** Where an element's own content stops: a nested block, a region, or the layout outlet of the page frame. */
24
+ const BOUNDARY = `[data-block-id], [${REGION_ATTRIBUTE}], [${LAYOUT_ROOT_ATTRIBUTE}]`;
25
+ /** The block or region element `el` belongs to: its own or the nearest one above it. */
26
+ export function ownerOf(el) {
27
+ const element = el?.closest(OWNER_SELECTOR);
28
+ if (!element)
29
+ return null;
30
+ const id = element.dataset.blockId;
31
+ if (id)
32
+ return { kind: 'block', id, key: `b:${id}`, element };
33
+ const name = element.getAttribute(REGION_ATTRIBUTE);
34
+ return name ? { kind: 'region', name, key: `r:${name}`, element } : null;
35
+ }
20
36
  /** Stands for a nested block in an element's text: an element around a child block never matches. */
21
37
  const NESTED = '\u0000';
22
38
  /** Elements whose text is not content. */
@@ -50,11 +66,11 @@ function indexBlocks(layout) {
50
66
  walk(layout.blocks);
51
67
  return index;
52
68
  }
53
- /** The block's own elements (the block element first), without nested blocks and their content. */
69
+ /** The owner's own elements (the owner element first), without nested blocks, regions and the layout outlet. */
54
70
  function ownElements(blockEl) {
55
71
  const out = [blockEl];
56
72
  const walker = blockEl.ownerDocument.createTreeWalker(blockEl, NodeFilter.SHOW_ELEMENT, {
57
- acceptNode: (node) => (node.hasAttribute('data-block-id') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
73
+ acceptNode: (node) => (node.matches(BOUNDARY) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
58
74
  });
59
75
  for (let node = walker.nextNode(); node; node = walker.nextNode())
60
76
  out.push(node);
@@ -83,7 +99,7 @@ function elementTexts(blockEl) {
83
99
  out += '\n';
84
100
  else if (SKIP_TAGS.has(element.tagName) || element.hasAttribute('data-builder-placeholder'))
85
101
  continue;
86
- else if (element.hasAttribute('data-block-id'))
102
+ else if (element.matches(BOUNDARY))
87
103
  out += NESTED;
88
104
  else
89
105
  out += walk(element);
@@ -202,11 +218,21 @@ export function createCanvasMapper(options) {
202
218
  }
203
219
  return index.get(id) ?? null;
204
220
  };
205
- const fresh = (el, id) => {
206
- const entry = entries.get(id);
207
- return Boolean(entry && entry.element === el && entry.block === blockOf(id) && !dirty.has(id));
221
+ /** The data an owner shows: a block of the layout on screen, or a region's values. */
222
+ const dataOf = (owner) => {
223
+ if (owner.kind === 'region') {
224
+ const region = options.region?.(owner.name) ?? null;
225
+ return { block: region?.block ?? null, definition: region?.definition };
226
+ }
227
+ const block = blockOf(owner.id);
228
+ return { block, definition: block ? options.definition(block.type) : undefined };
229
+ };
230
+ const skipped = (owner) => (owner.kind === 'region' ? Boolean(options.skipRegion?.(owner.name)) : options.skip(owner.id));
231
+ const fresh = (owner) => {
232
+ const entry = entries.get(owner.key);
233
+ return Boolean(entry && entry.element === owner.element && entry.block === dataOf(owner).block && !dirty.has(owner.key));
208
234
  };
209
- function mapBlock(blockEl, block) {
235
+ function mapBlock(blockEl, block, definition) {
210
236
  const entry = { element: blockEl, block, images: [], at: performance.now() };
211
237
  const own = ownElements(blockEl);
212
238
  for (const el of own)
@@ -214,8 +240,8 @@ export function createCanvasMapper(options) {
214
240
  el.removeAttribute(AUTO_TEXT_ATTRIBUTE);
215
241
  if (!block)
216
242
  return entry;
217
- const definition = options.definition(block.type);
218
- const stored = options.stored(block.id);
243
+ // Regions have no bindings: their values are the document's own fields.
244
+ const stored = block.id ? options.stored(block.id) : null;
219
245
  const source = stored?.bindings ? { ...block, bindings: stored.bindings } : block;
220
246
  const { texts, images } = blockCandidates(source, definition, blockEl.ownerDocument.baseURI);
221
247
  // Explicit marks win: their elements, the elements around and inside them, and their paths.
@@ -279,10 +305,11 @@ export function createCanvasMapper(options) {
279
305
  }
280
306
  return entry;
281
307
  }
282
- function remap(el, id) {
308
+ function remap(owner) {
283
309
  const started = performance.now();
284
- entries.set(id, mapBlock(el, blockOf(id)));
285
- dirty.delete(id);
310
+ const { block, definition } = dataOf(owner);
311
+ entries.set(owner.key, mapBlock(owner.element, block, definition));
312
+ dirty.delete(owner.key);
286
313
  const ms = performance.now() - started;
287
314
  stats.blocks++;
288
315
  stats.ms += ms;
@@ -298,9 +325,9 @@ export function createCanvasMapper(options) {
298
325
  for (const record of records) {
299
326
  const node = record.target;
300
327
  const el = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
301
- const id = el?.closest('[data-block-id]')?.dataset.blockId;
302
- if (id)
303
- dirty.add(id);
328
+ const owner = ownerOf(el);
329
+ if (owner)
330
+ dirty.add(owner.key);
304
331
  }
305
332
  schedule();
306
333
  });
@@ -318,17 +345,17 @@ export function createCanvasMapper(options) {
318
345
  let ms = 0;
319
346
  let sliced = false;
320
347
  let later = false;
321
- for (const el of root.querySelectorAll('[data-block-id]')) {
322
- const id = el.dataset.blockId;
348
+ for (const el of root.querySelectorAll(OWNER_SELECTOR)) {
349
+ const owner = ownerOf(el);
323
350
  // Repeated collection list items share their block's id: the first element is the block.
324
- if (!id || seen.has(id))
351
+ if (!owner || owner.element !== el || seen.has(owner.key))
325
352
  continue;
326
- seen.add(id);
327
- if (fresh(el, id) || options.skip(id))
353
+ seen.add(owner.key);
354
+ if (fresh(owner) || skipped(owner))
328
355
  continue;
329
356
  // Only its DOM changed, and it was mapped a moment ago: map it a little later.
330
- const entry = entries.get(id);
331
- if (entry && entry.element === el && entry.block === blockOf(id) && started - entry.at < DOM_REMAP_MS) {
357
+ const entry = entries.get(owner.key);
358
+ if (entry && entry.element === el && entry.block === dataOf(owner).block && started - entry.at < DOM_REMAP_MS) {
332
359
  later = true;
333
360
  continue;
334
361
  }
@@ -337,7 +364,7 @@ export function createCanvasMapper(options) {
337
364
  sliced = true;
338
365
  break;
339
366
  }
340
- ms += remap(el, id);
367
+ ms += remap(owner);
341
368
  mapped++;
342
369
  }
343
370
  // Blocks no longer on the page. After a cut pass, the next one finishes the rest.
@@ -365,10 +392,10 @@ export function createCanvasMapper(options) {
365
392
  frame = requestAnimationFrame(run);
366
393
  }
367
394
  function ensure(blockEl) {
368
- const id = blockEl.dataset.blockId;
369
- if (!id || options.skip(id) || fresh(blockEl, id))
395
+ const owner = ownerOf(blockEl);
396
+ if (!owner || owner.element !== blockEl || skipped(owner) || fresh(owner))
370
397
  return;
371
- remap(blockEl, id);
398
+ remap(owner);
372
399
  }
373
400
  return {
374
401
  stats,
@@ -377,16 +404,16 @@ export function createCanvasMapper(options) {
377
404
  imageTarget(x, y) {
378
405
  const root = options.root();
379
406
  const top = root?.ownerDocument.elementFromPoint(x, y);
380
- const blockEl = top?.closest('[data-block-id]');
381
- const id = blockEl?.dataset.blockId;
382
- if (!top || !blockEl || !id || !root?.contains(blockEl) || blockEl.closest('[data-builder-repeat]'))
407
+ const owner = ownerOf(top);
408
+ const blockEl = owner?.element;
409
+ if (!top || !owner || !blockEl || !root?.contains(blockEl) || blockEl.closest('[data-builder-repeat]'))
383
410
  return null;
384
411
  // Text on top of an image (a hero heading over its photo): the text wins.
385
412
  const text = top.closest(TEXT_MARK_SELECTOR);
386
- if (text && text.closest('[data-block-id]') === blockEl)
413
+ if (text && ownerOf(text)?.element === blockEl)
387
414
  return null;
388
415
  ensure(blockEl);
389
- const entry = entries.get(id);
416
+ const entry = entries.get(owner.key);
390
417
  if (!entry || entry.element !== blockEl)
391
418
  return null;
392
419
  const hits = [];
@@ -418,7 +445,7 @@ export function createCanvasMapper(options) {
418
445
  const { left, top: y0, width, height } = hit.rect;
419
446
  return [{ path: hit.path, kind: hit.kind, rect: { x: left, y: y0, width, height } }];
420
447
  });
421
- return { id, spots };
448
+ return owner.kind === 'region' ? { id: '', region: owner.name, spots } : { id: owner.id, spots };
422
449
  },
423
450
  invalidate() {
424
451
  for (const id of entries.keys())
@@ -35,10 +35,16 @@ export type InlineSession = {
35
35
  /**
36
36
  * Ends editing and puts the DOM back as React rendered it. `changed` is true when the value
37
37
  * changed after the last `onChange` call; `value` is the final value.
38
+ * `keep`: the edited text stays on screen (only the editing marks go) and `restore` puts React's
39
+ * DOM back later, right before React shows the new value. Plain text only; rich text always
40
+ * restores at once.
38
41
  */
39
- finish: () => {
42
+ finish: (options?: {
43
+ keep?: boolean;
44
+ }) => {
40
45
  changed: boolean;
41
46
  value: unknown;
47
+ restore?: () => void;
42
48
  };
43
49
  /** Rich text toolbar commands. */
44
50
  command?: (command: RichCommand) => void;
@@ -1,4 +1,4 @@
1
- import { createThrottle, placeCaret, restoreDom, snapshotDom } from './dom.js';
1
+ import { createThrottle, placeCaret, restoreAttributes, restoreDom, snapshotDom } from './dom.js';
2
2
  import { readText, singleLine } from './model.js';
3
3
  /** Typing reaches the admin (and collaborators) at most this often. */
4
4
  export const CHANGE_MS = 150;
@@ -155,7 +155,7 @@ export function startPlainSession(el, kind, options) {
155
155
  placeCaret(el, options.point, options.offset);
156
156
  return {
157
157
  element: el,
158
- finish() {
158
+ finish(finishing) {
159
159
  throttle.cancel();
160
160
  composing = false;
161
161
  const value = read();
@@ -172,6 +172,10 @@ export function startPlainSession(el, kind, options) {
172
172
  doc.getSelection()?.removeAllRanges();
173
173
  for (const d of decorations)
174
174
  d.removeAttribute('contenteditable');
175
+ if (finishing?.keep) {
176
+ restoreAttributes(el, snapshot);
177
+ return { changed, value, restore: () => restoreDom(el, snapshot) };
178
+ }
175
179
  restoreDom(el, snapshot);
176
180
  return { changed, value };
177
181
  },
@@ -1,3 +1,4 @@
1
+ import { LAYOUT_ROOT_ATTRIBUTE, REGION_ATTRIBUTE } from '../render/regions.js';
1
2
  const sameRect = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
2
3
  /** True when two measurements are equal. Stops at the first difference (scrolling changes `scroll` first). */
3
4
  export function sameMeasurement(a, b) {
@@ -19,6 +20,16 @@ export function sameMeasurement(a, b) {
19
20
  if (x.ownerId !== y.ownerId || x.slot !== y.slot || x.axis !== y.axis || x.empty !== y.empty || !sameRect(x.rect, y.rect))
20
21
  return false;
21
22
  }
23
+ if (Boolean(a.root) !== Boolean(b.root) || (a.root && b.root && !sameRect(a.root, b.root)))
24
+ return false;
25
+ const ra = a.regions ?? [];
26
+ const rb = b.regions ?? [];
27
+ if (ra.length !== rb.length)
28
+ return false;
29
+ for (let i = 0; i < ra.length; i++) {
30
+ if (ra[i].name !== rb[i].name || !sameRect(ra[i].rect, rb[i].rect))
31
+ return false;
32
+ }
22
33
  return true;
23
34
  }
24
35
  function toRect(r) {
@@ -56,10 +67,24 @@ export function measure(root) {
56
67
  const axis = empty && el.parentElement ? axisOf(el.parentElement) : axisOf(el);
57
68
  slots.set(key, { ownerId, slot, rect: toRect(el.getBoundingClientRect()), axis, empty });
58
69
  }
70
+ // In a page frame the layout fills its outlet, not the whole canvas: the root list's axis and
71
+ // box come from the outlet, so fixed regions never count as part of the layout.
72
+ const outlet = root.querySelector(`[${LAYOUT_ROOT_ATTRIBUTE}]`);
73
+ const regions = [];
74
+ if (outlet) {
75
+ for (const el of root.querySelectorAll(`[${REGION_ATTRIBUTE}]`)) {
76
+ const rect = el.getBoundingClientRect();
77
+ // Hidden copies (a mobile and a desktop version of one header) are left out.
78
+ if (rect.width === 0 && rect.height === 0)
79
+ continue;
80
+ regions.push({ name: el.getAttribute(REGION_ATTRIBUTE) ?? '', rect: toRect(rect) });
81
+ }
82
+ }
59
83
  return {
60
84
  blocks,
61
85
  slots: [...slots.values()],
62
- rootAxis: axisOf(root),
86
+ rootAxis: axisOf(outlet ?? root),
87
+ ...(outlet ? { root: toRect(outlet.getBoundingClientRect()), regions } : {}),
63
88
  viewport: { width: window.innerWidth, height: window.innerHeight },
64
89
  scroll: { x: window.scrollX, y: window.scrollY },
65
90
  documentHeight: document.documentElement.scrollHeight,
@@ -9,6 +9,8 @@ export { MotionStyle, MOTION_CSS } from './motion/style.js';
9
9
  export { previewMotion, startMotion, type MotionOptions } from './motion/runtime.js';
10
10
  export { fromPayloadComponent, fromPayloadComponents, PayloadSlot, type AnyPayloadComponent, type FromPayloadComponentOptions, type PayloadBlockData, type PayloadBlockProps, type PayloadBuilderProps, } from './render/payload.js';
11
11
  export { renderOnServer, withPageData } from './render/marks.js';
12
+ export { LAYOUT_ROOT_ATTRIBUTE, REGION_ATTRIBUTE, siteRegion, type RegionMark } from './render/regions.js';
13
+ export { LayoutOutlet } from './render/LayoutOutlet.js';
12
14
  export type { CanvasDocumentRef, CanvasScope, CanvasServer, CanvasServerRequest, CanvasServerResponse, CanvasServerResult, } from './render/canvasServerTypes.js';
13
15
  export { loadLayoutData, resolveLayoutData, urlResolver, type LoadLayoutOptions } from './render/resolve.js';
14
16
  export { attachListItems, listItemsOf, listQueries, type ListQuery } from './render/lists.js';
@@ -11,6 +11,8 @@ export { MotionStyle, MOTION_CSS } from './motion/style.js';
11
11
  export { previewMotion, startMotion } from './motion/runtime.js';
12
12
  export { fromPayloadComponent, fromPayloadComponents, PayloadSlot, } from './render/payload.js';
13
13
  export { renderOnServer, withPageData } from './render/marks.js';
14
+ export { LAYOUT_ROOT_ATTRIBUTE, REGION_ATTRIBUTE, siteRegion } from './render/regions.js';
15
+ export { LayoutOutlet } from './render/LayoutOutlet.js';
14
16
  export { loadLayoutData, resolveLayoutData, urlResolver } from './render/resolve.js';
15
17
  export { attachListItems, listItemsOf, listQueries } from './render/lists.js';
16
18
  export { fieldFor } from './components/Field.js';
@@ -0,0 +1,11 @@
1
+ import { type ReactNode } from 'react';
2
+ /** Canvas only. The live layout the canvas renders. `BuilderCanvas` provides it around the page frame. */
3
+ export declare const LayoutOutletContext: import("react").Context<ReactNode>;
4
+ /** Mount notifications include outlets that appear later through Suspense. */
5
+ export declare const LayoutOutletPresence: import("react").Context<(() => () => void) | null>;
6
+ /**
7
+ * Stands in for the layout in the page frame the canvas server action renders. The canvas fills
8
+ * it with the layout it renders itself, so every block stays live: selectable, draggable and
9
+ * edited in place, with no request to the server.
10
+ */
11
+ export declare function LayoutOutlet(): ReactNode;
@@ -0,0 +1,16 @@
1
+ 'use client';
2
+ import { createContext, useContext, useLayoutEffect } from 'react';
3
+ /** Canvas only. The live layout the canvas renders. `BuilderCanvas` provides it around the page frame. */
4
+ export const LayoutOutletContext = createContext(null);
5
+ /** Mount notifications include outlets that appear later through Suspense. */
6
+ export const LayoutOutletPresence = createContext(null);
7
+ /**
8
+ * Stands in for the layout in the page frame the canvas server action renders. The canvas fills
9
+ * it with the layout it renders itself, so every block stays live: selectable, draggable and
10
+ * edited in place, with no request to the server.
11
+ */
12
+ export function LayoutOutlet() {
13
+ const register = useContext(LayoutOutletPresence);
14
+ useLayoutEffect(() => register?.(), [register]);
15
+ return useContext(LayoutOutletContext);
16
+ }
@@ -0,0 +1,46 @@
1
+ import type { Payload } from 'payload';
2
+ import type { ReactNode } from 'react';
3
+ import { type TemplateContext } from '../../core/index.js';
4
+ import type { CanvasDocumentRef, CanvasScope, CanvasServerResponse } from './canvasServerTypes.js';
5
+ import { type RegionMark } from './regions.js';
6
+ import type { PageData, RenderMode } from './types.js';
7
+ /** What the page frame gets. */
8
+ export type CanvasFrameArgs = {
9
+ payload: Payload;
10
+ /** The signed-in user (the canvas needs one). */
11
+ user: unknown;
12
+ /** The document open in the builder. */
13
+ document: CanvasDocumentRef;
14
+ /** In a template: the sample document. Null on normal pages. */
15
+ context: TemplateContext | null;
16
+ /** The locale the editor shows, or null without localization. */
17
+ locale: string | null;
18
+ /** The document's latest draft, read as the signed-in user (`frameDepth`, the editor's locale). */
19
+ doc: Record<string, unknown>;
20
+ /** The page data, as the layout gets it. */
21
+ pageData: PageData;
22
+ /** Put it where the page shows the layout: the canvas renders the live layout there. */
23
+ layout: ReactNode;
24
+ /** Marks a region: `region('header', <Header … />)`. The name is a name from the collection's `regions`. */
25
+ region: RegionMark;
26
+ /** Always `'canvas'`: pass it to `editableText` and `editableImage` in the frame's components. */
27
+ mode: RenderMode;
28
+ };
29
+ export type CanvasFrameOptions = {
30
+ frame?: (args: CanvasFrameArgs) => ReactNode | Promise<ReactNode>;
31
+ frameDepth?: number;
32
+ };
33
+ /**
34
+ * Renders the page frame for the scope's document. Without regions in the collection: no frame
35
+ * (`node: null`), so the canvas shows the layout alone. With regions but no `frame` option:
36
+ * `missing`, so the canvas says what to add. The document loads as the user (field read access
37
+ * applies), with the latest draft and the editor's locale.
38
+ */
39
+ export declare function renderCanvasFrame(options: CanvasFrameOptions, args: {
40
+ payload: Payload;
41
+ user: unknown;
42
+ scope: CanvasScope;
43
+ locale: string | null;
44
+ context: TemplateContext | null;
45
+ pageData: PageData;
46
+ }): Promise<CanvasServerResponse>;
@@ -0,0 +1,59 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { regionValues } from '../../core/index.js';
3
+ import { builderConfigOf } from '../../live/document.js';
4
+ import { LayoutOutlet } from './LayoutOutlet.js';
5
+ import { localeArgs } from './locale.js';
6
+ import { PayloadRoot } from './PayloadRoot.js';
7
+ import { REGION_ATTRIBUTE } from './regions.js';
8
+ const message = (error) => (error instanceof Error ? error.message : String(error));
9
+ /**
10
+ * Renders the page frame for the scope's document. Without regions in the collection: no frame
11
+ * (`node: null`), so the canvas shows the layout alone. With regions but no `frame` option:
12
+ * `missing`, so the canvas says what to add. The document loads as the user (field read access
13
+ * applies), with the latest draft and the editor's locale.
14
+ */
15
+ export async function renderCanvasFrame(options, args) {
16
+ const { payload, user, scope, locale, context, pageData } = args;
17
+ const document = scope.document;
18
+ if (!document)
19
+ return { kind: 'frame', node: null, values: {} };
20
+ const regions = builderConfigOf(payload)?.collections[document.collection]?.regions ?? [];
21
+ if (regions.length === 0)
22
+ return { kind: 'frame', node: null, values: {} };
23
+ if (!options.frame)
24
+ return { kind: 'frame', node: null, values: {}, missing: true };
25
+ let doc;
26
+ try {
27
+ doc = (await payload.findByID({
28
+ collection: document.collection,
29
+ id: document.id,
30
+ depth: options.frameDepth ?? 1,
31
+ draft: true,
32
+ overrideAccess: false,
33
+ user: user,
34
+ ...localeArgs({ locale }),
35
+ }));
36
+ }
37
+ catch (error) {
38
+ return { kind: 'error', error: `Page frame: the document could not be read (${message(error)}).` };
39
+ }
40
+ const names = new Set(regions.map((r) => r.name));
41
+ const region = (name, node) => {
42
+ if (!names.has(name)) {
43
+ payload.logger.warn(`[builder] The page frame marks a region "${name}" that "${document.collection}" has no \`regions\` entry for. It shows, but cannot be selected.`);
44
+ return node;
45
+ }
46
+ // The region's attribute goes on the first element of `node`: no element is added.
47
+ return (_jsx(PayloadRoot, { attributes: { [REGION_ATTRIBUTE]: name }, label: name, placeholder: false, children: node }));
48
+ };
49
+ // The canvas renders the live layout here.
50
+ const layout = _jsx(LayoutOutlet, {});
51
+ try {
52
+ const node = await options.frame({ payload, user, document, context, locale, doc, pageData, layout, region, mode: 'canvas' });
53
+ return { kind: 'frame', node: node ?? null, values: regionValues(doc, regions) };
54
+ }
55
+ catch (error) {
56
+ payload.logger.error({ err: error, msg: '[builder] The page frame failed to render.' });
57
+ return { kind: 'error', error: `Page frame: ${message(error)}` };
58
+ }
59
+ }
@@ -1,5 +1,7 @@
1
1
  import { type BlockDefinition, type TemplateContext } from '../../core/index.js';
2
2
  import { type Payload, type SanitizedConfig } from 'payload';
3
+ import type { ReactNode } from 'react';
4
+ import { type CanvasFrameArgs } from './canvasFrame.js';
3
5
  import type { CanvasDocumentRef, CanvasServerRequest, CanvasServerResponse } from './canvasServerTypes.js';
4
6
  import type { BlockComponents, PageData, ResolveLink } from './types.js';
5
7
  /** What the `pageData` loader gets. */
@@ -17,6 +19,7 @@ export type PageDataArgs = {
17
19
  */
18
20
  locale: string | null;
19
21
  };
22
+ export type { CanvasFrameArgs } from './canvasFrame.js';
20
23
  export type CanvasServerOptions = {
21
24
  /** Your Payload config (`import config from '@payload-config'`). */
22
25
  config: SanitizedConfig | Promise<SanitizedConfig>;
@@ -34,6 +37,16 @@ export type CanvasServerOptions = {
34
37
  * when the canvas opens, and for each server render.
35
38
  */
36
39
  pageData?: (args: PageDataArgs) => PageData | Promise<PageData>;
40
+ /**
41
+ * The page around the layout, for collections with `regions`: the same component the site
42
+ * renders around its layout, so the canvas shows and edits the whole page. Render `layout`
43
+ * where the layout goes and mark each region with `region(name, node)`. Return `null` to show
44
+ * the layout alone. Runs on the server for the open document, and again after a region's field
45
+ * changes. Without it, the canvas shows the layout alone and says that the frame is missing.
46
+ */
47
+ frame?: (args: CanvasFrameArgs) => ReactNode | Promise<ReactNode>;
48
+ /** `depth` of the document the frame gets. Default 1 (uploads and relationships loaded). */
49
+ frameDepth?: number;
37
50
  };
38
51
  /**
39
52
  * The handler of the canvas server action. Blocks whose components the canvas cannot run (async
@@ -5,6 +5,7 @@ import { knownLocale, localeSettingsOf, normalizeLayout } from '../../core/index
5
5
  import { headers } from 'next/headers';
6
6
  import { getPayload } from 'payload';
7
7
  import { defaultComponents } from '../components/index.js';
8
+ import { renderCanvasFrame } from './canvasFrame.js';
8
9
  import { isRecord } from './fields.js';
9
10
  import { defaultResolveLink } from './link.js';
10
11
  import { renderPreviewBlock } from './RenderLayout.js';
@@ -114,6 +115,8 @@ export function createCanvasServer(options) {
114
115
  }
115
116
  if (request.kind === 'pageData')
116
117
  return { kind: 'pageData', data: pageData };
118
+ if (request.kind === 'frame')
119
+ return renderCanvasFrame(options, { payload, user, scope, locale, context, pageData });
117
120
  if (request.kind !== 'blocks' || !Array.isArray(request.blocks))
118
121
  return { kind: 'error', error: 'Unknown request.' };
119
122
  const items = request.blocks
@@ -35,6 +35,11 @@ export type CanvasServerRequest =
35
35
  key: string;
36
36
  block: Block;
37
37
  }>;
38
+ }
39
+ /** The page frame of the scope's document: the app's page around the layout, with its regions. */
40
+ | {
41
+ kind: 'frame';
42
+ scope: CanvasScope;
38
43
  };
39
44
  /** One rendered block, or why it failed. */
40
45
  export type CanvasServerResult = {
@@ -45,6 +50,18 @@ export type CanvasServerResult = {
45
50
  export type CanvasServerResponse = {
46
51
  kind: 'pageData';
47
52
  data: PageData;
53
+ }
54
+ /**
55
+ * The page frame. `node`: the frame's output, with a layout outlet where the canvas puts the
56
+ * live layout; null when the frame shows the layout alone. `values`: the regions' values, as the
57
+ * frame got them (documents loaded), for the canvas's text and image editing. `missing`: the
58
+ * collection has regions, but `createCanvasServer` has no `frame` option.
59
+ */
60
+ | {
61
+ kind: 'frame';
62
+ node: ReactNode | null;
63
+ values: Record<string, unknown>;
64
+ missing?: true;
48
65
  } | {
49
66
  kind: 'blocks';
50
67
  results: Record<string, CanvasServerResult>;
@@ -0,0 +1,13 @@
1
+ import type { ReactNode } from 'react';
2
+ /** The attribute that marks a region's element in the canvas. Its value is the region name. */
3
+ export declare const REGION_ATTRIBUTE = "data-builder-region";
4
+ /** The attribute of the canvas element that holds the live layout inside the page frame. */
5
+ export declare const LAYOUT_ROOT_ATTRIBUTE = "data-builder-layout";
6
+ /**
7
+ * Marks the part of the page frame that shows a region: `region('header', <Header … />)`. In the
8
+ * canvas it puts the region's attribute on the first element of `node` (no extra element), so the
9
+ * editor can select it. On the site it returns `node` as it is.
10
+ */
11
+ export type RegionMark = (name: string, node: ReactNode) => ReactNode;
12
+ /** The site's `region`: the node as it is. Pass it to the page frame on the site. */
13
+ export declare const siteRegion: RegionMark;
@@ -0,0 +1,8 @@
1
+ // Page regions on the site and in the canvas (the collection's `regions` option). Plain module:
2
+ // server components read these constants, so they must not live in a 'use client' file.
3
+ /** The attribute that marks a region's element in the canvas. Its value is the region name. */
4
+ export const REGION_ATTRIBUTE = 'data-builder-region';
5
+ /** The attribute of the canvas element that holds the live layout inside the page frame. */
6
+ export const LAYOUT_ROOT_ATTRIBUTE = 'data-builder-layout';
7
+ /** The site's `region`: the node as it is. Pass it to the page frame on the site. */
8
+ export const siteRegion = (_name, node) => node;
@@ -3,7 +3,8 @@ import { type Layout } from '../core/index.js';
3
3
  import { type RenderLocale } from './render/locale.js';
4
4
  export { loadLayoutData, type LoadLayoutOptions } from './render/resolve.js';
5
5
  export { localeArgs, localizeLayout, type RenderLocale } from './render/locale.js';
6
- export { createCanvasServer, type CanvasServerOptions, type PageDataArgs } from './render/canvasServer.js';
6
+ export { createCanvasServer, type CanvasFrameArgs, type CanvasServerOptions, type PageDataArgs } from './render/canvasServer.js';
7
+ export { siteRegion, type RegionMark } from './render/regions.js';
7
8
  export type { CanvasServerRequest, CanvasServerResponse } from './render/canvasServerTypes.js';
8
9
  export { loadTheme, ThemeStyle, type LoadedTheme, type ThemeStyleProps } from './theme/ThemeStyle.js';
9
10
  type Doc = Record<string, unknown>;
@@ -8,6 +8,7 @@ import { localeArgs } from './render/locale.js';
8
8
  export { loadLayoutData } from './render/resolve.js';
9
9
  export { localeArgs, localizeLayout } from './render/locale.js';
10
10
  export { createCanvasServer } from './render/canvasServer.js';
11
+ export { siteRegion } from './render/regions.js';
11
12
  export { loadTheme, ThemeStyle } from './theme/ThemeStyle.js';
12
13
  /** The generated CSS stored next to a layout field (`{ hash, css }`). */
13
14
  function cssOf(template) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload-canvas",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Payload Canvas: a visual drag-and-drop website builder for Payload CMS 3. Nested layout blocks, Tailwind styling, sections, templates, live AI editing over MCP, and the React renderer for your site.",
5
5
  "keywords": [
6
6
  "payload",