payload-canvas 0.6.2 → 0.6.4

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 (60) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +7 -5
  3. package/dist/admin/aiKeyField.scss +58 -58
  4. package/dist/admin/diff/layoutDiff.scss +181 -181
  5. package/dist/admin/editor/assistant/assistant.scss +944 -944
  6. package/dist/admin/editor/classes/manager.scss +262 -262
  7. package/dist/admin/editor/comments/comments.scss +539 -539
  8. package/dist/admin/editor/dnd/dnd.scss +261 -261
  9. package/dist/admin/editor/editor.scss +2629 -2629
  10. package/dist/admin/editor/empty/empty.scss +92 -92
  11. package/dist/admin/editor/fields/fields.scss +778 -778
  12. package/dist/admin/editor/generate/generate.scss +276 -276
  13. package/dist/admin/editor/layout/layout.scss +240 -240
  14. package/dist/admin/editor/live/presence.scss +24 -24
  15. package/dist/admin/editor/locale/locale.scss +154 -154
  16. package/dist/admin/editor/media/media.scss +233 -233
  17. package/dist/admin/editor/menu/menu.scss +132 -132
  18. package/dist/admin/editor/motion/motion.scss +84 -84
  19. package/dist/admin/editor/sections/components.scss +238 -238
  20. package/dist/admin/editor/sections/variants.scss +90 -90
  21. package/dist/admin/editor/styles/ClassCss.js +3 -3
  22. package/dist/admin/editor/styles/classes.scss +381 -381
  23. package/dist/admin/editor/styles/styles.scss +1123 -1123
  24. package/dist/admin/editor/styles/tokens.js +2 -1
  25. package/dist/admin/editor/templates/templates.scss +654 -654
  26. package/dist/admin/editor/tooltip/tooltip.scss +39 -39
  27. package/dist/admin/editor/topbar/DocumentActions.js +1 -1
  28. package/dist/admin/editor/topbar/contentMode.scss +26 -26
  29. package/dist/admin/editor/topbar/screens/screens.scss +134 -134
  30. package/dist/admin/editor/topbar/settingsDrawer.scss +32 -32
  31. package/dist/admin/editor/topbar/topbar.scss +645 -645
  32. package/dist/admin/editor/ui/controls.scss +320 -320
  33. package/dist/admin/forms/submissions.scss +197 -197
  34. package/dist/admin/layoutField.scss +69 -69
  35. package/dist/admin/templateConditions.scss +24 -24
  36. package/dist/ai/prompt.js +40 -40
  37. package/dist/blocks/client/marquee.js +14 -14
  38. package/dist/blocks/defaults.js +17 -1
  39. package/dist/blocks/payload.js +13 -3
  40. package/dist/core/responseError.d.ts +5 -0
  41. package/dist/core/responseError.js +8 -0
  42. package/dist/css/index.d.ts +6 -0
  43. package/dist/css/index.js +40 -1
  44. package/dist/css/shared.js +2 -2
  45. package/dist/live/session.js +18 -0
  46. package/dist/live/storage.d.ts +5 -0
  47. package/dist/live/storage.js +20 -0
  48. package/dist/mcp/shared.js +16 -16
  49. package/dist/plugin/index.d.ts +14 -1
  50. package/dist/plugin/index.js +46 -8
  51. package/dist/react/canvas/BuilderCanvas.js +4 -3
  52. package/dist/react/canvas/thumbnail/ThumbnailCanvas.js +2 -1
  53. package/dist/react/components/AutoplayVideo.d.ts +3 -1
  54. package/dist/react/components/AutoplayVideo.js +4 -3
  55. package/dist/react/components/Video.d.ts +1 -0
  56. package/dist/react/components/Video.js +13 -2
  57. package/dist/react/components/videoPlayback.d.ts +13 -0
  58. package/dist/react/components/videoPlayback.js +10 -0
  59. package/dist/theme/admin/fields.scss +363 -363
  60. package/package.json +1 -1
package/dist/ai/prompt.js CHANGED
@@ -101,32 +101,32 @@ function sectionCatalog(sections, saved) {
101
101
  /** The stable system prompt. Same input, same bytes: keep it free of request data. */
102
102
  export function systemPrompt(catalog) {
103
103
  const parts = [
104
- `You are the AI assistant inside a visual website builder for Payload CMS. The user has one page open in the editor and asks you to change it: add sections, write or rewrite text, restyle blocks, reorder or remove them. You make those changes with your tools.
105
-
106
- HOW YOUR EDITS WORK
107
- - Your tools edit the page the user has open. Each successful change appears on the user's canvas at once. You never save or publish: the editor saves the page as usual, and the user can undo your whole reply in one step.
108
- - Each user message comes with an <editor_context> block: the current layout JSON with every block id, the selected block, the canvas width and, for templates, the sample document. It shows the page when the user sent the message, including the user's own unsaved edits. The newest context block is the truth; older ones are history.
109
- - "this", "it" and "the selected block" mean the selected block.
110
- - Change only what the user asked for. Keep existing content unless the user asks you to replace it.
111
-
112
- HOW TO WORK
113
- 1. Start with one short sentence that says what you are going to do.
114
- 2. To build page parts (hero, features, pricing, testimonials, FAQ, call to action, contact, footer), PREFER a ready-made section from the section catalog: insertSection, then adjust its text, images and classes with applyOperations "update". Build from single blocks only when no section fits, or for small additions.
115
- 3. Put related changes into one applyOperations call. Operations apply in order, all or nothing.
116
- 4. When a tool returns an error, read it, fix the input and try again. Do not repeat a call that failed.
117
- 5. When you are done, say in one or two plain sentences what you changed. Do not list block ids or JSON. If you could not do something, say so.
118
- - If the request is unclear, or it would delete a lot of content, ask one short question instead of guessing.
119
-
120
- WRITING COPY
121
- - Keep copy short, concrete and on-brand: match the tone, names and facts already on the page.
122
- - Headings: a few words. Body text: one to three sentences.
123
- - Do not invent prices, statistics, customer names, quotes or contact details as if they were real. When the user wants example content, make it clearly a placeholder.
124
-
125
- IMAGES
126
- - Image and upload props hold the ID of a document in the media library. Find images with searchMedia. Never invent IDs or URLs.
127
- - generateImage makes a new image and saves it in the media library (it costs money). Use it when the user asks for a new or generated image, or when nothing in the library fits and the user wants an image. With blockId it puts the image straight into that block. If it says image generation is not set up, keep the current image and tell the user.
128
-
129
- RICH TEXT
104
+ `You are the AI assistant inside a visual website builder for Payload CMS. The user has one page open in the editor and asks you to change it: add sections, write or rewrite text, restyle blocks, reorder or remove them. You make those changes with your tools.
105
+
106
+ HOW YOUR EDITS WORK
107
+ - Your tools edit the page the user has open. Each successful change appears on the user's canvas at once. You never save or publish: the editor saves the page as usual, and the user can undo your whole reply in one step.
108
+ - Each user message comes with an <editor_context> block: the current layout JSON with every block id, the selected block, the canvas width and, for templates, the sample document. It shows the page when the user sent the message, including the user's own unsaved edits. The newest context block is the truth; older ones are history.
109
+ - "this", "it" and "the selected block" mean the selected block.
110
+ - Change only what the user asked for. Keep existing content unless the user asks you to replace it.
111
+
112
+ HOW TO WORK
113
+ 1. Start with one short sentence that says what you are going to do.
114
+ 2. To build page parts (hero, features, pricing, testimonials, FAQ, call to action, contact, footer), PREFER a ready-made section from the section catalog: insertSection, then adjust its text, images and classes with applyOperations "update". Build from single blocks only when no section fits, or for small additions.
115
+ 3. Put related changes into one applyOperations call. Operations apply in order, all or nothing.
116
+ 4. When a tool returns an error, read it, fix the input and try again. Do not repeat a call that failed.
117
+ 5. When you are done, say in one or two plain sentences what you changed. Do not list block ids or JSON. If you could not do something, say so.
118
+ - If the request is unclear, or it would delete a lot of content, ask one short question instead of guessing.
119
+
120
+ WRITING COPY
121
+ - Keep copy short, concrete and on-brand: match the tone, names and facts already on the page.
122
+ - Headings: a few words. Body text: one to three sentences.
123
+ - Do not invent prices, statistics, customer names, quotes or contact details as if they were real. When the user wants example content, make it clearly a placeholder.
124
+
125
+ IMAGES
126
+ - Image and upload props hold the ID of a document in the media library. Find images with searchMedia. Never invent IDs or URLs.
127
+ - generateImage makes a new image and saves it in the media library (it costs money). Use it when the user asks for a new or generated image, or when nothing in the library fits and the user wants an image. With blockId it puts the image straight into that block. If it says image generation is not set up, keep the current image and tell the user.
128
+
129
+ RICH TEXT
130
130
  - Rich text props hold Lexical JSON. Call getBlockSchema for the block before you write one.`,
131
131
  stylingGuide(catalog.tokens),
132
132
  layoutGuide('the block catalog'),
@@ -146,20 +146,20 @@ RICH TEXT
146
146
  */
147
147
  export function formSystemPrompt(catalog) {
148
148
  const parts = [
149
- `You are the AI assistant inside a form builder for Payload CMS. The user has one form open (a contact form, a booking request, a survey) and asks you to change its fields: add, rename, reorder or remove questions, make them required, set their options, display conditions and classes (the width too). You make those changes with your tools.
150
-
151
- HOW YOUR EDITS WORK
152
- - editFormFields changes the open form. Each change appears in the form builder at once. You never save: the builder saves as usual, and the user can undo your whole reply in one step.
153
- - Each user message comes with an <editor_context> block: the form's fields as a layout JSON (each block is one field; its type is "form" plus the field type, e.g. "formEmail"; its props are the field's values). The newest context block is the truth. getForm returns the fields in a simpler shape.
154
- - "this" and "the selected field" mean the selected block.
155
- - You cannot change the form's settings (title, submit button, confirmation message, emails, spam protection). When the user asks for one, tell them to click an empty spot of the canvas: the right panel then shows the form settings.
156
-
157
- HOW TO WORK
158
- 1. Start with one short sentence that says what you are going to do.
159
- 2. Put related changes into one editFormFields call. Changes apply in order, all or nothing.
160
- 3. Ask people only for what you need: keep forms short, mark only the needed fields required, and use the field type that fits (email for addresses, textarea for messages, select or radio for a fixed list of choices, checkbox to accept terms).
161
- 4. Labels are short questions or nouns ("Your name", "Email", "How can we help?"). Names are short, lowercase, with _ ("company_size").
162
- 5. When a tool returns an error, read it, fix the input and try again. Do not repeat a call that failed.
149
+ `You are the AI assistant inside a form builder for Payload CMS. The user has one form open (a contact form, a booking request, a survey) and asks you to change its fields: add, rename, reorder or remove questions, make them required, set their options, display conditions and classes (the width too). You make those changes with your tools.
150
+
151
+ HOW YOUR EDITS WORK
152
+ - editFormFields changes the open form. Each change appears in the form builder at once. You never save: the builder saves as usual, and the user can undo your whole reply in one step.
153
+ - Each user message comes with an <editor_context> block: the form's fields as a layout JSON (each block is one field; its type is "form" plus the field type, e.g. "formEmail"; its props are the field's values). The newest context block is the truth. getForm returns the fields in a simpler shape.
154
+ - "this" and "the selected field" mean the selected block.
155
+ - You cannot change the form's settings (title, submit button, confirmation message, emails, spam protection). When the user asks for one, tell them to click an empty spot of the canvas: the right panel then shows the form settings.
156
+
157
+ HOW TO WORK
158
+ 1. Start with one short sentence that says what you are going to do.
159
+ 2. Put related changes into one editFormFields call. Changes apply in order, all or nothing.
160
+ 3. Ask people only for what you need: keep forms short, mark only the needed fields required, and use the field type that fits (email for addresses, textarea for messages, select or radio for a fixed list of choices, checkbox to accept terms).
161
+ 4. Labels are short questions or nouns ("Your name", "Email", "How can we help?"). Names are short, lowercase, with _ ("company_size").
162
+ 5. When a tool returns an error, read it, fix the input and try again. Do not repeat a call that failed.
163
163
  6. When you are done, say in one or two plain sentences what you changed. Do not list ids or JSON.`,
164
164
  FORM_FIELDS_GUIDE,
165
165
  `FIELD TYPES (JSON). The types this form offers, with their props.\n${JSON.stringify(formFieldTypes(catalog.blocks))}`,
@@ -8,18 +8,18 @@ export const MARQUEE_SECONDS = { slow: 60, normal: 35, fast: 20 };
8
8
  * and moves by half its width, so the second copy takes the place of the first. Still on the
9
9
  * canvas and with reduced motion: the items wrap and the copy is not shown.
10
10
  */
11
- export const MARQUEE_CSS = `
12
- @keyframes builder-marquee { from { transform: translate3d(0, 0, 0) } to { transform: translate3d(-50%, 0, 0) } }
13
- [data-marquee] { overflow: hidden }
14
- [data-marquee-track] { display: flex; width: max-content; animation: builder-marquee var(--marquee-duration, 35s) linear infinite }
15
- [data-marquee-track] > * { flex-shrink: 0 }
16
- [data-marquee="right"] [data-marquee-track] { animation-direction: reverse }
17
- [data-marquee-pause]:hover [data-marquee-track], [data-marquee-pause]:focus-within [data-marquee-track] { animation-play-state: paused }
18
- [data-marquee-still] [data-marquee-track] { width: auto; animation: none }
19
- [data-marquee-still] [data-marquee-track] > * { flex-shrink: 1; flex-wrap: wrap }
20
- @media (prefers-reduced-motion: reduce) {
21
- [data-marquee-track] { width: auto; animation: none }
22
- [data-marquee-track] > * { flex-shrink: 1; flex-wrap: wrap }
23
- [data-marquee-copy] { display: none }
24
- }
11
+ export const MARQUEE_CSS = `
12
+ @keyframes builder-marquee { from { transform: translate3d(0, 0, 0) } to { transform: translate3d(-50%, 0, 0) } }
13
+ [data-marquee] { overflow: hidden }
14
+ [data-marquee-track] { display: flex; width: max-content; animation: builder-marquee var(--marquee-duration, 35s) linear infinite }
15
+ [data-marquee-track] > * { flex-shrink: 0 }
16
+ [data-marquee="right"] [data-marquee-track] { animation-direction: reverse }
17
+ [data-marquee-pause]:hover [data-marquee-track], [data-marquee-pause]:focus-within [data-marquee-track] { animation-play-state: paused }
18
+ [data-marquee-still] [data-marquee-track] { width: auto; animation: none }
19
+ [data-marquee-still] [data-marquee-track] > * { flex-shrink: 1; flex-wrap: wrap }
20
+ @media (prefers-reduced-motion: reduce) {
21
+ [data-marquee-track] { width: auto; animation: none }
22
+ [data-marquee-track] > * { flex-shrink: 1; flex-wrap: wrap }
23
+ [data-marquee-copy] { display: none }
24
+ }
25
25
  `;
@@ -27,6 +27,7 @@ export function listCollectionField(slugs, args) {
27
27
  : { name: 'collection', type: 'text', label: args.label, ...required, ...admin };
28
28
  }
29
29
  const PICKED_HELP = 'Shows only these, in this order.';
30
+ const PHONE_VIDEO_HELP = 'Optional. A smaller copy, such as an upright crop, that screens up to 767 px wide load instead. Keep the framing of the poster.';
30
31
  /** The collection list's picked documents: a relationship to `slugs`, or ids as text when there are none. */
31
32
  export function pickedDocumentsField(slugs) {
32
33
  if (!slugs || slugs.length === 0) {
@@ -450,6 +451,20 @@ export function defaultBlocks(options) {
450
451
  },
451
452
  custom: { ai: { description: 'A YouTube or Vimeo link, or a direct link to a video file.' } },
452
453
  },
454
+ {
455
+ name: 'phoneVideo',
456
+ type: 'upload',
457
+ label: 'Phone video',
458
+ relationTo: mediaCollection,
459
+ admin: { ...when('source', 'upload'), description: PHONE_VIDEO_HELP },
460
+ },
461
+ {
462
+ name: 'phoneUrl',
463
+ type: 'text',
464
+ label: 'Phone video link',
465
+ admin: { ...when('source', 'url'), placeholder: 'A video file', description: PHONE_VIDEO_HELP },
466
+ custom: { ai: { description: 'Optional. A direct link to a smaller video file that screens up to 767 px wide load instead.' } },
467
+ },
453
468
  { name: 'poster', type: 'upload', label: 'Poster image', relationTo: mediaCollection },
454
469
  {
455
470
  name: 'autoplay',
@@ -484,7 +499,8 @@ export function defaultBlocks(options) {
484
499
  'see the poster). For a background video behind a hero: put the video first in a stack with "relative isolate", ' +
485
500
  'set "autoplay", "muted", "loop" and "decorative": true (aria-hidden, no controls, no tab stop), "priority": ' +
486
501
  'true when it is the first thing on the page (preload="auto", the poster preloads with high fetch priority), ' +
487
- 'a "poster", and className "absolute inset-0 -z-10 size-full object-cover".',
502
+ 'a "poster", and className "absolute inset-0 -z-10 size-full object-cover". Optional "phoneVideo" (upload) or ' +
503
+ '"phoneUrl" (a video file link): a smaller copy, for example an upright crop, that screens up to 767 px wide load instead.',
488
504
  example: {
489
505
  type: 'video',
490
506
  props: { source: 'url', url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', controls: true },
@@ -24,13 +24,23 @@ const ICONS = [
24
24
  [/spacer/i, 'spacer'],
25
25
  [/rich|content|text|prose|copy|intro/i, 'richText'],
26
26
  ];
27
- const seenWarnings = new Set();
27
+ /**
28
+ * The warnings already printed, on `globalThis`: Next.js loads this module once per bundle (server
29
+ * components, SSR, route handlers, the admin) and again after each dev reload, so a module-level
30
+ * set would print the same warning on every render. One set per process, and per page load.
31
+ */
32
+ const SEEN_WARNINGS_KEY = Symbol.for('payload-canvas.fromPayloadBlocks.warnings');
33
+ function seenWarnings() {
34
+ const store = globalThis;
35
+ return (store[SEEN_WARNINGS_KEY] ??= new Set());
36
+ }
28
37
  function defaultWarn(message) {
29
38
  if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production')
30
39
  return;
31
- if (seenWarnings.has(message))
40
+ const seen = seenWarnings();
41
+ if (seen.has(message))
32
42
  return;
33
- seenWarnings.add(message);
43
+ seen.add(message);
34
44
  console.warn(message);
35
45
  }
36
46
  /** `{ max: 1 }` from `maxRows: 1`; nothing for a missing or invalid row count. */
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The message of a failed response: the endpoint's own `{ error }` text when it sent one (the CSS
3
+ * endpoints say what to change in the config), else the status. Client-safe.
4
+ */
5
+ export declare function responseErrorMessage(res: Response): Promise<string>;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The message of a failed response: the endpoint's own `{ error }` text when it sent one (the CSS
3
+ * endpoints say what to change in the config), else the status. Client-safe.
4
+ */
5
+ export async function responseErrorMessage(res) {
6
+ const body = (await res.json().catch(() => null));
7
+ return typeof body?.error === 'string' && body.error !== '' ? body.error : `${res.status} ${res.statusText}`;
8
+ }
@@ -25,6 +25,12 @@ export type CanvasCssInput = {
25
25
  entry: string;
26
26
  [key: string]: unknown;
27
27
  };
28
+ /**
29
+ * What stops the app's CSS entry from compiling, as messages that say what to change: an entry
30
+ * file that cannot be read, `@plugin` ids missing from `plugins` (every one of them), or another
31
+ * compile error. Empty: the entry compiles. The plugin runs it at startup (`websiteBuilder`).
32
+ */
33
+ export declare function cssEntryProblems(options: CssOptions): Promise<string[]>;
28
34
  /**
29
35
  * Compiles only the given classes against the app's CSS entry. Output: the utilities plus the
30
36
  * @property / @keyframes rules they need. No Preflight, no base layer, never overrides theme vars.
package/dist/css/index.js CHANGED
@@ -121,7 +121,11 @@ const hash = (...parts) => createHash('sha256').update(parts.join('\0')).digest(
121
121
  const inputCache = new Lru(8);
122
122
  /** countUtilityLayers() of an empty build, per recorded input. Server-side only. */
123
123
  const staticUtilityLayers = new WeakMap();
124
- async function recordInput(entryFile, entryCss, plugins) {
124
+ /**
125
+ * `onMissing`: called for each `@plugin` id missing from `plugins`, which then loads as an empty
126
+ * plugin (the startup check lists every missing id). Left out: a missing id throws.
127
+ */
128
+ async function recordInput(entryFile, entryCss, plugins, onMissing) {
125
129
  const entryDir = path.dirname(entryFile);
126
130
  const toVirtual = (real) => path.relative(entryDir, real).replaceAll('\\', '/') || ENTRY_BASE;
127
131
  const data = { version: 1, entry: entryCss, stylesheets: {}, plugins: [] };
@@ -143,6 +147,10 @@ async function recordInput(entryFile, entryCss, plugins) {
143
147
  loadModule: (id, base) => {
144
148
  if (!data.plugins.includes(id))
145
149
  data.plugins.push(id);
150
+ if (onMissing && !Object.hasOwn(plugins ?? {}, id)) {
151
+ onMissing(id);
152
+ return Promise.resolve({ path: id, base, module: (() => { }) });
153
+ }
146
154
  return loadPlugin(id, base, plugins);
147
155
  },
148
156
  });
@@ -164,6 +172,37 @@ async function getInput(options) {
164
172
  }
165
173
  // ---------------------------------------------------------------------------------------------
166
174
  // Public API
175
+ /**
176
+ * What stops the app's CSS entry from compiling, as messages that say what to change: an entry
177
+ * file that cannot be read, `@plugin` ids missing from `plugins` (every one of them), or another
178
+ * compile error. Empty: the entry compiles. The plugin runs it at startup (`websiteBuilder`).
179
+ */
180
+ export async function cssEntryProblems(options) {
181
+ let entryCss;
182
+ try {
183
+ entryCss = await readCached(options.entry);
184
+ }
185
+ catch {
186
+ return [`The CSS entry "${options.entry}" cannot be read. Set \`css.entry\` of websiteBuilder() to the app's Tailwind entry CSS, absolute or relative to the folder the app starts in.`];
187
+ }
188
+ const missing = [];
189
+ try {
190
+ await recordInput(options.entry, entryCss, options.plugins, (id) => {
191
+ if (!missing.includes(id))
192
+ missing.push(id);
193
+ });
194
+ }
195
+ catch (error) {
196
+ return [...(missing.length > 0 ? [missingPluginsMessage(missing)] : []), `The CSS entry "${options.entry}" does not compile: ${error instanceof Error ? error.message : String(error)}`];
197
+ }
198
+ return missing.length > 0 ? [missingPluginsMessage(missing)] : [];
199
+ }
200
+ function missingPluginsMessage(ids) {
201
+ const list = ids.map((id) => `"${id}"`).join(', ');
202
+ const entries = ids.map((id) => `'${id}': plugin`).join(', ');
203
+ return (`The CSS entry uses @plugin ${list}, but \`css.plugins\` of websiteBuilder() does not have ${ids.length === 1 ? 'it' : 'them'}. ` +
204
+ `Import each plugin in the Payload config and pass it: css: { entry, plugins: { ${entries} } }.`);
205
+ }
167
206
  const cssCache = new Lru(100);
168
207
  /**
169
208
  * Compiles only the given classes against the app's CSS entry. Output: the utilities plus the
@@ -5,8 +5,8 @@ import { BUILDER_CSS_CLASS } from './marker.js';
5
5
  export const ENTRY_BASE = '.';
6
6
  export const stylesheetKey = (id, base) => `${id}|${base}`;
7
7
  export function missingPluginError(id) {
8
- return new Error(`Tailwind plugin "${id}" is used by @plugin in the CSS entry but is not in the plugins map. ` +
9
- `Pass it as plugins: { '${id}': plugin }.`);
8
+ return new Error(`Tailwind plugin "${id}" is used by @plugin in the CSS entry but is not in the plugins map ` +
9
+ `(\`css.plugins\` of websiteBuilder()). Import it and pass it as plugins: { '${id}': plugin }.`);
10
10
  }
11
11
  export function loadPlugin(id, base, plugins = {}) {
12
12
  if (!Object.hasOwn(plugins, id))
@@ -119,6 +119,8 @@ function rememberRows(session) {
119
119
  }
120
120
  /** The answer of a session save that found nothing left to write. */
121
121
  const SKIPPED = Symbol('skipped');
122
+ /** The answer of a session save whose layout the field already stores: nothing written. */
123
+ const UNCHANGED = Symbol('unchanged');
122
124
  /**
123
125
  * The session save waits: a reset action owns the layout until its save or rollback finishes, or
124
126
  * a committed save's hook changes are not in the layout yet (`session.adopting`).
@@ -423,6 +425,14 @@ export function createSessionManager(options = {}) {
423
425
  const problems = codec.problems(layout);
424
426
  if (problems.length > 0)
425
427
  throw Object.assign(new Error(problems.join(' ')), { status: 422 });
428
+ // The layout as the field would store it equals the stored value (a commit set a value it
429
+ // already had, or later commits undid it): no write, so no new draft version. Read now,
430
+ // inside the gate: the session's copy can be older than a save outside the session.
431
+ const current = (await readStored(session))[target.field];
432
+ if (activeActions.has(session.key))
433
+ return PAUSED;
434
+ if (codec.isStored ? codec.isStored(layout, current) : sameJson(codec.encode(layout, current), current))
435
+ return UNCHANGED;
426
436
  session.writing = true;
427
437
  try {
428
438
  return await write(layout, req);
@@ -477,6 +487,14 @@ export function createSessionManager(options = {}) {
477
487
  clearFailure(session);
478
488
  return;
479
489
  }
490
+ if (saved === UNCHANGED) {
491
+ // Saved as far as anyone can tell: the stored value already is this layout.
492
+ session.persistedSeq = Math.max(session.persistedSeq, seq);
493
+ session.unsaved = session.unsaved.filter((entry) => entry.seq > session.persistedSeq);
494
+ clearFailure(session);
495
+ deliver(session, savedEvent(seq));
496
+ return;
497
+ }
480
498
  session.persistedSeq = Math.max(session.persistedSeq, seq);
481
499
  session.unsaved = session.unsaved.filter((entry) => entry.seq > session.persistedSeq);
482
500
  clearFailure(session);
@@ -12,6 +12,11 @@ export type LayoutCodec = {
12
12
  encode(layout: Layout, previous?: unknown): unknown;
13
13
  /** What in a layout the field cannot store. Empty: it can be stored as it is. */
14
14
  problems(layout: Layout): string[];
15
+ /**
16
+ * True when saving `layout` over the stored `value` would store nothing new: the session then
17
+ * writes nothing, so no draft version. Left out: the encoded layout must deep-equal `value`.
18
+ */
19
+ isStored?(layout: Layout, value: unknown): boolean;
15
20
  /**
16
21
  * The resolved operations of a commit as the field stores them (a Payload blocks field gives
17
22
  * copied rows new ids; `owned`: the row ids the document's stored value has held). Returns `ops`
@@ -10,6 +10,7 @@
10
10
  import { APIError, docAccessOperation } from 'payload';
11
11
  import { decodePayloadBlocks, encodePayloadBlocks, payloadBlocksProblems, payloadRowIds, withUniqueRowIds } from '../core/payloadBlocks.js';
12
12
  import { upgradeLayout } from '../core/blocks.js';
13
+ import { sameJson } from '../core/fieldSemantics.js';
13
14
  import { normalizeLayout } from '../core/tree.js';
14
15
  import { applyOperation } from '../core/operations.js';
15
16
  export const JSON_CODEC = {
@@ -17,7 +18,25 @@ export const JSON_CODEC = {
17
18
  decode: (value) => normalizeLayout(value),
18
19
  encode: (layout) => layout,
19
20
  problems: () => [],
21
+ // A JSON field stores the layout exactly: a `null` prop (cleared) differs from a missing one.
22
+ isStored: (layout, value) => sameJson(layout, value),
20
23
  };
24
+ /**
25
+ * A value without its `null` and `undefined` object keys, at every depth. Payload keeps a block
26
+ * row's stored value for a key the saved row leaves out, and reads unset fields (`blockName` too)
27
+ * as `null`: for a blocks field, a missing key and a `null` one store the same thing.
28
+ */
29
+ function withoutNulls(value) {
30
+ if (Array.isArray(value))
31
+ return value.map(withoutNulls);
32
+ if (value === null || typeof value !== 'object')
33
+ return value;
34
+ const out = {};
35
+ for (const [key, v] of Object.entries(value))
36
+ if (v !== null && v !== undefined)
37
+ out[key] = withoutNulls(v);
38
+ return out;
39
+ }
21
40
  /** The codec of the builder's JSON layout that upgrades old blocks (`BlockDefinition.upgrade`) on read. */
22
41
  export function jsonCodec(blocks) {
23
42
  return { ...JSON_CODEC, decode: (value) => upgradeLayout(normalizeLayout(value), blocks) };
@@ -36,6 +55,7 @@ export function payloadBlocksCodec(storage) {
36
55
  },
37
56
  encode: (layout, previous) => encodePayloadBlocks(layout, storage, previous),
38
57
  problems: (layout) => payloadBlocksProblems(layout, storage),
58
+ isStored: (layout, value) => sameJson(withoutNulls(encodePayloadBlocks(layout, storage, value)), withoutNulls(value ?? [])),
39
59
  prepare: (layout, ops, owned) => withUniqueRowIds(layout, ops, storage, owned),
40
60
  rowIds: (value) => payloadRowIds(value, storage),
41
61
  };
@@ -42,22 +42,22 @@ export function motionGuide() {
42
42
  * (a tool name, or "the block catalog").
43
43
  */
44
44
  export function layoutGuide(blocksFrom) {
45
- return `
46
- LAYOUT MODEL. A layout is JSON: { "version": 1, "blocks": Block[] }. A Block is { id, type, props?, className?, slots?, bindings?, visibility?, hidden?, motion?, attrs?, partClassName? }.
47
- - id: a string, unique in the whole layout. Operations target blocks by id, never by array index. New blocks need new ids: use "b_" plus 6 lowercase letters or digits (e.g. "b_k3x9qa").
48
- - type: a block type from ${blocksFrom}.
49
- - props: the block's own values. Get the exact shape with getBlockSchema. Upload and relationship props hold document IDs.
50
- - className: Tailwind CSS v4 utility classes, with variants such as md:, lg:, hover:, dark:. Theme classes work (bg-primary, text-primary-foreground, text-muted-foreground, font-heading). CSS is generated on save, so any valid class works. In "update", className replaces the whole list; addClassName and removeClassName (space-separated) change single classes and keep the rest.
51
- - slots: child blocks by slot name, e.g. { "children": [ ...blocks ] }. Only block types with slots take children. ${blocksFrom} shows which types each slot accepts. A type with "onlyInside" goes only directly inside those types (e.g. "listItem" only in a "list"). A slot with "maxBlocks" holds at most that many direct children: inserting into a full slot fails, so replace (update or remove) the block there instead. A slot with "minBlocks" needs that many before the page can be published.
52
- - bindings: (templates, and blocks inside the "item" slot of a collection list or repeat, only) prop path -> document field path, e.g. { "text": "title" }, { "image": "featuredImage" }, { "link": "$url" }. At render time the prop takes the document's value; when the document has no value the literal prop stays. Get field paths from getBindingSources.
53
- - visibility: (templates, and blocks inside the "item" slot of a collection list or repeat, only) conditions that show the block only when they match the document (see VISIBILITY in the bindings guide). Leave it out when the block always shows.
54
- - On a normal page, outside list and repeat items, there is no current document: bindings and visibility do nothing (the block always shows), and the tools return a "no-effect" warning. Use "hidden": true to hide a block there.
55
- - motion: animations of the block (see MOTION below). Leave it out when the block has none.
56
- - partClassName: Tailwind classes of a block's inner elements, by part name, e.g. { "empty": "col-span-full text-center" } on a collection list or { "arrow": "size-12 rounded-full bg-white" } on a carousel. Only the "parts" listed in ${blocksFrom} take them. In "update" it merges per part; null removes a part's classes.
57
- - attrs: HTML attributes of the block element: { id?, ariaLabel?, ariaHidden? }. "id" is an anchor for "#id" links (e.g. "contact"), unique in the layout, letters, digits, - and _, starting with a letter; never the block id. "ariaLabel" names the element for screen readers (e.g. a nav or an icon-only link). "ariaHidden": true hides decorative blocks from screen readers. Copies of a section or a block leave out an id the page already uses.
58
- - section: { id, variant? } on the root block of a ready-made section, set by insertSection. Editors use it to switch the section to another variant. Keep it as it is; never write it yourself.
59
- - Canonical form: leave out empty props, slots, bindings, visibility and motion objects and empty slot lists. Set hidden only when true.
60
- POSITION = { parentId, slot?, index }. parentId null means the page root, whose only slot is "children". slot defaults to "children". index is the block's FINAL index in the target list (0 = first; the list length = append). For a move inside the same list, count positions after the block is taken out.
45
+ return `
46
+ LAYOUT MODEL. A layout is JSON: { "version": 1, "blocks": Block[] }. A Block is { id, type, props?, className?, slots?, bindings?, visibility?, hidden?, motion?, attrs?, partClassName? }.
47
+ - id: a string, unique in the whole layout. Operations target blocks by id, never by array index. New blocks need new ids: use "b_" plus 6 lowercase letters or digits (e.g. "b_k3x9qa").
48
+ - type: a block type from ${blocksFrom}.
49
+ - props: the block's own values. Get the exact shape with getBlockSchema. Upload and relationship props hold document IDs.
50
+ - className: Tailwind CSS v4 utility classes, with variants such as md:, lg:, hover:, dark:. Theme classes work (bg-primary, text-primary-foreground, text-muted-foreground, font-heading). CSS is generated on save, so any valid class works. In "update", className replaces the whole list; addClassName and removeClassName (space-separated) change single classes and keep the rest.
51
+ - slots: child blocks by slot name, e.g. { "children": [ ...blocks ] }. Only block types with slots take children. ${blocksFrom} shows which types each slot accepts. A type with "onlyInside" goes only directly inside those types (e.g. "listItem" only in a "list"). A slot with "maxBlocks" holds at most that many direct children: inserting into a full slot fails, so replace (update or remove) the block there instead. A slot with "minBlocks" needs that many before the page can be published.
52
+ - bindings: (templates, and blocks inside the "item" slot of a collection list or repeat, only) prop path -> document field path, e.g. { "text": "title" }, { "image": "featuredImage" }, { "link": "$url" }. At render time the prop takes the document's value; when the document has no value the literal prop stays. Get field paths from getBindingSources.
53
+ - visibility: (templates, and blocks inside the "item" slot of a collection list or repeat, only) conditions that show the block only when they match the document (see VISIBILITY in the bindings guide). Leave it out when the block always shows.
54
+ - On a normal page, outside list and repeat items, there is no current document: bindings and visibility do nothing (the block always shows), and the tools return a "no-effect" warning. Use "hidden": true to hide a block there.
55
+ - motion: animations of the block (see MOTION below). Leave it out when the block has none.
56
+ - partClassName: Tailwind classes of a block's inner elements, by part name, e.g. { "empty": "col-span-full text-center" } on a collection list or { "arrow": "size-12 rounded-full bg-white" } on a carousel. Only the "parts" listed in ${blocksFrom} take them. In "update" it merges per part; null removes a part's classes.
57
+ - attrs: HTML attributes of the block element: { id?, ariaLabel?, ariaHidden? }. "id" is an anchor for "#id" links (e.g. "contact"), unique in the layout, letters, digits, - and _, starting with a letter; never the block id. "ariaLabel" names the element for screen readers (e.g. a nav or an icon-only link). "ariaHidden": true hides decorative blocks from screen readers. Copies of a section or a block leave out an id the page already uses.
58
+ - section: { id, variant? } on the root block of a ready-made section, set by insertSection. Editors use it to switch the section to another variant. Keep it as it is; never write it yourself.
59
+ - Canonical form: leave out empty props, slots, bindings, visibility and motion objects and empty slot lists. Set hidden only when true.
60
+ POSITION = { parentId, slot?, index }. parentId null means the page root, whose only slot is "children". slot defaults to "children". index is the block's FINAL index in the target list (0 = first; the list length = append). For a move inside the same list, count positions after the block is taken out.
61
61
  ${motionGuide()}`.trim();
62
62
  }
63
63
  export const BINDINGS_GUIDE = [
@@ -103,9 +103,16 @@ export type WebsiteBuilderOptions = {
103
103
  * items have no `$url`. Each slug must be a collection of the config.
104
104
  */
105
105
  listCollections?: string[];
106
+ /**
107
+ * The app's Tailwind CSS. Required in every mode, also when the builder edits a Payload blocks
108
+ * field: the canvas compiles Tailwind against the entry, and the editor reads its breakpoints and
109
+ * theme from it. Checked at startup: no `entry` stops the app with a message that says what to
110
+ * pass; an `@plugin` of the entry missing from `plugins` is logged as an error.
111
+ */
106
112
  css: {
107
113
  /** Path to the app's Tailwind entry CSS, absolute or relative to process.cwd(). */
108
114
  entry: string;
115
+ /** Every plugin the entry loads with `@plugin "<id>"`, by that id. */
109
116
  plugins?: TailwindPlugins;
110
117
  /**
111
118
  * The font families the site really uses, by font variable name (`sans`, `heading`, `mono`, …).
@@ -126,7 +133,8 @@ export type WebsiteBuilderOptions = {
126
133
  savedSections?: SavedSectionsOptions | false;
127
134
  /**
128
135
  * Live editing: every open editor and every AI agent (MCP) edits one shared in-memory session
129
- * per document, and the server saves its draft about a second after the last change. Sessions
136
+ * per document, and the server saves its draft about a second after the last change (only when
137
+ * the stored layout would change: a save that changes nothing makes no draft version). Sessions
130
138
  * live in one app server process: with several servers, route each document to one server.
131
139
  */
132
140
  live?: {
@@ -191,6 +199,11 @@ export declare const BUILDER_VIEW_KEY = "websiteBuilder";
191
199
  export declare const BUILDER_VIEW_PATH = "/builder/:collection/:id";
192
200
  /** Name of the hidden field that stores the generated CSS (`{ hash, css }`) for a layout field. */
193
201
  export declare function cssFieldName(field: string): string;
202
+ /**
203
+ * `css` of websiteBuilder() as the compile needs it: the entry as an absolute path. Throws a
204
+ * message that says what to pass when `css.entry` is missing.
205
+ */
206
+ export declare function resolveCssOptions(css: WebsiteBuilderOptions['css'] | undefined, cwd?: string): CssOptions;
194
207
  export declare function websiteBuilder(options: WebsiteBuilderOptions): Plugin;
195
208
  /** Name of the hidden virtual field that carries the builder's config for a Payload blocks field. */
196
209
  export declare function builderConfigFieldName(field: string): string;
@@ -10,7 +10,7 @@ import { localeSettingsOf } from '../core/locale.js';
10
10
  import { resolveRegions } from '../core/regions.js';
11
11
  import { decodePayloadBlocks, payloadBlocksProblems, payloadBlocksStorage } from '../core/payloadBlocks.js';
12
12
  import { EMPTY_LAYOUT, } from '../core/types.js';
13
- import { applyFontFamilies, getCanvasCssInput, getStyleTokens } from '../css/index.js';
13
+ import { applyFontFamilies, cssEntryProblems, getCanvasCssInput, getStyleTokens } from '../css/index.js';
14
14
  import { DEFAULT_THEME_SLUG, THEME_CONFIG_KEY, THEME_PATH } from '../theme/config.js';
15
15
  import { themeFontFamilies, themeOutput } from '../theme/css.js';
16
16
  import { themeGlobal } from '../theme/global.js';
@@ -81,8 +81,32 @@ function sectionsThatFit(sections, fits) {
81
81
  return [section.variants ? { ...section, variants: section.variants.filter((v) => fits(v.blocks)) } : section];
82
82
  });
83
83
  }
84
+ /**
85
+ * `css` of websiteBuilder() as the compile needs it: the entry as an absolute path. Throws a
86
+ * message that says what to pass when `css.entry` is missing.
87
+ */
88
+ export function resolveCssOptions(css, cwd = process.cwd()) {
89
+ if (!css || typeof css !== 'object' || typeof css.entry !== 'string' || css.entry.trim() === '') {
90
+ throw new Error("[websiteBuilder] `css.entry` is missing. Pass the path to the app's Tailwind entry CSS, absolute or relative to the folder the app starts in, " +
91
+ "for example `css: { entry: 'src/app/globals.css' }`. Every builder needs it, also one that edits a Payload blocks field: " +
92
+ 'the canvas compiles Tailwind against it, and the editor reads its breakpoints and theme from it. ' +
93
+ "When the entry has @plugin lines, pass those plugins too: `css: { entry, plugins: { '@tailwindcss/typography': typography } }`.");
94
+ }
95
+ if (css.plugins !== undefined && (css.plugins === null || typeof css.plugins !== 'object' || Array.isArray(css.plugins))) {
96
+ throw new Error("[websiteBuilder] `css.plugins` must be an object that maps each @plugin id of the CSS entry to the plugin, for example `{ '@tailwindcss/typography': typography }`.");
97
+ }
98
+ return { entry: path.resolve(cwd, css.entry), plugins: css.plugins };
99
+ }
100
+ /** A CSS endpoint's failure as a message the editor shows and the server logs, not a bare 500. */
101
+ function cssFailure(req, what, error) {
102
+ const message = `[websiteBuilder] ${what} could not be built: ${error instanceof Error ? error.message : String(error)}`;
103
+ req.payload.logger.error(message);
104
+ return Response.json({ error: message }, { status: 500, headers: { 'Cache-Control': 'no-store' } });
105
+ }
84
106
  export function websiteBuilder(options) {
85
107
  return (config) => {
108
+ // First: without the CSS entry nothing in the builder works.
109
+ const css = resolveCssOptions(options.css);
86
110
  const apiRoute = config.routes?.api ?? '/api';
87
111
  const canvasPath = options.canvasPath ?? '/builder-canvas';
88
112
  const sourceCollections = config.collections ?? [];
@@ -270,10 +294,6 @@ export function websiteBuilder(options) {
270
294
  const clientBlocks = toJsonSafe(blocks);
271
295
  // Relationship targets of every collection, so the canvas resolves `<path>.$url` bindings.
272
296
  const relations = bindingRelations(collections);
273
- const css = {
274
- entry: path.resolve(process.cwd(), options.css.entry),
275
- plugins: options.css.plugins,
276
- };
277
297
  // Editable classes: a collection, a hidden global with the compiled stylesheet, endpoints.
278
298
  const classes = resolveClasses(options.classes, { apiRoute, css, blocks, collections, globals: config.globals ?? [] });
279
299
  // Comments on the canvas: a collection the editor reads and writes over REST.
@@ -501,8 +521,13 @@ export function websiteBuilder(options) {
501
521
  if (!req.user)
502
522
  return Response.json({ error: 'Unauthorized' }, { status: 401 });
503
523
  // With the theme's variables, so `bg-brand` works on the canvas. Not cached: a theme save changes it.
504
- const input = await getCanvasCssInput(await withThemeVariables(req.payload, css));
505
- return Response.json(input, { headers: { 'Cache-Control': 'private, no-cache' } });
524
+ try {
525
+ const input = await getCanvasCssInput(await withThemeVariables(req.payload, css));
526
+ return Response.json(input, { headers: { 'Cache-Control': 'private, no-cache' } });
527
+ }
528
+ catch (error) {
529
+ return cssFailure(req, 'The canvas CSS', error);
530
+ }
506
531
  },
507
532
  },
508
533
  {
@@ -511,7 +536,13 @@ export function websiteBuilder(options) {
511
536
  handler: async (req) => {
512
537
  if (!req.user)
513
538
  return Response.json({ error: 'Unauthorized' }, { status: 401 });
514
- const tokens = await themeStyleTokens(req.payload, css);
539
+ let tokens;
540
+ try {
541
+ tokens = await themeStyleTokens(req.payload, css);
542
+ }
543
+ catch (error) {
544
+ return cssFailure(req, 'The style tokens', error);
545
+ }
515
546
  const custom = await Promise.resolve(options.css.fontFamilies?.(req.payload)).catch(() => undefined);
516
547
  const families = { ...(await themeFamilies(req.payload)), ...custom };
517
548
  const fonts = applyFontFamilies(tokens.fonts, families);
@@ -544,6 +575,13 @@ export function websiteBuilder(options) {
544
575
  // …and when a Local API update ended, also a failed one without a transaction.
545
576
  installLocalApiBoundary(payload, writeGate);
546
577
  await config.onInit?.(payload);
578
+ // The CSS entry and its @plugin lines, checked once at startup: a plugin missing from
579
+ // `css.plugins` would otherwise fail only when the builder loads. Not awaited: startup does
580
+ // not wait for a Tailwind compile.
581
+ void cssEntryProblems(css).then((problems) => {
582
+ for (const problem of problems)
583
+ payload.logger.error(`[websiteBuilder] ${problem}`);
584
+ }, () => { });
547
585
  // Save unsaved live edits when the server stops.
548
586
  installShutdownFlush(live.sessions);
549
587
  for (const [slug, field] of Object.entries(fieldNames)) {
@@ -3,6 +3,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
3
3
  // Runs inside the canvas iframe. It renders the layout it gets from the admin editor and reports
4
4
  // block and slot rectangles, the pointer and editor shortcuts back. It holds no selection or drop logic.
5
5
  import { collectClasses, createId, findBlock, joinListItem, TEXT_LIST_ITEM_BLOCK, } from '../../core/index.js';
6
+ import { responseErrorMessage } from '../../core/responseError.js';
6
7
  import { createCanvasCompiler } from '../../css/browser.js';
7
8
  import { THEME_CHANNEL } from '../../theme/config.js';
8
9
  import { classNamesOf, withoutClassNames } from '../../classes/shared.js';
@@ -876,7 +877,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
876
877
  fetch(endpoint, { credentials: 'include', cache: 'no-store' })
877
878
  .then(async (res) => {
878
879
  if (!res.ok)
879
- throw new Error(`${res.status} ${res.statusText}`);
880
+ throw new Error(await responseErrorMessage(res));
880
881
  const input = (await res.json());
881
882
  if (!cancelled)
882
883
  setCssInput(input);
@@ -885,7 +886,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
885
886
  if (cancelled)
886
887
  return;
887
888
  setCompiler({ status: 'failed' });
888
- send({ type: 'error', message: `Canvas CSS failed to load: ${String(error)}` });
889
+ send({ type: 'error', message: `Canvas CSS failed to load: ${error instanceof Error ? error.message : String(error)}` });
889
890
  });
890
891
  return () => {
891
892
  cancelled = true;
@@ -912,7 +913,7 @@ function EditorCanvas({ blocks, components, plugins, resolveLink, server }) {
912
913
  if (cancelled)
913
914
  return;
914
915
  setCompiler({ status: 'failed' });
915
- send({ type: 'error', message: `Canvas CSS failed to load: ${String(error)}` });
916
+ send({ type: 'error', message: `Canvas CSS failed to load: ${error instanceof Error ? error.message : String(error)}` });
916
917
  });
917
918
  return () => {
918
919
  cancelled = true;