payload-canvas 0.5.1 → 0.6.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 (194) hide show
  1. package/README.md +333 -28
  2. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  3. package/dist/admin/ArrayRowLabel.js +21 -0
  4. package/dist/admin/DocumentEditView.js +9 -2
  5. package/dist/admin/client.d.ts +1 -0
  6. package/dist/admin/client.js +2 -0
  7. package/dist/admin/editor/Editor.js +8 -1
  8. package/dist/admin/editor/Inspector.js +23 -17
  9. package/dist/admin/editor/Library.d.ts +2 -2
  10. package/dist/admin/editor/Library.js +7 -5
  11. package/dist/admin/editor/Outline.js +20 -12
  12. package/dist/admin/editor/Overlay.js +6 -4
  13. package/dist/admin/editor/actions.d.ts +7 -2
  14. package/dist/admin/editor/actions.js +44 -12
  15. package/dist/admin/editor/assistant/AssistantPanel.js +32 -20
  16. package/dist/admin/editor/comments/controller.d.ts +7 -0
  17. package/dist/admin/editor/comments/controller.js +12 -0
  18. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  19. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  20. package/dist/admin/editor/dnd/smooth.js +1 -1
  21. package/dist/admin/editor/editor.scss +28 -0
  22. package/dist/admin/editor/fields/ArrayField.js +3 -3
  23. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  24. package/dist/admin/editor/fields/FormBlock.js +167 -0
  25. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  26. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  27. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  28. package/dist/admin/editor/fields/GroupField.js +30 -1
  29. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  30. package/dist/admin/editor/fields/MergeTags.js +62 -0
  31. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  32. package/dist/admin/editor/fields/arrayRows.js +0 -4
  33. package/dist/admin/editor/fields/fields.scss +150 -0
  34. package/dist/admin/editor/fields/values.d.ts +0 -2
  35. package/dist/admin/editor/fields/values.js +0 -14
  36. package/dist/admin/editor/icons.d.ts +3 -0
  37. package/dist/admin/editor/icons.js +3 -0
  38. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  39. package/dist/admin/editor/insert/picker.d.ts +3 -2
  40. package/dist/admin/editor/insert/picker.js +9 -3
  41. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  42. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  43. package/dist/admin/editor/layout/leftTabs.js +18 -0
  44. package/dist/admin/editor/media/ImageEditor.d.ts +8 -2
  45. package/dist/admin/editor/media/ImageEditor.js +16 -10
  46. package/dist/admin/editor/media/media.scss +12 -2
  47. package/dist/admin/editor/media/model.d.ts +10 -1
  48. package/dist/admin/editor/media/model.js +19 -0
  49. package/dist/admin/editor/menu/blockMenu.js +3 -3
  50. package/dist/admin/editor/names.d.ts +9 -0
  51. package/dist/admin/editor/names.js +18 -0
  52. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  53. package/dist/admin/editor/regions/RegionFields.js +122 -0
  54. package/dist/admin/editor/regions/RegionPane.js +5 -3
  55. package/dist/admin/editor/regions/RegionRows.js +2 -2
  56. package/dist/admin/editor/regions/required.d.ts +16 -0
  57. package/dist/admin/editor/regions/required.js +43 -0
  58. package/dist/admin/editor/renderField.d.ts +9 -2
  59. package/dist/admin/editor/renderField.js +86 -32
  60. package/dist/admin/editor/runtime.d.ts +3 -2
  61. package/dist/admin/editor/runtime.js +12 -18
  62. package/dist/admin/editor/styles/StylesPanel.js +4 -2
  63. package/dist/admin/editor/styles/context.js +9 -4
  64. package/dist/admin/editor/topbar/ContentModeToggle.js +1 -1
  65. package/dist/admin/editor/topbar/DocumentActions.js +4 -3
  66. package/dist/admin/editor/topbar/contentMode.scss +0 -9
  67. package/dist/admin/editor/topbar/topbar.scss +1 -41
  68. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  69. package/dist/admin/editor/ui/Tabs.js +17 -0
  70. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  71. package/dist/admin/forms/SubmissionCells.js +31 -0
  72. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  73. package/dist/admin/forms/SubmissionView.js +106 -0
  74. package/dist/admin/forms/submissionData.d.ts +32 -0
  75. package/dist/admin/forms/submissionData.js +63 -0
  76. package/dist/admin/forms/submissions.scss +197 -0
  77. package/dist/admin/rsc.d.ts +2 -0
  78. package/dist/admin/rsc.js +5 -0
  79. package/dist/ai/endpoint.d.ts +5 -0
  80. package/dist/ai/endpoint.js +18 -8
  81. package/dist/ai/prompt.d.ts +8 -0
  82. package/dist/ai/prompt.js +30 -0
  83. package/dist/ai/tools.d.ts +6 -1
  84. package/dist/ai/tools.js +90 -6
  85. package/dist/blocks/builtins/carousel.js +10 -1
  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 +21 -2
  181. package/dist/plugin/links.js +32 -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/render/LayoutOutlet.d.ts +7 -3
  189. package/dist/react/render/LayoutOutlet.js +9 -4
  190. package/dist/react/render/RenderLayout.js +13 -7
  191. package/dist/react/render/resolve.d.ts +1 -0
  192. package/dist/react/render/resolve.js +5 -1
  193. package/dist/react/server.js +19 -0
  194. package/package.json +5 -1
@@ -0,0 +1,167 @@
1
+ // More field types for `@payloadcms/plugin-form-builder`, as Payload block configs for the
2
+ // plugin's `fields` option: phone, web address, hidden field, consent box and file upload. And the
3
+ // email fields of a form, Contact Form 7 style, for the plugin's `formOverrides.fields`.
4
+ // Client-safe. The app renders the field types; `formSubmissionConditions` checks their answers
5
+ // and `formFileUploads` stores the files.
6
+ import { fileCountFields } from './fieldSettings.js';
7
+ /** `admin.custom.builderMergeTags`: the builder adds an "Insert field" menu with the form's merge tags. */
8
+ export const MERGE_TAGS_MARKER = 'builderMergeTags';
9
+ const mergeTags = { [MERGE_TAGS_MARKER]: true };
10
+ const name = { name: 'name', type: 'text', label: 'Name', required: true, admin: { description: 'Lowercase, no spaces. Emails show the answer with {{name}}.' } };
11
+ const label = { name: 'label', type: 'text', label: 'Label', localized: true };
12
+ const width = { name: 'width', type: 'number', label: 'Field width (percentage)', min: 10, max: 100 };
13
+ const required = { name: 'required', type: 'checkbox', label: 'Required' };
14
+ const placeholder = { name: 'placeholder', type: 'text', label: 'Placeholder', localized: true };
15
+ const textLike = (slug, singular, plural) => ({
16
+ slug,
17
+ labels: { singular, plural },
18
+ fields: [
19
+ { type: 'row', fields: [name, label] },
20
+ { type: 'row', fields: [width, { name: 'defaultValue', type: 'text', label: 'Default value', localized: true }] },
21
+ placeholder,
22
+ required,
23
+ ],
24
+ });
25
+ /** A phone number. The form checks that it has 6 to 15 digits. */
26
+ export const phoneFormField = textLike('phone', 'Phone', 'Phones');
27
+ /** A web address. The form checks that it is an http or https address. */
28
+ export const urlFormField = textLike('url', 'Web address', 'Web addresses');
29
+ /** A value sent with every answer that visitors do not see, for example the campaign. */
30
+ export const hiddenFormField = {
31
+ slug: 'hidden',
32
+ labels: { singular: 'Hidden field', plural: 'Hidden fields' },
33
+ fields: [
34
+ { type: 'row', fields: [name, { ...label, admin: { description: 'For emails and submissions only. Visitors do not see it.' } }] },
35
+ { name: 'defaultValue', type: 'text', label: 'Value', admin: { description: 'Sent with every answer.' } },
36
+ ],
37
+ };
38
+ /** A box to tick whose text is rich text, so it can link to the privacy policy. */
39
+ export const consentFormField = {
40
+ slug: 'consent',
41
+ labels: { singular: 'Consent', plural: 'Consents' },
42
+ fields: [
43
+ { type: 'row', fields: [name, { ...label, admin: { description: 'A short name for emails and submissions.' } }] },
44
+ {
45
+ name: 'text',
46
+ type: 'richText',
47
+ label: 'Text',
48
+ localized: true,
49
+ admin: { description: 'The text next to the box. Select words and add a link, for example to the privacy policy.' },
50
+ },
51
+ width,
52
+ { ...required, defaultValue: true },
53
+ ],
54
+ };
55
+ /** Default and upper limit of a file field's size, in MB. */
56
+ export const FILE_FIELD_MAX_MB = 10;
57
+ /** Files the visitor uploads: one, or several when "Allow several files" is on. `formFileUploads` stores them in a private upload collection. */
58
+ export const fileFormField = {
59
+ slug: 'file',
60
+ labels: { singular: 'File upload', plural: 'File uploads' },
61
+ fields: [
62
+ { type: 'row', fields: [name, label] },
63
+ width,
64
+ required,
65
+ {
66
+ name: 'accept',
67
+ type: 'text',
68
+ label: 'Allowed file types',
69
+ defaultValue: 'image/*, application/pdf',
70
+ admin: { description: 'File types or endings, separated by commas, for example "image/*, application/pdf, .docx". Empty: images, PDF, office documents, text and CSV. HTML, SVG, scripts and XML are never taken.' },
71
+ },
72
+ {
73
+ name: 'maxSize',
74
+ type: 'number',
75
+ label: 'Largest file (MB)',
76
+ defaultValue: 5,
77
+ min: 0.1,
78
+ max: FILE_FIELD_MAX_MB,
79
+ admin: { description: `For each file. At most ${FILE_FIELD_MAX_MB} MB.` },
80
+ },
81
+ ...fileCountFields(),
82
+ ],
83
+ };
84
+ /** The extra field types by slug, for the plugin's `fields` option. */
85
+ export const moreFormFields = {
86
+ phone: phoneFormField,
87
+ url: urlFormField,
88
+ hidden: hiddenFormField,
89
+ consent: consentFormField,
90
+ file: fileFormField,
91
+ };
92
+ const tagHelp = 'Type {{name}} for a field’s answer, or use Insert field.';
93
+ /**
94
+ * The fields of one form email: To, From name, From email, Reply-To, CC, BCC, Subject and the body
95
+ * (rich text or custom HTML). The plugin's own names stay, so stored emails keep working; the
96
+ * from name, the body type and the HTML body are new. Every line and the body take merge tags.
97
+ */
98
+ export function formEmailFields() {
99
+ return [
100
+ {
101
+ name: 'emailTo',
102
+ type: 'text',
103
+ label: 'To',
104
+ admin: { placeholder: 'owner@example.com or {{email}}', description: `Addresses separated by commas. {{email}} sends to the visitor. ${tagHelp}`, custom: mergeTags },
105
+ },
106
+ {
107
+ type: 'row',
108
+ fields: [
109
+ { name: 'fromName', type: 'text', label: 'From name', admin: { placeholder: 'Your site', custom: mergeTags } },
110
+ { name: 'emailFrom', type: 'text', label: 'From email', admin: { placeholder: 'noreply@example.com', description: 'Empty: the site’s address.' } },
111
+ ],
112
+ },
113
+ { name: 'replyTo', type: 'text', label: 'Reply-To', admin: { placeholder: '{{email}}', custom: mergeTags } },
114
+ {
115
+ type: 'row',
116
+ fields: [
117
+ { name: 'cc', type: 'text', label: 'CC', admin: { custom: mergeTags } },
118
+ { name: 'bcc', type: 'text', label: 'BCC', admin: { custom: mergeTags } },
119
+ ],
120
+ },
121
+ { name: 'subject', type: 'text', label: 'Subject', localized: true, required: true, defaultValue: 'New message: {{formTitle}}', admin: { custom: mergeTags } },
122
+ {
123
+ name: 'bodyType',
124
+ type: 'radio',
125
+ label: 'Body',
126
+ defaultValue: 'richText',
127
+ options: [
128
+ { label: 'Rich text', value: 'richText' },
129
+ { label: 'Custom HTML', value: 'html' },
130
+ ],
131
+ admin: { layout: 'horizontal' },
132
+ },
133
+ {
134
+ name: 'message',
135
+ type: 'richText',
136
+ label: 'Message',
137
+ localized: true,
138
+ admin: {
139
+ description: `${tagHelp} {{*}} adds every answer as a table.`,
140
+ condition: (_, siblings) => siblings?.bodyType !== 'html',
141
+ custom: { ...mergeTags, builderCondition: { field: 'bodyType', notEquals: 'html' } },
142
+ },
143
+ },
144
+ {
145
+ name: 'html',
146
+ type: 'code',
147
+ label: 'HTML body',
148
+ localized: true,
149
+ admin: {
150
+ language: 'html',
151
+ description: `Your own HTML. ${tagHelp} {{*}} adds every answer as a table. Answers are escaped.`,
152
+ condition: (_, siblings) => siblings?.bodyType === 'html',
153
+ custom: { ...mergeTags, builderCondition: { field: 'bodyType', equals: 'html' } },
154
+ },
155
+ },
156
+ ];
157
+ }
158
+ /**
159
+ * The forms collection's fields with the emails of `formEmailFields`, for
160
+ * `formBuilderPlugin({ formOverrides: { fields: ({ defaultFields }) => withFormEmailFields(defaultFields) } })`.
161
+ * The `emails` array keeps its access and description.
162
+ */
163
+ export function withFormEmailFields(fields) {
164
+ return fields.map((field) => 'name' in field && field.name === 'emails' && field.type === 'array'
165
+ ? { ...field, label: 'Emails', labels: { singular: 'Email', plural: 'Emails' }, fields: formEmailFields() }
166
+ : field);
167
+ }
@@ -0,0 +1,78 @@
1
+ import type { BlockDefinition, Layout, Operation } from '../core/types.js';
2
+ import { type FormFieldConditions } from './conditions.js';
3
+ /** The format guide for agents: field types, props and display conditions. */
4
+ export declare const FORM_FIELDS_GUIDE: string;
5
+ /** One field of a form, as agents read it. */
6
+ export type FormFieldView = {
7
+ id: string;
8
+ type: string;
9
+ name?: string;
10
+ label?: string;
11
+ required?: boolean;
12
+ placeholder?: string;
13
+ /** The field's own classes (its box), width included. */
14
+ className?: string;
15
+ defaultValue?: unknown;
16
+ options?: unknown;
17
+ /** "message" fields: the text. */
18
+ message?: string;
19
+ conditions?: FormFieldConditions;
20
+ /** The conditions in one sentence: "Shows when Topic equals “sales”". */
21
+ shows?: string;
22
+ /** Any other props the field type has. */
23
+ [key: string]: unknown;
24
+ };
25
+ /** One change of a form's fields. `field` is the field's name or its id. */
26
+ export type FormFieldChange = {
27
+ action: 'add';
28
+ type: string;
29
+ values?: Record<string, unknown>;
30
+ index?: number;
31
+ } | {
32
+ action: 'update';
33
+ field: string;
34
+ values?: Record<string, unknown>;
35
+ unset?: string[];
36
+ } | {
37
+ action: 'move';
38
+ field: string;
39
+ index: number;
40
+ } | {
41
+ action: 'remove';
42
+ field: string;
43
+ } | {
44
+ action: 'setConditions';
45
+ field: string;
46
+ conditions: FormFieldConditions | null;
47
+ };
48
+ /** The fields of a form layout (the decoded `fields` blocks), in order. */
49
+ export declare function formFieldsOf(layout: Layout): FormFieldView[];
50
+ /** The field types a form offers, with their props, for agents. */
51
+ export declare function formFieldTypes(definitions: readonly BlockDefinition[]): {
52
+ type: string;
53
+ label: string;
54
+ description?: string | undefined;
55
+ props: {
56
+ name: string;
57
+ type: string;
58
+ required?: boolean | undefined;
59
+ }[];
60
+ }[];
61
+ /** A field name made from a label: "Company size" -> "company_size". */
62
+ export declare function nameFromLabel(label: string): string;
63
+ export type FormFieldOpsResult = {
64
+ ok: true;
65
+ ops: Operation[];
66
+ notes: string[];
67
+ } | {
68
+ ok: false;
69
+ error: string;
70
+ };
71
+ /**
72
+ * The builder operations for a list of field changes, applied in order (each change sees the
73
+ * ones before it). `definitions` are the form's field block definitions: they give the types and
74
+ * the start values of a new field. Checks names (unique, valid) and conditions (rules name other
75
+ * fields). Renaming a field rewrites the rules that read it. The operations themselves are checked
76
+ * again by the live session (prop types, required props on publish).
77
+ */
78
+ export declare function formFieldOps(layout: Layout, changes: readonly FormFieldChange[], definitions: readonly BlockDefinition[]): FormFieldOpsResult;
@@ -0,0 +1,378 @@
1
+ // Form field edits for AI agents: the MCP tools (mcp/forms.ts) and the editor's assistant
2
+ // (ai/tools.ts). An agent names fields by their `name` (or block id) and sends small changes
3
+ // ("add an email field", "make phone required", "show company only when topic is sales").
4
+ // `formFieldOps` turns them into the builder's normal operations, so they reach the form's live
5
+ // session like any editor change, and an open form builder shows them at once.
6
+ // Pure: no Payload, no I/O.
7
+ import { isRichText, plainToRichText, richTextToPlain } from '../core/bindings.js';
8
+ import { dataFields } from '../core/fields.js';
9
+ import { createId } from '../core/ids.js';
10
+ import { isPlainObject } from '../core/tree.js';
11
+ import { describeConditions, FORM_CONDITION_OPERATORS, FORM_CONDITIONS_FIELD } from './conditions.js';
12
+ import { formFieldSlug, formFieldType } from './blocks.js';
13
+ import { FORM_FIELD_CLASS_KEY, FORM_FIELD_WIDTH_CLASSES, FORM_FIELD_WIDTH_KEY } from './fieldSettings.js';
14
+ /** The format guide for agents: field types, props and display conditions. */
15
+ export const FORM_FIELDS_GUIDE = [
16
+ 'FORM FIELDS. A form is a list of fields, shown in order. Each field has a `type` and props:',
17
+ '- name (text, required): the key of the answer in a submission. Letters, digits and _ only, unique in the form (e.g. "email", "company_size").',
18
+ '- label (text): the question people see. required (boolean): the form refuses to send without an answer.',
19
+ '- placeholder (text, where the type has it).',
20
+ '- Where the site has them (see `fieldTypes`): description (help text under the field), labelVisibility ("visible" or "hidden": screen readers still read a hidden label), display for radio ("list", "inline", "buttons", "cards"), multiple and maxFiles for file (several files, at most maxFiles).',
21
+ `- className (Tailwind classes of the box around the field; null clears them). Looks are classes, the width too: there is no width setting. The fields wrap in a row with a 1rem gap, so "${FORM_FIELD_WIDTH_CLASSES[50]}" is half a row from the sm breakpoint (two fields side by side), "${FORM_FIELD_WIDTH_CLASSES[33]}" a third, "${FORM_FIELD_WIDTH_CLASSES[67]}" two thirds. No width class: full width. update replaces all of the field's classes, so send the ones to keep too.`,
22
+ '- defaultValue: text for text-like fields, a number for "number", true/false for "checkbox".',
23
+ '- options (select, radio): [{ label, value }]. You may send plain strings; each becomes { label, value } with a value made from the label.',
24
+ '- message ("message" type only): text shown between the fields. Send plain text (one paragraph per line); it is stored as rich text. A message has no name and collects no answer.',
25
+ 'Types (the form\'s `fieldTypes` lists the ones this site has and their props): text (one line), email (checks the address), textarea (long text), number, select (dropdown), radio, checkbox (true/false, e.g. accept the terms), country, state (US states), date, message, upload, payment.',
26
+ `DISPLAY CONDITIONS. A field may show only when other fields have some values: conditions = { match: "all" | "any", rules: [{ field, operator, value }] }. field = the name of another field of the same form. operator: ${FORM_CONDITION_OPERATORS.join(', ')}. value is text, needed for equals, notEquals and contains (a checkbox compares with "true" or "false"). Text compares without case. match "all" (default) needs every rule, "any" one rule. A hidden field is never required, and its answer is not sent. A rule that reads a hidden field sees it as empty. null or no rules: the field always shows.`,
27
+ 'Example: show "company" only when "topic" equals "sales": { "action": "setConditions", "field": "company", "conditions": { "rules": [{ "field": "topic", "operator": "equals", "value": "sales" }] } }.',
28
+ ].join('\n');
29
+ const KNOWN_KEYS = new Set(['id', 'type']);
30
+ /** The fields of a form layout (the decoded `fields` blocks), in order. */
31
+ export function formFieldsOf(layout) {
32
+ return layout.blocks.map((block) => formFieldView(block, layout.blocks));
33
+ }
34
+ function formFieldView(block, all) {
35
+ const props = (block.props ?? {});
36
+ const out = { id: block.id, type: formFieldSlug(block.type) ?? block.type };
37
+ if (block.className)
38
+ out.className = block.className;
39
+ for (const [key, value] of Object.entries(props)) {
40
+ if (KNOWN_KEYS.has(key) || key === FORM_FIELD_WIDTH_KEY || value === null || value === undefined || value === '')
41
+ continue;
42
+ if (key === 'message') {
43
+ out.message = isRichText(value) ? richTextToPlain(value) : String(value);
44
+ continue;
45
+ }
46
+ if (key === FORM_CONDITIONS_FIELD) {
47
+ const conditions = cleanConditions(value);
48
+ if (!conditions)
49
+ continue;
50
+ out.conditions = conditions;
51
+ const labels = new Map(all.map((b) => [String(b.props?.name ?? ''), String(b.props?.label ?? b.props?.name ?? '')]));
52
+ const shows = describeConditions({ conditions }, (name) => labels.get(name) || name);
53
+ if (shows)
54
+ out.shows = shows;
55
+ continue;
56
+ }
57
+ if (Array.isArray(value)) {
58
+ // Array rows keep their values, without Payload's row ids.
59
+ out[key] = value.map((row) => (isPlainObject(row) ? Object.fromEntries(Object.entries(row).filter(([k]) => k !== 'id')) : row));
60
+ continue;
61
+ }
62
+ out[key] = value;
63
+ }
64
+ return out;
65
+ }
66
+ /** Conditions with rules, without row ids. Null when there is no rule. */
67
+ function cleanConditions(value) {
68
+ if (!isPlainObject(value))
69
+ return null;
70
+ const rules = Array.isArray(value.rules)
71
+ ? value.rules.filter(isPlainObject).map((rule) => ({
72
+ field: typeof rule.field === 'string' ? rule.field : null,
73
+ operator: (typeof rule.operator === 'string' ? rule.operator : 'equals'),
74
+ ...(typeof rule.value === 'string' && rule.value !== '' ? { value: rule.value } : {}),
75
+ }))
76
+ : [];
77
+ if (rules.length === 0)
78
+ return null;
79
+ return { ...(value.match === 'any' ? { match: 'any' } : {}), rules };
80
+ }
81
+ /** The field types a form offers, with their props, for agents. */
82
+ export function formFieldTypes(definitions) {
83
+ return definitions.flatMap((def) => {
84
+ const slug = formFieldSlug(def.type);
85
+ if (!slug)
86
+ return [];
87
+ // Hidden fields (the plugin's old `width`) are no setting to offer.
88
+ const props = dataFields(def.fields)
89
+ .filter((f) => f.name !== FORM_CONDITIONS_FIELD && !f.admin?.hidden)
90
+ .map((f) => ({ name: f.name, type: f.type, ...(f.required ? { required: true } : {}) }));
91
+ return [{ type: slug, label: def.label, ...(def.description ? { description: def.description } : {}), props }];
92
+ });
93
+ }
94
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
95
+ /** Lowercase ASCII words of a label joined by `separator`, at most 40 characters ("Été 2026" -> "ete_2026"). */
96
+ function slugOf(label, separator) {
97
+ return label
98
+ .normalize('NFKD')
99
+ .replace(/[\u0300-\u036f]/g, '')
100
+ .toLowerCase()
101
+ .replace(/[^a-z0-9]+/g, separator)
102
+ .slice(0, 40)
103
+ .split(separator)
104
+ .filter(Boolean)
105
+ .join(separator);
106
+ }
107
+ /** A field name made from a label: "Company size" -> "company_size". */
108
+ export function nameFromLabel(label) {
109
+ const base = slugOf(label, '_');
110
+ return base === '' ? 'field' : /^\d/.test(base) ? `field_${base}` : base;
111
+ }
112
+ /** `base`, else `base2`, `base3`, … : the first name no field has. */
113
+ function freeName(base, taken) {
114
+ if (!taken.has(base))
115
+ return base;
116
+ let n = 2;
117
+ while (taken.has(`${base}${n}`))
118
+ n++;
119
+ return `${base}${n}`;
120
+ }
121
+ /** An option value made from its label: "Not sure" -> "not-sure", "5k to 20k" -> "5k-to-20k". */
122
+ const optionValue = (label) => slugOf(label, '-') || 'option';
123
+ /** Why a field change may not set `width`. */
124
+ const WIDTH_PROBLEM = `fields have no \`width\` setting: set the width with classes, e.g. { "className": "${FORM_FIELD_WIDTH_CLASSES[50]}" } for half a row.`;
125
+ /** The classes a change sets: `className` (or `cssClass`, the plugin's name). Undefined: no change. */
126
+ function classNameOf(values) {
127
+ const value = values.className !== undefined ? values.className : values[FORM_FIELD_CLASS_KEY];
128
+ if (value === undefined)
129
+ return undefined;
130
+ return typeof value === 'string' && value.trim() ? value.trim().replace(/\s+/g, ' ') : null;
131
+ }
132
+ /** The values with the shapes agents send fixed: options as strings, a message as plain text, conditions. */
133
+ function normalizeValues(values) {
134
+ const out = {};
135
+ for (const [key, value] of Object.entries(values)) {
136
+ if (key === 'id' || key === 'blockType' || key === 'type' || key === 'className' || key === FORM_FIELD_CLASS_KEY)
137
+ continue;
138
+ if (key === FORM_FIELD_WIDTH_KEY)
139
+ return WIDTH_PROBLEM;
140
+ if (key === 'options' && Array.isArray(value)) {
141
+ out.options = value.map((option) => {
142
+ if (typeof option === 'string')
143
+ return { label: option, value: optionValue(option) };
144
+ if (isPlainObject(option) && typeof option.label === 'string' && (option.value === undefined || option.value === '')) {
145
+ return { ...option, value: optionValue(option.label) };
146
+ }
147
+ return option;
148
+ });
149
+ continue;
150
+ }
151
+ if (key === 'message' && typeof value === 'string') {
152
+ out.message = plainToRichText(value);
153
+ continue;
154
+ }
155
+ if (key === FORM_CONDITIONS_FIELD) {
156
+ const conditions = conditionsValue(value);
157
+ if (typeof conditions === 'string')
158
+ return conditions;
159
+ out[key] = conditions;
160
+ continue;
161
+ }
162
+ out[key] = value;
163
+ }
164
+ return out;
165
+ }
166
+ /** Checks the conditions' shape. Null clears them. */
167
+ function conditionsValue(value) {
168
+ if (value === null || value === undefined)
169
+ return null;
170
+ if (!isPlainObject(value))
171
+ return '`conditions` must be { match?, rules: [{ field, operator, value? }] } or null.';
172
+ if (value.match !== undefined && value.match !== null && value.match !== 'all' && value.match !== 'any')
173
+ return '`conditions.match` must be "all" or "any".';
174
+ const rules = value.rules ?? [];
175
+ if (!Array.isArray(rules))
176
+ return '`conditions.rules` must be a list.';
177
+ const out = [];
178
+ for (const [i, rule] of rules.entries()) {
179
+ if (!isPlainObject(rule) || typeof rule.field !== 'string' || !rule.field.trim())
180
+ return `Rule ${i + 1} needs \`field\`: the name of another field.`;
181
+ const operator = rule.operator ?? 'equals';
182
+ if (typeof operator !== 'string' || !FORM_CONDITION_OPERATORS.includes(operator)) {
183
+ return `Rule ${i + 1}: \`operator\` must be one of ${FORM_CONDITION_OPERATORS.join(', ')}.`;
184
+ }
185
+ const needsValue = operator === 'equals' || operator === 'notEquals' || operator === 'contains';
186
+ if (needsValue && (rule.value === undefined || rule.value === null))
187
+ return `Rule ${i + 1}: "${operator}" needs a \`value\`.`;
188
+ out.push({ field: rule.field.trim(), operator: operator, ...(needsValue ? { value: String(rule.value) } : {}) });
189
+ }
190
+ if (out.length === 0)
191
+ return null;
192
+ return { match: value.match === 'any' ? 'any' : 'all', rules: out };
193
+ }
194
+ /**
195
+ * The builder operations for a list of field changes, applied in order (each change sees the
196
+ * ones before it). `definitions` are the form's field block definitions: they give the types and
197
+ * the start values of a new field. Checks names (unique, valid) and conditions (rules name other
198
+ * fields). Renaming a field rewrites the rules that read it. The operations themselves are checked
199
+ * again by the live session (prop types, required props on publish).
200
+ */
201
+ export function formFieldOps(layout, changes, definitions) {
202
+ // A working list: id, type and props of each field, so later changes see earlier ones.
203
+ let fields = layout.blocks.map((b) => ({ id: b.id, type: b.type, props: { ...b.props } }));
204
+ const ops = [];
205
+ const notes = [];
206
+ const ids = new Set(fields.map((f) => f.id));
207
+ const nameOf = (f) => (typeof f.props.name === 'string' ? f.props.name : '');
208
+ const find = (ref) => {
209
+ if (typeof ref !== 'string' || !ref)
210
+ return undefined;
211
+ return fields.find((f) => f.id === ref) ?? fields.find((f) => nameOf(f) === ref);
212
+ };
213
+ const missing = (ref, i) => `Change ${i + 1}: there is no field "${String(ref)}". Fields: ${fields.map((f) => nameOf(f) || f.id).join(', ') || 'none'}.`;
214
+ const checkRules = (conditions, self, i) => {
215
+ if (!isPlainObject(conditions) || !Array.isArray(conditions.rules))
216
+ return null;
217
+ for (const rule of conditions.rules) {
218
+ if (rule.field === self)
219
+ return `Change ${i + 1}: a field cannot depend on itself ("${self}").`;
220
+ if (!fields.some((f) => nameOf(f) === rule.field))
221
+ return `Change ${i + 1}: the rule names "${rule.field}", which is not a field of this form.`;
222
+ }
223
+ return null;
224
+ };
225
+ for (const [i, change] of changes.entries()) {
226
+ if (!isPlainObject(change))
227
+ return { ok: false, error: `Change ${i + 1} must be an object.` };
228
+ switch (change.action) {
229
+ case 'add': {
230
+ const blockType = typeof change.type === 'string' ? (formFieldSlug(change.type) ? change.type : formFieldType(change.type)) : '';
231
+ const def = definitions.find((d) => d.type === blockType);
232
+ if (!def) {
233
+ const known = definitions.map((d) => formFieldSlug(d.type)).filter(Boolean);
234
+ return { ok: false, error: `Change ${i + 1}: unknown field type "${String(change.type)}". This form offers: ${known.join(', ')}.` };
235
+ }
236
+ const values = normalizeValues(isPlainObject(change.values) ? change.values : {});
237
+ if (typeof values === 'string')
238
+ return { ok: false, error: `Change ${i + 1}: ${values}` };
239
+ const named = dataFields(def.fields).some((f) => f.name === 'name');
240
+ const props = {};
241
+ // The type's start values (a label, and `name`), as the editor's insert gives them.
242
+ for (const f of dataFields(def.fields))
243
+ if (f.defaultValue !== undefined && typeof f.defaultValue !== 'function')
244
+ props[f.name] = f.defaultValue;
245
+ Object.assign(props, values);
246
+ if (named) {
247
+ const taken = new Set(fields.map(nameOf).filter(Boolean));
248
+ if (typeof values.name === 'string') {
249
+ if (!NAME.test(values.name))
250
+ return { ok: false, error: `Change ${i + 1}: the name "${values.name}" must use letters, digits and _ only.` };
251
+ if (taken.has(values.name))
252
+ return { ok: false, error: `Change ${i + 1}: another field is already named "${values.name}". Names must be unique.` };
253
+ }
254
+ else {
255
+ const base = typeof values.label === 'string' && values.label.trim() ? nameFromLabel(values.label) : (formFieldSlug(def.type) ?? 'field');
256
+ props.name = freeName(base, taken);
257
+ }
258
+ }
259
+ const problem = checkRules(props[FORM_CONDITIONS_FIELD], String(props.name ?? ''), i);
260
+ if (problem)
261
+ return { ok: false, error: problem };
262
+ let id = createId();
263
+ while (ids.has(id))
264
+ id = createId();
265
+ ids.add(id);
266
+ const index = typeof change.index === 'number' && Number.isInteger(change.index) ? Math.max(0, Math.min(change.index, fields.length)) : fields.length;
267
+ const clean = Object.fromEntries(Object.entries(props).filter(([, v]) => v !== null && v !== undefined));
268
+ const className = classNameOf(isPlainObject(change.values) ? change.values : {});
269
+ ops.push({ type: 'insert', block: { id, type: def.type, props: clean, ...(className ? { className } : {}) }, to: { parentId: null, slot: 'children', index } });
270
+ fields = [...fields.slice(0, index), { id, type: def.type, props: clean }, ...fields.slice(index)];
271
+ if (!named)
272
+ break;
273
+ notes.push(`Added "${String(clean.name)}" (${formFieldSlug(def.type)}) with id ${id}.`);
274
+ break;
275
+ }
276
+ case 'update': {
277
+ const field = find(change.field);
278
+ if (!field)
279
+ return { ok: false, error: missing(change.field, i) };
280
+ const values = normalizeValues(isPlainObject(change.values) ? change.values : {});
281
+ if (typeof values === 'string')
282
+ return { ok: false, error: `Change ${i + 1}: ${values}` };
283
+ const unset = Array.isArray(change.unset) ? change.unset.filter((k) => typeof k === 'string' && k !== 'name') : [];
284
+ const oldName = nameOf(field);
285
+ if ('name' in values) {
286
+ const next = values.name;
287
+ if (typeof next !== 'string' || !NAME.test(next))
288
+ return { ok: false, error: `Change ${i + 1}: the name must use letters, digits and _ only.` };
289
+ if (next !== oldName && fields.some((f) => f !== field && nameOf(f) === next))
290
+ return { ok: false, error: `Change ${i + 1}: another field is already named "${next}".` };
291
+ }
292
+ if (FORM_CONDITIONS_FIELD in values) {
293
+ const problem = checkRules(values[FORM_CONDITIONS_FIELD], typeof values.name === 'string' ? values.name : oldName, i);
294
+ if (problem)
295
+ return { ok: false, error: problem };
296
+ }
297
+ const props = Object.fromEntries(Object.entries(values).filter(([, v]) => v !== undefined));
298
+ const className = classNameOf(isPlainObject(change.values) ? change.values : {});
299
+ if (Object.keys(props).length === 0 && unset.length === 0 && className === undefined)
300
+ return { ok: false, error: `Change ${i + 1}: \`values\` or \`unset\` is needed.` };
301
+ ops.push({
302
+ type: 'update',
303
+ id: field.id,
304
+ ...(Object.keys(props).length > 0 ? { props } : {}),
305
+ ...(unset.length > 0 ? { unsetProps: unset } : {}),
306
+ ...(className !== undefined ? { className } : {}),
307
+ });
308
+ field.props = { ...field.props, ...props };
309
+ for (const key of unset)
310
+ delete field.props[key];
311
+ // A rename: rules that read the old name now read the new one.
312
+ const newName = nameOf(field);
313
+ if (oldName && newName !== oldName) {
314
+ for (const other of fields) {
315
+ const conditions = other.props[FORM_CONDITIONS_FIELD];
316
+ if (other === field || !isPlainObject(conditions) || !Array.isArray(conditions.rules))
317
+ continue;
318
+ if (!conditions.rules.some((r) => isPlainObject(r) && r.field === oldName))
319
+ continue;
320
+ const next = { ...conditions, rules: conditions.rules.map((r) => (isPlainObject(r) && r.field === oldName ? { ...r, field: newName } : r)) };
321
+ ops.push({ type: 'update', id: other.id, props: { [FORM_CONDITIONS_FIELD]: next } });
322
+ other.props = { ...other.props, [FORM_CONDITIONS_FIELD]: next };
323
+ notes.push(`The conditions of "${nameOf(other)}" now read "${newName}".`);
324
+ }
325
+ }
326
+ break;
327
+ }
328
+ case 'move': {
329
+ const field = find(change.field);
330
+ if (!field)
331
+ return { ok: false, error: missing(change.field, i) };
332
+ if (typeof change.index !== 'number' || !Number.isInteger(change.index) || change.index < 0)
333
+ return { ok: false, error: `Change ${i + 1}: \`index\` must be a whole number from 0.` };
334
+ const rest = fields.filter((f) => f !== field);
335
+ const index = Math.min(change.index, rest.length);
336
+ ops.push({ type: 'move', id: field.id, to: { parentId: null, slot: 'children', index } });
337
+ fields = [...rest.slice(0, index), field, ...rest.slice(index)];
338
+ break;
339
+ }
340
+ case 'remove': {
341
+ const field = find(change.field);
342
+ if (!field)
343
+ return { ok: false, error: missing(change.field, i) };
344
+ ops.push({ type: 'remove', id: field.id });
345
+ fields = fields.filter((f) => f !== field);
346
+ const name = nameOf(field);
347
+ const readers = name
348
+ ? fields.filter((f) => {
349
+ const c = f.props[FORM_CONDITIONS_FIELD];
350
+ return isPlainObject(c) && Array.isArray(c.rules) && c.rules.some((r) => isPlainObject(r) && r.field === name);
351
+ })
352
+ : [];
353
+ if (readers.length > 0)
354
+ notes.push(`Rules of ${readers.map((f) => `"${nameOf(f)}"`).join(', ')} still read "${name}", which is gone: such a rule sees an empty value. Change or clear them with setConditions.`);
355
+ break;
356
+ }
357
+ case 'setConditions': {
358
+ const field = find(change.field);
359
+ if (!field)
360
+ return { ok: false, error: missing(change.field, i) };
361
+ const conditions = conditionsValue(change.conditions);
362
+ if (typeof conditions === 'string')
363
+ return { ok: false, error: `Change ${i + 1}: ${conditions}` };
364
+ const problem = checkRules(conditions, nameOf(field), i);
365
+ if (problem)
366
+ return { ok: false, error: problem };
367
+ // No rules: the group stays, empty, as Payload's form leaves it.
368
+ const value = conditions ?? { match: 'all', rules: [] };
369
+ ops.push({ type: 'update', id: field.id, props: { [FORM_CONDITIONS_FIELD]: value } });
370
+ field.props = { ...field.props, [FORM_CONDITIONS_FIELD]: value };
371
+ break;
372
+ }
373
+ default:
374
+ return { ok: false, error: `Change ${i + 1}: \`action\` must be add, update, move, remove or setConditions.` };
375
+ }
376
+ }
377
+ return { ok: true, ops, notes };
378
+ }