payload-canvas 0.5.2 → 0.7.0-next.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 (325) hide show
  1. package/README.md +350 -45
  2. package/dist/admin/AiKeyField.d.ts +4 -3
  3. package/dist/admin/AiKeyField.js +3 -3
  4. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  5. package/dist/admin/ArrayRowLabel.js +21 -0
  6. package/dist/admin/BuilderTab.js +1 -1
  7. package/dist/admin/DocumentEditView.d.ts +1 -1
  8. package/dist/admin/DocumentEditView.js +2 -3
  9. package/dist/admin/LayoutField.d.ts +1 -1
  10. package/dist/admin/LayoutField.js +2 -2
  11. package/dist/admin/TemplateConditionsField.d.ts +2 -2
  12. package/dist/admin/TemplateConditionsField.js +2 -2
  13. package/dist/admin/aiKeyField.css +58 -0
  14. package/dist/admin/client.d.ts +1 -0
  15. package/dist/admin/client.js +2 -0
  16. package/dist/admin/diff/LayoutDiff.js +3 -3
  17. package/dist/admin/diff/LayoutJsonDiff.d.ts +1 -1
  18. package/dist/admin/diff/LayoutJsonDiff.js +1 -1
  19. package/dist/admin/diff/layoutDiff.css +180 -0
  20. package/dist/admin/editor/Editor.d.ts +2 -2
  21. package/dist/admin/editor/Editor.js +10 -3
  22. package/dist/admin/editor/Inspector.js +23 -17
  23. package/dist/admin/editor/Library.d.ts +2 -2
  24. package/dist/admin/editor/Library.js +8 -7
  25. package/dist/admin/editor/Outline.js +20 -12
  26. package/dist/admin/editor/Overlay.js +6 -4
  27. package/dist/admin/editor/actions.d.ts +7 -2
  28. package/dist/admin/editor/actions.js +44 -12
  29. package/dist/admin/editor/assistant/AssistantPanel.d.ts +1 -1
  30. package/dist/admin/editor/assistant/AssistantPanel.js +33 -21
  31. package/dist/admin/editor/assistant/{assistant.scss → assistant.css} +322 -315
  32. package/dist/admin/editor/classes/ClassManager.d.ts +1 -1
  33. package/dist/admin/editor/classes/ClassManager.js +1 -1
  34. package/dist/admin/editor/classes/manager.css +258 -0
  35. package/dist/admin/editor/comments/CommentLayer.d.ts +1 -1
  36. package/dist/admin/editor/comments/CommentLayer.js +1 -1
  37. package/dist/admin/editor/comments/CommentsPanel.d.ts +1 -1
  38. package/dist/admin/editor/comments/CommentsPanel.js +1 -1
  39. package/dist/admin/editor/comments/{comments.scss → comments.css} +121 -140
  40. package/dist/admin/editor/comments/controller.d.ts +7 -0
  41. package/dist/admin/editor/comments/controller.js +12 -0
  42. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  43. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  44. package/dist/admin/editor/dnd/{dnd.scss → dnd.css} +78 -80
  45. package/dist/admin/editor/dnd/smooth.js +1 -1
  46. package/dist/admin/editor/{editor.scss → editor.css} +798 -751
  47. package/dist/admin/editor/empty/EmptyStart.d.ts +1 -1
  48. package/dist/admin/editor/empty/EmptyStart.js +3 -3
  49. package/dist/admin/editor/empty/{empty.scss → empty.css} +12 -13
  50. package/dist/admin/editor/fields/ArrayField.js +3 -3
  51. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  52. package/dist/admin/editor/fields/FormBlock.js +167 -0
  53. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  54. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  55. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  56. package/dist/admin/editor/fields/GroupField.js +30 -1
  57. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  58. package/dist/admin/editor/fields/MergeTags.js +62 -0
  59. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  60. package/dist/admin/editor/fields/arrayRows.js +0 -4
  61. package/dist/admin/editor/fields/fields.css +786 -0
  62. package/dist/admin/editor/fields/values.d.ts +0 -2
  63. package/dist/admin/editor/fields/values.js +0 -14
  64. package/dist/admin/editor/generate/GenerateImage.d.ts +1 -1
  65. package/dist/admin/editor/generate/GenerateImage.js +1 -1
  66. package/dist/admin/editor/generate/{generate.scss → generate.css} +83 -82
  67. package/dist/admin/editor/icons.d.ts +3 -0
  68. package/dist/admin/editor/icons.js +3 -0
  69. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  70. package/dist/admin/editor/insert/picker.d.ts +3 -2
  71. package/dist/admin/editor/insert/picker.js +9 -3
  72. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  73. package/dist/admin/editor/layout/layout.css +243 -0
  74. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  75. package/dist/admin/editor/layout/leftTabs.js +18 -0
  76. package/dist/admin/editor/layout/panels.js +1 -1
  77. package/dist/admin/editor/live/PresenceUI.d.ts +1 -1
  78. package/dist/admin/editor/live/PresenceUI.js +2 -2
  79. package/dist/admin/editor/live/{presence.scss → presence.css} +5 -4
  80. package/dist/admin/editor/locale/LocaleField.d.ts +1 -1
  81. package/dist/admin/editor/locale/LocaleField.js +1 -1
  82. package/dist/admin/editor/locale/LocaleSwitcher.d.ts +1 -1
  83. package/dist/admin/editor/locale/LocaleSwitcher.js +1 -1
  84. package/dist/admin/editor/locale/locale.css +153 -0
  85. package/dist/admin/editor/media/ImageEditor.d.ts +9 -3
  86. package/dist/admin/editor/media/ImageEditor.js +17 -11
  87. package/dist/admin/editor/media/{media.scss → media.css} +70 -60
  88. package/dist/admin/editor/media/model.d.ts +10 -1
  89. package/dist/admin/editor/media/model.js +19 -0
  90. package/dist/admin/editor/menu/Menu.d.ts +1 -1
  91. package/dist/admin/editor/menu/Menu.js +1 -1
  92. package/dist/admin/editor/menu/blockMenu.js +3 -3
  93. package/dist/admin/editor/menu/menu.css +132 -0
  94. package/dist/admin/editor/motion/MotionPanel.d.ts +2 -2
  95. package/dist/admin/editor/motion/MotionPanel.js +2 -2
  96. package/dist/admin/editor/motion/{motion.scss → motion.css} +24 -21
  97. package/dist/admin/editor/names.d.ts +9 -0
  98. package/dist/admin/editor/names.js +18 -0
  99. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  100. package/dist/admin/editor/regions/RegionFields.js +122 -0
  101. package/dist/admin/editor/regions/RegionPane.js +5 -3
  102. package/dist/admin/editor/regions/RegionRows.js +2 -2
  103. package/dist/admin/editor/regions/required.d.ts +16 -0
  104. package/dist/admin/editor/regions/required.js +43 -0
  105. package/dist/admin/editor/renderField.d.ts +10 -3
  106. package/dist/admin/editor/renderField.js +87 -33
  107. package/dist/admin/editor/runtime.d.ts +3 -2
  108. package/dist/admin/editor/runtime.js +12 -18
  109. package/dist/admin/editor/sections/ComponentFields.d.ts +1 -1
  110. package/dist/admin/editor/sections/ComponentFields.js +2 -3
  111. package/dist/admin/editor/sections/PropertyControls.d.ts +1 -1
  112. package/dist/admin/editor/sections/PropertyControls.js +1 -1
  113. package/dist/admin/editor/sections/components.css +244 -0
  114. package/dist/admin/editor/sections/variants.css +93 -0
  115. package/dist/admin/editor/sections/variants.d.ts +1 -1
  116. package/dist/admin/editor/sections/variants.js +1 -1
  117. package/dist/admin/editor/styles/ClassBar.d.ts +1 -1
  118. package/dist/admin/editor/styles/ClassBar.js +1 -1
  119. package/dist/admin/editor/styles/StylesPanel.d.ts +1 -1
  120. package/dist/admin/editor/styles/StylesPanel.js +5 -3
  121. package/dist/admin/editor/styles/{classes.scss → classes.css} +128 -125
  122. package/dist/admin/editor/styles/context.js +9 -4
  123. package/dist/admin/editor/styles/{styles.scss → styles.css} +368 -370
  124. package/dist/admin/editor/templates/Bindable.d.ts +1 -1
  125. package/dist/admin/editor/templates/Bindable.js +1 -1
  126. package/dist/admin/editor/templates/binding.js +4 -1
  127. package/dist/admin/editor/templates/{templates.scss → templates.css} +207 -206
  128. package/dist/admin/editor/tooltip/Tooltips.d.ts +1 -1
  129. package/dist/admin/editor/tooltip/Tooltips.js +1 -1
  130. package/dist/admin/editor/tooltip/{tooltip.scss → tooltip.css} +11 -10
  131. package/dist/admin/editor/topbar/ContentModeToggle.d.ts +1 -1
  132. package/dist/admin/editor/topbar/ContentModeToggle.js +2 -2
  133. package/dist/admin/editor/topbar/DocumentActions.js +5 -5
  134. package/dist/admin/editor/topbar/TopBar.d.ts +1 -1
  135. package/dist/admin/editor/topbar/TopBar.js +2 -3
  136. package/dist/admin/editor/topbar/contentMode.css +25 -0
  137. package/dist/admin/editor/topbar/screens/DrawerRouter.d.ts +1 -1
  138. package/dist/admin/editor/topbar/screens/DrawerRouter.js +52 -40
  139. package/dist/admin/editor/topbar/screens/ScreenDrawer.d.ts +1 -1
  140. package/dist/admin/editor/topbar/screens/ScreenDrawer.js +4 -5
  141. package/dist/admin/editor/topbar/screens/drawerRouterSupport.d.ts +5 -5
  142. package/dist/admin/editor/topbar/screens/drawerRouterSupport.js +7 -7
  143. package/dist/admin/editor/topbar/screens/screens.css +139 -0
  144. package/dist/admin/editor/topbar/settingsDrawer.css +33 -0
  145. package/dist/admin/editor/topbar/settingsDrawer.d.ts +1 -1
  146. package/dist/admin/editor/topbar/settingsDrawer.js +3 -3
  147. package/dist/admin/editor/topbar/{topbar.scss → topbar.css} +189 -231
  148. package/dist/admin/editor/ui/Select.d.ts +1 -1
  149. package/dist/admin/editor/ui/Select.js +1 -1
  150. package/dist/admin/editor/ui/Slider.d.ts +1 -1
  151. package/dist/admin/editor/ui/Slider.js +1 -1
  152. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  153. package/dist/admin/editor/ui/Tabs.js +17 -0
  154. package/dist/admin/editor/ui/controls.css +301 -0
  155. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  156. package/dist/admin/forms/SubmissionCells.js +31 -0
  157. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  158. package/dist/admin/forms/SubmissionView.js +106 -0
  159. package/dist/admin/forms/submissionData.d.ts +32 -0
  160. package/dist/admin/forms/submissionData.js +63 -0
  161. package/dist/admin/forms/submissions.css +200 -0
  162. package/dist/admin/layoutField.css +70 -0
  163. package/dist/admin/rsc.d.ts +2 -0
  164. package/dist/admin/rsc.js +5 -0
  165. package/dist/admin/screen/BuilderScreen.d.ts +1 -1
  166. package/dist/admin/screen/BuilderScreen.js +1 -1
  167. package/dist/admin/templateConditions.css +25 -0
  168. package/dist/ai/endpoint.d.ts +5 -0
  169. package/dist/ai/endpoint.js +18 -8
  170. package/dist/ai/images/service.js +2 -2
  171. package/dist/ai/prompt.d.ts +8 -0
  172. package/dist/ai/prompt.js +30 -0
  173. package/dist/ai/settings/index.js +3 -0
  174. package/dist/ai/tools.d.ts +6 -1
  175. package/dist/ai/tools.js +90 -6
  176. package/dist/blocks/builtins/carousel.js +10 -1
  177. package/dist/blocks/index.d.ts +1 -1
  178. package/dist/blocks/index.js +1 -1
  179. package/dist/blocks/payload.d.ts +7 -0
  180. package/dist/blocks/payload.js +16 -2
  181. package/dist/classes/collection.js +1 -0
  182. package/dist/classes/sheet.js +2 -0
  183. package/dist/comments/collection.js +3 -0
  184. package/dist/comments/shared.d.ts +5 -0
  185. package/dist/comments/shared.js +5 -0
  186. package/dist/core/blocks.d.ts +17 -3
  187. package/dist/core/blocks.js +92 -10
  188. package/dist/core/classes.d.ts +5 -0
  189. package/dist/core/classes.js +26 -1
  190. package/dist/core/conditions.d.ts +7 -0
  191. package/dist/core/conditions.js +22 -0
  192. package/dist/core/dropTarget.d.ts +3 -2
  193. package/dist/core/dropTarget.js +7 -1
  194. package/dist/core/fieldHooks.d.ts +1 -1
  195. package/dist/core/index.d.ts +6 -3
  196. package/dist/core/index.js +6 -3
  197. package/dist/core/payloadBlocks.js +25 -3
  198. package/dist/core/references.d.ts +7 -0
  199. package/dist/core/references.js +29 -11
  200. package/dist/core/regions.d.ts +14 -0
  201. package/dist/core/regions.js +17 -1
  202. package/dist/core/rowLabel.d.ts +8 -0
  203. package/dist/core/rowLabel.js +98 -0
  204. package/dist/core/starter.d.ts +10 -0
  205. package/dist/core/starter.js +40 -0
  206. package/dist/core/tree.js +4 -0
  207. package/dist/core/types.d.ts +96 -0
  208. package/dist/core/uniqueProps.d.ts +40 -0
  209. package/dist/core/uniqueProps.js +156 -0
  210. package/dist/core/validate.js +43 -3
  211. package/dist/forms/answers.d.ts +21 -0
  212. package/dist/forms/answers.js +82 -0
  213. package/dist/forms/blocks.d.ts +33 -0
  214. package/dist/forms/blocks.js +178 -0
  215. package/dist/forms/conditions.d.ts +78 -0
  216. package/dist/forms/conditions.js +184 -0
  217. package/dist/forms/emails.d.ts +23 -0
  218. package/dist/forms/emails.js +64 -0
  219. package/dist/forms/fieldConfigs.d.ts +35 -0
  220. package/dist/forms/fieldConfigs.js +167 -0
  221. package/dist/forms/fieldOps.d.ts +78 -0
  222. package/dist/forms/fieldOps.js +378 -0
  223. package/dist/forms/fieldSettings.d.ts +81 -0
  224. package/dist/forms/fieldSettings.js +239 -0
  225. package/dist/forms/files.d.ts +54 -0
  226. package/dist/forms/files.js +128 -0
  227. package/dist/forms/index.d.ts +16 -0
  228. package/dist/forms/index.js +18 -0
  229. package/dist/forms/mergeTags.d.ts +103 -0
  230. package/dist/forms/mergeTags.js +150 -0
  231. package/dist/forms/noScript.d.ts +60 -0
  232. package/dist/forms/noScript.js +109 -0
  233. package/dist/forms/pageForms.d.ts +99 -0
  234. package/dist/forms/pageForms.js +294 -0
  235. package/dist/forms/pageSync.d.ts +91 -0
  236. package/dist/forms/pageSync.js +325 -0
  237. package/dist/forms/rateLimit.d.ts +21 -0
  238. package/dist/forms/rateLimit.js +50 -0
  239. package/dist/forms/settings.d.ts +13 -0
  240. package/dist/forms/settings.js +92 -0
  241. package/dist/forms/spam.d.ts +100 -0
  242. package/dist/forms/spam.js +218 -0
  243. package/dist/forms/spamSettings.d.ts +43 -0
  244. package/dist/forms/spamSettings.js +25 -0
  245. package/dist/forms/submission.d.ts +34 -0
  246. package/dist/forms/submission.js +89 -0
  247. package/dist/forms/submissionsAdmin.d.ts +26 -0
  248. package/dist/forms/submissionsAdmin.js +108 -0
  249. package/dist/forms/summary.d.ts +60 -0
  250. package/dist/forms/summary.js +113 -0
  251. package/dist/forms/uploads.d.ts +41 -0
  252. package/dist/forms/uploads.js +132 -0
  253. package/dist/index.d.ts +8 -2
  254. package/dist/index.js +8 -2
  255. package/dist/live/document.d.ts +12 -0
  256. package/dist/live/document.js +8 -1
  257. package/dist/live/draftAccess.js +1 -1
  258. package/dist/live/endpoints.d.ts +1 -0
  259. package/dist/live/session.js +3 -1
  260. package/dist/live/storage.d.ts +13 -2
  261. package/dist/live/storage.js +18 -7
  262. package/dist/mcp/forms.d.ts +26 -0
  263. package/dist/mcp/forms.js +280 -0
  264. package/dist/mcp/index.d.ts +7 -0
  265. package/dist/mcp/index.js +29 -10
  266. package/dist/mcp/shared.d.ts +1 -0
  267. package/dist/mcp/shared.js +1 -0
  268. package/dist/plugin/forms.d.ts +30 -0
  269. package/dist/plugin/forms.js +63 -0
  270. package/dist/plugin/formsSync.d.ts +138 -0
  271. package/dist/plugin/formsSync.js +345 -0
  272. package/dist/plugin/hook.d.ts +22 -0
  273. package/dist/plugin/hook.js +19 -7
  274. package/dist/plugin/index.d.ts +14 -0
  275. package/dist/plugin/index.js +101 -30
  276. package/dist/plugin/links.d.ts +7 -2
  277. package/dist/plugin/links.js +9 -3
  278. package/dist/plugin/references.d.ts +6 -0
  279. package/dist/plugin/references.js +12 -0
  280. package/dist/plugin/sections.js +3 -0
  281. package/dist/plugin/templates.js +5 -1
  282. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  283. package/dist/react/canvas/BuilderCanvas.js +29 -6
  284. package/dist/react/canvas/inline/candidates.js +2 -2
  285. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  286. package/dist/react/canvas/inline/mapper.js +35 -4
  287. package/dist/react/canvas/inline/rich/editor.js +9 -1
  288. package/dist/react/components/Image.d.ts +1 -1
  289. package/dist/react/components/Image.js +2 -2
  290. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  291. package/dist/react/render/LayoutOutlet.js +9 -4
  292. package/dist/react/render/RenderLayout.js +13 -7
  293. package/dist/react/render/resolve.d.ts +1 -0
  294. package/dist/react/render/resolve.js +7 -1
  295. package/dist/react/render/templates.js +3 -1
  296. package/dist/react/server.js +19 -0
  297. package/dist/react/theme/ThemeStyle.js +1 -1
  298. package/dist/theme/admin/ColorField.d.ts +4 -3
  299. package/dist/theme/admin/ColorField.js +1 -1
  300. package/dist/theme/admin/FontField.d.ts +4 -3
  301. package/dist/theme/admin/FontField.js +1 -1
  302. package/dist/theme/admin/SaveSignal.js +1 -1
  303. package/dist/theme/admin/SliderField.d.ts +1 -1
  304. package/dist/theme/admin/SliderField.js +1 -1
  305. package/dist/theme/admin/Variables.d.ts +4 -3
  306. package/dist/theme/admin/Variables.js +2 -2
  307. package/dist/theme/admin/fields.css +327 -0
  308. package/dist/theme/global.js +2 -0
  309. package/package.json +29 -24
  310. package/dist/admin/aiKeyField.scss +0 -58
  311. package/dist/admin/diff/layoutDiff.scss +0 -181
  312. package/dist/admin/editor/classes/manager.scss +0 -262
  313. package/dist/admin/editor/fields/fields.scss +0 -628
  314. package/dist/admin/editor/layout/layout.scss +0 -240
  315. package/dist/admin/editor/locale/locale.scss +0 -154
  316. package/dist/admin/editor/menu/menu.scss +0 -132
  317. package/dist/admin/editor/sections/components.scss +0 -238
  318. package/dist/admin/editor/sections/variants.scss +0 -90
  319. package/dist/admin/editor/topbar/contentMode.scss +0 -35
  320. package/dist/admin/editor/topbar/screens/screens.scss +0 -134
  321. package/dist/admin/editor/topbar/settingsDrawer.scss +0 -32
  322. package/dist/admin/editor/ui/controls.scss +0 -320
  323. package/dist/admin/layoutField.scss +0 -69
  324. package/dist/admin/templateConditions.scss +0 -24
  325. package/dist/theme/admin/fields.scss +0 -363
@@ -0,0 +1,280 @@
1
+ // MCP tools for the forms of `@payloadcms/plugin-form-builder` (`websiteBuilder({ forms })`):
2
+ // listForms, getForm, createForm, editFormFields, updateFormSettings.
3
+ //
4
+ // Field edits are commits to the form's live session, the same path as the form builder's own
5
+ // edits, so an open form builder shows them at once. Settings go through the regions' fields
6
+ // endpoint code (`writeRegionFields`): Payload's Local API as the user, with the write gate, and
7
+ // the builder's settings panel reloads them from the `saved` event.
8
+ import { z } from 'zod';
9
+ import { normalizeLayout } from '../core/tree.js';
10
+ import { FORM_FIELDS_FIELD } from '../plugin/forms.js';
11
+ import { formFieldOps, formFieldsOf, formFieldTypes, FORM_FIELDS_GUIDE } from '../forms/fieldOps.js';
12
+ import { formSettingsChanges, formSettingsView, FORM_SETTINGS_GUIDE } from '../forms/settings.js';
13
+ import { builderConfigOf } from '../live/document.js';
14
+ import { writeRegionFields } from '../live/regions.js';
15
+ import { liveRuntimeOf } from '../live/runtime.js';
16
+ import { codecOf } from '../live/storage.js';
17
+ import { builderViewPath } from '../plugin/links.js';
18
+ const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
19
+ const changeSchema = z
20
+ .object({
21
+ action: z.enum(['add', 'update', 'move', 'remove', 'setConditions']),
22
+ type: z.string().optional().describe('add: the field type, e.g. "email".'),
23
+ field: z.string().optional().describe('update, move, remove, setConditions: the field\'s name (or id from getForm).'),
24
+ values: z
25
+ .record(z.string(), z.unknown())
26
+ .optional()
27
+ .describe('add, update: props to set, e.g. { "label": "Your email", "required": true, "className": "sm:w-[calc(50%-0.5rem)]" }. update merges them; other props stay. Width is classes (className), never a prop.'),
28
+ unset: z.array(z.string()).optional().describe('update: prop names to clear.'),
29
+ index: z.number().int().min(0).optional().describe('add: position (default: the end). move: the final position. 0 is the first field.'),
30
+ conditions: z
31
+ .record(z.string(), z.unknown())
32
+ .nullable()
33
+ .optional()
34
+ .describe('setConditions: { match?: "all" | "any", rules: [{ field, operator, value? }] }. null: always show.'),
35
+ })
36
+ .describe('One change of the form\'s fields.');
37
+ export function formMcpTools(ctx) {
38
+ const { slug, text, fail } = ctx;
39
+ const collectionArg = z.enum([slug]).default(slug).describe(`The forms collection. Always "${slug}" (may be left out).`);
40
+ const idArg = z.string().min(1).describe('Form id (from listForms).');
41
+ /** The plugin's server config of the forms collection, or an error text when forms are off. */
42
+ const formsConfig = (req) => {
43
+ const server = builderConfigOf(req.payload)?.collections[slug];
44
+ if (!server)
45
+ return `The form builder is off: set \`forms: true\` in websiteBuilder() for the "${slug}" collection.`;
46
+ const codec = codecOf(server);
47
+ const settings = (server.regions ?? []).flatMap((region) => (region.panel ? region.fields.map((f) => f.path) : []));
48
+ return { server, codec, definitions: codec.blocks ?? [], settings };
49
+ };
50
+ const editorUrl = (req, id) => `${ctx.siteOf(req)}${builderViewPath(req.payload.config.routes?.admin ?? '/admin', slug, String(id))}`;
51
+ const listForms = {
52
+ name: 'listForms',
53
+ routing: { kind: 'collection', action: 'read' },
54
+ description: 'Lists the site\'s forms (contact, newsletter, booking, …): id, title, the field names and the link to the form builder. Then getForm reads one form, editFormFields changes its fields, updateFormSettings its title, confirmation and emails, createForm makes a new one. A page shows a form with a "form" block that points at its id.',
55
+ parameters: { collection: collectionArg, search: z.string().optional().describe('Only forms whose title contains this text.') },
56
+ handler: async (args, req) => {
57
+ const config = formsConfig(req);
58
+ if (typeof config === 'string')
59
+ return fail(config);
60
+ try {
61
+ const result = await req.payload.find({
62
+ collection: slug,
63
+ where: typeof args.search === 'string' && args.search ? { title: { like: args.search } } : {},
64
+ depth: 0,
65
+ limit: 100,
66
+ sort: 'title',
67
+ overrideAccess: false,
68
+ user: req.user,
69
+ req,
70
+ });
71
+ return text({
72
+ collection: slug,
73
+ forms: result.docs.map((doc) => {
74
+ const fields = Array.isArray(doc[FORM_FIELDS_FIELD]) ? doc[FORM_FIELDS_FIELD] : [];
75
+ return {
76
+ id: doc.id,
77
+ title: doc.title,
78
+ fields: fields.map((f) => (typeof f.name === 'string' && f.name ? f.name : String(f.blockType))),
79
+ updatedAt: doc.updatedAt,
80
+ editorUrl: editorUrl(req, doc.id),
81
+ };
82
+ }),
83
+ ...(result.totalDocs > result.docs.length ? { more: result.totalDocs - result.docs.length } : {}),
84
+ });
85
+ }
86
+ catch (error) {
87
+ return fail(errorMessage(error));
88
+ }
89
+ },
90
+ };
91
+ const getForm = {
92
+ name: 'getForm',
93
+ routing: { kind: 'collection', action: 'read' },
94
+ description: 'Reads one form: its fields in order (id, type, name, label, required, className (its classes, width included), placeholder, defaultValue, options, message text, display conditions and `shows`, the conditions in words), the field types this site offers (`fieldTypes`, with their props), the settings (title, submit button, confirmation, redirect, emails, spam protection) and `editorUrl`, the form builder where a person sees your changes live. Includes unsaved edits of people who have the form open. The result\'s `guide` explains fields, conditions and settings.',
95
+ parameters: { collection: collectionArg, id: idArg },
96
+ handler: async (args, req) => {
97
+ const config = formsConfig(req);
98
+ if (typeof config === 'string')
99
+ return fail(config);
100
+ let doc;
101
+ let layout;
102
+ try {
103
+ doc = await ctx.loadDraft(req, slug, String(args.id));
104
+ layout = (await ctx.currentLayout(req, slug, doc)).layout;
105
+ }
106
+ catch (error) {
107
+ return fail(errorMessage(error));
108
+ }
109
+ return text({
110
+ collection: slug,
111
+ id: doc.id,
112
+ title: doc.title,
113
+ fields: formFieldsOf(layout),
114
+ settings: formSettingsView(doc, config.settings),
115
+ fieldTypes: formFieldTypes(config.definitions),
116
+ editorUrl: editorUrl(req, doc.id),
117
+ guide: `${FORM_FIELDS_GUIDE}\n\n${FORM_SETTINGS_GUIDE}`,
118
+ });
119
+ },
120
+ };
121
+ const editFormFields = {
122
+ name: 'editFormFields',
123
+ routing: { kind: 'collection', action: 'update' },
124
+ description: [
125
+ 'Changes the fields of a form, applied in order, all or nothing. People with the form open in the form builder see each change live; the form saves about a second later. Call getForm first for the field names.',
126
+ 'Changes: add { type, values?, index? }; update { field, values?, unset? } (merges values; renaming a field also renames it 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.',
127
+ FORM_FIELDS_GUIDE,
128
+ ].join('\n\n'),
129
+ parameters: {
130
+ collection: collectionArg,
131
+ id: idArg,
132
+ changes: z.array(changeSchema).min(1).describe('Changes, applied in order.'),
133
+ },
134
+ handler: async (args, req) => {
135
+ const config = formsConfig(req);
136
+ if (typeof config === 'string')
137
+ return fail(config);
138
+ let notes = [];
139
+ const result = await ctx.apply(req, slug, String(args.id), (layout) => {
140
+ const planned = formFieldOps(layout, args.changes, config.definitions);
141
+ if (!planned.ok)
142
+ return planned.error;
143
+ notes = planned.notes;
144
+ return planned.ops;
145
+ });
146
+ if (!result.ok)
147
+ return fail(result.error, result.errors);
148
+ return text({
149
+ ok: true,
150
+ seq: result.seq,
151
+ fields: formFieldsOf(result.layout),
152
+ ...(notes.length > 0 ? { notes } : {}),
153
+ ...ctx.warnings(req, slug, result),
154
+ });
155
+ },
156
+ };
157
+ const updateFormSettings = {
158
+ name: 'updateFormSettings',
159
+ routing: { kind: 'collection', action: 'update' },
160
+ description: [
161
+ 'Changes the settings of a form (not its fields: editFormFields does those). Saves at once; an open form builder shows the new settings.',
162
+ FORM_SETTINGS_GUIDE,
163
+ ].join('\n\n'),
164
+ parameters: {
165
+ collection: collectionArg,
166
+ id: idArg,
167
+ settings: z.record(z.string(), z.unknown()).describe('The settings to change, e.g. { "submitButtonLabel": "Send", "confirmationMessage": "Thanks! We reply within a day." }.'),
168
+ },
169
+ handler: async (args, req) => {
170
+ const config = formsConfig(req);
171
+ if (typeof config === 'string')
172
+ return fail(config);
173
+ const regions = (config.server.regions ?? []).filter((region) => region.panel);
174
+ if (regions.length === 0)
175
+ return fail('This form has no settings the builder knows.');
176
+ let doc;
177
+ try {
178
+ doc = await ctx.loadDraft(req, slug, String(args.id));
179
+ }
180
+ catch (error) {
181
+ return fail(errorMessage(error));
182
+ }
183
+ const changes = formSettingsChanges((args.settings ?? {}), config.settings, doc);
184
+ if (typeof changes === 'string')
185
+ return fail(changes);
186
+ const collectionConfig = req.payload.collections[slug]?.config;
187
+ const drafts = collectionConfig?.versions?.drafts;
188
+ const result = await writeRegionFields(req, {
189
+ target: {
190
+ collection: slug,
191
+ id: doc.id,
192
+ field: FORM_FIELDS_FIELD,
193
+ drafts: Boolean(drafts),
194
+ autosave: typeof drafts === 'object' && drafts !== null && Boolean(drafts.autosave),
195
+ },
196
+ regions,
197
+ changes,
198
+ runtime: liveRuntimeOf(req.payload),
199
+ });
200
+ if (!result.ok)
201
+ return fail(result.error, result.errors ?? result.conflicts);
202
+ return text({ ok: true, changed: result.changed, settings: formSettingsView(result.values, config.settings) });
203
+ },
204
+ };
205
+ const createForm = {
206
+ name: 'createForm',
207
+ routing: { kind: 'collection', action: 'create' },
208
+ description: [
209
+ 'Creates a new form with its fields and settings. Returns its id and the form builder link. To show it on a page, put a "form" block on the page with the form\'s id (applyOperations).',
210
+ 'fields: a list of { type, ...props } in order, e.g. [{ "type": "text", "label": "Name", "required": true }, { "type": "email", "label": "Email", "required": true }, { "type": "textarea", "label": "Message" }]. A name is made from the label when you leave it out. Conditions go in `conditions` (format below).',
211
+ FORM_FIELDS_GUIDE,
212
+ FORM_SETTINGS_GUIDE,
213
+ ].join('\n\n'),
214
+ parameters: {
215
+ collection: collectionArg,
216
+ title: z.string().min(1).describe('The form\'s name, e.g. "Contact".'),
217
+ fields: z.array(z.record(z.string(), z.unknown())).min(1).describe('The fields, in order: { type, name?, label, required?, className?, options?, conditions?, … }. Width is classes (className).'),
218
+ settings: z.record(z.string(), z.unknown()).optional().describe('Optional settings: submitButtonLabel, confirmationType, confirmationMessage, redirect, emails, …'),
219
+ },
220
+ handler: async (args, req) => {
221
+ const config = formsConfig(req);
222
+ if (typeof config === 'string')
223
+ return fail(config);
224
+ // Every field is an "add", so names, options, messages and conditions get the same checks.
225
+ // Conditions may name later fields: they are set after all fields exist.
226
+ const fields = args.fields;
227
+ const adds = fields.map(({ type, conditions: _conditions, ...values }) => ({ action: 'add', type: String(type ?? ''), values }));
228
+ const conditions = [];
229
+ const planned = formFieldOps({ version: 1, blocks: [] }, adds, config.definitions);
230
+ if (!planned.ok)
231
+ return fail(planned.error);
232
+ const blocks = planned.ops.flatMap((op) => (op.type === 'insert' ? [op.block] : []));
233
+ fields.forEach((field, i) => {
234
+ if (field.conditions)
235
+ conditions.push({ action: 'setConditions', field: blocks[i].id, conditions: field.conditions });
236
+ });
237
+ let layout = normalizeLayout({ version: 1, blocks });
238
+ if (conditions.length > 0) {
239
+ const withRules = formFieldOps(layout, conditions, config.definitions);
240
+ if (!withRules.ok)
241
+ return fail(withRules.error);
242
+ const byId = new Map(withRules.ops.flatMap((op) => (op.type === 'update' ? [[op.id, op.props ?? {}]] : [])));
243
+ layout = { ...layout, blocks: layout.blocks.map((b) => (byId.has(b.id) ? { ...b, props: { ...b.props, ...byId.get(b.id) } } : b)) };
244
+ }
245
+ const problems = config.codec.problems(layout);
246
+ if (problems.length > 0)
247
+ return fail(problems.join(' '));
248
+ const settings = args.settings ? formSettingsChanges(args.settings, config.settings, {}) : [];
249
+ if (typeof settings === 'string')
250
+ return fail(settings);
251
+ try {
252
+ const doc = (await req.payload.create({
253
+ collection: slug,
254
+ data: {
255
+ ...Object.fromEntries(settings.map((c) => [c.path, c.value])),
256
+ title: args.title,
257
+ [FORM_FIELDS_FIELD]: config.codec.encode(layout),
258
+ },
259
+ depth: 0,
260
+ overrideAccess: false,
261
+ user: req.user,
262
+ req,
263
+ }));
264
+ return text({
265
+ ok: true,
266
+ id: doc.id,
267
+ title: doc.title,
268
+ fields: formFieldsOf(config.codec.decode(doc[FORM_FIELDS_FIELD])),
269
+ editorUrl: editorUrl(req, doc.id),
270
+ ...(planned.notes.length > 0 ? { notes: planned.notes } : {}),
271
+ next: 'Show it on a page: applyOperations insert a "form" block with this form\'s id as its form prop (getBlockSchema "form" shows the prop).',
272
+ });
273
+ }
274
+ catch (error) {
275
+ return fail(errorMessage(error), error.data);
276
+ }
277
+ },
278
+ };
279
+ return [listForms, getForm, createForm, editFormFields, updateFormSettings];
280
+ }
@@ -53,6 +53,13 @@ export type BuilderMcpToolsOptions = {
53
53
  classes?: {
54
54
  slug?: string;
55
55
  } | false;
56
+ /**
57
+ * The form tools (listForms, getForm, createForm, editFormFields, updateFormSettings) for the
58
+ * forms of `websiteBuilder({ forms })`. Set the same value as there: `true`, or `{ collection }`.
59
+ */
60
+ forms?: {
61
+ collection?: string;
62
+ } | boolean;
56
63
  };
57
64
  /** The long format guide. listBlocks returns it (`guide`), so tool descriptions stay short. */
58
65
  declare const LAYOUT_GUIDE: string;
package/dist/mcp/index.js CHANGED
@@ -7,6 +7,7 @@
7
7
  // toolkit checks the API key's scope for that collection. Handlers run as the key's user with
8
8
  // `overrideAccess: false`. Writes are commits to the document's live session, the same path as
9
9
  // the editor's own edits, so AI changes merge with people's edits as they happen.
10
+ import { FORM_BLOCK, FORM_SLOT, FORM_SUBMIT_BLOCK } from '../forms/pageForms.js';
10
11
  import { z } from 'zod';
11
12
  import { COLLECTION_LIST_BLOCK, REPEAT_BLOCK, DEFAULT_TEMPLATES_SLUG, FIELD_BLOCK, TEMPLATE_CONDITIONS_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_PREVIEW_FIELD, TEMPLATE_PRIORITY_FIELD, TEMPLATE_TARGET_FIELD, templateConditions, withoutBoundRequired, } from '../core/bindings.js';
12
13
  import { createId } from '../core/ids.js';
@@ -39,6 +40,8 @@ import { IMAGE_ASPECT_RATIOS } from '../ai/images/ratios.js';
39
40
  import { SECTION_REF_BLOCK } from '../blocks/builtins/sectionRef.js';
40
41
  import { classesConfigOf, loadClasses, mergeSiteClasses } from '../classes/index.js';
41
42
  import { classMcpTools } from '../classes/mcp.js';
43
+ import { FORM_FIELDS_FIELD } from '../plugin/forms.js';
44
+ import { formMcpTools } from './forms.js';
42
45
  import { BINDINGS_GUIDE, changeSummary, componentListing, contextOnlyWarnings, describeBlock, layoutGuide, missingContent, missingContentHint, outline, repairRootParents, sectionInsertOps, sectionToInsert, touchedIds, variantsListing, withNewIds, } from './shared.js';
43
46
  // ---------------------------------------------------------------------------
44
47
  // Texts for the AI. Tool descriptions are prompts: keep them exact and complete.
@@ -245,18 +248,25 @@ export function builderMcpTools(options) {
245
248
  const listable = listableCollections(options.collections, options.listCollections);
246
249
  // The same block list the plugin validates against (collection list: the collections with a url
247
250
  // and `listCollections`; the live saved section block, which the plugin adds when saved sections are on).
248
- const blocks = prepareBlocks(options.blocks, listable, DEFAULT_SAVED_SECTIONS_SLUG);
251
+ const appBlocks = prepareBlocks(options.blocks, listable, DEFAULT_SAVED_SECTIONS_SLUG);
252
+ /**
253
+ * The block list of a request: the plugin's own (forms on pages completed: the Form block's
254
+ * settings and the field blocks of the forms collection), else the app's list.
255
+ */
256
+ const blocksOf = (req) => (req?.payload?.config ? builderConfigOf(req.payload)?.blocks : undefined) ?? appBlocks;
249
257
  // A section block without a className gets its type's default classes, as in the plugin.
250
258
  // Variants stay under their section (core/sections.ts); insertSection takes `variant`.
251
259
  checkSectionVariants(options.sections ?? []);
252
- const sections = sectionsWithDefaultClassNames(options.sections ?? [], blocks);
260
+ const sections = sectionsWithDefaultClassNames(options.sections ?? [], appBlocks);
253
261
  const collections = templatesSlug
254
262
  ? { ...options.collections, [templatesSlug]: { field: TEMPLATE_LAYOUT_FIELD } }
255
263
  : options.collections;
256
264
  const slugs = Object.keys(collections);
257
265
  if (slugs.length === 0)
258
266
  throw new Error('[builderMcpTools] `collections` is empty.');
259
- const fieldOf = (collection) => collections[collection]?.field ?? 'layout';
267
+ // Forms have their own tools; their builder field is the form-builder plugin's `fields` blocks field.
268
+ const formsSlug = options.forms ? ((options.forms === true ? undefined : options.forms.collection) ?? 'forms') : null;
269
+ const fieldOf = (collection) => (collection === formsSlug ? FORM_FIELDS_FIELD : (collections[collection]?.field ?? 'layout'));
260
270
  const apiKeyCollection = options.apiKeyCollection ?? 'payload-mcp-api-keys';
261
271
  const keyNames = new Map();
262
272
  const collectionEnum = z
@@ -304,6 +314,7 @@ export function builderMcpTools(options) {
304
314
  };
305
315
  /** Commits operations to the document's live session as the AI collaborator. */
306
316
  const apply = async (req, collection, id, ops) => {
317
+ const blocks = blocksOf(req);
307
318
  const runtime = liveRuntimeOf(req.payload);
308
319
  const drafts = collectionConfig(req, collection)?.versions?.drafts;
309
320
  if (!(await runtime.canUpdate(req, collection, id))) {
@@ -407,11 +418,12 @@ export function builderMcpTools(options) {
407
418
  'Lists every block type you can use in page layouts: label, description, props, slots (which child types they accept), parts and an example, plus the site\'s own classes and design variables (named colors, sizes and fonts). Call it once before you build or edit a layout: its `guide` is the layout format (block keys, ids, positions, classes, motion presets, HTML attrs, canonical form) and `bindings` the binding and VISIBILITY format.',
408
419
  'For whole page parts (hero, features, pricing, call to action, footer), PREFER ready-made sections: listSections, then insertSection. Use single blocks for small additions and edits.',
409
420
  `Dynamic blocks: "${FIELD_BLOCK}" shows one field of the current document (templates), "${COLLECTION_LIST_BLOCK}" lists documents of a collection and repeats its "item" slot per document, "${REPEAT_BLOCK}" repeats its "item" slot per row of an array or hasMany field of the current document.`,
421
+ `Forms on pages (when the list has a "${FORM_BLOCK}" block): build a form right on the page. A "${FORM_BLOCK}" block in mode "build" holds its own field blocks (formText, formEmail, formTextarea, formSelect, formRadio, formCheckbox, …), one "${FORM_SUBMIT_BLOCK}" block and layout blocks in its "${FORM_SLOT}" slot. Field blocks and "${FORM_SUBMIT_BLOCK}" go only inside a Form block (at any depth). Each field's \`name\` is unique in its form. The form's settings (title, submitButtonLabel, confirmationType, confirmationMessage, redirect, emails, spamProtection) are props of the Form block. Publishing the page saves the form to the forms collection. Mode "saved" shows an existing form instead (\`form\`: its id).`,
410
422
  ].join('\n\n'),
411
423
  parameters: { collection: collectionArg },
412
424
  handler: async (_args, req) => text({
413
425
  guide: LAYOUT_GUIDE,
414
- blocks: blocks.map(describeBlock),
426
+ blocks: blocksOf(req).map(describeBlock),
415
427
  ...(await siteClassesOf(req)),
416
428
  ...(await variablesOf(req)),
417
429
  sections: sections.length,
@@ -426,7 +438,8 @@ export function builderMcpTools(options) {
426
438
  routing: { kind: 'collection', action: 'read' },
427
439
  description: 'Returns the JSON Schema (draft 2020-12) of one block type: its props, className, slots and motion (animations, under $defs.$motion), with nested child block schemas under $defs. Use it to write valid props.',
428
440
  parameters: { collection: collectionArg, type: z.string().min(1).describe('Block type from listBlocks.') },
429
- handler: async (args) => {
441
+ handler: async (args, req) => {
442
+ const blocks = blocksOf(req);
430
443
  const def = blocks.find((b) => b.type === args.type);
431
444
  if (!def)
432
445
  return fail(`Unknown block type "${String(args.type)}". Known types: ${blocks.map((b) => b.type).join(', ')}.`);
@@ -448,6 +461,7 @@ export function builderMcpTools(options) {
448
461
  full: z.boolean().optional().describe('Include the full block JSON. Default false.'),
449
462
  },
450
463
  handler: async (args, req) => {
464
+ const blocks = blocksOf(req);
451
465
  const all = await allSections(req);
452
466
  const list = all.filter((s) => !args.category || s.category === args.category);
453
467
  return text({
@@ -495,6 +509,7 @@ export function builderMcpTools(options) {
495
509
  .describe('Saved sections only. true: a copy that stays in sync with the saved section (default for components). false: plain blocks.'),
496
510
  },
497
511
  handler: async (args, req) => {
512
+ const blocks = blocksOf(req);
498
513
  const all = await allSections(req);
499
514
  const found = findSectionVersion(all, String(args.sectionId), typeof args.variant === 'string' ? args.variant : undefined);
500
515
  if (typeof found === 'string')
@@ -541,6 +556,7 @@ export function builderMcpTools(options) {
541
556
  ].join('\n\n'),
542
557
  parameters: { collection: collectionArg, id: idArg, locale: localeArg },
543
558
  handler: async (args, req) => {
559
+ const blocks = blocksOf(req);
544
560
  const collection = String(args.collection);
545
561
  const at = localeArgOf(req, collection, args.locale);
546
562
  if (typeof at === 'string')
@@ -645,6 +661,7 @@ export function builderMcpTools(options) {
645
661
  layout: z.unknown().optional().describe('A layout { version: 1, blocks: [...] }. Leave out to check the saved draft.'),
646
662
  },
647
663
  handler: async (args, req) => {
664
+ const blocks = blocksOf(req);
648
665
  let layout = args.layout;
649
666
  if (typeof layout === 'string') {
650
667
  try {
@@ -700,6 +717,8 @@ export function builderMcpTools(options) {
700
717
  return text({ valid: blocking.length === 0, errors: blocking, warnings });
701
718
  },
702
719
  };
720
+ /** The site's absolute origin, for links. */
721
+ const siteOf = (req) => (options.siteUrl || req.payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL || (req.url ? new URL(req.url).origin : '')).replace(/\/$/, '');
703
722
  const getPreviewUrl = {
704
723
  name: 'getPreviewUrl',
705
724
  routing: { kind: 'collection', action: 'read' },
@@ -714,10 +733,7 @@ export function builderMcpTools(options) {
714
733
  catch (error) {
715
734
  return fail(errorMessage(error));
716
735
  }
717
- const site = (options.siteUrl ||
718
- req.payload.config.serverURL ||
719
- process.env.NEXT_PUBLIC_SERVER_URL ||
720
- (req.url ? new URL(req.url).origin : '')).replace(/\/$/, '');
736
+ const site = siteOf(req);
721
737
  const absolute = (path) => !path ? undefined : /^https?:\/\//.test(path) ? path : `${site}${path.startsWith('/') ? '' : '/'}${path}`;
722
738
  const url = absolute(documentPath(options.collections[collection]?.url, doc));
723
739
  const previewUrl = absolute(await draftPreviewPath(req, collection, doc));
@@ -775,7 +791,10 @@ export function builderMcpTools(options) {
775
791
  };
776
792
  // Editable classes: listClasses, getClass, upsertClass, deleteClass.
777
793
  const classTools = options.classes === false ? [] : classMcpTools(options.classes);
778
- const tools = [listBlocks, getBlockSchema, listSections, insertSection, getLayout, applyOperationsTool, validateLayoutTool, getPreviewUrl, generateImage, ...classTools];
794
+ const formTools = formsSlug
795
+ ? formMcpTools({ slug: formsSlug, apply, currentLayout, loadDraft, warnings: touchedWarnings, siteOf, text, fail })
796
+ : [];
797
+ const tools = [listBlocks, getBlockSchema, listSections, insertSection, getLayout, applyOperationsTool, validateLayoutTool, getPreviewUrl, generateImage, ...classTools, ...formTools];
779
798
  if (!templatesSlug)
780
799
  return tools;
781
800
  const listTemplates = {
@@ -58,6 +58,7 @@ export declare function describeBlock(def: BlockDefinition): {
58
58
  slots: {
59
59
  [k: string]: {
60
60
  label?: string | undefined;
61
+ description?: string | undefined;
61
62
  accepts: string | string[];
62
63
  minBlocks?: number | undefined;
63
64
  maxBlocks?: number | undefined;
@@ -180,6 +180,7 @@ export function describeBlock(def) {
180
180
  name,
181
181
  {
182
182
  ...(slot.label ? { label: slot.label } : {}),
183
+ ...(slot.description ? { description: slot.description } : {}),
183
184
  accepts: slot.allow && !slot.allow.includes('*') ? slot.allow : 'any block',
184
185
  ...(typeof slot.min === 'number' ? { minBlocks: slot.min } : {}),
185
186
  ...(typeof slot.max === 'number' ? { maxBlocks: slot.max } : {}),
@@ -0,0 +1,30 @@
1
+ import type { CollectionConfig, Field } from 'payload';
2
+ import type { BlockDefinition } from '../core/types.js';
3
+ import type { RegionOption } from '../core/regions.js';
4
+ import { FORM_SETTINGS_REGION } from '../forms/blocks.js';
5
+ export { FORM_SETTINGS_REGION };
6
+ export type FormsOptions = {
7
+ /** Slug of the form-builder plugin's forms collection. Default "forms". */
8
+ collection?: string;
9
+ };
10
+ /** The blocks field of a form: the form-builder plugin names it `fields`. */
11
+ export declare const FORM_FIELDS_FIELD = "fields";
12
+ export type ResolvedForms = {
13
+ slug: string;
14
+ /** The builder definitions of the form's field blocks (`formText`, `formEmail`, …). */
15
+ blocks: BlockDefinition[];
16
+ /** The collection's builder options. */
17
+ collection: {
18
+ field: string;
19
+ regions: RegionOption[];
20
+ sections: false;
21
+ };
22
+ /** The form's settings (title, submit button, confirmation, emails, other groups), in panel order. */
23
+ settings: string[];
24
+ /** The Form block's settings fields for pages: the same fields, in folding sections (`formSettingsFields`). */
25
+ settingsFields: Field[];
26
+ /** Slug of the form submissions collection (the collection with `submissionData`), or null. */
27
+ submissions: string | null;
28
+ };
29
+ /** Checks the `forms` option against the config. Null when it is off. */
30
+ export declare function resolveForms(option: FormsOptions | boolean | undefined, collections: readonly CollectionConfig[], listed: Record<string, unknown>): ResolvedForms | null;
@@ -0,0 +1,63 @@
1
+ // The `forms` option: the full-screen builder for the forms of `@payloadcms/plugin-form-builder`.
2
+ // A form's `fields` is a Payload blocks field, so the builder edits it in place like any
3
+ // collection whose builder field is its own blocks field (one source of truth, no copy). The
4
+ // form's other fields (title, submit button, confirmation, emails) are a page region with
5
+ // `panel: true`: the inspector edits them when no field is selected, in folding sections (General,
6
+ // After submit, Mail). Every other top-level group field of the collection (for example spam
7
+ // protection settings) joins the region and folds on its own. Form fields are not page sections:
8
+ // the builder offers no sections there.
9
+ import { fromPayloadBlocks } from '../blocks/payload.js';
10
+ import { FORM_SETTINGS_REGION, formFieldBlocks } from '../forms/blocks.js';
11
+ import { FORM_SETTINGS_SECTIONS, formSettingNames, formSettingsFields } from '../forms/pageForms.js';
12
+ export { FORM_SETTINGS_REGION };
13
+ /** The blocks field of a form: the form-builder plugin names it `fields`. */
14
+ export const FORM_FIELDS_FIELD = 'fields';
15
+ /** Checks the `forms` option against the config. Null when it is off. */
16
+ export function resolveForms(option, collections, listed) {
17
+ if (!option)
18
+ return null;
19
+ const slug = (option === true ? undefined : option.collection) ?? 'forms';
20
+ const source = collections.find((c) => c.slug === slug);
21
+ if (!source) {
22
+ throw new Error(`[websiteBuilder] \`forms\`: there is no "${slug}" collection. Add formBuilderPlugin() to \`plugins\` before websiteBuilder(), or set \`forms.collection\` to its slug.`);
23
+ }
24
+ if (listed[slug]) {
25
+ throw new Error(`[websiteBuilder] \`forms\` and \`collections\` both name "${slug}". Leave it out of \`collections\`: the \`forms\` option sets it up.`);
26
+ }
27
+ const field = source.fields.find((f) => 'name' in f && f.name === FORM_FIELDS_FIELD);
28
+ if (!field || field.type !== 'blocks') {
29
+ throw new Error(`[websiteBuilder] \`forms\`: "${slug}" has no "${FORM_FIELDS_FIELD}" blocks field. Is it the form-builder plugin's forms collection?`);
30
+ }
31
+ const configs = (field.blocks ?? []).filter((b) => typeof b === 'object' && b !== null);
32
+ const names = new Set(source.fields.flatMap((f) => ('name' in f && typeof f.name === 'string' ? [f.name] : [])));
33
+ const sections = FORM_SETTINGS_SECTIONS.map((section) => ({ label: section.label, fields: section.fields.filter((name) => names.has(name)) })).filter((s) => s.fields.length > 0);
34
+ // Other top-level groups (spam protection, …) fold on their own after the sections.
35
+ const settings = formSettingNames(source.fields);
36
+ // The same setting fields as Form block props: simple `admin.condition` functions become builder conditions.
37
+ const chosen = source.fields.filter((f) => 'name' in f && settings.includes(f.name));
38
+ const converted = fromPayloadBlocks([{ slug: 'formSettings', fields: chosen }], { onWarning: false })[0]?.fields ?? [];
39
+ return {
40
+ slug,
41
+ blocks: formFieldBlocks(configs),
42
+ collection: {
43
+ field: FORM_FIELDS_FIELD,
44
+ regions: settings.length > 0 ? [{ name: FORM_SETTINGS_REGION, label: 'Form settings', fields: settings, panel: true, sections }] : [],
45
+ sections: false,
46
+ },
47
+ settings,
48
+ settingsFields: formSettingsFields(converted),
49
+ submissions: collections.find((c) => hasFieldNamed(c.fields, 'submissionData') && hasFieldNamed(c.fields, 'form'))?.slug ?? null,
50
+ };
51
+ }
52
+ /** True when a data field of this name is in the list, also inside rows, collapsibles and unnamed tabs. */
53
+ function hasFieldNamed(fields, name) {
54
+ return fields.some((f) => {
55
+ if ('name' in f && f.name === name)
56
+ return true;
57
+ if (!('name' in f && f.name) && 'fields' in f && Array.isArray(f.fields))
58
+ return hasFieldNamed(f.fields, name);
59
+ if (f.type === 'tabs')
60
+ return f.tabs.some((tab) => !('name' in tab && tab.name) && hasFieldNamed(tab.fields, name));
61
+ return false;
62
+ });
63
+ }