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
@@ -12,6 +12,7 @@ import { BlockContextMenu, blockMenuEntries } from './menu/blockMenu.js';
12
12
  import { MenuButton } from './menu/Menu.js';
13
13
  import { blockName } from './names.js';
14
14
  import { PeerCursors, PeerSelections } from './live/PresenceUI.js';
15
+ import { RegionOverlay } from './regions/RegionOverlay.js';
15
16
  import { shortName } from './live/presence.js';
16
17
  import { toRect, useRuntime } from './runtime.js';
17
18
  import { useEditor } from './store.js';
@@ -124,7 +125,7 @@ export function Overlay() {
124
125
  transform: `translate3d(${smooth.placeholder.x}px, ${smooth.placeholder.y}px, 0)`,
125
126
  width: smooth.placeholder.width,
126
127
  height: smooth.placeholder.height,
127
- }, children: _jsx("span", { className: "builder-editor__drop-label builder-dnd-gap__label", hidden: !smooth.into, "data-label": smooth.into ? `Into ${smooth.into}` : '', children: _jsx(Icon, { name: "plus", size: 12 }) }) }) })), hovered && hoverRect && (_jsx("div", { className: "builder-editor__hover", style: box(hoverRect), children: _jsxs("span", { ...tagProps(hoverRect, 'hover'), children: [_jsx(BlockIcon, { name: runtime.blockIcon(hovered.type), size: 12 }), blockName(hovered, runtime.blockLabel(hovered.type))] }) })), sourceRect && _jsx("div", { className: "builder-editor__source", style: box(sourceRect) }), selected && selectedRect && (_jsxs(_Fragment, { children: [_jsxs("div", { hidden: Boolean(smooth), className: `builder-editor__selection${selected.hidden ? ' builder-editor__selection--hidden' : ''}${editing ? ' builder-editor__selection--editing' : ''}`, style: box(editing && editRect ? editRect : selectedRect), children: [editing && editRect && inline?.kind !== 'rich' && (_jsxs("span", { ...tagProps(editRect, 'editing'), children: [_jsx(Icon, { name: "rename", size: 12 }), "Editing text \u00B7 Esc to finish"] })), !drag && !editing && (_jsxs("span", { ...tagProps(selectedRect, undefined, selectedRect.width * zoom < NARROW_BLOCK), children: [_jsx(BlockIcon, { name: runtime.blockIcon(selected.type), size: 12 }), blockName(selected, runtime.blockLabel(selected.type)), selected.bindings && Object.keys(selected.bindings).length > 0 && (_jsx("span", { className: "builder-editor__tag-bound", "data-tooltip": "Shows data from a document", children: _jsx(Icon, { name: "bind", size: 11 }) })), selected.hidden && _jsx(Icon, { name: "eyeOff", size: 12 })] }))] }), _jsx(ActionBar, { id: selected.id, label: runtime.blockLabel(selected.type), icon: runtime.blockIcon(selected.type), parentId: findLocation(layout, selected.id)?.parentId ?? null, rect: selectedRect, inside: !roomAbove(selectedRect), below: selectedRect.width * zoom < NARROW_BLOCK, hidden: Boolean(drag) || Boolean(smooth) || editing }), editing && editRect && inline?.kind === 'rich' && _jsx(InlineToolbar, { inline: inline, rect: editRect, zoom: zoom })] })), _jsx(InsertHandle, {}), _jsx(ImageEditor, {}), _jsx(BlockContextMenu, {}), _jsx(Tooltips, {}), _jsx(PeerCursors, {}), indicator && (_jsx("div", { className: `builder-editor__drop builder-editor__drop--${indicator.kind}`, style: box(indicator.rect), children: dropParent && (_jsxs("span", { className: "builder-editor__drop-label", children: [_jsx(Icon, { name: "plus", size: 12 }), " Into ", runtime.blockLabel(dropParent.type)] })) })), _jsx(PeerSelections, {}), [...(live?.changes ?? [])].map(([id, change]) => {
128
+ }, children: _jsx("span", { className: "builder-editor__drop-label builder-dnd-gap__label", hidden: !smooth.into, "data-label": smooth.into ? `Into ${smooth.into}` : '', children: _jsx(Icon, { name: "plus", size: 12 }) }) }) })), hovered && hoverRect && (_jsx("div", { className: "builder-editor__hover", style: box(hoverRect), children: _jsxs("span", { ...tagProps(hoverRect, 'hover'), children: [_jsx(BlockIcon, { name: runtime.blockIcon(hovered.type), size: 12 }), blockName(hovered, runtime.blockLabel(hovered.type))] }) })), sourceRect && _jsx("div", { className: "builder-editor__source", style: box(sourceRect) }), selected && selectedRect && (_jsxs(_Fragment, { children: [_jsxs("div", { hidden: Boolean(smooth), className: `builder-editor__selection${selected.hidden ? ' builder-editor__selection--hidden' : ''}${editing ? ' builder-editor__selection--editing' : ''}`, style: box(editing && editRect ? editRect : selectedRect), children: [editing && editRect && inline?.kind !== 'rich' && (_jsxs("span", { ...tagProps(editRect, 'editing'), children: [_jsx(Icon, { name: "rename", size: 12 }), "Editing text \u00B7 Esc to finish"] })), !drag && !editing && (_jsxs("span", { ...tagProps(selectedRect, undefined, selectedRect.width * zoom < NARROW_BLOCK), children: [_jsx(BlockIcon, { name: runtime.blockIcon(selected.type), size: 12 }), blockName(selected, runtime.blockLabel(selected.type)), selected.bindings && Object.keys(selected.bindings).length > 0 && (_jsx("span", { className: "builder-editor__tag-bound", "data-tooltip": "Shows data from a document", children: _jsx(Icon, { name: "bind", size: 11 }) })), selected.hidden && _jsx(Icon, { name: "eyeOff", size: 12 })] }))] }), _jsx(ActionBar, { id: selected.id, label: runtime.blockLabel(selected.type), icon: runtime.blockIcon(selected.type), parentId: findLocation(layout, selected.id)?.parentId ?? null, rect: selectedRect, inside: !roomAbove(selectedRect), below: selectedRect.width * zoom < NARROW_BLOCK, hidden: Boolean(drag) || Boolean(smooth) || editing }), editing && editRect && inline?.kind === 'rich' && _jsx(InlineToolbar, { inline: inline, rect: editRect, zoom: zoom })] })), _jsx(RegionOverlay, { tagProps: tagProps, editedRect: inline?.region ? editedRect(runtime.iframeRef.current) : null, zoom: zoom }), _jsx(InsertHandle, {}), _jsx(ImageEditor, {}), _jsx(BlockContextMenu, {}), _jsx(Tooltips, {}), _jsx(PeerCursors, {}), indicator && (_jsx("div", { className: `builder-editor__drop builder-editor__drop--${indicator.kind}`, style: box(indicator.rect), children: dropParent && (_jsxs("span", { className: "builder-editor__drop-label", children: [_jsx(Icon, { name: "plus", size: 12 }), " Into ", runtime.blockLabel(dropParent.type)] })) })), _jsx(PeerSelections, {}), [...(live?.changes ?? [])].map(([id, change]) => {
128
129
  const rect = rectOf(id);
129
130
  if (!rect)
130
131
  return null;
@@ -32,6 +32,11 @@ export declare function insertBlocks(runtime: Runtime, blocks: Block[], to: Posi
32
32
  export declare function duplicateBlock(runtime: Runtime, id: string): void;
33
33
  export declare function removeBlock(runtime: Runtime, id: string): void;
34
34
  export declare function toggleHidden(runtime: Runtime, id: string): void;
35
+ /**
36
+ * True when the layout field stores the builder's own block data (Tailwind classes, animations,
37
+ * bindings, hidden blocks). False for a Payload blocks field: its blocks hold their fields only.
38
+ */
39
+ export declare function storesBuilderData(runtime: Pick<Runtime, 'config'>): boolean;
35
40
  /** Gives a block its own name in the outline and the breadcrumbs. An empty name removes it. */
36
41
  export declare function renameBlock(runtime: Runtime, id: string, label: string): void;
37
42
  /** How many blocks are in the list `slot` of `parentId` (the page itself when `parentId` is null). */
@@ -3,6 +3,7 @@
3
3
  // shortcuts: insert, duplicate, remove, hide, move, copy and paste (blocks and styles).
4
4
  import { createId, findBlock, findLocation, getBlockDefinition, slotAcceptsAt, slotNames } from '../../core/index.js';
5
5
  import { normalizeClasses, parseStyles, setStylesOps, stylesText } from './menu/styleClipboard.js';
6
+ import { countText } from './counts.js';
6
7
  /**
7
8
  * Where a click-inserted block goes: into the selected container's first slot, else after the
8
9
  * selected block, else at the end of the page. Each choice must pass the nesting rules (a form
@@ -112,10 +113,22 @@ export function removeBlock(runtime, id) {
112
113
  runtime.store.apply({ type: 'remove', id }, { select: selectedId === id ? parentId : undefined });
113
114
  }
114
115
  export function toggleHidden(runtime, id) {
116
+ // A Payload blocks field has no "hidden" for a block: the change would not survive a reload.
117
+ if (!storesBuilderData(runtime)) {
118
+ runtime.notify('Blocks of this page cannot be hidden: its blocks field has no place for it.');
119
+ return;
120
+ }
115
121
  const block = findBlock(runtime.store.getState().layout, id);
116
122
  if (block)
117
123
  runtime.store.apply({ type: 'update', id, hidden: !block.hidden });
118
124
  }
125
+ /**
126
+ * True when the layout field stores the builder's own block data (Tailwind classes, animations,
127
+ * bindings, hidden blocks). False for a Payload blocks field: its blocks hold their fields only.
128
+ */
129
+ export function storesBuilderData(runtime) {
130
+ return runtime.config.storage !== 'payload-blocks';
131
+ }
119
132
  /** Gives a block its own name in the outline and the breadcrumbs. An empty name removes it. */
120
133
  export function renameBlock(runtime, id, label) {
121
134
  const block = findBlock(runtime.store.getState().layout, id);
@@ -245,7 +258,7 @@ export function pasteBlocks(runtime, blocks) {
245
258
  return false;
246
259
  const done = insertBlocks(runtime, blocks, insertPosition(runtime, first));
247
260
  if (done)
248
- runtime.notify(blocks.length === 1 ? `Pasted ${runtime.blockLabel(first.type)}` : `Pasted ${blocks.length} blocks`);
261
+ runtime.notify(blocks.length === 1 ? `Pasted ${runtime.blockLabel(first.type)}` : `Pasted ${countText(blocks.length, { one: 'block', many: 'blocks' })}`);
249
262
  return done;
250
263
  }
251
264
  // ---------------------------------------------------------------------------
@@ -265,6 +278,10 @@ export function storedStyles() {
265
278
  }
266
279
  /** Copies the block's classes (all breakpoints and states) and animations. Other tabs and pages can paste them. */
267
280
  export function copyStyles(runtime, id) {
281
+ if (!storesBuilderData(runtime)) {
282
+ runtime.notify('Blocks of this page have no styles: their blocks field has no place for them.');
283
+ return false;
284
+ }
268
285
  const block = findBlock(runtime.store.getState().layout, id);
269
286
  if (!block)
270
287
  return false;
@@ -300,6 +317,11 @@ export function resetStyles(runtime, ids) {
300
317
  return applyStyles(runtime, ids, { className: '' }, 'Styles reset');
301
318
  }
302
319
  function applyStyles(runtime, ids, styles, notice) {
320
+ // A Payload blocks field stores no classes or animations: the change would not be saved.
321
+ if (!storesBuilderData(runtime)) {
322
+ runtime.notify('Blocks of this page have no styles: their blocks field has no place for them.');
323
+ return false;
324
+ }
303
325
  const ops = setStylesOps(runtime.store.getState().layout, runtime.config.blocks, ids, styles);
304
326
  if (ops.length === 0) {
305
327
  runtime.notify('The styles are the same already.');
@@ -0,0 +1,6 @@
1
+ /** `total` with its noun: `none` for 0, `one` for 1, else the grouped number and `many`. */
2
+ export declare function countText(total: number, words: {
3
+ none?: string;
4
+ one: string;
5
+ many: string;
6
+ }, locale?: string): string;
@@ -0,0 +1,10 @@
1
+ // Counts in the editor's text: "No blocks", "1 block", "1,001 blocks" (digits grouped in the
2
+ // browser's locale). Pure, safe in tests.
3
+ /** `total` with its noun: `none` for 0, `one` for 1, else the grouped number and `many`. */
4
+ export function countText(total, words, locale) {
5
+ if (total === 0 && words.none)
6
+ return words.none;
7
+ if (total === 1)
8
+ return `1 ${words.one}`;
9
+ return `${new Intl.NumberFormat(locale).format(total)} ${words.many}`;
10
+ }
@@ -95,7 +95,9 @@ export function canvasPreview(layout, measurement, source, target) {
95
95
  items.push({ id: child.id, rect });
96
96
  }
97
97
  const axis = ownerId === null ? measurement.rootAxis : (slotRect(ownerId, slot)?.axis ?? 'y');
98
- const bounds = ownerId === null ? { x: 0, y: 0, width: measurement.viewport.width, height: measurement.documentHeight } : (slotRect(ownerId, slot)?.rect ?? rects.get(ownerId) ?? null);
98
+ const bounds = ownerId === null
99
+ ? (measurement.root ?? { x: 0, y: 0, width: measurement.viewport.width, height: measurement.documentHeight })
100
+ : (slotRect(ownerId, slot)?.rect ?? rects.get(ownerId) ?? null);
99
101
  return { axis, wraps: wraps(items, axis), items, bounds };
100
102
  };
101
103
  /** A list that grows by `delta` (vertical lists only) pushes what follows its container. */
@@ -1777,6 +1777,59 @@
1777
1777
  background: var(--theme-error-500);
1778
1778
  }
1779
1779
 
1780
+ // A button with a word next to its icon ("Edit fields" on a page region).
1781
+ .builder-editor__action--text {
1782
+ display: inline-flex;
1783
+ gap: 4px;
1784
+ width: auto;
1785
+ padding: 0 6px;
1786
+ font-size: var(--be-text-s);
1787
+ font-weight: var(--be-weight-medium);
1788
+ white-space: nowrap;
1789
+ }
1790
+
1791
+ // Page regions: fixed parts of the page frame, drawn dashed so they read as "not a block".
1792
+ .builder-editor__hover--region {
1793
+ box-shadow: none;
1794
+ outline: var(--be-px) dashed var(--be-accent);
1795
+ outline-offset: calc(var(--be-px) * -1);
1796
+ }
1797
+
1798
+ .builder-editor__selection--region:not(.builder-editor__selection--editing) {
1799
+ box-shadow: none;
1800
+ outline: calc(var(--be-px) * 2) dashed var(--be-accent);
1801
+ outline-offset: calc(var(--be-px) * -2);
1802
+ }
1803
+
1804
+ .builder-editor__tag-note {
1805
+ margin-left: 2px;
1806
+ opacity: 0.75;
1807
+ font-weight: var(--be-weight-medium);
1808
+ }
1809
+
1810
+ .builder-region__rows {
1811
+ display: grid;
1812
+ gap: 1px;
1813
+ padding: 4px 6px;
1814
+ border-bottom: 1px solid var(--theme-elevation-100);
1815
+ }
1816
+
1817
+ .builder-region__row {
1818
+ width: 100%;
1819
+ border: 0;
1820
+ background: transparent;
1821
+ font: inherit;
1822
+ text-align: left;
1823
+ }
1824
+
1825
+ .builder-region__fields {
1826
+ display: grid;
1827
+ gap: 2px;
1828
+ margin: 0 0 12px;
1829
+ padding: 0;
1830
+ list-style: none;
1831
+ }
1832
+
1780
1833
  .builder-editor__handle {
1781
1834
  cursor: grab;
1782
1835
  touch-action: none;
@@ -12,6 +12,8 @@ export type InlineEditing = {
12
12
  format: RichFormatState | null;
13
13
  /** Set to the current time to open the link form (Ctrl+K in the canvas). */
14
14
  linkRequest: number;
15
+ /** The session edits a field of this page region; `id` is empty and `path` is a document path. */
16
+ region?: string;
15
17
  };
16
18
  /**
17
19
  * The canvas started an editing session. A session on the item a list key moved to continues that
@@ -21,6 +23,8 @@ export declare function noteInlineStart(runtime: Runtime, message: {
21
23
  session: string;
22
24
  id: string;
23
25
  path: string;
26
+ region?: string;
27
+ base?: unknown;
24
28
  }): void;
25
29
  /** The inline editing session of this editor, or null. */
26
30
  export declare function inlineEditing(runtime: Runtime): ValueStore<InlineEditing | null>;
@@ -37,6 +41,7 @@ export declare function applyInlineChange(runtime: Runtime, change: {
37
41
  id: string;
38
42
  path: string;
39
43
  value: unknown;
44
+ region?: string;
40
45
  }): void;
41
46
  /**
42
47
  * The inline start check: the canvas started editing `path` of a block. A prop this user may not
@@ -46,9 +51,16 @@ export declare function applyInlineChange(runtime: Runtime, change: {
46
51
  export declare function refuseLockedInline(runtime: Runtime, message: {
47
52
  id: string;
48
53
  path: string;
54
+ region?: string;
49
55
  }): boolean;
50
56
  /** Starts inline editing of a block's text (Enter on a selected block), optionally `offset` characters in. */
51
57
  export declare function startInlineEditing(runtime: Runtime, id: string, offset?: number): void;
58
+ /** Starts inline editing of a region's first text field (Enter on a selected region). */
59
+ export declare function startRegionEditing(runtime: Runtime, region: string): void;
60
+ /** A region editing session ended: its newest value goes to the document. Nothing typed: nothing saved. */
61
+ export declare function endRegionInline(runtime: Runtime, message: {
62
+ session: string;
63
+ }): void;
52
64
  /** Enter in a list item on the canvas: the next item gets the text after the caret. */
53
65
  export declare function applyInlineSplit(runtime: Runtime, message: {
54
66
  id: string;
@@ -4,10 +4,21 @@
4
4
  // the store, so it syncs to collaborators like any edit. All updates of one editing session merge
5
5
  // into one undo step. In a list, Enter and Backspace move the editing to another item: typing,
6
6
  // the new and joined items and the typing in them stay one undo step until editing ends.
7
- import { createId, findBlock, joinListItem, splitListItem, TEXT_LIST_ITEM_BLOCK } from '../../core/index.js';
7
+ // A page region's text is a document field: its newest value is kept while editing and saved to
8
+ // the document once when editing ends (one save, one undo step).
9
+ import { createId, findBlock, joinListItem, splitListItem, TEXT_LIST_ITEM_BLOCK, valueAtDocPath } from '../../core/index.js';
8
10
  import { setPropPath } from '../../protocol/index.js';
9
11
  import { lockedMessage, propAccessNow } from './fields/accessRules.js';
10
12
  import { createValueStore } from './valueStore.js';
13
+ const regionDrafts = new WeakMap();
14
+ const draftsOf = (runtime) => {
15
+ let drafts = regionDrafts.get(runtime);
16
+ if (!drafts) {
17
+ drafts = new Map();
18
+ regionDrafts.set(runtime, drafts);
19
+ }
20
+ return drafts;
21
+ };
11
22
  const stores = new WeakMap();
12
23
  const listRuns = new WeakMap();
13
24
  /**
@@ -15,6 +26,13 @@ const listRuns = new WeakMap();
15
26
  * key's run; a new session on a list item starts a run; any other session ends it.
16
27
  */
17
28
  export function noteInlineStart(runtime, message) {
29
+ if (message.region) {
30
+ listRuns.delete(runtime);
31
+ // The canvas sends the text it started from; else the value the editor has now.
32
+ const base = 'base' in message ? message.base : valueAtDocPath(runtime.regions?.state.get().values, message.path);
33
+ draftsOf(runtime).set(message.session, { path: message.path, base, locale: runtime.store.getState().locale, changed: false });
34
+ return;
35
+ }
18
36
  const run = listRuns.get(runtime);
19
37
  if (run && run.next === message.id) {
20
38
  listRuns.set(runtime, { ...run, session: message.session, next: null });
@@ -55,6 +73,12 @@ export function inlineUpdate(block, path, value) {
55
73
  }
56
74
  /** Applies one value from the canvas. Every change of a session joins the same undo step. */
57
75
  export function applyInlineChange(runtime, change) {
76
+ if (change.region) {
77
+ const draft = draftsOf(runtime).get(change.session);
78
+ if (draft && draft.path === change.path)
79
+ draftsOf(runtime).set(change.session, { ...draft, value: change.value, changed: true });
80
+ return;
81
+ }
58
82
  // The block as the canvas shows it (the editor's locale): the store writes that locale.
59
83
  const block = findBlock(runtime.store.getState().view, change.id);
60
84
  // A prop the user may not change (field access): the canvas session was stopped; drop late values.
@@ -72,8 +96,15 @@ export function applyInlineChange(runtime, change) {
72
96
  * Returns true when it refused.
73
97
  */
74
98
  export function refuseLockedInline(runtime, message) {
75
- const block = findBlock(runtime.store.getState().view, message.id);
76
- const text = block ? lockedMessage(runtime, block, message.path) : null;
99
+ const block = message.region ? null : findBlock(runtime.store.getState().view, message.id);
100
+ // `null` from `lockedMessage` means allowed: only a missing regions controller is a refusal.
101
+ const text = message.region
102
+ ? runtime.regions
103
+ ? runtime.regions.lockedMessage(message.path)
104
+ : 'This page has no regions.'
105
+ : block
106
+ ? lockedMessage(runtime, block, message.path)
107
+ : null;
77
108
  if (!text)
78
109
  return false;
79
110
  runtime.postToCanvas({ type: 'inlineStop' });
@@ -85,6 +116,20 @@ export function startInlineEditing(runtime, id, offset) {
85
116
  runtime.iframeRef.current?.focus();
86
117
  runtime.postToCanvas({ type: 'inlineStart', id, ...(offset === undefined ? {} : { offset }) });
87
118
  }
119
+ /** Starts inline editing of a region's first text field (Enter on a selected region). */
120
+ export function startRegionEditing(runtime, region) {
121
+ runtime.iframeRef.current?.focus();
122
+ runtime.postToCanvas({ type: 'inlineStart', id: '', region });
123
+ }
124
+ /** A region editing session ended: its newest value goes to the document. Nothing typed: nothing saved. */
125
+ export function endRegionInline(runtime, message) {
126
+ const drafts = draftsOf(runtime);
127
+ const draft = drafts.get(message.session);
128
+ drafts.delete(message.session);
129
+ if (!draft?.changed || !runtime.regions)
130
+ return;
131
+ void runtime.regions.write([{ path: draft.path, value: draft.value, base: draft.base }], { locale: draft.locale });
132
+ }
88
133
  /**
89
134
  * Applies a list item key press, selects the item to edit and edits it. It joins the undo step of
90
135
  * the list run (the session the key ended). A new item's text is typed in the editor's locale.
@@ -137,8 +137,10 @@ export function insertSpotAt(layout, blocks, measurement, p, options = {}) {
137
137
  return between(ownerId, slot, best.i, p[axis] < center(best.rect, axis) ? 'before' : 'after');
138
138
  };
139
139
  if (layout.blocks.length === 0) {
140
- const rect = { x: 0, y: 0, width: measurement.viewport.width, height: EMPTY_PAGE_HEIGHT };
141
- return { parentId: null, slot: DEFAULT_SLOT, index: 0, kind: 'empty', axis: measurement.rootAxis, at: { x: rect.width / 2, y: rect.height / 2 }, rect };
140
+ // In a page frame the empty layout sits in its outlet, between the fixed regions.
141
+ const root = measurement.root;
142
+ const rect = root ? { ...root, height: Math.max(root.height, EMPTY_PAGE_HEIGHT) } : { x: 0, y: 0, width: measurement.viewport.width, height: EMPTY_PAGE_HEIGHT };
143
+ return { parentId: null, slot: DEFAULT_SLOT, index: 0, kind: 'empty', axis: measurement.rootAxis, at: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }, rect };
142
144
  }
143
145
  const hitId = deepestBlockAt(layout, measurement, p);
144
146
  const hit = hitId ? index.get(hitId) : undefined;
@@ -304,6 +304,7 @@ export function useMultiplayer(runtime, { docId, highlightMs = 2500 }) {
304
304
  others.set(collaborator.clientId, collaborator);
305
305
  }
306
306
  engine.session(data.seq, normalizeLayout(data.layout), data.sessionId ?? null, data.reset === true);
307
+ runtime.regions?.reload();
307
308
  const savedSeq = data.savedSeq ?? data.seq;
308
309
  // A save error still current follows this event.
309
310
  publish({ self: data.self ?? null, status: 'open', lastError: null, savedSeq, unsaved: data.seq > savedSeq, saveError: null });
@@ -337,6 +338,8 @@ export function useMultiplayer(runtime, { docId, highlightMs = 2500 }) {
337
338
  return;
338
339
  resuming = false;
339
340
  engine.resumed();
341
+ // Saved events are not replayed, so region fields may have changed while disconnected.
342
+ runtime.regions?.reload();
340
343
  publish({ status: 'open' });
341
344
  publishOffline();
342
345
  lastSent = null;
@@ -364,6 +367,7 @@ export function useMultiplayer(runtime, { docId, highlightMs = 2500 }) {
364
367
  publish({ savedSeq: Math.max(state.savedSeq, data.seq), savedAt: data.at, saveError: null });
365
368
  publishSaveState();
366
369
  runtime.doc.handleEvent(data);
370
+ runtime.regions?.handleEvent(data);
367
371
  });
368
372
  es.addEventListener('saveFailed', (e) => {
369
373
  const data = parse(e);
@@ -372,8 +376,10 @@ export function useMultiplayer(runtime, { docId, highlightMs = 2500 }) {
372
376
  });
373
377
  es.addEventListener('published', (e) => {
374
378
  const data = parse(e);
375
- if (data)
376
- runtime.doc.handleEvent(data);
379
+ if (!data)
380
+ return;
381
+ runtime.doc.handleEvent(data);
382
+ runtime.regions?.handleEvent(data);
377
383
  });
378
384
  es.addEventListener('collaborators', (e) => {
379
385
  const data = parse(e);
@@ -12,11 +12,12 @@ import { findBlock } from '../../../core/index.js';
12
12
  import { GenerateImage } from '../generate/GenerateImage.js';
13
13
  import { Icon } from '../icons.js';
14
14
  import { inlineEditing } from '../inline.js';
15
+ import { ownerKey, selectOwner } from '../regions/select.js';
15
16
  import { useRuntime } from '../runtime.js';
16
17
  import { useEditor } from '../store.js';
17
18
  import { Popover, usePopover } from '../styles/popover.js';
18
19
  import { Select } from '../ui/Select.js';
19
- import { useValue, useValueSelector } from '../valueStore.js';
20
+ import { useOptionalValue, useValue, useValueSelector } from '../valueStore.js';
20
21
  import { imageEditor, imageSpotContext, loadMedia, removeImage, saveMediaAlt, setAltProp, setImage, setImageValue, updateImageEditor, uploadImage, } from './actions.js';
21
22
  import { altPropPath, mediaRef, propAt } from './model.js';
22
23
  import './media.scss';
@@ -55,7 +56,7 @@ export const ImageEditor = memo(function ImageEditor() {
55
56
  const target = open?.target ?? held ?? state.hover;
56
57
  const spotIndex = open && target === open.target ? Math.min(open.spot, target.spots.length - 1) : 0;
57
58
  const spot = target?.spots[spotIndex] ?? null;
58
- const busy = Boolean(state.busy && target && state.busy.id === target.id && spot && state.busy.path === spot.path);
59
+ const busy = Boolean(state.busy && target && state.busy.key === ownerKey(target) && spot && state.busy.path === spot.path);
59
60
  const visible = Boolean(target && spot) && (Boolean(open) || state.dropping || busy || (!dragging && !locked && !editing));
60
61
  // An open request (double-click, chip, Enter): show the popover under the chip.
61
62
  const openAt = open?.at;
@@ -92,13 +93,13 @@ export const ImageEditor = memo(function ImageEditor() {
92
93
  popover.hide();
93
94
  return;
94
95
  }
95
- runtime.store.select(target.id);
96
+ selectOwner(runtime, target);
96
97
  updateImageEditor(runtime, { open: { target, spot: spotIndex, at: Date.now() } });
97
98
  }, children: [busy ? _jsx("span", { className: "builder-media__spinner", "aria-hidden": "true" }) : _jsx(Icon, { name: "image", size: 12 }), chipLabel] })] })), createPortal(_jsx(Popover, { ...popover.props, className: "builder-media__popover", label: "Image", children: popover.open && open && (_jsx(MediaPanel, { target: open.target, spotIndex: Math.min(open.spot, open.target.spots.length - 1), onSpot: (index) => updateImageEditor(runtime, { open: { ...open, spot: index } }), onLibrary: (collection, path) => {
98
99
  popover.hide();
99
- setLibrary({ collection, id: open.target.id, path, at: Date.now() });
100
+ setLibrary({ collection, owner: open.target, path, at: Date.now() });
100
101
  }, onDone: () => popover.hide() })) }), host), library && (_jsx(LibraryDrawer, { collection: library.collection, onSelect: (collection, docId) => {
101
- if (setImage(runtime, library.id, library.path, collection, docId))
102
+ if (setImage(runtime, library.owner, library.path, collection, docId))
102
103
  runtime.notify('Image replaced');
103
104
  }, onClose: () => setLibrary(null) }, library.at))] }));
104
105
  });
@@ -130,9 +131,10 @@ function MediaPanel({ target, spotIndex, onSpot, onLibrary, onDone, }) {
130
131
  const fileRef = useRef(null);
131
132
  const spot = target.spots[spotIndex];
132
133
  const path = spot?.path ?? '';
133
- // Renders again when the block changes (a pick, an undo, a collaborator).
134
- const block = useEditor(runtime.store, (s) => findBlock(s.view, target.id));
135
- const context = block && spot ? imageSpotContext(runtime, target.id, path) : null;
134
+ // Renders again when the block changes (a pick, an undo, a collaborator), or the region's values.
135
+ const block = useEditor(runtime.store, (s) => (target.region ? null : findBlock(s.view, target.id)));
136
+ const regionValues = useOptionalValue(runtime.regions?.state ?? null)?.values ?? null;
137
+ const context = (block || (target.region && regionValues)) && spot ? imageSpotContext(runtime, target, path) : null;
136
138
  const value = context ? propAt(context.block.props, path) : undefined;
137
139
  const ref = context ? mediaRef(context.spot, value) : null;
138
140
  const refKey = ref ? `${ref.collection}:${ref.id}` : '';
@@ -140,7 +142,7 @@ function MediaPanel({ target, spotIndex, onSpot, onLibrary, onDone, }) {
140
142
  const [alt, setAlt] = useState(null);
141
143
  const [error, setError] = useState(null);
142
144
  const [saving, setSaving] = useState(false);
143
- const busy = useValueSelector(imageEditor(runtime), (s) => Boolean(s.busy && s.busy.id === target.id && s.busy.path === path));
145
+ const busy = useValueSelector(imageEditor(runtime), (s) => Boolean(s.busy && s.busy.key === ownerKey(target) && s.busy.path === path));
144
146
  useEffect(() => {
145
147
  if (!ref)
146
148
  return;
@@ -165,7 +167,7 @@ function MediaPanel({ target, spotIndex, onSpot, onLibrary, onDone, }) {
165
167
  const altValue = altPath ? asString(propAt(context.block.props, altPath)) : asString(doc?.alt);
166
168
  const preview = asString(doc?.thumbnailURL) || (asString(doc?.mimeType).startsWith('image/') ? asString(doc?.url) : '');
167
169
  const options = target.spots.map((s, i) => {
168
- const label = imageSpotContext(runtime, target.id, s.path)?.label ?? s.path;
170
+ const label = imageSpotContext(runtime, target, s.path)?.label ?? s.path;
169
171
  return { value: String(i), label: `${label}${KIND_NOTE[s.kind]}` };
170
172
  });
171
173
  const saveAlt = async () => {
@@ -173,7 +175,7 @@ function MediaPanel({ target, spotIndex, onSpot, onLibrary, onDone, }) {
173
175
  return;
174
176
  setError(null);
175
177
  if (altPath) {
176
- setAltProp(runtime, target.id, altPath, alt);
178
+ setAltProp(runtime, target, altPath, alt);
177
179
  return;
178
180
  }
179
181
  if (!ref)
@@ -201,15 +203,19 @@ function MediaPanel({ target, spotIndex, onSpot, onLibrary, onDone, }) {
201
203
  if (url && e.currentTarget.getAttribute('src') !== url)
202
204
  e.currentTarget.src = url;
203
205
  } })) : _jsx("span", { className: "builder-media__thumb builder-media__thumb--empty", children: _jsx(Icon, { name: isVideo ? 'video' : 'image', size: 16 }) }), _jsx("span", { className: "builder-media__file", children: ref ? asString(doc?.filename) || 'Loading…' : 'No media set' })] }), _jsxs("div", { className: "builder-media__actions", children: [_jsxs("button", { type: "button", className: "builder-editor__menu-item", disabled: busy, onClick: () => onLibrary(collection, path), children: [_jsx(Icon, { name: "folder", size: 14 }), "Choose from library"] }), _jsxs("button", { type: "button", className: "builder-editor__menu-item", disabled: busy, onClick: () => fileRef.current?.click(), children: [_jsx(Icon, { name: "arrowUp", size: 14 }), busy ? 'Uploading…' : 'Upload a file'] }), ref && !context.spot.required && (_jsxs("button", { type: "button", className: "builder-editor__menu-item builder-editor__menu-item--danger", disabled: busy, onClick: () => {
204
- if (removeImage(runtime, target.id, path))
206
+ if (removeImage(runtime, target, path))
205
207
  onDone();
206
208
  }, children: [_jsx(Icon, { name: "delete", size: 14 }), "Remove"] })), _jsx("input", { ref: fileRef, type: "file", hidden: true, accept: isVideo ? 'video/*' : 'image/*', onChange: (e) => {
207
209
  const file = e.target.files?.[0];
208
210
  e.target.value = '';
209
211
  if (file)
210
- void uploadImage(runtime, target.id, path, file);
211
- } })] }), !isVideo && (_jsx(GenerateImage, { relationTo: context.spot.field.relationTo ?? collection, hasMany: false, value: value, onChange: (next) => setImageValue(runtime, target.id, path, next) })), (altPath || ref) && (_jsxs("div", { className: "builder-media__alt", children: [_jsx("label", { className: "builder-media__label", htmlFor: `${id}-alt`, children: "Alt text" }), _jsx("input", { id: `${id}-alt`, className: "builder-media__input", type: "text", value: alt ?? altValue, placeholder: altPath && doc ? asString(doc.alt) || 'Describe the image' : 'Describe the image', disabled: saving, onChange: (e) => setAlt(e.target.value), onBlur: () => void saveAlt(), onKeyDown: (e) => {
212
+ void uploadImage(runtime, target, path, file);
213
+ } })] }), !isVideo && (_jsx(GenerateImage, { relationTo: context.spot.field.relationTo ?? collection, hasMany: false, value: value, onChange: (next) => setImageValue(runtime, target, path, next) })), (altPath || ref) && (_jsxs("div", { className: "builder-media__alt", children: [_jsx("label", { className: "builder-media__label", htmlFor: `${id}-alt`, children: "Alt text" }), _jsx("input", { id: `${id}-alt`, className: "builder-media__input", type: "text", value: alt ?? altValue, placeholder: altPath && doc ? asString(doc.alt) || 'Describe the image' : 'Describe the image', disabled: saving, onChange: (e) => setAlt(e.target.value), onBlur: () => void saveAlt(), onKeyDown: (e) => {
212
214
  if (e.key === 'Enter')
213
215
  void saveAlt();
214
- } }), _jsx("p", { className: "builder-media__note", children: altPath ? 'Saved on this block.' : `Saved on the ${collection} document: it changes everywhere this file is used.` })] })), error && (_jsx("p", { className: "builder-media__error", role: "alert", children: error }))] }));
216
+ } }), _jsx("p", { className: "builder-media__note", children: altPath
217
+ ? target.region
218
+ ? 'Saved on this page.'
219
+ : 'Saved on this block.'
220
+ : `Saved on the ${collection} document: it changes everywhere this file is used.` })] })), error && (_jsx("p", { className: "builder-media__error", role: "alert", children: error }))] }));
215
221
  }
@@ -1,5 +1,6 @@
1
1
  import type { Block, BlockDefinition } from '../../../core/types.js';
2
2
  import type { CanvasImageTarget } from '../../../protocol/index.js';
3
+ import { type CanvasOwner } from '../regions/select.js';
3
4
  import type { Runtime } from '../runtime.js';
4
5
  import { type ValueStore } from '../valueStore.js';
5
6
  import { type UploadSpotField } from './model.js';
@@ -14,40 +15,43 @@ export type ImageEditorState = {
14
15
  spot: number;
15
16
  at: number;
16
17
  } | null;
17
- /** An upload in progress, shown on the image. */
18
+ /** An upload in progress, shown on the image. `key`: the owner's key (`ownerKey`). */
18
19
  busy: {
19
- id: string;
20
+ key: string;
20
21
  path: string;
21
22
  } | null;
22
23
  };
23
24
  /** The image editing state of this editor. */
24
25
  export declare function imageEditor(runtime: Runtime): ValueStore<ImageEditorState>;
25
26
  export declare function updateImageEditor(runtime: Runtime, change: Partial<ImageEditorState>): void;
26
- /** What the editor needs to edit the upload at `path` of a block. */
27
+ /** What the editor needs to edit the upload at `path` of a block or a region. */
27
28
  export type ImageSpotContext = {
29
+ /** The block, or for a region its values as block props (no id). */
28
30
  block: Block;
29
31
  definition: BlockDefinition;
30
32
  spot: UploadSpotField;
31
33
  /** "Photo", or "Image · Gallery Items 4" inside an array row. */
32
34
  label: string;
35
+ /** The region, when the image shows a document field. */
36
+ region?: string;
33
37
  };
34
38
  /** The block, its definition and the upload field behind a canvas image, or null when one is gone. */
35
- export declare function imageSpotContext(runtime: Runtime, blockId: string, path: string): ImageSpotContext | null;
39
+ export declare function imageSpotContext(runtime: Runtime, owner: CanvasOwner, path: string): ImageSpotContext | null;
36
40
  /** Sets the stored value of the upload at `path` (an id, or `{ relationTo, value }`): one undo step. */
37
- export declare function setImageValue(runtime: Runtime, blockId: string, path: string, value: unknown): boolean;
41
+ export declare function setImageValue(runtime: Runtime, owner: CanvasOwner, path: string, value: unknown): boolean;
38
42
  /** Sets a media document on the upload at `path`: one undo step. */
39
- export declare function setImage(runtime: Runtime, blockId: string, path: string, collection: string, id: string | number): boolean;
43
+ export declare function setImage(runtime: Runtime, owner: CanvasOwner, path: string, collection: string, id: string | number): boolean;
40
44
  /** Empties the upload at `path` (removes the item of a hasMany upload): one undo step. */
41
- export declare function removeImage(runtime: Runtime, blockId: string, path: string): boolean;
45
+ export declare function removeImage(runtime: Runtime, owner: CanvasOwner, path: string): boolean;
42
46
  /** Sets a text prop (alt text next to the upload). Typing in one field merges into one undo step. */
43
- export declare function setAltProp(runtime: Runtime, blockId: string, path: string, value: string): void;
47
+ export declare function setAltProp(runtime: Runtime, owner: CanvasOwner, path: string, value: string): void;
44
48
  type Doc = Record<string, unknown> & {
45
49
  id: string | number;
46
50
  };
47
51
  /** Uploads a file to an upload collection as the signed-in user. Alt text defaults to the file name. */
48
52
  export declare function uploadMedia(runtime: Runtime, collection: string, file: File): Promise<Doc>;
49
53
  /** Uploads `file` and sets it on the upload at `path`. Shows progress on the image and the result. */
50
- export declare function uploadImage(runtime: Runtime, blockId: string, path: string, file: File): Promise<boolean>;
54
+ export declare function uploadImage(runtime: Runtime, owner: CanvasOwner, path: string, file: File): Promise<boolean>;
51
55
  /** A media document with its alt text and preview URL, or null. */
52
56
  export declare function loadMedia(runtime: Runtime, collection: string, id: string | number): Promise<Doc | null>;
53
57
  /**