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
@@ -0,0 +1,231 @@
1
+ 'use client';
2
+ // Page regions in the editor: the document fields outside the layout that the page frame shows
3
+ // (the collection's `regions` option). The editor loads their values and the user's access from
4
+ // `GET {live}/:collection/:id/regions`, edits them on the canvas (text and images) and saves each
5
+ // change to the document with `POST …/fields`. Every other field edit goes through Payload's
6
+ // settings drawer. Saves by anyone (the drawer, REST, another editor) show again through the
7
+ // live stream's `saved` events.
8
+ import { regionAccessAt, regionDefinition, regionFieldOf, regionsTouched, valueAtDocPath } from '../../../core/regions.js';
9
+ import { createValueStore } from '../valueStore.js';
10
+ /** Equal field values: empty text, null and a missing value are one value. */
11
+ const sameValue = (a, b) => JSON.stringify(a === '' || a === undefined ? null : a) === JSON.stringify(b === '' || b === undefined ? null : b);
12
+ const fieldKey = (locale, path) => JSON.stringify([locale, path]);
13
+ function historyBefore(edits, fields) {
14
+ return edits.map((edit) => {
15
+ const before = valueAtDocPath(fields?.storedValues, edit.path) ?? null;
16
+ const shown = 'base' in edit ? edit.base : valueAtDocPath(fields?.values, edit.path);
17
+ return { path: edit.path, before, after: edit.value, ...(!sameValue(before, shown) ? { beforeShown: shown } : {}) };
18
+ });
19
+ }
20
+ export function createRegionsController(context) {
21
+ const { regions, endpoint } = context;
22
+ const state = createValueStore({ values: null, storedValues: null, access: null, status: 'loading', error: null });
23
+ const selected = createValueStore(null);
24
+ const hovered = createValueStore(null);
25
+ const definitions = new Map(regions.map((r) => [r.name, regionDefinition(r)]));
26
+ let loadRun = 0;
27
+ /** `updatedAt` of this editor's own last save: its `saved` event needs no reload. */
28
+ let ownSave = null;
29
+ let writes = Promise.resolve();
30
+ // Queued saves may finish after the editor switches locale. History still needs their own values.
31
+ const fieldsByLocale = new Map();
32
+ // Repeated blur/Enter for an already queued value is not another edit or history step.
33
+ const queuedValues = new Map();
34
+ const readFields = async (locale) => {
35
+ const response = await fetch(`${endpoint}/regions${locale ? `?locale=${encodeURIComponent(locale)}` : ''}`, {
36
+ credentials: 'include',
37
+ headers: { Accept: 'application/json' },
38
+ });
39
+ const body = (await response.json().catch(() => null));
40
+ if (!body?.ok)
41
+ throw new Error(body && !body.ok ? body.error : `Could not load the page fields (${response.status}).`);
42
+ return { values: body.values, storedValues: body.storedValues ?? body.values, access: body.access };
43
+ };
44
+ const load = async () => {
45
+ const run = ++loadRun;
46
+ const locale = context.locale();
47
+ try {
48
+ const fields = await readFields(locale);
49
+ if (run !== loadRun)
50
+ return;
51
+ fieldsByLocale.set(locale, fields);
52
+ if (locale === context.locale())
53
+ state.set({ ...fields, status: 'ready', error: null });
54
+ }
55
+ catch (error) {
56
+ if (run === loadRun && locale === context.locale())
57
+ state.set({ ...state.get(), status: 'error', error: error instanceof Error ? error.message : 'Could not load the page fields. Check your connection.' });
58
+ }
59
+ };
60
+ /**
61
+ * Saves changes in `locale`. Effective display values and own stored values replace the
62
+ * current ones only while the editor still shows that locale.
63
+ */
64
+ const send = async (changes, locale, before) => {
65
+ try {
66
+ const response = await fetch(`${endpoint}/fields`, {
67
+ method: 'POST',
68
+ credentials: 'include',
69
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
70
+ body: JSON.stringify({ changes, locale }),
71
+ });
72
+ const body = (await response.json().catch(() => null));
73
+ if (!body?.ok) {
74
+ context.warn(body && !body.ok ? body.error : `Not saved (HTTP ${response.status}).`);
75
+ // Someone else's value (a conflict), or the old value again: the page shows what is stored.
76
+ void load();
77
+ context.refreshFrame();
78
+ return { ok: false, retryable: response.status !== 403 && response.status !== 409, values: null };
79
+ }
80
+ ownSave = body.updatedAt;
81
+ const storedValues = body.storedValues ?? body.values;
82
+ fieldsByLocale.set(locale, { ...before, values: body.values, storedValues });
83
+ if (locale === context.locale()) {
84
+ loadRun++;
85
+ state.set({ ...state.get(), values: body.values, storedValues, status: 'ready', error: null });
86
+ }
87
+ else
88
+ void load();
89
+ context.refreshFrame();
90
+ return { ok: true, values: body.values, storedValues };
91
+ }
92
+ catch {
93
+ context.warn('Not saved. Check your connection.');
94
+ context.refreshFrame();
95
+ return { ok: false, retryable: true, values: null };
96
+ }
97
+ };
98
+ const post = (changes, locale) => {
99
+ const request = Symbol();
100
+ for (const change of changes)
101
+ queuedValues.set(fieldKey(locale, change.path), { value: change.value, request });
102
+ const result = writes.then(async () => {
103
+ let before = fieldsByLocale.get(locale);
104
+ if (!before) {
105
+ // A new locale may still be loading or its read may have failed. Never borrow another locale.
106
+ try {
107
+ before = await readFields(locale);
108
+ fieldsByLocale.set(locale, before);
109
+ if (locale === context.locale()) {
110
+ loadRun++;
111
+ state.set({ ...before, status: 'ready', error: null });
112
+ }
113
+ }
114
+ catch (error) {
115
+ context.warn(error instanceof Error ? error.message : 'Could not load the page fields. Check your connection.');
116
+ context.refreshFrame();
117
+ return { ok: false, retryable: true, values: null, changes: [], before };
118
+ }
119
+ }
120
+ const blocked = changes.map((change) => lockedMessage(change.path, before.access)).find((text) => text !== null);
121
+ if (blocked) {
122
+ context.warn(blocked);
123
+ context.refreshFrame();
124
+ return { ok: false, retryable: context.settingsOpen(), values: null, changes: [], before };
125
+ }
126
+ // Only omitted bases follow earlier queued saves. An inline session's explicit base stays fixed.
127
+ const real = changes.map((change) => ({ ...change, base: 'base' in change ? change.base : valueAtDocPath(before.values, change.path) }))
128
+ .filter((change) => !sameValue(change.value, change.base));
129
+ if (real.length === 0) {
130
+ context.refreshFrame();
131
+ return { ok: true, values: before.values, storedValues: before.storedValues, changes: real, before };
132
+ }
133
+ return { ...await send(real, locale, before), changes: real, before };
134
+ }).finally(() => {
135
+ for (const change of changes) {
136
+ const key = fieldKey(locale, change.path);
137
+ if (queuedValues.get(key)?.request === request)
138
+ queuedValues.delete(key);
139
+ }
140
+ });
141
+ writes = result.catch(() => undefined);
142
+ return result;
143
+ };
144
+ const lockedMessage = (path, access = state.get().access, allowUnloaded = false) => {
145
+ const found = regionFieldOf(regions, path);
146
+ if (!found)
147
+ return 'This is not a field of the page.';
148
+ if (context.settingsOpen())
149
+ return 'Close the page settings first: they hold their own copy of these fields.';
150
+ if (!access)
151
+ return allowUnloaded ? null : state.get().status === 'error' ? (state.get().error ?? 'The page fields are not loaded.') : 'The page fields are still loading.';
152
+ const right = regionAccessAt(access, path);
153
+ if (!right.read)
154
+ return `You may not see ${found.field.label}.`;
155
+ if (!right.update)
156
+ return `You may not change ${found.field.label}.`;
157
+ return null;
158
+ };
159
+ return {
160
+ config: regions,
161
+ state,
162
+ selected,
163
+ hovered,
164
+ load,
165
+ reload() {
166
+ void load();
167
+ context.refreshFrame();
168
+ },
169
+ async write(changes, options = {}) {
170
+ const locale = options.locale !== undefined ? options.locale : context.locale();
171
+ const known = fieldsByLocale.get(locale);
172
+ const blocked = changes.map((c) => lockedMessage(c.path, known?.access ?? null, true)).find((text) => text !== null);
173
+ if (blocked) {
174
+ context.warn(blocked);
175
+ context.refreshFrame();
176
+ return false;
177
+ }
178
+ const edits = changes.filter((change) => {
179
+ if ('base' in change)
180
+ return !sameValue(change.value, change.base);
181
+ const queued = queuedValues.get(fieldKey(locale, change.path));
182
+ if (queued)
183
+ return !sameValue(change.value, queued.value);
184
+ return !known || !sameValue(change.value, valueAtDocPath(known.values, change.path));
185
+ });
186
+ if (edits.length === 0) {
187
+ // A duplicate blur must not request an old frame before its queued save has finished.
188
+ if (!changes.some((change) => queuedValues.has(fieldKey(locale, change.path))))
189
+ context.refreshFrame();
190
+ return true;
191
+ }
192
+ let finish;
193
+ if (options.history !== false) {
194
+ const saved = new Promise((resolve) => { finish = resolve; });
195
+ context.record(historyBefore(edits, known), locale, saved);
196
+ }
197
+ const result = await post(edits, locale);
198
+ finish?.(result.ok && result.changes.length > 0 ? historyBefore(result.changes, result.before).map((edit) => {
199
+ const shown = valueAtDocPath(result.values, edit.path);
200
+ const own = valueAtDocPath(result.storedValues, edit.path) ?? null;
201
+ return { ...edit, after: own, ...(!sameValue(own, shown) ? { afterShown: shown } : {}) };
202
+ }) : null);
203
+ return result.ok;
204
+ },
205
+ async writeEdits(changes, locale) {
206
+ const result = await post(changes, locale);
207
+ return result.ok || (result.retryable ? 'retry' : false);
208
+ },
209
+ region: (name) => regions.find((r) => r.name === name) ?? null,
210
+ fieldOf: (path) => regionFieldOf(regions, path),
211
+ definition: (name) => definitions.get(name) ?? null,
212
+ lockedMessage,
213
+ handleEvent(event) {
214
+ if (event.type === 'saved') {
215
+ const fields = event.fields ?? [];
216
+ // Only the layout changed, or this editor's own save, which already shows.
217
+ if (fields.length === 0 || (event.updatedAt && event.updatedAt === ownSave))
218
+ return;
219
+ // The frame may show other fields too (a title in a breadcrumb), so it always shows again.
220
+ if (regionsTouched(regions, fields).length > 0)
221
+ void load();
222
+ context.refreshFrame();
223
+ return;
224
+ }
225
+ // Publish, unpublish, revert, restore: every field may differ now.
226
+ void load();
227
+ context.refreshFrame();
228
+ },
229
+ refreshFrame: context.refreshFrame,
230
+ };
231
+ }
@@ -0,0 +1,17 @@
1
+ import type { CanvasMeasurement, Point } from '../../../core/types.js';
2
+ import type { Runtime } from '../runtime.js';
3
+ /** Who owns an edit on the canvas: a block of the layout, or a region of the page frame. */
4
+ export type CanvasOwner = {
5
+ id: string;
6
+ region?: string;
7
+ };
8
+ /**
9
+ * The region under a point (iframe viewport coordinates), or null. The smallest box wins, so a
10
+ * region inside another one can still be picked. Points inside the layout outlet never count:
11
+ * the layout's blocks own them.
12
+ */
13
+ export declare function regionAt(measurement: CanvasMeasurement, point: Point): string | null;
14
+ /** Selects the owner of a canvas edit: the region, or the block. */
15
+ export declare function selectOwner(runtime: Runtime, owner: CanvasOwner): void;
16
+ /** The key of an owner, for state that may belong to a block or a region (an upload in progress). */
17
+ export declare const ownerKey: (owner: CanvasOwner) => string;
@@ -0,0 +1,31 @@
1
+ 'use client';
2
+ import { rectContains } from '../../../protocol/index.js';
3
+ /**
4
+ * The region under a point (iframe viewport coordinates), or null. The smallest box wins, so a
5
+ * region inside another one can still be picked. Points inside the layout outlet never count:
6
+ * the layout's blocks own them.
7
+ */
8
+ export function regionAt(measurement, point) {
9
+ if (measurement.root && rectContains(measurement.root, point.x, point.y))
10
+ return null;
11
+ let best = null;
12
+ for (const { name, rect } of measurement.regions ?? []) {
13
+ if (!rectContains(rect, point.x, point.y))
14
+ continue;
15
+ const area = rect.width * rect.height;
16
+ if (!best || area < best.area)
17
+ best = { name, area };
18
+ }
19
+ return best?.name ?? null;
20
+ }
21
+ /** Selects the owner of a canvas edit: the region, or the block. */
22
+ export function selectOwner(runtime, owner) {
23
+ if (owner.region && runtime.regions) {
24
+ runtime.regions.selected.set(owner.region);
25
+ return;
26
+ }
27
+ runtime.regions?.selected.set(null);
28
+ runtime.store.select(owner.id);
29
+ }
30
+ /** The key of an owner, for state that may belong to a block or a region (an upload in progress). */
31
+ export const ownerKey = (owner) => (owner.region ? `r:${owner.region}` : `b:${owner.id}`);
@@ -13,6 +13,7 @@ import { type SectionsController } from './sections/controller.js';
13
13
  import { type ThumbnailService } from './sections/thumbnails.js';
14
14
  import type { CollaboratorCursor, LiveState, Peer, PeerCursor } from './live/index.js';
15
15
  import { type TemplateState } from './templates/state.js';
16
+ import { type RegionsController } from './regions/controller.js';
16
17
  export declare const OUTLINE_INDENT = 16;
17
18
  /** `data` attached to every dnd-kit draggable (canvas handle, outline row, library item, section card). */
18
19
  export type DragData = {
@@ -88,6 +89,11 @@ export type Runtime = {
88
89
  problemsRequest: ValueStore<number>;
89
90
  /** The AI assistant chat. Null when the plugin has no `ai` option. */
90
91
  assistant: AssistantController | null;
92
+ /**
93
+ * The page's fixed regions (the collection's `regions` option): document fields outside the
94
+ * layout, shown by the page frame. Null without regions: the editor works on the layout alone.
95
+ */
96
+ regions: RegionsController | null;
91
97
  /** Blocks the assistant just changed, with the time of the change. The overlay flashes them. */
92
98
  assistantFlash: ValueStore<ReadonlyMap<string, number>>;
93
99
  /** Set to the current time to focus the assistant's input (the panel opened). */
@@ -1,17 +1,19 @@
1
1
  'use client';
2
2
  import { createContext, createRef, use } from 'react';
3
- import { canvasDropTarget, createId, EMPTY_LAYOUT, findBlock, getBlockDefinition, outlineDropTarget, starterSlots, withFieldDefaults } from '../../core/index.js';
3
+ import { canvasDropTarget, createId, EMPTY_LAYOUT, findBlock, getBlockDefinition, outlineDropTarget, starterSlots, withFieldDefaults, } from '../../core/index.js';
4
4
  import { post, rectContains } from '../../protocol/index.js';
5
5
  import { removeBlock } from './actions.js';
6
+ import { storageProblemOf } from './storage.js';
6
7
  import { createAssistant } from './assistant/controller.js';
7
8
  import { createEditorStore } from './store.js';
8
9
  import { createDocumentController } from './topbar/document.js';
9
- import { problemSummary, publishProblems } from './topbar/problems.js';
10
+ import { problemSummary, publishProblems, withoutSavedFields } from './topbar/problems.js';
10
11
  import { createValueStore } from './valueStore.js';
11
12
  import { readLeftTab } from './layout/leftTabs.js';
12
13
  import { createSectionsController } from './sections/controller.js';
13
14
  import { createThumbnailService } from './sections/thumbnails.js';
14
15
  import { initialTemplateState } from './templates/state.js';
16
+ import { createRegionsController } from './regions/controller.js';
15
17
  export const OUTLINE_INDENT = 16;
16
18
  const COLLAPSED_KEY = 'payload-builder:collapsed';
17
19
  function loadCollapsed() {
@@ -28,7 +30,9 @@ function loadCollapsed() {
28
30
  * `document` is the open document as the server loaded it.
29
31
  */
30
32
  export function createRuntime(config, api, document, options = {}) {
33
+ const storageProblem = storageProblemOf(config);
31
34
  const store = createEditorStore(EMPTY_LAYOUT, {
35
+ ...(storageProblem ? { storageProblem } : {}),
32
36
  sync: { blocks: config.blocks },
33
37
  // Localized layouts: the editor shows and edits one locale (the `?locale=` of the address, or Payload's locale preference).
34
38
  ...(config.localization ? { localization: { settings: config.localization, blocks: config.blocks, locale: options.locale } } : {}),
@@ -68,6 +72,7 @@ export function createRuntime(config, api, document, options = {}) {
68
72
  cssEndpoint: config.cssEndpoint,
69
73
  api,
70
74
  document: { collection: document.collection, id: document.id },
75
+ ...(config.regions?.length ? { regions: config.regions } : {}),
71
76
  };
72
77
  const runtime = {
73
78
  config,
@@ -103,10 +108,13 @@ export function createRuntime(config, api, document, options = {}) {
103
108
  return problemSummary(list) || null;
104
109
  },
105
110
  onPublished: () => problems.set([]),
111
+ // The settings drawer, a region or a rename saved a field: its old problem is gone.
112
+ onFieldsSaved: (fields) => problems.set(withoutSavedFields(problems.get(), fields)),
106
113
  }, document),
107
114
  problems,
108
115
  problemsRequest,
109
116
  assistant: null,
117
+ regions: null,
110
118
  assistantFlash: createValueStore(new Map()),
111
119
  assistantFocus: createValueStore(0),
112
120
  toggleAssistant(open) {
@@ -120,7 +128,7 @@ export function createRuntime(config, api, document, options = {}) {
120
128
  runtime.assistantFocus.set(Date.now());
121
129
  },
122
130
  insertSpot: createValueStore(null),
123
- sections: createSectionsController(api, config.savedSections?.collection ?? null),
131
+ sections: createSectionsController(api, config.savedSections?.collection ?? null, storageProblem ? (section) => storageProblem({ version: 1, blocks: section.blocks }) === null : undefined),
124
132
  thumbnails: createThumbnailService({
125
133
  canvasPath: config.canvasPath,
126
134
  init: canvasInit,
@@ -143,11 +151,17 @@ export function createRuntime(config, api, document, options = {}) {
143
151
  runtime.help.set(false);
144
152
  else if (runtime.follow.get())
145
153
  runtime.follow.set(null);
154
+ else if (runtime.regions?.selected.get())
155
+ runtime.regions.selected.set(null);
146
156
  else
147
157
  store.select(null);
148
158
  }
149
159
  if (key === 'delete' && selectedId)
150
160
  removeBlock(runtime, selectedId);
161
+ // A fixed region is part of the page frame, never of the layout.
162
+ const region = runtime.regions?.region(runtime.regions.selected.get());
163
+ if (key === 'delete' && !selectedId && region)
164
+ runtime.notify(`${region.label} is a fixed part of the page. It cannot be deleted or moved.`);
151
165
  },
152
166
  notify: (text) => notice.set({ text, at: Date.now() }),
153
167
  warn: (text) => notice.set({ text, at: Date.now(), tone: 'warning' }),
@@ -163,7 +177,8 @@ export function createRuntime(config, api, document, options = {}) {
163
177
  const props = withFieldDefaults({}, def.fields);
164
178
  if (Object.keys(props).length > 0)
165
179
  block.props = props;
166
- if (def.defaultClassName)
180
+ // A Payload blocks field stores no classes: a new block there starts without them.
181
+ if (def.defaultClassName && config.storage !== 'payload-blocks')
167
182
  block.className = def.defaultClassName;
168
183
  // A new list starts with one list item (see `starterSlots`).
169
184
  const slots = starterSlots(config.blocks, type, createId);
@@ -184,6 +199,36 @@ export function createRuntime(config, api, document, options = {}) {
184
199
  });
185
200
  if (config.ai)
186
201
  runtime.assistant = createAssistant(runtime, config.ai.endpoint);
202
+ if (config.regions?.length) {
203
+ const regions = createRegionsController({
204
+ regions: config.regions,
205
+ endpoint: `${config.liveEndpoint}/${encodeURIComponent(document.collection)}/${encodeURIComponent(document.id)}`,
206
+ locale: () => store.getState().locale,
207
+ settingsOpen: () => runtime.doc.settingsOpen.get(),
208
+ refreshFrame: () => runtime.postToCanvas({ type: 'frameRefresh' }),
209
+ record: (edits, locale, saved) => store.recordFields(edits, locale, saved),
210
+ warn: (text) => runtime.warn(text),
211
+ });
212
+ runtime.regions = regions;
213
+ store.setFieldWriter((changes, locale) => regions.writeEdits(changes, locale));
214
+ // A selected block and a selected region exclude each other.
215
+ store.subscribe(() => {
216
+ if (store.getState().selectedId && regions.selected.get())
217
+ regions.selected.set(null);
218
+ });
219
+ regions.selected.subscribe(() => {
220
+ if (regions.selected.get())
221
+ store.select(null);
222
+ });
223
+ // Another language: the fields load in it (the canvas asks for the frame by itself).
224
+ let locale = store.getState().locale;
225
+ store.subscribe(() => {
226
+ if (store.getState().locale === locale)
227
+ return;
228
+ locale = store.getState().locale;
229
+ void regions.load();
230
+ });
231
+ }
187
232
  return runtime;
188
233
  }
189
234
  export const RuntimeContext = createContext(null);
@@ -26,5 +26,9 @@ export type SectionsController = {
26
26
  rename: (section: SectionDefinition, name: string, category?: string) => Promise<SectionDefinition | string>;
27
27
  remove: (section: SectionDefinition) => Promise<true | string>;
28
28
  };
29
- /** `api` is Payload's REST route ("/api"); `collection` the saved sections slug, or null when turned off. */
30
- export declare function createSectionsController(api: string, collection: string | null): SectionsController;
29
+ /**
30
+ * `api` is Payload's REST route ("/api"); `collection` the saved sections slug, or null when turned
31
+ * off. `accepts`: the sections this editor can insert (a Payload blocks field takes only sections
32
+ * it can store). Left out: every section.
33
+ */
34
+ export declare function createSectionsController(api: string, collection: string | null, accepts?: (section: SectionDefinition) => boolean): SectionsController;
@@ -31,13 +31,19 @@ async function docOf(res) {
31
31
  const body = (await res.json());
32
32
  return (body.doc && toSavedSection(body.doc)) || 'The server returned no section.';
33
33
  }
34
- /** `api` is Payload's REST route ("/api"); `collection` the saved sections slug, or null when turned off. */
35
- export function createSectionsController(api, collection) {
34
+ /**
35
+ * `api` is Payload's REST route ("/api"); `collection` the saved sections slug, or null when turned
36
+ * off. `accepts`: the sections this editor can insert (a Payload blocks field takes only sections
37
+ * it can store). Left out: every section.
38
+ */
39
+ export function createSectionsController(api, collection, accepts = () => true) {
36
40
  const saved = createValueStore(null);
37
41
  const dialog = createValueStore(null);
38
42
  const base = collection ? `${api}/${encodeURIComponent(collection)}` : null;
39
43
  let loading = null;
40
44
  const replace = (section) => {
45
+ if (!accepts(section))
46
+ return;
41
47
  const list = saved.get() ?? [];
42
48
  saved.set(list.some((s) => s.id === section.id) ? list.map((s) => (s.id === section.id ? section : s)) : [section, ...list]);
43
49
  };
@@ -56,7 +62,7 @@ export function createSectionsController(api, collection) {
56
62
  if (!res.ok)
57
63
  throw new Error(await errorText(res));
58
64
  const body = (await res.json());
59
- saved.set((body.docs ?? []).flatMap((doc) => toSavedSection(doc) ?? []));
65
+ saved.set((body.docs ?? []).flatMap((doc) => toSavedSection(doc) ?? []).filter(accepts));
60
66
  })
61
67
  .catch(() => {
62
68
  // No access or offline: the library shows the built-in sections only. A later call retries.
@@ -4,7 +4,7 @@
4
4
  import { keyAction } from '../../protocol/index.js';
5
5
  import { findLocation } from '../../core/index.js';
6
6
  import { copySelection, copyStyles, duplicateBlock, moveBy, parseClipboard, pasteBlocks, pasteStyles, removeBlock, storedClipboard, toggleHidden, } from './actions.js';
7
- import { startInlineEditing } from './inline.js';
7
+ import { startInlineEditing, startRegionEditing } from './inline.js';
8
8
  import { leftTabForDigit, selectLeftTab } from './layout/leftTabs.js';
9
9
  import { BLOCK_KEYS, isMac, keyCaps } from './menu/keys.js';
10
10
  import { openSelectionMenu, requestRename } from './menu/requests.js';
@@ -186,10 +186,15 @@ export function bindShortcuts(runtime, doc, { forwarded }) {
186
186
  case 'assistant':
187
187
  runtime.toggleAssistant();
188
188
  return;
189
- case 'editText':
189
+ case 'editText': {
190
190
  if (selectedId)
191
191
  startInlineEditing(runtime, selectedId);
192
+ // A selected page region: edit its first text field on the canvas.
193
+ const region = runtime.regions?.selected.get();
194
+ if (!selectedId && region)
195
+ startRegionEditing(runtime, region);
192
196
  return;
197
+ }
193
198
  case 'copyStyles':
194
199
  if (selectedId)
195
200
  copyStyles(runtime, selectedId);
@@ -255,14 +260,16 @@ export function bindShortcuts(runtime, doc, { forwarded }) {
255
260
  if (action === 'escape' && document.querySelector(OPEN_MENU))
256
261
  return;
257
262
  const { selectedId } = runtime.store.getState();
263
+ // Enter also edits a selected page region's text; other block keys do nothing on a region.
264
+ const editable = Boolean(selectedId) || (action === 'editText' && Boolean(runtime.regions?.selected.get()));
258
265
  if ((action === 'copy' || action === 'cut') && (hasTextSelection(doc) || !selectedId))
259
266
  return;
260
267
  // Without a selection these keys keep their normal meaning (Alt+arrows, Shift+Enter, Shift+F10).
261
- if (!selectedId && NEEDS_SELECTION.has(action))
268
+ if (!editable && NEEDS_SELECTION.has(action))
262
269
  return;
263
270
  // Enter edits text only when nothing else has the focus (a focused button keeps its own Enter).
264
271
  // In the canvas, links and buttons inside blocks are not controls, so any target counts.
265
- if (action === 'editText' && (!selectedId || (!forwarded && !onPage(e.target, doc))))
272
+ if (action === 'editText' && (!editable || (!forwarded && !onPage(e.target, doc))))
266
273
  return;
267
274
  // Copy and paste keep the browser default, so the native clipboard events still fire.
268
275
  if (action !== 'copy' && action !== 'paste')
@@ -0,0 +1,7 @@
1
+ import type { BuilderClientConfig, Layout } from '../../core/types.js';
2
+ /**
3
+ * For a Payload blocks field (`config.storage`): what a layout holds that the field cannot store,
4
+ * as one message, else null. The server refuses the same (core/payloadBlocks.ts). Null for the
5
+ * builder's JSON layout, which stores everything.
6
+ */
7
+ export declare function storageProblemOf(config: BuilderClientConfig): ((layout: Layout) => string | null) | null;
@@ -0,0 +1,15 @@
1
+ // What the editor's layout field can store. A Payload blocks field holds its blocks' fields only;
2
+ // the editor refuses an own edit it could not save, as the server does (core/payloadBlocks.ts).
3
+ // Pure, safe in the admin and in tests.
4
+ import { payloadBlocksProblems } from '../../core/payloadBlocks.js';
5
+ /**
6
+ * For a Payload blocks field (`config.storage`): what a layout holds that the field cannot store,
7
+ * as one message, else null. The server refuses the same (core/payloadBlocks.ts). Null for the
8
+ * builder's JSON layout, which stores everything.
9
+ */
10
+ export function storageProblemOf(config) {
11
+ if (config.storage !== 'payload-blocks')
12
+ return null;
13
+ const storage = { blocks: config.blocks, rootTypes: config.payloadRootTypes ?? config.blocks.map((b) => b.type) };
14
+ return (layout) => payloadBlocksProblems(layout, storage)[0] ?? null;
15
+ }
@@ -1,10 +1,38 @@
1
1
  import { type Variant } from '../../core/index.js';
2
2
  import type { BlockDefinition, Layout, LocaleSettings, Operation } from '../../core/types.js';
3
+ import type { LiveFieldChange } from '../../live/types.js';
3
4
  import { type SyncOptions, type SyncUpdate } from './live/sync.js';
4
5
  import { type Equality } from './valueStore.js';
6
+ /** Own stored values of a region field. `Shown` values include locale fallback, for conflict checks. */
7
+ export type FieldEdit = {
8
+ path: string;
9
+ before: unknown;
10
+ after: unknown;
11
+ beforeShown?: unknown;
12
+ afterShown?: unknown;
13
+ };
14
+ /**
15
+ * Saves field changes for undo and redo, in `locale` (the locale the step was made in, null
16
+ * without localization). False: refused. `retry`: temporary failure; keep the step.
17
+ */
18
+ export type FieldWriteResult = boolean | 'retry';
19
+ export type FieldWriter = (changes: LiveFieldChange[], locale: string | null) => Promise<FieldWriteResult>;
5
20
  type HistoryEntry = {
6
21
  /** Applied in order, these undo (or redo) one user action. */
7
22
  ops: Operation[];
23
+ /**
24
+ * A step of document field changes (a region's text or image), saved to the document instead of
25
+ * applied to the layout. Undo writes `before` back, redo `after`; each expects the other value
26
+ * there, so a field someone else changed since is never overwritten.
27
+ */
28
+ fields?: FieldEdit[];
29
+ /** The original save must finish before undo can use its hook-adjusted values. */
30
+ fieldsReady?: Promise<boolean>;
31
+ /**
32
+ * The locale a field step was made in. Undo and redo write that locale, whatever the editor
33
+ * shows now, as layout operations keep their own `locale`.
34
+ */
35
+ fieldLocale?: string | null;
8
36
  /** Selection to restore when this entry is applied. */
9
37
  selectedId: string | null;
10
38
  /**
@@ -80,6 +108,11 @@ export type EditorStoreOptions = {
80
108
  blocks: readonly BlockDefinition[];
81
109
  locale?: string | null;
82
110
  };
111
+ /**
112
+ * What the layout field cannot store (a Payload blocks field): the reason, or null. An own edit
113
+ * whose result it refuses is not applied, so nothing shows that the server would refuse.
114
+ */
115
+ storageProblem?: (layout: Layout) => string | null;
83
116
  };
84
117
  export declare const UNDO_PARTIAL = "Couldn't undo everything \u2014 someone else changed this.";
85
118
  export declare const UNDO_NONE = "Couldn't undo \u2014 someone else changed this.";
@@ -123,6 +156,12 @@ export declare function createEditorStore(initial: Layout, options?: EditorStore
123
156
  apply(ops: Operation | Operation[], applyOptions?: ApplyOptions): boolean;
124
157
  undo(): void;
125
158
  redo(): void;
159
+ /**
160
+ * Records the action immediately. `saved` replaces its values after hooks, or removes a failed save.
161
+ */
162
+ recordFields(edits: FieldEdit[], locale?: string | null, saved?: Promise<FieldEdit[] | null>): void;
163
+ /** Saves the field changes of undo and redo. Without one, field steps cannot be undone. */
164
+ setFieldWriter(writer: FieldWriter | null): void;
126
165
  /**
127
166
  * Ends the current merge run: the next edit starts a new undo step even with the same
128
167
  * `mergeKey` (a text field lost the focus). Groups are not affected.