payload-canvas 0.5.2 → 0.6.1

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 (203) hide show
  1. package/README.md +342 -30
  2. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  3. package/dist/admin/ArrayRowLabel.js +21 -0
  4. package/dist/admin/client.d.ts +1 -0
  5. package/dist/admin/client.js +2 -0
  6. package/dist/admin/editor/Editor.js +8 -1
  7. package/dist/admin/editor/Inspector.js +23 -17
  8. package/dist/admin/editor/Library.d.ts +2 -2
  9. package/dist/admin/editor/Library.js +7 -5
  10. package/dist/admin/editor/Outline.js +20 -12
  11. package/dist/admin/editor/Overlay.js +6 -4
  12. package/dist/admin/editor/actions.d.ts +7 -2
  13. package/dist/admin/editor/actions.js +44 -12
  14. package/dist/admin/editor/assistant/AssistantPanel.js +32 -20
  15. package/dist/admin/editor/comments/controller.d.ts +7 -0
  16. package/dist/admin/editor/comments/controller.js +12 -0
  17. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  18. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  19. package/dist/admin/editor/dnd/smooth.js +1 -1
  20. package/dist/admin/editor/editor.scss +28 -0
  21. package/dist/admin/editor/fields/ArrayField.js +3 -3
  22. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  23. package/dist/admin/editor/fields/FormBlock.js +167 -0
  24. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  25. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  26. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  27. package/dist/admin/editor/fields/GroupField.js +30 -1
  28. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  29. package/dist/admin/editor/fields/MergeTags.js +62 -0
  30. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  31. package/dist/admin/editor/fields/arrayRows.js +0 -4
  32. package/dist/admin/editor/fields/fields.scss +150 -0
  33. package/dist/admin/editor/fields/values.d.ts +0 -2
  34. package/dist/admin/editor/fields/values.js +0 -14
  35. package/dist/admin/editor/icons.d.ts +3 -0
  36. package/dist/admin/editor/icons.js +3 -0
  37. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  38. package/dist/admin/editor/insert/picker.d.ts +3 -2
  39. package/dist/admin/editor/insert/picker.js +9 -3
  40. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  41. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  42. package/dist/admin/editor/layout/leftTabs.js +18 -0
  43. package/dist/admin/editor/media/ImageEditor.d.ts +8 -2
  44. package/dist/admin/editor/media/ImageEditor.js +16 -10
  45. package/dist/admin/editor/media/media.scss +12 -2
  46. package/dist/admin/editor/media/model.d.ts +10 -1
  47. package/dist/admin/editor/media/model.js +19 -0
  48. package/dist/admin/editor/menu/blockMenu.js +3 -3
  49. package/dist/admin/editor/names.d.ts +9 -0
  50. package/dist/admin/editor/names.js +18 -0
  51. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  52. package/dist/admin/editor/regions/RegionFields.js +122 -0
  53. package/dist/admin/editor/regions/RegionPane.js +5 -3
  54. package/dist/admin/editor/regions/RegionRows.js +2 -2
  55. package/dist/admin/editor/regions/required.d.ts +16 -0
  56. package/dist/admin/editor/regions/required.js +43 -0
  57. package/dist/admin/editor/renderField.d.ts +9 -2
  58. package/dist/admin/editor/renderField.js +86 -32
  59. package/dist/admin/editor/runtime.d.ts +3 -2
  60. package/dist/admin/editor/runtime.js +12 -18
  61. package/dist/admin/editor/styles/StylesPanel.js +4 -2
  62. package/dist/admin/editor/styles/context.js +9 -4
  63. package/dist/admin/editor/topbar/ContentModeToggle.js +1 -1
  64. package/dist/admin/editor/topbar/DocumentActions.js +4 -3
  65. package/dist/admin/editor/topbar/contentMode.scss +0 -9
  66. package/dist/admin/editor/topbar/topbar.scss +1 -41
  67. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  68. package/dist/admin/editor/ui/Tabs.js +17 -0
  69. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  70. package/dist/admin/forms/SubmissionCells.js +31 -0
  71. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  72. package/dist/admin/forms/SubmissionView.js +106 -0
  73. package/dist/admin/forms/submissionData.d.ts +32 -0
  74. package/dist/admin/forms/submissionData.js +63 -0
  75. package/dist/admin/forms/submissions.scss +197 -0
  76. package/dist/admin/rsc.d.ts +2 -0
  77. package/dist/admin/rsc.js +5 -0
  78. package/dist/ai/endpoint.d.ts +5 -0
  79. package/dist/ai/endpoint.js +18 -8
  80. package/dist/ai/prompt.d.ts +8 -0
  81. package/dist/ai/prompt.js +30 -0
  82. package/dist/ai/tools.d.ts +6 -1
  83. package/dist/ai/tools.js +90 -6
  84. package/dist/blocks/builtins/carousel.js +10 -1
  85. package/dist/blocks/defaults.js +27 -2
  86. package/dist/blocks/index.d.ts +1 -1
  87. package/dist/blocks/index.js +1 -1
  88. package/dist/blocks/payload.d.ts +7 -0
  89. package/dist/blocks/payload.js +16 -2
  90. package/dist/comments/shared.d.ts +5 -0
  91. package/dist/comments/shared.js +5 -0
  92. package/dist/core/blocks.d.ts +17 -3
  93. package/dist/core/blocks.js +92 -10
  94. package/dist/core/classes.d.ts +5 -0
  95. package/dist/core/classes.js +26 -1
  96. package/dist/core/conditions.d.ts +7 -0
  97. package/dist/core/conditions.js +22 -0
  98. package/dist/core/dropTarget.d.ts +3 -2
  99. package/dist/core/dropTarget.js +7 -1
  100. package/dist/core/index.d.ts +6 -3
  101. package/dist/core/index.js +6 -3
  102. package/dist/core/payloadBlocks.js +25 -3
  103. package/dist/core/references.d.ts +7 -0
  104. package/dist/core/references.js +29 -11
  105. package/dist/core/regions.d.ts +14 -0
  106. package/dist/core/regions.js +17 -1
  107. package/dist/core/rowLabel.d.ts +8 -0
  108. package/dist/core/rowLabel.js +98 -0
  109. package/dist/core/starter.d.ts +10 -0
  110. package/dist/core/starter.js +40 -0
  111. package/dist/core/tree.js +4 -0
  112. package/dist/core/types.d.ts +96 -0
  113. package/dist/core/uniqueProps.d.ts +40 -0
  114. package/dist/core/uniqueProps.js +156 -0
  115. package/dist/core/validate.js +43 -3
  116. package/dist/forms/answers.d.ts +21 -0
  117. package/dist/forms/answers.js +82 -0
  118. package/dist/forms/blocks.d.ts +33 -0
  119. package/dist/forms/blocks.js +178 -0
  120. package/dist/forms/conditions.d.ts +78 -0
  121. package/dist/forms/conditions.js +184 -0
  122. package/dist/forms/emails.d.ts +23 -0
  123. package/dist/forms/emails.js +64 -0
  124. package/dist/forms/fieldConfigs.d.ts +35 -0
  125. package/dist/forms/fieldConfigs.js +167 -0
  126. package/dist/forms/fieldOps.d.ts +78 -0
  127. package/dist/forms/fieldOps.js +378 -0
  128. package/dist/forms/fieldSettings.d.ts +81 -0
  129. package/dist/forms/fieldSettings.js +239 -0
  130. package/dist/forms/files.d.ts +54 -0
  131. package/dist/forms/files.js +128 -0
  132. package/dist/forms/index.d.ts +16 -0
  133. package/dist/forms/index.js +18 -0
  134. package/dist/forms/mergeTags.d.ts +103 -0
  135. package/dist/forms/mergeTags.js +150 -0
  136. package/dist/forms/noScript.d.ts +60 -0
  137. package/dist/forms/noScript.js +109 -0
  138. package/dist/forms/pageForms.d.ts +99 -0
  139. package/dist/forms/pageForms.js +294 -0
  140. package/dist/forms/pageSync.d.ts +91 -0
  141. package/dist/forms/pageSync.js +325 -0
  142. package/dist/forms/rateLimit.d.ts +21 -0
  143. package/dist/forms/rateLimit.js +50 -0
  144. package/dist/forms/settings.d.ts +13 -0
  145. package/dist/forms/settings.js +92 -0
  146. package/dist/forms/spam.d.ts +100 -0
  147. package/dist/forms/spam.js +218 -0
  148. package/dist/forms/spamSettings.d.ts +43 -0
  149. package/dist/forms/spamSettings.js +25 -0
  150. package/dist/forms/submission.d.ts +34 -0
  151. package/dist/forms/submission.js +89 -0
  152. package/dist/forms/submissionsAdmin.d.ts +26 -0
  153. package/dist/forms/submissionsAdmin.js +108 -0
  154. package/dist/forms/summary.d.ts +60 -0
  155. package/dist/forms/summary.js +113 -0
  156. package/dist/forms/uploads.d.ts +41 -0
  157. package/dist/forms/uploads.js +132 -0
  158. package/dist/index.d.ts +8 -2
  159. package/dist/index.js +8 -2
  160. package/dist/live/document.d.ts +12 -0
  161. package/dist/live/document.js +8 -1
  162. package/dist/live/endpoints.d.ts +1 -0
  163. package/dist/live/session.js +3 -1
  164. package/dist/live/storage.d.ts +13 -2
  165. package/dist/live/storage.js +18 -7
  166. package/dist/mcp/forms.d.ts +26 -0
  167. package/dist/mcp/forms.js +280 -0
  168. package/dist/mcp/index.d.ts +7 -0
  169. package/dist/mcp/index.js +29 -10
  170. package/dist/mcp/shared.d.ts +1 -0
  171. package/dist/mcp/shared.js +1 -0
  172. package/dist/plugin/forms.d.ts +30 -0
  173. package/dist/plugin/forms.js +63 -0
  174. package/dist/plugin/formsSync.d.ts +138 -0
  175. package/dist/plugin/formsSync.js +345 -0
  176. package/dist/plugin/hook.d.ts +22 -0
  177. package/dist/plugin/hook.js +19 -7
  178. package/dist/plugin/index.d.ts +14 -0
  179. package/dist/plugin/index.js +99 -28
  180. package/dist/plugin/links.d.ts +7 -2
  181. package/dist/plugin/links.js +9 -3
  182. package/dist/plugin/references.d.ts +6 -0
  183. package/dist/plugin/references.js +12 -0
  184. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  185. package/dist/react/canvas/BuilderCanvas.js +29 -6
  186. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  187. package/dist/react/canvas/inline/mapper.js +35 -4
  188. package/dist/react/components/AutoplayVideo.d.ts +20 -0
  189. package/dist/react/components/AutoplayVideo.js +34 -0
  190. package/dist/react/components/Video.d.ts +9 -1
  191. package/dist/react/components/Video.js +39 -11
  192. package/dist/react/components/lazy.d.ts +2 -0
  193. package/dist/react/components/lazy.js +2 -0
  194. package/dist/react/components/videoPlayback.d.ts +30 -0
  195. package/dist/react/components/videoPlayback.js +33 -0
  196. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  197. package/dist/react/render/LayoutOutlet.js +9 -4
  198. package/dist/react/render/RenderLayout.js +18 -9
  199. package/dist/react/render/resolve.d.ts +1 -0
  200. package/dist/react/render/resolve.js +5 -1
  201. package/dist/react/render/types.d.ts +1 -1
  202. package/dist/react/server.js +19 -0
  203. package/package.json +5 -1
@@ -13,7 +13,7 @@ import { missingAdapterProblem, SETTINGS_KEY_HINT } from './config.js';
13
13
  import { createImageService, generateImageToMedia } from './images/service.js';
14
14
  import { adapterIdentity, runAgent } from './loop.js';
15
15
  import { classesConfigOf, loadClasses } from '../classes/index.js';
16
- import { breakpointsPx, contextText, systemPrompt } from './prompt.js';
16
+ import { breakpointsPx, contextText, formSystemPrompt, systemPrompt } from './prompt.js';
17
17
  import { withSettingsKey } from './settings/index.js';
18
18
  import { toolDefinitions, Workspace } from './tools.js';
19
19
  /** Path of the assistant endpoints below the API route. */
@@ -185,6 +185,13 @@ export function aiEndpoints(options) {
185
185
  };
186
186
  // Built once, in a fixed order: tools and system prompt are the cached prompt prefix.
187
187
  const tools = toolDefinitions({ ...env, searchMedia: async () => [] });
188
+ // The form builder: its own field types, tools and prompt (forms/fieldOps.ts).
189
+ const forms = options.forms ?? null;
190
+ const formEnv = forms
191
+ ? { blocks: forms.blocks, sections: [], savedSections: false, bindingSources: null, mediaCollection, form: true }
192
+ : null;
193
+ const formTools = formEnv ? toolDefinitions({ ...formEnv, searchMedia: async () => [] }) : [];
194
+ const formSystem = forms ? [{ text: formSystemPrompt({ blocks: forms.blocks, instructions: ai.instructions }), cache: true }] : [];
188
195
  let prompt = null;
189
196
  const getPrompt = async (req) => {
190
197
  const tokens = await options.getTokens(req).catch(() => null);
@@ -259,7 +266,10 @@ export function aiEndpoints(options) {
259
266
  if (foreign) {
260
267
  return errorResponse(409, 'invalid_request', `This chat was started with another AI model (${foreign.provider}). The assistant now uses ${identity}. Start a new chat.`);
261
268
  }
262
- const { system, breakpoints } = await getPrompt(req);
269
+ const isForm = forms !== null && formEnv !== null && body.collection === forms.slug;
270
+ const prompted = await getPrompt(req);
271
+ const system = isForm ? formSystem : prompted.system;
272
+ const { breakpoints } = prompted;
263
273
  // The key from the AI settings, read now: a new key works without a restart.
264
274
  const settings = options.settings ?? null;
265
275
  const settingsKey = settings && adapter.acceptsApiKey ? await settings.keyFor(req.payload, 'chat') : undefined;
@@ -269,14 +279,14 @@ export function aiEndpoints(options) {
269
279
  const localization = target.localization ?? null;
270
280
  const locale = localization ? knownLocale(localization, body.locale) : null;
271
281
  const contentOnly = !(await canEditDesign(req));
272
- const workspace = new Workspace(layout, blocks, { localization, locale, contentOnly });
282
+ const workspace = new Workspace(layout, isForm ? forms.blocks : blocks, { localization, locale, contentOnly });
273
283
  const selectedId = body.selectedId && indexLayout(layout).has(body.selectedId) ? body.selectedId : null;
274
284
  const titleField = config?.admin?.useAsTitle;
275
285
  const title = titleField && typeof doc[titleField] === 'string' ? doc[titleField] : undefined;
276
286
  // Saved sections differ per user and change often: they go in the context, not the cached prompt.
277
- const saved = savedSections ? await loadSavedSections(req, savedSections.slug) : [];
287
+ const saved = savedSections && !isForm ? await loadSavedSections(req, savedSections.slug) : [];
278
288
  // Editable classes change at any time too.
279
- const classes = classesConfigOf(req.payload) ? await loadClasses(req).catch(() => []) : [];
289
+ const classes = classesConfigOf(req.payload) && !isForm ? await loadClasses(req).catch(() => []) : [];
280
290
  const isTemplate = templates !== null && body.collection === templates.slug;
281
291
  const templateTarget = isTemplate
282
292
  ? (typeof doc[TEMPLATE_TARGET_FIELD] === 'string' ? doc[TEMPLATE_TARGET_FIELD] : (body.context?.collection ?? null))
@@ -332,15 +342,15 @@ export function aiEndpoints(options) {
332
342
  await runAgent({
333
343
  adapter: model,
334
344
  system,
335
- tools,
345
+ tools: isForm ? formTools : tools,
336
346
  effort: ai.effort,
337
347
  maxSteps: ai.maxSteps ?? DEFAULT_MAX_STEPS,
338
348
  messages: body.messages,
339
349
  context,
340
350
  workspace,
341
351
  env: {
342
- ...env,
343
- sections: [...sections, ...saved],
352
+ ...(isForm ? formEnv : env),
353
+ sections: isForm ? [] : [...sections, ...saved],
344
354
  searchMedia: mediaSearch(req, mediaCollection),
345
355
  generateImage: assistantImageGenerator(req, images, controller.signal),
346
356
  },
@@ -18,6 +18,14 @@ export declare function breakpointsPx(tokens: StyleTokens | null): Array<{
18
18
  }>;
19
19
  /** The stable system prompt. Same input, same bytes: keep it free of request data. */
20
20
  export declare function systemPrompt(catalog: PromptCatalog): string;
21
+ /**
22
+ * The system prompt of the form builder (`websiteBuilder({ forms })`): the assistant edits a
23
+ * form's fields, not a page. `blocks` are the form's field types.
24
+ */
25
+ export declare function formSystemPrompt(catalog: {
26
+ blocks: BlockDefinition[];
27
+ instructions?: string;
28
+ }): string;
21
29
  export type ContextInput = {
22
30
  collection: string;
23
31
  id: string | number;
package/dist/ai/prompt.js CHANGED
@@ -7,6 +7,7 @@ import { localeLabel } from '../core/locale.js';
7
7
  import { sectionVersions } from '../core/sections.js';
8
8
  import { BINDINGS_GUIDE, describeBlock, layoutGuide, outline } from '../mcp/shared.js';
9
9
  import { componentProperties } from '../core/components.js';
10
+ import { formFieldTypes, FORM_FIELDS_GUIDE } from '../forms/fieldOps.js';
10
11
  /** Default Tailwind palette colors (red-500 …) and keywords. The prompt lists only theme colors. */
11
12
  const PALETTE = /-\d{2,3}$/;
12
13
  const KEYWORDS = new Set(['black', 'white', 'transparent', 'current', 'inherit']);
@@ -139,6 +140,35 @@ RICH TEXT
139
140
  parts.push(`INSTRUCTIONS FROM THE SITE OWNER\n${extra}`);
140
141
  return parts.join('\n\n');
141
142
  }
143
+ /**
144
+ * The system prompt of the form builder (`websiteBuilder({ forms })`): the assistant edits a
145
+ * form's fields, not a page. `blocks` are the form's field types.
146
+ */
147
+ export function formSystemPrompt(catalog) {
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.
163
+ 6. When you are done, say in one or two plain sentences what you changed. Do not list ids or JSON.`,
164
+ FORM_FIELDS_GUIDE,
165
+ `FIELD TYPES (JSON). The types this form offers, with their props.\n${JSON.stringify(formFieldTypes(catalog.blocks))}`,
166
+ ];
167
+ const extra = catalog.instructions?.trim();
168
+ if (extra)
169
+ parts.push(`INSTRUCTIONS FROM THE SITE OWNER\n${extra}`);
170
+ return parts.join('\n\n');
171
+ }
142
172
  const MAX_STRING = 160;
143
173
  const MAX_ITEMS = 5;
144
174
  const MAX_DEPTH = 3;
@@ -35,6 +35,11 @@ export type ToolEnv = {
35
35
  }) => Promise<GenerateImageOutcome>;
36
36
  /** The upload collection images come from and go to. Default "media". */
37
37
  mediaCollection?: string;
38
+ /**
39
+ * The open document is a form (`websiteBuilder({ forms })`): `blocks` are its field types, and
40
+ * the tools are getForm, getBlockSchema and editFormFields (forms/fieldOps.ts).
41
+ */
42
+ form?: boolean;
38
43
  };
39
44
  /** Result of one tool call. `ops` is set when the call changed the layout. */
40
45
  export type ToolOutcome = {
@@ -87,7 +92,7 @@ export declare class Workspace {
87
92
  };
88
93
  }
89
94
  /** "Added 2 blocks, updated 1 block" for the editor. */
90
- export declare function describeOps(ops: Operation[]): string;
95
+ export declare function describeOps(ops: Operation[], noun?: string): string;
91
96
  /** Tool definitions in a fixed order (the order is part of the cached prompt prefix). */
92
97
  export declare function toolDefinitions(env: ToolEnv): AiToolDefinition[];
93
98
  /** Running summaries, shown while the tool input streams in. */
package/dist/ai/tools.js CHANGED
@@ -16,6 +16,8 @@ import { validateLayout } from '../core/validate.js';
16
16
  import { resolveOperations, splitLayoutErrors } from '../live/apply.js';
17
17
  import { componentListing, isRootParentId, missingContent, sectionInsertOps, sectionToInsert, variantsListing } from '../mcp/shared.js';
18
18
  import { findSectionVersion } from '../core/sections.js';
19
+ import { formFieldSlug } from '../forms/blocks.js';
20
+ import { formFieldOps, formFieldsOf, formFieldTypes, FORM_FIELDS_GUIDE } from '../forms/fieldOps.js';
19
21
  // ---------------------------------------------------------------------------
20
22
  // Working copy
21
23
  // ---------------------------------------------------------------------------
@@ -129,18 +131,22 @@ function changedIds(ops) {
129
131
  }
130
132
  return changed;
131
133
  }
132
- const plural = (n) => `${n} block${n === 1 ? '' : 's'}`;
134
+ const plural = (n, noun = 'block') => `${n} ${noun}${n === 1 ? '' : 's'}`;
135
+ /** "Added 2 fields, updated 1 field" for the form builder. */
136
+ function describeFormOps(ops) {
137
+ return describeOps(ops, 'field');
138
+ }
133
139
  /** "Added 2 blocks, updated 1 block" for the editor. */
134
- export function describeOps(ops) {
140
+ export function describeOps(ops, noun = 'block') {
135
141
  const count = { insert: 0, update: 0, move: 0, remove: 0 };
136
142
  for (const op of ops)
137
143
  if (op.type in count)
138
144
  count[op.type]++;
139
145
  const parts = [
140
- count.insert ? `added ${plural(count.insert)}` : '',
141
- count.update ? `updated ${plural(count.update)}` : '',
142
- count.move ? `moved ${plural(count.move)}` : '',
143
- count.remove ? `removed ${plural(count.remove)}` : '',
146
+ count.insert ? `added ${plural(count.insert, noun)}` : '',
147
+ count.update ? `updated ${plural(count.update, noun)}` : '',
148
+ count.move ? `moved ${plural(count.move, noun)}` : '',
149
+ count.remove ? `removed ${plural(count.remove, noun)}` : '',
144
150
  ].filter(Boolean);
145
151
  const text = parts.join(', ') || 'no changes';
146
152
  return text.charAt(0).toUpperCase() + text.slice(1);
@@ -231,8 +237,65 @@ const FLAT_OPERATIONS_SCHEMA = {
231
237
  },
232
238
  required: ['operations'],
233
239
  };
240
+ /** The form builder's tools: the same field changes as the MCP tool editFormFields. */
241
+ function formToolDefinitions(env) {
242
+ const types = env.blocks.map((b) => formFieldSlug(b.type) ?? b.type);
243
+ return [
244
+ {
245
+ name: 'getForm',
246
+ description: 'Returns the fields of the open form in order (id, type, name, label, required, className (its classes, width included), options, message text, conditions and `shows`, the conditions in words), including your changes so far in this reply.',
247
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
248
+ strict: true,
249
+ },
250
+ {
251
+ name: 'getBlockSchema',
252
+ description: 'Returns the JSON Schema of the props of one field type. Its block type is "form" plus the type, e.g. "formEmail". Call it when a prop shape is unclear.',
253
+ inputSchema: {
254
+ type: 'object',
255
+ properties: { type: { type: 'string', enum: env.blocks.map((b) => b.type) } },
256
+ required: ['type'],
257
+ additionalProperties: false,
258
+ },
259
+ strict: true,
260
+ },
261
+ {
262
+ // Not strict: `values` and `conditions` are free-form. formFieldOps checks every change.
263
+ name: 'editFormFields',
264
+ description: [
265
+ 'Changes the fields of the open form, applied in order, all or nothing. Each change appears in the form builder at once.',
266
+ "Changes: add { type, values?, index? }; update { field, values?, unset? } (merges values; a rename also renames the field in other fields' rules); move { field, index } (final position, 0 = first); remove { field }; setConditions { field, conditions } (null = always show). `field` is the field's name or id.",
267
+ FORM_FIELDS_GUIDE,
268
+ ].join('\n\n'),
269
+ inputSchema: {
270
+ type: 'object',
271
+ properties: {
272
+ changes: {
273
+ type: 'array',
274
+ minItems: 1,
275
+ items: {
276
+ type: 'object',
277
+ properties: {
278
+ action: { type: 'string', enum: ['add', 'update', 'move', 'remove', 'setConditions'] },
279
+ type: { type: 'string', enum: types, description: 'add: the field type.' },
280
+ field: { type: 'string', description: "The field's name or id." },
281
+ values: { type: 'object', description: 'add, update: props, e.g. { "label": "Email", "required": true, "className": "sm:w-[calc(50%-0.5rem)]" }. Width is classes (className), never a prop.' },
282
+ unset: { type: 'array', items: { type: 'string' } },
283
+ index: { type: 'integer', minimum: 0 },
284
+ conditions: { type: ['object', 'null'], description: '{ match?: "all" | "any", rules: [{ field, operator, value? }] }' },
285
+ },
286
+ required: ['action'],
287
+ },
288
+ },
289
+ },
290
+ required: ['changes'],
291
+ },
292
+ },
293
+ ];
294
+ }
234
295
  /** Tool definitions in a fixed order (the order is part of the cached prompt prefix). */
235
296
  export function toolDefinitions(env) {
297
+ if (env.form)
298
+ return formToolDefinitions(env);
236
299
  const types = env.blocks.map((b) => b.type);
237
300
  const saved = env.savedSections === true;
238
301
  const sectionIds = env.sections.map((s) => s.id);
@@ -445,6 +508,8 @@ export const RUNNING_SUMMARY = {
445
508
  searchMedia: 'Searching the media library',
446
509
  generateImage: 'Generating an image',
447
510
  getBindingSources: 'Reading document fields',
511
+ getForm: 'Reading the form',
512
+ editFormFields: 'Editing the form',
448
513
  };
449
514
  // ---------------------------------------------------------------------------
450
515
  // Execution
@@ -663,6 +728,25 @@ export async function runTool(name, rawInput, workspace, env) {
663
728
  switch (name) {
664
729
  case 'getLayout':
665
730
  return ok({ layout: workspace.view }, 'Read the page');
731
+ case 'getForm':
732
+ return ok({ fields: formFieldsOf(workspace.view), fieldTypes: formFieldTypes(env.blocks) }, 'Read the form');
733
+ case 'editFormFields': {
734
+ const changes = parseJson(input.changes);
735
+ if (!Array.isArray(changes) || changes.length === 0)
736
+ return fail('`changes` must be a non-empty list', 'Edit failed');
737
+ const planned = formFieldOps(workspace.layout, changes, env.blocks);
738
+ if (!planned.ok)
739
+ return fail(planned.error, 'Edit failed');
740
+ const result = workspace.apply(planned.ops);
741
+ if (!result.ok)
742
+ return fail(result.error, 'Edit failed', result.errors);
743
+ return ok({
744
+ ok: true,
745
+ fields: formFieldsOf(workspace.view),
746
+ ...(planned.notes.length > 0 ? { notes: planned.notes } : {}),
747
+ ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),
748
+ }, describeFormOps(result.ops), result.ops);
749
+ }
666
750
  case 'getBlockSchema': {
667
751
  const def = env.blocks.find((b) => b.type === input.type);
668
752
  if (!def)
@@ -4,6 +4,8 @@ import { classesOf, labelField, labelsField, labelsHelp } from './shared.js';
4
4
  export { CAROUSEL_CLASS_MAP, CAROUSEL_LABELS, CAROUSEL_PART_CLASSES };
5
5
  export const CAROUSEL_BLOCK = 'carousel';
6
6
  const CAROUSEL_CLASS = 'flex flex-col gap-4';
7
+ /** A new slide: one full-width slide at a time, its content in a column. */
8
+ const SLIDE_CLASS = 'flex min-w-0 shrink-0 grow-0 basis-full flex-col gap-3';
7
9
  /**
8
10
  * The carousel's inner elements that take classes (`block.partClassName`), with the classes a new
9
11
  * carousel starts with. The "slides" slot (the track) is a part too.
@@ -73,7 +75,14 @@ export function carouselBlock() {
73
75
  labelsField(CAROUSEL_LABELS, LABEL_NAMES),
74
76
  ],
75
77
  slots: {
76
- slides: { label: 'Slides', styles: true, defaultClassName: CAROUSEL_PART_CLASSES.slides },
78
+ slides: {
79
+ label: 'Slides',
80
+ styles: true,
81
+ defaultClassName: CAROUSEL_PART_CLASSES.slides,
82
+ description: 'Each block here is one slide',
83
+ itemLabel: 'Slide',
84
+ newBlock: { type: 'stack', label: 'Slide', className: SLIDE_CLASS },
85
+ },
77
86
  previous: { label: 'Previous button', allow: ARROW_CONTENT, max: 1 },
78
87
  next: { label: 'Next button', allow: ARROW_CONTENT, max: 1 },
79
88
  },
@@ -451,15 +451,40 @@ export function defaultBlocks(options) {
451
451
  custom: { ai: { description: 'A YouTube or Vimeo link, or a direct link to a video file.' } },
452
452
  },
453
453
  { name: 'poster', type: 'upload', label: 'Poster image', relationTo: mediaCollection },
454
- { name: 'autoplay', type: 'checkbox', label: 'Autoplay', admin: { description: 'Works only when muted.' } },
454
+ {
455
+ name: 'autoplay',
456
+ type: 'checkbox',
457
+ label: 'Autoplay',
458
+ admin: { description: 'Works only when muted. Stays paused for visitors who ask for less motion.' },
459
+ },
455
460
  { name: 'loop', type: 'checkbox', label: 'Loop' },
456
461
  { name: 'muted', type: 'checkbox', label: 'Muted' },
457
462
  { name: 'controls', type: 'checkbox', label: 'Show controls', defaultValue: true },
463
+ {
464
+ name: 'decorative',
465
+ type: 'checkbox',
466
+ label: 'Decorative',
467
+ admin: { description: 'For a background video: hidden from screen readers, no controls.' },
468
+ },
469
+ {
470
+ name: 'priority',
471
+ type: 'checkbox',
472
+ label: 'Load first',
473
+ admin: { description: 'For the main video at the top.' },
474
+ // Unlike images, a video never gets this from `priorityImages`: it would load the whole file.
475
+ custom: { builderAutoPriority: false },
476
+ },
458
477
  ],
459
478
  defaultClassName: 'w-full',
460
479
  ai: {
461
480
  description: `A video: an upload from the "${mediaCollection}" collection (source "upload", set "video") or a ` +
462
- 'YouTube, Vimeo or video file URL (source "url", set "url").',
481
+ 'YouTube, Vimeo or video file URL (source "url", set "url"). "poster" is an image upload shown before ' +
482
+ 'the video plays; its focal point (focalX, focalY) sets object-position. "autoplay" starts the video ' +
483
+ 'from script on the site, never on the editor canvas and never for visitors with reduced motion (they ' +
484
+ 'see the poster). For a background video behind a hero: put the video first in a stack with "relative isolate", ' +
485
+ 'set "autoplay", "muted", "loop" and "decorative": true (aria-hidden, no controls, no tab stop), "priority": ' +
486
+ '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".',
463
488
  example: {
464
489
  type: 'video',
465
490
  props: { source: 'url', url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', controls: true },
@@ -1,7 +1,7 @@
1
1
  export { defaultBlocks, FIELD_CLASS_MAP, MENU_CLASS_MAP, MENU_LABELS, type DefaultBlocksOptions } from './defaults.js';
2
2
  export * from './builtins/index.js';
3
3
  export { isLinkField, linkField, type BuilderCondition, type LinkFieldOptions } from './link.js';
4
- export { fromPayloadBlocks, type FromPayloadBlocksOptions, type PayloadBlockOverride } from './payload.js';
4
+ export { BLOCK_KEY_MARKER, fromPayloadBlocks, type FromPayloadBlocksOptions, type PayloadBlockOverride } from './payload.js';
5
5
  export { defineBlock, defineSection, type SectionBlockInput, type SectionInput, sectionsWithVariants, withDefaultClassNames, withInlineBlocks } from '../core/blocks.js';
6
6
  export { BUILDER_CSS_CLASS, withBuilderCssClass } from '../css/marker.js';
7
7
  export { listCollectionsOf, prepareBlocks } from '../plugin/listCollections.js';
@@ -4,7 +4,7 @@
4
4
  export { defaultBlocks, FIELD_CLASS_MAP, MENU_CLASS_MAP, MENU_LABELS } from './defaults.js';
5
5
  export * from './builtins/index.js';
6
6
  export { isLinkField, linkField } from './link.js';
7
- export { fromPayloadBlocks } from './payload.js';
7
+ export { BLOCK_KEY_MARKER, fromPayloadBlocks } from './payload.js';
8
8
  export { defineBlock, defineSection, sectionsWithVariants, withDefaultClassNames, withInlineBlocks } from '../core/blocks.js';
9
9
  export { BUILDER_CSS_CLASS, withBuilderCssClass } from '../css/marker.js';
10
10
  // Public since 0.4.0. 0.5.0 dropped this line by mistake; `exports.test.ts` keeps it.
@@ -40,6 +40,13 @@ export type FromPayloadBlocksOptions = {
40
40
  onWarning?: ((message: string) => void) | false;
41
41
  };
42
42
  type Config = PayloadBlockConfig;
43
+ /**
44
+ * `admin.custom.builderBlockKey` on a top-level field of a Payload block: the field stores the
45
+ * block's `className` (a text field) or `partClassName` (a json field). `fromPayloadBlocks` leaves
46
+ * the field out of the props and records it in `payload.classKeys`, so a Payload blocks field keeps
47
+ * the block's classes and the editor offers its Styles tab. Hide the field in Payload's admin.
48
+ */
49
+ export declare const BLOCK_KEY_MARKER = "builderBlockKey";
43
50
  /**
44
51
  * Builder block definitions from Payload block configs, so a site keeps its own blocks.
45
52
  *
@@ -3,6 +3,13 @@
3
3
  import { conditionFromFunction } from '../core/conditions.js';
4
4
  import { textOf } from '../core/fields.js';
5
5
  import { isPlainObject } from '../core/tree.js';
6
+ /**
7
+ * `admin.custom.builderBlockKey` on a top-level field of a Payload block: the field stores the
8
+ * block's `className` (a text field) or `partClassName` (a json field). `fromPayloadBlocks` leaves
9
+ * the field out of the props and records it in `payload.classKeys`, so a Payload blocks field keeps
10
+ * the block's classes and the editor offers its Styles tab. Hide the field in Payload's admin.
11
+ */
12
+ export const BLOCK_KEY_MARKER = 'builderBlockKey';
6
13
  const ICONS = [
7
14
  [/head|title/i, 'heading'],
8
15
  [/video/i, 'video'],
@@ -77,6 +84,7 @@ export function fromPayloadBlocks(blocks, options = {}) {
77
84
  function definitionOf(block) {
78
85
  const notes = [];
79
86
  const slots = {};
87
+ const classKeys = {};
80
88
  const fields = adaptFields(block.fields, true, '');
81
89
  const override = options.overrides?.[block.slug] ?? {};
82
90
  const label = override.label ?? textOf(block.labels?.singular) ?? words(block.slug);
@@ -95,11 +103,11 @@ export function fromPayloadBlocks(blocks, options = {}) {
95
103
  label,
96
104
  fields,
97
105
  ...(hasSlots ? { slots } : {}),
98
- styles: override.styles ?? options.styles ?? false,
106
+ styles: override.styles ?? options.styles ?? Boolean(classKeys.className),
99
107
  icon: override.icon ?? (hasSlots ? 'section' : (ICONS.find(([test]) => test.test(block.slug))?.[1] ?? 'block')),
100
108
  category: override.category ?? textOf(block.admin?.group) ?? options.category ?? (hasSlots ? 'Site sections' : 'Site blocks'),
101
109
  ai: override.ai ?? { description: `${label}: a block of the site's own design.${slotText}` },
102
- payload: { slug: block.slug },
110
+ payload: { slug: block.slug, ...(Object.keys(classKeys).length > 0 ? { classKeys } : {}) },
103
111
  };
104
112
  if (override.defaultClassName)
105
113
  def.defaultClassName = override.defaultClassName;
@@ -125,6 +133,12 @@ export function fromPayloadBlocks(blocks, options = {}) {
125
133
  const name = typeof field.name === 'string' ? field.name : '';
126
134
  const at = name ? `${path}${name}` : path;
127
135
  readAdmin(field, at);
136
+ // A field that stores the block's classes is block data, not a prop.
137
+ const blockKey = isPlainObject(field.admin) && isPlainObject(field.admin.custom) ? field.admin.custom[BLOCK_KEY_MARKER] : undefined;
138
+ if (top && name && (blockKey === 'className' || blockKey === 'partClassName')) {
139
+ classKeys[blockKey] = name;
140
+ return null;
141
+ }
128
142
  switch (field.type) {
129
143
  case 'blocks': {
130
144
  const allowed = blocksOfField(field);
@@ -2,6 +2,11 @@
2
2
  export declare const DEFAULT_COMMENTS_SLUG = "builder-comments";
3
3
  /** Server-only key in `config.custom` that holds `CommentsServerConfig`. */
4
4
  export declare const COMMENTS_CONFIG_KEY = "websiteBuilderComments";
5
+ /**
6
+ * The builder URL's search parameter that opens one thread in comment mode:
7
+ * `/admin/builder/pages/12?comment=34`. The dashboard's "Open comments" links use it.
8
+ */
9
+ export declare const COMMENT_PARAM = "comment";
5
10
  /** Longest comment text, in characters. */
6
11
  export declare const COMMENT_MAX = 5000;
7
12
  /** What the editor needs: the collection it reads and writes over Payload's REST API. */
@@ -5,6 +5,11 @@
5
5
  export const DEFAULT_COMMENTS_SLUG = 'builder-comments';
6
6
  /** Server-only key in `config.custom` that holds `CommentsServerConfig`. */
7
7
  export const COMMENTS_CONFIG_KEY = 'websiteBuilderComments';
8
+ /**
9
+ * The builder URL's search parameter that opens one thread in comment mode:
10
+ * `/admin/builder/pages/12?comment=34`. The dashboard's "Open comments" links use it.
11
+ */
12
+ export const COMMENT_PARAM = 'comment';
8
13
  /** Longest comment text, in characters. */
9
14
  export const COMMENT_MAX = 5000;
10
15
  const text = (value) => (typeof value === 'string' && value ? value : null);
@@ -76,18 +76,30 @@ export declare function sectionsWithDefaultClassNames(sections: readonly Section
76
76
  * block is inline.
77
77
  */
78
78
  export declare function withInlineBlocks(blocks: BlockDefinition[]): BlockDefinition[];
79
+ /**
80
+ * The layout with `BlockDefinition.upgrade` run on every block (slots too, children first). The
81
+ * same layout when no block changes, or when no definition has an upgrade.
82
+ */
83
+ export declare function upgradeLayout(layout: Layout, blocks: readonly BlockDefinition[]): Layout;
79
84
  export declare function getBlockDefinition(blocks: readonly BlockDefinition[], type: string): BlockDefinition | undefined;
80
85
  /** Slot names of a block type, in declared order. */
81
86
  export declare function slotNames(def: BlockDefinition | undefined): string[];
82
87
  /** The block's name for people: its own `label`, else the block type's label, else the type. */
83
88
  export declare function blockName(block: Pick<Block, 'type' | 'label'>, blocks: readonly BlockDefinition[]): string;
89
+ /**
90
+ * Why a block (a type, or a whole block with its children) cannot sit below blocks of the types
91
+ * `above` (outermost first; empty for the root list) by the `ancestors` rules of its types, or
92
+ * `null`. Inside the placed subtree, a block's own ancestors in the subtree count too.
93
+ */
94
+ export declare function ancestorsError(blocks: readonly BlockDefinition[], block: string | Block, above: readonly string[]): string | null;
84
95
  /**
85
96
  * Why `block` (a type, or a whole block with its children) cannot go into `slot` of `parentId`,
86
97
  * or `null` when it can. Checks the direct slot's `allow` and `disallow`, and the `disallow` of
87
98
  * every ancestor slot up to the root, against every type in the placed subtree, the placed
88
- * block's own `parents` rule, and the direct slot's `max` (a block already in that slot, being
89
- * moved within it, does not count as one more). The root list accepts every type without a `parents` rule. The
90
- * message is readable, e.g. `Button cannot go inside Link`.
99
+ * block's own `parents` rule, the `ancestors` rules of every type in the subtree, and the direct
100
+ * slot's `max` (a block already in that slot, being moved within it, does not count as one more).
101
+ * The root list accepts every type without a `parents` or `ancestors` rule. The message is
102
+ * readable, e.g. `Button cannot go inside Link`.
91
103
  */
92
104
  export declare function placementError(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string, block: string | Block, index?: Map<string, IndexedBlock>): string | null;
93
105
  /** The slot's name for people: its `label`, else its name. */
@@ -104,6 +116,8 @@ export declare function slotFullError(blocks: readonly BlockDefinition[], owner:
104
116
  * a slot without a limit, or an unknown parent.
105
117
  */
106
118
  export declare function slotRoom(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string): number;
119
+ /** The definition of `slot` of block `parentId`. Undefined for the root list and undeclared slots. */
120
+ export declare function slotDefinitionAt(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string): SlotDefinition | undefined;
107
121
  /** True when `block` (a type or a whole block) may go into `slot` of `parentId`. See `placementError`. */
108
122
  export declare function slotAcceptsAt(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string, block: string | Block): boolean;
109
123
  /**