payload-canvas 0.5.2 → 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 (193) 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/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/index.d.ts +1 -1
  86. package/dist/blocks/index.js +1 -1
  87. package/dist/blocks/payload.d.ts +7 -0
  88. package/dist/blocks/payload.js +16 -2
  89. package/dist/comments/shared.d.ts +5 -0
  90. package/dist/comments/shared.js +5 -0
  91. package/dist/core/blocks.d.ts +17 -3
  92. package/dist/core/blocks.js +92 -10
  93. package/dist/core/classes.d.ts +5 -0
  94. package/dist/core/classes.js +26 -1
  95. package/dist/core/conditions.d.ts +7 -0
  96. package/dist/core/conditions.js +22 -0
  97. package/dist/core/dropTarget.d.ts +3 -2
  98. package/dist/core/dropTarget.js +7 -1
  99. package/dist/core/index.d.ts +6 -3
  100. package/dist/core/index.js +6 -3
  101. package/dist/core/payloadBlocks.js +25 -3
  102. package/dist/core/references.d.ts +7 -0
  103. package/dist/core/references.js +29 -11
  104. package/dist/core/regions.d.ts +14 -0
  105. package/dist/core/regions.js +17 -1
  106. package/dist/core/rowLabel.d.ts +8 -0
  107. package/dist/core/rowLabel.js +98 -0
  108. package/dist/core/starter.d.ts +10 -0
  109. package/dist/core/starter.js +40 -0
  110. package/dist/core/tree.js +4 -0
  111. package/dist/core/types.d.ts +96 -0
  112. package/dist/core/uniqueProps.d.ts +40 -0
  113. package/dist/core/uniqueProps.js +156 -0
  114. package/dist/core/validate.js +43 -3
  115. package/dist/forms/answers.d.ts +21 -0
  116. package/dist/forms/answers.js +82 -0
  117. package/dist/forms/blocks.d.ts +33 -0
  118. package/dist/forms/blocks.js +178 -0
  119. package/dist/forms/conditions.d.ts +78 -0
  120. package/dist/forms/conditions.js +184 -0
  121. package/dist/forms/emails.d.ts +23 -0
  122. package/dist/forms/emails.js +64 -0
  123. package/dist/forms/fieldConfigs.d.ts +35 -0
  124. package/dist/forms/fieldConfigs.js +167 -0
  125. package/dist/forms/fieldOps.d.ts +78 -0
  126. package/dist/forms/fieldOps.js +378 -0
  127. package/dist/forms/fieldSettings.d.ts +81 -0
  128. package/dist/forms/fieldSettings.js +239 -0
  129. package/dist/forms/files.d.ts +54 -0
  130. package/dist/forms/files.js +128 -0
  131. package/dist/forms/index.d.ts +16 -0
  132. package/dist/forms/index.js +18 -0
  133. package/dist/forms/mergeTags.d.ts +103 -0
  134. package/dist/forms/mergeTags.js +150 -0
  135. package/dist/forms/noScript.d.ts +60 -0
  136. package/dist/forms/noScript.js +109 -0
  137. package/dist/forms/pageForms.d.ts +99 -0
  138. package/dist/forms/pageForms.js +294 -0
  139. package/dist/forms/pageSync.d.ts +91 -0
  140. package/dist/forms/pageSync.js +325 -0
  141. package/dist/forms/rateLimit.d.ts +21 -0
  142. package/dist/forms/rateLimit.js +50 -0
  143. package/dist/forms/settings.d.ts +13 -0
  144. package/dist/forms/settings.js +92 -0
  145. package/dist/forms/spam.d.ts +100 -0
  146. package/dist/forms/spam.js +218 -0
  147. package/dist/forms/spamSettings.d.ts +43 -0
  148. package/dist/forms/spamSettings.js +25 -0
  149. package/dist/forms/submission.d.ts +34 -0
  150. package/dist/forms/submission.js +89 -0
  151. package/dist/forms/submissionsAdmin.d.ts +26 -0
  152. package/dist/forms/submissionsAdmin.js +108 -0
  153. package/dist/forms/summary.d.ts +60 -0
  154. package/dist/forms/summary.js +113 -0
  155. package/dist/forms/uploads.d.ts +41 -0
  156. package/dist/forms/uploads.js +132 -0
  157. package/dist/index.d.ts +8 -2
  158. package/dist/index.js +8 -2
  159. package/dist/live/document.d.ts +12 -0
  160. package/dist/live/document.js +8 -1
  161. package/dist/live/endpoints.d.ts +1 -0
  162. package/dist/live/session.js +3 -1
  163. package/dist/live/storage.d.ts +13 -2
  164. package/dist/live/storage.js +18 -7
  165. package/dist/mcp/forms.d.ts +26 -0
  166. package/dist/mcp/forms.js +280 -0
  167. package/dist/mcp/index.d.ts +7 -0
  168. package/dist/mcp/index.js +29 -10
  169. package/dist/mcp/shared.d.ts +1 -0
  170. package/dist/mcp/shared.js +1 -0
  171. package/dist/plugin/forms.d.ts +30 -0
  172. package/dist/plugin/forms.js +63 -0
  173. package/dist/plugin/formsSync.d.ts +138 -0
  174. package/dist/plugin/formsSync.js +345 -0
  175. package/dist/plugin/hook.d.ts +22 -0
  176. package/dist/plugin/hook.js +19 -7
  177. package/dist/plugin/index.d.ts +14 -0
  178. package/dist/plugin/index.js +99 -28
  179. package/dist/plugin/links.d.ts +7 -2
  180. package/dist/plugin/links.js +9 -3
  181. package/dist/plugin/references.d.ts +6 -0
  182. package/dist/plugin/references.js +12 -0
  183. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  184. package/dist/react/canvas/BuilderCanvas.js +29 -6
  185. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  186. package/dist/react/canvas/inline/mapper.js +35 -4
  187. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  188. package/dist/react/render/LayoutOutlet.js +9 -4
  189. package/dist/react/render/RenderLayout.js +13 -7
  190. package/dist/react/render/resolve.d.ts +1 -0
  191. package/dist/react/render/resolve.js +5 -1
  192. package/dist/react/server.js +19 -0
  193. package/package.json +5 -1
@@ -0,0 +1,178 @@
1
+ // Builder block definitions for the field blocks of a form-builder form (`forms.fields`).
2
+ // Client-safe: Payload block configs in, plain definitions out.
3
+ import { fromPayloadBlocks } from '../blocks/payload.js';
4
+ import { FORM_CONDITIONS_FIELD } from './conditions.js';
5
+ import { FORM_FIELD_WIDTH_CLASSES, withHiddenWidth, withWidthClass } from './fieldSettings.js';
6
+ /** `admin.custom.builderFieldName` on a field's `name`: the builder warns when a form with submissions renames it. */
7
+ export const FIELD_NAME_MARKER = 'builderFieldName';
8
+ /** Prefix of the builder types: the form-builder block `text` is the builder type `formText`. */
9
+ export const FORM_FIELD_PREFIX = 'form';
10
+ /** Name of the form settings region. The app's form frame marks the submit button with it. */
11
+ export const FORM_SETTINGS_REGION = 'settings';
12
+ /** Library category of the form field blocks. */
13
+ export const FORM_FIELD_CATEGORY = 'Fields';
14
+ /** The builder type of a form-builder field block: `text` -> `formText`. */
15
+ export function formFieldType(slug) {
16
+ return `${FORM_FIELD_PREFIX}${slug.charAt(0).toUpperCase()}${slug.slice(1)}`;
17
+ }
18
+ /** The form-builder block slug of a builder type: `formText` -> `text`. Null for other types. */
19
+ export function formFieldSlug(type) {
20
+ if (!type.startsWith(FORM_FIELD_PREFIX) || type.length === FORM_FIELD_PREFIX.length)
21
+ return null;
22
+ const rest = type.slice(FORM_FIELD_PREFIX.length);
23
+ return rest.charAt(0) === rest.charAt(0).toUpperCase() ? `${rest.charAt(0).toLowerCase()}${rest.slice(1)}` : null;
24
+ }
25
+ /** Labels and library tooltips of the known field types. Other blocks keep their own. */
26
+ const KNOWN = {
27
+ text: { label: 'Text', icon: 'text', description: 'A one-line answer, such as a name.' },
28
+ email: { label: 'Email', icon: 'mail', description: 'An email address. The form checks its format.' },
29
+ textarea: { label: 'Long text', icon: 'richText', description: 'A longer answer over several lines, such as a message.' },
30
+ number: { label: 'Number', icon: 'hash', description: 'A number.' },
31
+ phone: { label: 'Phone', icon: 'phone', description: 'A phone number. The form checks that it has 6 to 15 digits.' },
32
+ url: { label: 'Web address', icon: 'link', description: 'A web address, such as https://example.com. The form checks its format.' },
33
+ select: { label: 'Dropdown', icon: 'select', description: 'One choice from a list of options.' },
34
+ radio: { label: 'Radio buttons', icon: 'radio', description: 'One choice from a few options, all shown at once.' },
35
+ checkbox: { label: 'Checkbox', icon: 'check', description: 'A box to tick, for example to join the newsletter.' },
36
+ consent: { label: 'Consent', icon: 'check', description: 'A box to tick next to text with a link, for example "I accept the privacy policy".' },
37
+ country: { label: 'Country', icon: 'select', description: 'A list of countries.' },
38
+ state: { label: 'State', icon: 'select', description: 'A list of US states.' },
39
+ date: { label: 'Date', icon: 'calendar', description: 'A date, picked from a calendar.' },
40
+ file: { label: 'File upload', icon: 'upload', description: 'A file the visitor uploads, such as a CV. You set the file types and the size limit.' },
41
+ hidden: { label: 'Hidden field', icon: 'eyeOff', description: 'A value sent with every answer that visitors do not see, such as the campaign name.' },
42
+ message: { label: 'Message', icon: 'richText', description: 'Text between the fields, such as a note. Visitors do not fill it in.' },
43
+ upload: { label: 'File upload', icon: 'upload', description: 'A file the visitor uploads.' },
44
+ payment: { label: 'Payment', icon: 'block', description: 'A payment field.' },
45
+ };
46
+ /** The parts of a field block (its own classes win over the form's). */
47
+ export const FORM_FIELD_PARTS = {
48
+ label: 'Label',
49
+ input: 'Input',
50
+ help: 'Help text',
51
+ error: 'Error message',
52
+ options: 'Options',
53
+ };
54
+ /** The parts each field type has. Types not listed have label, input, help text and error. */
55
+ const FIELD_PARTS_BY_SLUG = {
56
+ message: [],
57
+ hidden: [],
58
+ checkbox: ['label', 'help', 'error'],
59
+ consent: ['label', 'help', 'error'],
60
+ radio: ['label', 'options', 'help', 'error'],
61
+ file: ['label', 'help', 'error'],
62
+ };
63
+ /** The `parts` of a field block of the plugin's type `slug`. Undefined when it has none. */
64
+ export function formFieldParts(slug) {
65
+ const names = FIELD_PARTS_BY_SLUG[slug] ?? ['label', 'input', 'help', 'error'];
66
+ if (names.length === 0)
67
+ return undefined;
68
+ // Until the field sets its own classes, a part uses the same part of its Form block (options have none there).
69
+ return Object.fromEntries(names.map((name) => [name, { label: FORM_FIELD_PARTS[name], ...(name === 'options' ? {} : { inherits: { ancestor: 'form' } }) }]));
70
+ }
71
+ /**
72
+ * The tab of a form field's settings, by field name. Other fields stay on the Field tab (content,
73
+ * label visibility, radio display). Looks are no setting: the Styles panel sets them, the width too.
74
+ */
75
+ const TAB_OF = {
76
+ required: 'Validation',
77
+ accept: 'Validation',
78
+ maxSize: 'Validation',
79
+ multiple: 'Validation',
80
+ maxFiles: 'Validation',
81
+ uploadCollection: 'Validation',
82
+ mimeTypes: 'Validation',
83
+ maxFileSize: 'Validation',
84
+ [FORM_CONDITIONS_FIELD]: 'Conditions',
85
+ };
86
+ const TAB_ORDER = ['Validation', 'Conditions'];
87
+ /** The classes of the old width presets: the generated CSS has them wherever form fields are. */
88
+ export const FORM_FIELD_CLASSES = Object.values(FORM_FIELD_WIDTH_CLASSES);
89
+ /**
90
+ * One definition per block of the form's `fields` blocks field. Types get the `form` prefix
91
+ * (`formText`), so they never clash with page blocks; the stored data keeps the plugin's
92
+ * `blockType`. The plugin's `forms` option calls this with the forms collection's own blocks.
93
+ */
94
+ export function formFieldBlocks(blocks) {
95
+ const overrides = Object.fromEntries(blocks.map((block) => {
96
+ const known = KNOWN[block.slug];
97
+ return [
98
+ block.slug,
99
+ {
100
+ category: FORM_FIELD_CATEGORY,
101
+ ...(known ? { label: known.label, icon: known.icon } : {}),
102
+ ai: {
103
+ description: `${known?.label ?? block.slug} field of a form (form-builder "${block.slug}" block). On a page it goes inside a Form block (at any depth); \`name\` is unique in that form.`,
104
+ },
105
+ },
106
+ ];
107
+ }));
108
+ return fromPayloadBlocks(blocks, { prefix: FORM_FIELD_PREFIX, overrides, onWarning: false }).map((def) => {
109
+ const slug = def.payload?.slug ?? '';
110
+ const known = KNOWN[slug];
111
+ // A new field starts with a name and a label, so the form saves at once (the plugin requires
112
+ // a name). Only the builder's insert uses these defaults; the stored data is unchanged.
113
+ const fields = inTabs(withHiddenWidth(withNameMarker(withStartValues(def.fields, { name: slug, label: known?.label ?? def.label }))));
114
+ // Two fields with one name would overwrite each other's answers: a new or copied field gets `text2`.
115
+ // Parts: the label, input, help text, error and options take classes of their own (Styles panel).
116
+ // A stored `width` (the plugin's setting) becomes classes when the builder opens the form; until
117
+ // then the site draws it with the same classes, so the generated CSS lists them.
118
+ const parts = formFieldParts(slug);
119
+ return {
120
+ ...def,
121
+ fields,
122
+ uniqueProps: ['name'],
123
+ classes: [...(def.classes ?? []), ...FORM_FIELD_CLASSES],
124
+ upgrade: withWidthClass,
125
+ ...(parts ? { parts } : {}),
126
+ ...(known ? { description: known.description } : {}),
127
+ };
128
+ });
129
+ }
130
+ /** The fields with `defaultValue` set on the top-level `name` and `label` fields (also inside rows) that have none. */
131
+ function withStartValues(fields, values) {
132
+ return fields.map((raw) => {
133
+ const field = raw;
134
+ if (Array.isArray(field.fields) && !field.name)
135
+ return { ...field, fields: withStartValues(field.fields, values) };
136
+ const name = typeof field.name === 'string' ? field.name : '';
137
+ if (name in values && field.defaultValue === undefined)
138
+ return { ...field, defaultValue: values[name] };
139
+ return raw;
140
+ });
141
+ }
142
+ /** The fields with the top-level `name` text (also inside rows) marked for the rename warning. */
143
+ function withNameMarker(fields) {
144
+ return fields.map((raw) => {
145
+ const field = raw;
146
+ if (Array.isArray(field.fields) && !field.name)
147
+ return { ...field, fields: withNameMarker(field.fields) };
148
+ if (field.name !== 'name' || field.type !== 'text')
149
+ return raw;
150
+ const admin = (field.admin ?? {});
151
+ return { ...field, admin: { ...admin, custom: { ...admin.custom, [FIELD_NAME_MARKER]: true } } };
152
+ });
153
+ }
154
+ /**
155
+ * The fields split over the tabs Field, Validation and Conditions (unnamed tabs: the
156
+ * data stays as it is). Fields leave their rows; an empty row goes. A tab without fields is left
157
+ * out; with only the Field tab the list stays as it is.
158
+ */
159
+ function inTabs(fields) {
160
+ const moved = { Validation: [], Conditions: [] };
161
+ const pull = (list) => list.flatMap((raw) => {
162
+ const field = raw;
163
+ if (Array.isArray(field.fields) && !field.name) {
164
+ const kept = pull(field.fields);
165
+ return kept.length > 0 ? [{ ...field, fields: kept }] : [];
166
+ }
167
+ const tab = typeof field.name === 'string' ? TAB_OF[field.name] : undefined;
168
+ if (!tab)
169
+ return [raw];
170
+ moved[tab].push(raw);
171
+ return [];
172
+ });
173
+ const main = pull(fields);
174
+ const others = TAB_ORDER.filter((label) => moved[label].length > 0);
175
+ if (others.length === 0)
176
+ return fields;
177
+ return [{ type: 'tabs', tabs: [{ label: 'Field', fields: main }, ...others.map((label) => ({ label, fields: moved[label] }))] }];
178
+ }
@@ -0,0 +1,78 @@
1
+ import type { Field } from 'payload';
2
+ export declare const FORM_CONDITION_OPERATORS: readonly ['equals', 'notEquals', 'contains', 'isEmpty', 'isNotEmpty'];
3
+ export type FormConditionOperator = (typeof FORM_CONDITION_OPERATORS)[number];
4
+ /** One test: the value of the form field named `field` against `value`. */
5
+ export type FormConditionRule = {
6
+ field?: string | null;
7
+ operator?: FormConditionOperator | null;
8
+ value?: string | null;
9
+ };
10
+ /** `match: 'all'` (the default): every rule must hold. `'any'`: one rule is enough. */
11
+ export type FormFieldConditions = {
12
+ match?: 'all' | 'any' | null;
13
+ rules?: FormConditionRule[] | null;
14
+ };
15
+ /** A field of a form document, as the form-builder plugin stores it. */
16
+ export type FormFieldLike = {
17
+ blockType?: string;
18
+ name?: string | null;
19
+ required?: boolean | null;
20
+ conditions?: FormFieldConditions | null;
21
+ };
22
+ /** A value a visitor entered. Checkboxes give booleans, other fields text. */
23
+ export type FormValue = string | number | boolean | null | undefined;
24
+ /** Name of the conditions field in every form field block. */
25
+ export declare const FORM_CONDITIONS_FIELD = "conditions";
26
+ /** Empty: no value, blank text, or a checkbox that is not ticked. */
27
+ export declare function isEmptyFormValue(value: FormValue): boolean;
28
+ /** A rule that names a field and an operator (and a value, when the operator needs one). */
29
+ export declare function isCompleteRule(rule: FormConditionRule | null | undefined): rule is FormConditionRule & {
30
+ field: string;
31
+ operator: FormConditionOperator;
32
+ };
33
+ /**
34
+ * True when the rule holds for `value`. Text compares without case and surrounding spaces; a
35
+ * ticked checkbox equals "true" (also "yes", "on" or "1"), an unticked one "false".
36
+ */
37
+ export declare function ruleMet(rule: FormConditionRule & {
38
+ operator: FormConditionOperator;
39
+ }, value: FormValue): boolean;
40
+ /** The complete rules of a field. A field without complete rules always shows. */
41
+ export declare function conditionRules(field: FormFieldLike): Array<FormConditionRule & {
42
+ field: string;
43
+ operator: FormConditionOperator;
44
+ }>;
45
+ /** True when the field shows for these values (the values of hidden fields left out). */
46
+ export declare function conditionsMet(field: FormFieldLike, values: Record<string, FormValue>): boolean;
47
+ /**
48
+ * The names of the fields their conditions hide. A rule that reads a hidden field sees it as
49
+ * empty, so a chain (C depends on B, B on A) hides C when A hides B. Rules that form a loop
50
+ * (A depends on B, B on A) read the entered values. Fields without a name (messages) are never
51
+ * in the set.
52
+ */
53
+ export declare function hiddenFormFields(fields: readonly FormFieldLike[] | null | undefined, values: Record<string, FormValue>): Set<string>;
54
+ /** True when the field shows: it has no name (a message) or no condition hides it. */
55
+ export declare function isFormFieldShown(field: FormFieldLike, hidden: ReadonlySet<string>): boolean;
56
+ /** One line for editors: "Shows when Topic equals Sales and Email is not empty". */
57
+ export declare function describeConditions(field: FormFieldLike, labelOf?: (name: string) => string): string | null;
58
+ /**
59
+ * The `conditions` field for a form field block. Add it to the blocks of the form-builder
60
+ * plugin's `fields` option with `withFormConditions`. The builder edits it in its right panel;
61
+ * Payload's edit screen shows it as a group.
62
+ *
63
+ * `admin.custom.builderFormField` makes the builder show the rule's field as a list of the
64
+ * form's other fields. `admin.custom.builderCondition` hides the value for "is empty" and
65
+ * "is not empty" in the builder; `admin.condition` does the same in Payload's edit screen.
66
+ */
67
+ export declare function formConditionsField(): Field;
68
+ type BlockLike = {
69
+ slug: string;
70
+ fields: Field[];
71
+ };
72
+ /**
73
+ * The block with the `conditions` field added, for the form-builder plugin's `fields` option:
74
+ * `formBuilderPlugin({ fields: { text: withFormConditions(fields.text) } })`, with `fields` from
75
+ * `@payloadcms/plugin-form-builder`. A block that has the field already stays as it is.
76
+ */
77
+ export declare function withFormConditions<T extends BlockLike>(block: T): T;
78
+ export {};
@@ -0,0 +1,184 @@
1
+ // Display conditions for the fields of a form made with `@payloadcms/plugin-form-builder`.
2
+ // A form field may show only when other fields of the same form have some values:
3
+ // conditions: { match: 'all' | 'any', rules: [{ field, operator, value }] }
4
+ // Pure and client-safe: the site's form renderer, the submission hook and the builder use it.
5
+ export const FORM_CONDITION_OPERATORS = ['equals', 'notEquals', 'contains', 'isEmpty', 'isNotEmpty'];
6
+ /** Name of the conditions field in every form field block. */
7
+ export const FORM_CONDITIONS_FIELD = 'conditions';
8
+ /** Operators that compare with a value. The others test only whether the field is empty. */
9
+ const NEEDS_VALUE = new Set(['equals', 'notEquals', 'contains']);
10
+ const OPERATOR_LABELS = {
11
+ equals: 'equals',
12
+ notEquals: 'does not equal',
13
+ contains: 'contains',
14
+ isEmpty: 'is empty',
15
+ isNotEmpty: 'is not empty',
16
+ };
17
+ const text = (value) => (value === null || value === undefined ? '' : String(value).trim());
18
+ /** Empty: no value, blank text, or a checkbox that is not ticked. */
19
+ export function isEmptyFormValue(value) {
20
+ return value === false || text(value) === '';
21
+ }
22
+ /** A rule that names a field and an operator (and a value, when the operator needs one). */
23
+ export function isCompleteRule(rule) {
24
+ if (!rule || typeof rule.field !== 'string' || !rule.field.trim())
25
+ return false;
26
+ return typeof rule.operator === 'string' && FORM_CONDITION_OPERATORS.includes(rule.operator);
27
+ }
28
+ /**
29
+ * True when the rule holds for `value`. Text compares without case and surrounding spaces; a
30
+ * ticked checkbox equals "true" (also "yes", "on" or "1"), an unticked one "false".
31
+ */
32
+ export function ruleMet(rule, value) {
33
+ if (rule.operator === 'isEmpty')
34
+ return isEmptyFormValue(value);
35
+ if (rule.operator === 'isNotEmpty')
36
+ return !isEmptyFormValue(value);
37
+ const actual = typeof value === 'boolean' ? String(value) : text(value).toLowerCase();
38
+ let expected = text(rule.value).toLowerCase();
39
+ if (typeof value === 'boolean' && ['yes', 'on', '1', 'checked', 'ticked'].includes(expected))
40
+ expected = 'true';
41
+ if (typeof value === 'boolean' && ['no', 'off', '0', 'unchecked'].includes(expected))
42
+ expected = 'false';
43
+ if (rule.operator === 'contains')
44
+ return expected === '' || actual.includes(expected);
45
+ const equal = actual === expected;
46
+ return rule.operator === 'equals' ? equal : !equal;
47
+ }
48
+ /** The complete rules of a field. A field without complete rules always shows. */
49
+ export function conditionRules(field) {
50
+ return (field.conditions?.rules ?? []).filter(isCompleteRule);
51
+ }
52
+ /** True when the field shows for these values (the values of hidden fields left out). */
53
+ export function conditionsMet(field, values) {
54
+ const rules = conditionRules(field);
55
+ if (rules.length === 0)
56
+ return true;
57
+ const met = (rule) => ruleMet(rule, values[rule.field.trim()]);
58
+ return field.conditions?.match === 'any' ? rules.some(met) : rules.every(met);
59
+ }
60
+ /**
61
+ * The names of the fields their conditions hide. A rule that reads a hidden field sees it as
62
+ * empty, so a chain (C depends on B, B on A) hides C when A hides B. Rules that form a loop
63
+ * (A depends on B, B on A) read the entered values. Fields without a name (messages) are never
64
+ * in the set.
65
+ */
66
+ export function hiddenFormFields(fields, values) {
67
+ const byName = new Map();
68
+ for (const field of fields ?? [])
69
+ if (typeof field?.name === 'string' && field.name !== '' && !byName.has(field.name))
70
+ byName.set(field.name, field);
71
+ const shown = new Map();
72
+ const visiting = new Set();
73
+ const isShown = (name) => {
74
+ const known = shown.get(name);
75
+ if (known !== undefined)
76
+ return known;
77
+ const field = byName.get(name);
78
+ // Not a field of the form, or a loop: the entered value counts.
79
+ if (!field || visiting.has(name))
80
+ return true;
81
+ visiting.add(name);
82
+ const seen = {};
83
+ for (const rule of conditionRules(field)) {
84
+ const other = rule.field.trim();
85
+ seen[other] = isShown(other) ? values[other] : undefined;
86
+ }
87
+ visiting.delete(name);
88
+ const result = conditionsMet(field, seen);
89
+ shown.set(name, result);
90
+ return result;
91
+ };
92
+ return new Set([...byName.keys()].filter((name) => !isShown(name)));
93
+ }
94
+ /** True when the field shows: it has no name (a message) or no condition hides it. */
95
+ export function isFormFieldShown(field, hidden) {
96
+ return !field.name || !hidden.has(field.name);
97
+ }
98
+ /** One line for editors: "Shows when Topic equals Sales and Email is not empty". */
99
+ export function describeConditions(field, labelOf = (name) => name) {
100
+ const rules = conditionRules(field);
101
+ if (rules.length === 0)
102
+ return null;
103
+ const parts = rules.map((rule) => {
104
+ const head = `${labelOf(rule.field.trim())} ${OPERATOR_LABELS[rule.operator]}`;
105
+ return NEEDS_VALUE.has(rule.operator) ? `${head} “${text(rule.value)}”` : head;
106
+ });
107
+ return `Shows when ${parts.join(field.conditions?.match === 'any' ? ' or ' : ' and ')}`;
108
+ }
109
+ // ---------------------------------------------------------------------------
110
+ // The Payload field
111
+ // ---------------------------------------------------------------------------
112
+ /**
113
+ * The `conditions` field for a form field block. Add it to the blocks of the form-builder
114
+ * plugin's `fields` option with `withFormConditions`. The builder edits it in its right panel;
115
+ * Payload's edit screen shows it as a group.
116
+ *
117
+ * `admin.custom.builderFormField` makes the builder show the rule's field as a list of the
118
+ * form's other fields. `admin.custom.builderCondition` hides the value for "is empty" and
119
+ * "is not empty" in the builder; `admin.condition` does the same in Payload's edit screen.
120
+ */
121
+ export function formConditionsField() {
122
+ return {
123
+ name: FORM_CONDITIONS_FIELD,
124
+ type: 'group',
125
+ label: 'Display conditions',
126
+ admin: {
127
+ description: 'Show this field only when other fields of the form have some values. Without rules it always shows.',
128
+ },
129
+ fields: [
130
+ {
131
+ name: 'match',
132
+ type: 'select',
133
+ label: 'Show when',
134
+ defaultValue: 'all',
135
+ options: [
136
+ { label: 'All rules match', value: 'all' },
137
+ { label: 'Any rule matches', value: 'any' },
138
+ ],
139
+ },
140
+ {
141
+ name: 'rules',
142
+ type: 'array',
143
+ label: 'Rules',
144
+ labels: { singular: 'Rule', plural: 'Rules' },
145
+ fields: [
146
+ {
147
+ // Not required: a rule without a field is ignored, and the form keeps saving while it is filled in.
148
+ name: 'field',
149
+ type: 'text',
150
+ label: 'Field',
151
+ admin: { description: 'The name of another field of this form.', custom: { builderFormField: true } },
152
+ },
153
+ {
154
+ name: 'operator',
155
+ type: 'select',
156
+ label: 'Test',
157
+ defaultValue: 'equals',
158
+ options: FORM_CONDITION_OPERATORS.map((value) => ({ label: OPERATOR_LABELS[value], value })),
159
+ },
160
+ {
161
+ name: 'value',
162
+ type: 'text',
163
+ label: 'Value',
164
+ admin: {
165
+ description: 'For a checkbox: "true" when ticked, "false" when not.',
166
+ condition: (_, siblings) => siblings?.operator !== 'isEmpty' && siblings?.operator !== 'isNotEmpty',
167
+ custom: { builderCondition: { field: 'operator', notEquals: ['isEmpty', 'isNotEmpty'] } },
168
+ },
169
+ },
170
+ ],
171
+ },
172
+ ],
173
+ };
174
+ }
175
+ /**
176
+ * The block with the `conditions` field added, for the form-builder plugin's `fields` option:
177
+ * `formBuilderPlugin({ fields: { text: withFormConditions(fields.text) } })`, with `fields` from
178
+ * `@payloadcms/plugin-form-builder`. A block that has the field already stays as it is.
179
+ */
180
+ export function withFormConditions(block) {
181
+ if (block.fields.some((f) => 'name' in f && f.name === FORM_CONDITIONS_FIELD))
182
+ return block;
183
+ return { ...block, fields: [...block.fields, formConditionsField()] };
184
+ }
@@ -0,0 +1,23 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ /** An email as the plugin formats it before `beforeEmail`. */
3
+ type PluginEmail = {
4
+ to?: string;
5
+ from?: string;
6
+ };
7
+ /** What the plugin passes: the submission's `afterChange` arguments (its types call them `beforeChangeParams`). */
8
+ type HookArgs = {
9
+ data?: Record<string, any>;
10
+ doc?: Record<string, any>;
11
+ req: PayloadRequest;
12
+ };
13
+ export type FormEmailsOptions = {
14
+ /** Slug of the forms collection. Default "forms". */
15
+ forms?: string;
16
+ };
17
+ /**
18
+ * The `beforeEmail` hook: `formBuilderPlugin({ beforeEmail: formEmails() })`. It reads the form
19
+ * again and builds every email from the stored answers (hidden fields already dropped). An email
20
+ * without a To address is not sent.
21
+ */
22
+ export declare function formEmails(options?: FormEmailsOptions): <T extends PluginEmail>(emails: T[], args: HookArgs) => Promise<T[]>;
23
+ export {};
@@ -0,0 +1,64 @@
1
+ // Server: the form-builder plugin's `beforeEmail` hook that builds each email of a form from the
2
+ // fields of `formEmailFields` (from name, custom HTML body, merge tags with `{{*}}` as a table).
3
+ // The plugin sends what this returns.
4
+ import { convertLexicalToHTML } from '@payloadcms/richtext-lexical/html';
5
+ import { formAnswers, formEmailMessage, tablesOutsideParagraphs } from './mergeTags.js';
6
+ const idOf = (value) => {
7
+ if (typeof value === 'string' || typeof value === 'number')
8
+ return value;
9
+ if (value && typeof value === 'object' && 'id' in value)
10
+ return idOf(value.id);
11
+ return null;
12
+ };
13
+ function richTextHtml(value) {
14
+ if (!value || typeof value !== 'object' || !('root' in value))
15
+ return '';
16
+ try {
17
+ // The answers table may not sit in a <p>.
18
+ return tablesOutsideParagraphs(convertLexicalToHTML({ data: value, disableContainer: true }));
19
+ }
20
+ catch {
21
+ return '';
22
+ }
23
+ }
24
+ /**
25
+ * The `beforeEmail` hook: `formBuilderPlugin({ beforeEmail: formEmails() })`. It reads the form
26
+ * again and builds every email from the stored answers (hidden fields already dropped). An email
27
+ * without a To address is not sent.
28
+ */
29
+ export function formEmails(options = {}) {
30
+ const formsSlug = options.forms ?? 'forms';
31
+ return async (emails, args) => {
32
+ const req = args.req;
33
+ const id = idOf(args.doc?.form ?? args.data?.form);
34
+ if (id === null)
35
+ return emails;
36
+ const form = (await req.payload
37
+ .findByID({ collection: formsSlug, id, depth: 0, req, overrideAccess: true, locale: req.locale ?? undefined })
38
+ .catch(() => null));
39
+ const configs = form?.emails ?? [];
40
+ // The plugin made one email per entry, in order. Anything else: leave its emails alone.
41
+ if (!form || configs.length !== emails.length)
42
+ return emails;
43
+ const rows = (args.doc?.submissionData ?? args.data?.submissionData);
44
+ const answers = formAnswers(form.fields, rows, new Set(['formSubmissionID']));
45
+ const fieldNames = new Set((form.fields ?? []).flatMap((f) => (f.name ? [f.name] : [])));
46
+ const adapter = req.payload.email;
47
+ const defaults = { fromName: adapter?.defaultFromName ?? '', fromAddress: adapter?.defaultFromAddress ?? '' };
48
+ const extra = { formSubmissionID: String(args.doc?.id ?? ''), formTitle: form.title ?? '' };
49
+ return configs
50
+ .map((config, index) => {
51
+ const plugin = emails[index];
52
+ const message = formEmailMessage(config, {
53
+ answers,
54
+ fieldNames,
55
+ extra,
56
+ richTextHtml: config.bodyType === 'html' ? '' : richTextHtml(config.message),
57
+ defaults: { ...defaults, to: typeof plugin.to === 'string' ? plugin.to : '' },
58
+ });
59
+ // The plugin's own keys stay (attachments a later hook adds); ours win.
60
+ return { ...plugin, ...message };
61
+ })
62
+ .filter((email) => email.to);
63
+ };
64
+ }
@@ -0,0 +1,35 @@
1
+ import type { Block, Field } from 'payload';
2
+ /** `admin.custom.builderMergeTags`: the builder adds an "Insert field" menu with the form's merge tags. */
3
+ export declare const MERGE_TAGS_MARKER = "builderMergeTags";
4
+ /** A phone number. The form checks that it has 6 to 15 digits. */
5
+ export declare const phoneFormField: Block;
6
+ /** A web address. The form checks that it is an http or https address. */
7
+ export declare const urlFormField: Block;
8
+ /** A value sent with every answer that visitors do not see, for example the campaign. */
9
+ export declare const hiddenFormField: Block;
10
+ /** A box to tick whose text is rich text, so it can link to the privacy policy. */
11
+ export declare const consentFormField: Block;
12
+ /** Default and upper limit of a file field's size, in MB. */
13
+ export declare const FILE_FIELD_MAX_MB = 10;
14
+ /** Files the visitor uploads: one, or several when "Allow several files" is on. `formFileUploads` stores them in a private upload collection. */
15
+ export declare const fileFormField: Block;
16
+ /** The extra field types by slug, for the plugin's `fields` option. */
17
+ export declare const moreFormFields: {
18
+ readonly phone: Block;
19
+ readonly url: Block;
20
+ readonly hidden: Block;
21
+ readonly consent: Block;
22
+ readonly file: Block;
23
+ };
24
+ /**
25
+ * The fields of one form email: To, From name, From email, Reply-To, CC, BCC, Subject and the body
26
+ * (rich text or custom HTML). The plugin's own names stay, so stored emails keep working; the
27
+ * from name, the body type and the HTML body are new. Every line and the body take merge tags.
28
+ */
29
+ export declare function formEmailFields(): Field[];
30
+ /**
31
+ * The forms collection's fields with the emails of `formEmailFields`, for
32
+ * `formBuilderPlugin({ formOverrides: { fields: ({ defaultFields }) => withFormEmailFields(defaultFields) } })`.
33
+ * The `emails` array keeps its access and description.
34
+ */
35
+ export declare function withFormEmailFields(fields: readonly Field[]): Field[];