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.
- package/README.md +333 -28
- package/dist/admin/ArrayRowLabel.d.ts +12 -0
- package/dist/admin/ArrayRowLabel.js +21 -0
- package/dist/admin/client.d.ts +1 -0
- package/dist/admin/client.js +2 -0
- package/dist/admin/editor/Editor.js +8 -1
- package/dist/admin/editor/Inspector.js +23 -17
- package/dist/admin/editor/Library.d.ts +2 -2
- package/dist/admin/editor/Library.js +7 -5
- package/dist/admin/editor/Outline.js +20 -12
- package/dist/admin/editor/Overlay.js +6 -4
- package/dist/admin/editor/actions.d.ts +7 -2
- package/dist/admin/editor/actions.js +44 -12
- package/dist/admin/editor/assistant/AssistantPanel.js +32 -20
- package/dist/admin/editor/comments/controller.d.ts +7 -0
- package/dist/admin/editor/comments/controller.js +12 -0
- package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
- package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
- package/dist/admin/editor/dnd/smooth.js +1 -1
- package/dist/admin/editor/editor.scss +28 -0
- package/dist/admin/editor/fields/ArrayField.js +3 -3
- package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
- package/dist/admin/editor/fields/FormBlock.js +167 -0
- package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
- package/dist/admin/editor/fields/FormFieldName.js +58 -0
- package/dist/admin/editor/fields/GroupField.d.ts +22 -2
- package/dist/admin/editor/fields/GroupField.js +30 -1
- package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
- package/dist/admin/editor/fields/MergeTags.js +62 -0
- package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
- package/dist/admin/editor/fields/arrayRows.js +0 -4
- package/dist/admin/editor/fields/fields.scss +150 -0
- package/dist/admin/editor/fields/values.d.ts +0 -2
- package/dist/admin/editor/fields/values.js +0 -14
- package/dist/admin/editor/icons.d.ts +3 -0
- package/dist/admin/editor/icons.js +3 -0
- package/dist/admin/editor/insert/InsertHandle.js +1 -1
- package/dist/admin/editor/insert/picker.d.ts +3 -2
- package/dist/admin/editor/insert/picker.js +9 -3
- package/dist/admin/editor/layout/LeftPanel.js +5 -3
- package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
- package/dist/admin/editor/layout/leftTabs.js +18 -0
- package/dist/admin/editor/media/ImageEditor.d.ts +8 -2
- package/dist/admin/editor/media/ImageEditor.js +16 -10
- package/dist/admin/editor/media/media.scss +12 -2
- package/dist/admin/editor/media/model.d.ts +10 -1
- package/dist/admin/editor/media/model.js +19 -0
- package/dist/admin/editor/menu/blockMenu.js +3 -3
- package/dist/admin/editor/names.d.ts +9 -0
- package/dist/admin/editor/names.js +18 -0
- package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
- package/dist/admin/editor/regions/RegionFields.js +122 -0
- package/dist/admin/editor/regions/RegionPane.js +5 -3
- package/dist/admin/editor/regions/RegionRows.js +2 -2
- package/dist/admin/editor/regions/required.d.ts +16 -0
- package/dist/admin/editor/regions/required.js +43 -0
- package/dist/admin/editor/renderField.d.ts +9 -2
- package/dist/admin/editor/renderField.js +86 -32
- package/dist/admin/editor/runtime.d.ts +3 -2
- package/dist/admin/editor/runtime.js +12 -18
- package/dist/admin/editor/styles/StylesPanel.js +4 -2
- package/dist/admin/editor/styles/context.js +9 -4
- package/dist/admin/editor/topbar/ContentModeToggle.js +1 -1
- package/dist/admin/editor/topbar/DocumentActions.js +4 -3
- package/dist/admin/editor/topbar/contentMode.scss +0 -9
- package/dist/admin/editor/topbar/topbar.scss +1 -41
- package/dist/admin/editor/ui/Tabs.d.ts +17 -0
- package/dist/admin/editor/ui/Tabs.js +17 -0
- package/dist/admin/forms/SubmissionCells.d.ts +6 -0
- package/dist/admin/forms/SubmissionCells.js +31 -0
- package/dist/admin/forms/SubmissionView.d.ts +5 -0
- package/dist/admin/forms/SubmissionView.js +106 -0
- package/dist/admin/forms/submissionData.d.ts +32 -0
- package/dist/admin/forms/submissionData.js +63 -0
- package/dist/admin/forms/submissions.scss +197 -0
- package/dist/admin/rsc.d.ts +2 -0
- package/dist/admin/rsc.js +5 -0
- package/dist/ai/endpoint.d.ts +5 -0
- package/dist/ai/endpoint.js +18 -8
- package/dist/ai/prompt.d.ts +8 -0
- package/dist/ai/prompt.js +30 -0
- package/dist/ai/tools.d.ts +6 -1
- package/dist/ai/tools.js +90 -6
- package/dist/blocks/builtins/carousel.js +10 -1
- package/dist/blocks/index.d.ts +1 -1
- package/dist/blocks/index.js +1 -1
- package/dist/blocks/payload.d.ts +7 -0
- package/dist/blocks/payload.js +16 -2
- package/dist/comments/shared.d.ts +5 -0
- package/dist/comments/shared.js +5 -0
- package/dist/core/blocks.d.ts +17 -3
- package/dist/core/blocks.js +92 -10
- package/dist/core/classes.d.ts +5 -0
- package/dist/core/classes.js +26 -1
- package/dist/core/conditions.d.ts +7 -0
- package/dist/core/conditions.js +22 -0
- package/dist/core/dropTarget.d.ts +3 -2
- package/dist/core/dropTarget.js +7 -1
- package/dist/core/index.d.ts +6 -3
- package/dist/core/index.js +6 -3
- package/dist/core/payloadBlocks.js +25 -3
- package/dist/core/references.d.ts +7 -0
- package/dist/core/references.js +29 -11
- package/dist/core/regions.d.ts +14 -0
- package/dist/core/regions.js +17 -1
- package/dist/core/rowLabel.d.ts +8 -0
- package/dist/core/rowLabel.js +98 -0
- package/dist/core/starter.d.ts +10 -0
- package/dist/core/starter.js +40 -0
- package/dist/core/tree.js +4 -0
- package/dist/core/types.d.ts +96 -0
- package/dist/core/uniqueProps.d.ts +40 -0
- package/dist/core/uniqueProps.js +156 -0
- package/dist/core/validate.js +43 -3
- package/dist/forms/answers.d.ts +21 -0
- package/dist/forms/answers.js +82 -0
- package/dist/forms/blocks.d.ts +33 -0
- package/dist/forms/blocks.js +178 -0
- package/dist/forms/conditions.d.ts +78 -0
- package/dist/forms/conditions.js +184 -0
- package/dist/forms/emails.d.ts +23 -0
- package/dist/forms/emails.js +64 -0
- package/dist/forms/fieldConfigs.d.ts +35 -0
- package/dist/forms/fieldConfigs.js +167 -0
- package/dist/forms/fieldOps.d.ts +78 -0
- package/dist/forms/fieldOps.js +378 -0
- package/dist/forms/fieldSettings.d.ts +81 -0
- package/dist/forms/fieldSettings.js +239 -0
- package/dist/forms/files.d.ts +54 -0
- package/dist/forms/files.js +128 -0
- package/dist/forms/index.d.ts +16 -0
- package/dist/forms/index.js +18 -0
- package/dist/forms/mergeTags.d.ts +103 -0
- package/dist/forms/mergeTags.js +150 -0
- package/dist/forms/noScript.d.ts +60 -0
- package/dist/forms/noScript.js +109 -0
- package/dist/forms/pageForms.d.ts +99 -0
- package/dist/forms/pageForms.js +294 -0
- package/dist/forms/pageSync.d.ts +91 -0
- package/dist/forms/pageSync.js +325 -0
- package/dist/forms/rateLimit.d.ts +21 -0
- package/dist/forms/rateLimit.js +50 -0
- package/dist/forms/settings.d.ts +13 -0
- package/dist/forms/settings.js +92 -0
- package/dist/forms/spam.d.ts +100 -0
- package/dist/forms/spam.js +218 -0
- package/dist/forms/spamSettings.d.ts +43 -0
- package/dist/forms/spamSettings.js +25 -0
- package/dist/forms/submission.d.ts +34 -0
- package/dist/forms/submission.js +89 -0
- package/dist/forms/submissionsAdmin.d.ts +26 -0
- package/dist/forms/submissionsAdmin.js +108 -0
- package/dist/forms/summary.d.ts +60 -0
- package/dist/forms/summary.js +113 -0
- package/dist/forms/uploads.d.ts +41 -0
- package/dist/forms/uploads.js +132 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +8 -2
- package/dist/live/document.d.ts +12 -0
- package/dist/live/document.js +8 -1
- package/dist/live/endpoints.d.ts +1 -0
- package/dist/live/session.js +3 -1
- package/dist/live/storage.d.ts +13 -2
- package/dist/live/storage.js +18 -7
- package/dist/mcp/forms.d.ts +26 -0
- package/dist/mcp/forms.js +280 -0
- package/dist/mcp/index.d.ts +7 -0
- package/dist/mcp/index.js +29 -10
- package/dist/mcp/shared.d.ts +1 -0
- package/dist/mcp/shared.js +1 -0
- package/dist/plugin/forms.d.ts +30 -0
- package/dist/plugin/forms.js +63 -0
- package/dist/plugin/formsSync.d.ts +138 -0
- package/dist/plugin/formsSync.js +345 -0
- package/dist/plugin/hook.d.ts +22 -0
- package/dist/plugin/hook.js +19 -7
- package/dist/plugin/index.d.ts +14 -0
- package/dist/plugin/index.js +99 -28
- package/dist/plugin/links.d.ts +7 -2
- package/dist/plugin/links.js +9 -3
- package/dist/plugin/references.d.ts +6 -0
- package/dist/plugin/references.js +12 -0
- package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
- package/dist/react/canvas/BuilderCanvas.js +29 -6
- package/dist/react/canvas/inline/mapper.d.ts +6 -1
- package/dist/react/canvas/inline/mapper.js +35 -4
- package/dist/react/render/LayoutOutlet.d.ts +7 -3
- package/dist/react/render/LayoutOutlet.js +9 -4
- package/dist/react/render/RenderLayout.js +13 -7
- package/dist/react/render/resolve.d.ts +1 -0
- package/dist/react/render/resolve.js +5 -1
- package/dist/react/server.js +19 -0
- package/package.json +5 -1
package/dist/ai/endpoint.js
CHANGED
|
@@ -13,7 +13,7 @@ import { missingAdapterProblem, SETTINGS_KEY_HINT } from './config.js';
|
|
|
13
13
|
import { createImageService, generateImageToMedia } from './images/service.js';
|
|
14
14
|
import { adapterIdentity, runAgent } from './loop.js';
|
|
15
15
|
import { classesConfigOf, loadClasses } from '../classes/index.js';
|
|
16
|
-
import { breakpointsPx, contextText, systemPrompt } from './prompt.js';
|
|
16
|
+
import { breakpointsPx, contextText, formSystemPrompt, systemPrompt } from './prompt.js';
|
|
17
17
|
import { withSettingsKey } from './settings/index.js';
|
|
18
18
|
import { toolDefinitions, Workspace } from './tools.js';
|
|
19
19
|
/** Path of the assistant endpoints below the API route. */
|
|
@@ -185,6 +185,13 @@ export function aiEndpoints(options) {
|
|
|
185
185
|
};
|
|
186
186
|
// Built once, in a fixed order: tools and system prompt are the cached prompt prefix.
|
|
187
187
|
const tools = toolDefinitions({ ...env, searchMedia: async () => [] });
|
|
188
|
+
// The form builder: its own field types, tools and prompt (forms/fieldOps.ts).
|
|
189
|
+
const forms = options.forms ?? null;
|
|
190
|
+
const formEnv = forms
|
|
191
|
+
? { blocks: forms.blocks, sections: [], savedSections: false, bindingSources: null, mediaCollection, form: true }
|
|
192
|
+
: null;
|
|
193
|
+
const formTools = formEnv ? toolDefinitions({ ...formEnv, searchMedia: async () => [] }) : [];
|
|
194
|
+
const formSystem = forms ? [{ text: formSystemPrompt({ blocks: forms.blocks, instructions: ai.instructions }), cache: true }] : [];
|
|
188
195
|
let prompt = null;
|
|
189
196
|
const getPrompt = async (req) => {
|
|
190
197
|
const tokens = await options.getTokens(req).catch(() => null);
|
|
@@ -259,7 +266,10 @@ export function aiEndpoints(options) {
|
|
|
259
266
|
if (foreign) {
|
|
260
267
|
return errorResponse(409, 'invalid_request', `This chat was started with another AI model (${foreign.provider}). The assistant now uses ${identity}. Start a new chat.`);
|
|
261
268
|
}
|
|
262
|
-
const
|
|
269
|
+
const isForm = forms !== null && formEnv !== null && body.collection === forms.slug;
|
|
270
|
+
const prompted = await getPrompt(req);
|
|
271
|
+
const system = isForm ? formSystem : prompted.system;
|
|
272
|
+
const { breakpoints } = prompted;
|
|
263
273
|
// The key from the AI settings, read now: a new key works without a restart.
|
|
264
274
|
const settings = options.settings ?? null;
|
|
265
275
|
const settingsKey = settings && adapter.acceptsApiKey ? await settings.keyFor(req.payload, 'chat') : undefined;
|
|
@@ -269,14 +279,14 @@ export function aiEndpoints(options) {
|
|
|
269
279
|
const localization = target.localization ?? null;
|
|
270
280
|
const locale = localization ? knownLocale(localization, body.locale) : null;
|
|
271
281
|
const contentOnly = !(await canEditDesign(req));
|
|
272
|
-
const workspace = new Workspace(layout, blocks, { localization, locale, contentOnly });
|
|
282
|
+
const workspace = new Workspace(layout, isForm ? forms.blocks : blocks, { localization, locale, contentOnly });
|
|
273
283
|
const selectedId = body.selectedId && indexLayout(layout).has(body.selectedId) ? body.selectedId : null;
|
|
274
284
|
const titleField = config?.admin?.useAsTitle;
|
|
275
285
|
const title = titleField && typeof doc[titleField] === 'string' ? doc[titleField] : undefined;
|
|
276
286
|
// Saved sections differ per user and change often: they go in the context, not the cached prompt.
|
|
277
|
-
const saved = savedSections ? await loadSavedSections(req, savedSections.slug) : [];
|
|
287
|
+
const saved = savedSections && !isForm ? await loadSavedSections(req, savedSections.slug) : [];
|
|
278
288
|
// Editable classes change at any time too.
|
|
279
|
-
const classes = classesConfigOf(req.payload) ? await loadClasses(req).catch(() => []) : [];
|
|
289
|
+
const classes = classesConfigOf(req.payload) && !isForm ? await loadClasses(req).catch(() => []) : [];
|
|
280
290
|
const isTemplate = templates !== null && body.collection === templates.slug;
|
|
281
291
|
const templateTarget = isTemplate
|
|
282
292
|
? (typeof doc[TEMPLATE_TARGET_FIELD] === 'string' ? doc[TEMPLATE_TARGET_FIELD] : (body.context?.collection ?? null))
|
|
@@ -332,15 +342,15 @@ export function aiEndpoints(options) {
|
|
|
332
342
|
await runAgent({
|
|
333
343
|
adapter: model,
|
|
334
344
|
system,
|
|
335
|
-
tools,
|
|
345
|
+
tools: isForm ? formTools : tools,
|
|
336
346
|
effort: ai.effort,
|
|
337
347
|
maxSteps: ai.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
338
348
|
messages: body.messages,
|
|
339
349
|
context,
|
|
340
350
|
workspace,
|
|
341
351
|
env: {
|
|
342
|
-
...env,
|
|
343
|
-
sections: [...sections, ...saved],
|
|
352
|
+
...(isForm ? formEnv : env),
|
|
353
|
+
sections: isForm ? [] : [...sections, ...saved],
|
|
344
354
|
searchMedia: mediaSearch(req, mediaCollection),
|
|
345
355
|
generateImage: assistantImageGenerator(req, images, controller.signal),
|
|
346
356
|
},
|
package/dist/ai/prompt.d.ts
CHANGED
|
@@ -18,6 +18,14 @@ export declare function breakpointsPx(tokens: StyleTokens | null): Array<{
|
|
|
18
18
|
}>;
|
|
19
19
|
/** The stable system prompt. Same input, same bytes: keep it free of request data. */
|
|
20
20
|
export declare function systemPrompt(catalog: PromptCatalog): string;
|
|
21
|
+
/**
|
|
22
|
+
* The system prompt of the form builder (`websiteBuilder({ forms })`): the assistant edits a
|
|
23
|
+
* form's fields, not a page. `blocks` are the form's field types.
|
|
24
|
+
*/
|
|
25
|
+
export declare function formSystemPrompt(catalog: {
|
|
26
|
+
blocks: BlockDefinition[];
|
|
27
|
+
instructions?: string;
|
|
28
|
+
}): string;
|
|
21
29
|
export type ContextInput = {
|
|
22
30
|
collection: string;
|
|
23
31
|
id: string | number;
|
package/dist/ai/prompt.js
CHANGED
|
@@ -7,6 +7,7 @@ import { localeLabel } from '../core/locale.js';
|
|
|
7
7
|
import { sectionVersions } from '../core/sections.js';
|
|
8
8
|
import { BINDINGS_GUIDE, describeBlock, layoutGuide, outline } from '../mcp/shared.js';
|
|
9
9
|
import { componentProperties } from '../core/components.js';
|
|
10
|
+
import { formFieldTypes, FORM_FIELDS_GUIDE } from '../forms/fieldOps.js';
|
|
10
11
|
/** Default Tailwind palette colors (red-500 …) and keywords. The prompt lists only theme colors. */
|
|
11
12
|
const PALETTE = /-\d{2,3}$/;
|
|
12
13
|
const KEYWORDS = new Set(['black', 'white', 'transparent', 'current', 'inherit']);
|
|
@@ -139,6 +140,35 @@ RICH TEXT
|
|
|
139
140
|
parts.push(`INSTRUCTIONS FROM THE SITE OWNER\n${extra}`);
|
|
140
141
|
return parts.join('\n\n');
|
|
141
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* The system prompt of the form builder (`websiteBuilder({ forms })`): the assistant edits a
|
|
145
|
+
* form's fields, not a page. `blocks` are the form's field types.
|
|
146
|
+
*/
|
|
147
|
+
export function formSystemPrompt(catalog) {
|
|
148
|
+
const parts = [
|
|
149
|
+
`You are the AI assistant inside a form builder for Payload CMS. The user has one form open (a contact form, a booking request, a survey) and asks you to change its fields: add, rename, reorder or remove questions, make them required, set their options, display conditions and classes (the width too). You make those changes with your tools.
|
|
150
|
+
|
|
151
|
+
HOW YOUR EDITS WORK
|
|
152
|
+
- editFormFields changes the open form. Each change appears in the form builder at once. You never save: the builder saves as usual, and the user can undo your whole reply in one step.
|
|
153
|
+
- Each user message comes with an <editor_context> block: the form's fields as a layout JSON (each block is one field; its type is "form" plus the field type, e.g. "formEmail"; its props are the field's values). The newest context block is the truth. getForm returns the fields in a simpler shape.
|
|
154
|
+
- "this" and "the selected field" mean the selected block.
|
|
155
|
+
- You cannot change the form's settings (title, submit button, confirmation message, emails, spam protection). When the user asks for one, tell them to click an empty spot of the canvas: the right panel then shows the form settings.
|
|
156
|
+
|
|
157
|
+
HOW TO WORK
|
|
158
|
+
1. Start with one short sentence that says what you are going to do.
|
|
159
|
+
2. Put related changes into one editFormFields call. Changes apply in order, all or nothing.
|
|
160
|
+
3. Ask people only for what you need: keep forms short, mark only the needed fields required, and use the field type that fits (email for addresses, textarea for messages, select or radio for a fixed list of choices, checkbox to accept terms).
|
|
161
|
+
4. Labels are short questions or nouns ("Your name", "Email", "How can we help?"). Names are short, lowercase, with _ ("company_size").
|
|
162
|
+
5. When a tool returns an error, read it, fix the input and try again. Do not repeat a call that failed.
|
|
163
|
+
6. When you are done, say in one or two plain sentences what you changed. Do not list ids or JSON.`,
|
|
164
|
+
FORM_FIELDS_GUIDE,
|
|
165
|
+
`FIELD TYPES (JSON). The types this form offers, with their props.\n${JSON.stringify(formFieldTypes(catalog.blocks))}`,
|
|
166
|
+
];
|
|
167
|
+
const extra = catalog.instructions?.trim();
|
|
168
|
+
if (extra)
|
|
169
|
+
parts.push(`INSTRUCTIONS FROM THE SITE OWNER\n${extra}`);
|
|
170
|
+
return parts.join('\n\n');
|
|
171
|
+
}
|
|
142
172
|
const MAX_STRING = 160;
|
|
143
173
|
const MAX_ITEMS = 5;
|
|
144
174
|
const MAX_DEPTH = 3;
|
package/dist/ai/tools.d.ts
CHANGED
|
@@ -35,6 +35,11 @@ export type ToolEnv = {
|
|
|
35
35
|
}) => Promise<GenerateImageOutcome>;
|
|
36
36
|
/** The upload collection images come from and go to. Default "media". */
|
|
37
37
|
mediaCollection?: string;
|
|
38
|
+
/**
|
|
39
|
+
* The open document is a form (`websiteBuilder({ forms })`): `blocks` are its field types, and
|
|
40
|
+
* the tools are getForm, getBlockSchema and editFormFields (forms/fieldOps.ts).
|
|
41
|
+
*/
|
|
42
|
+
form?: boolean;
|
|
38
43
|
};
|
|
39
44
|
/** Result of one tool call. `ops` is set when the call changed the layout. */
|
|
40
45
|
export type ToolOutcome = {
|
|
@@ -87,7 +92,7 @@ export declare class Workspace {
|
|
|
87
92
|
};
|
|
88
93
|
}
|
|
89
94
|
/** "Added 2 blocks, updated 1 block" for the editor. */
|
|
90
|
-
export declare function describeOps(ops: Operation[]): string;
|
|
95
|
+
export declare function describeOps(ops: Operation[], noun?: string): string;
|
|
91
96
|
/** Tool definitions in a fixed order (the order is part of the cached prompt prefix). */
|
|
92
97
|
export declare function toolDefinitions(env: ToolEnv): AiToolDefinition[];
|
|
93
98
|
/** Running summaries, shown while the tool input streams in. */
|
package/dist/ai/tools.js
CHANGED
|
@@ -16,6 +16,8 @@ import { validateLayout } from '../core/validate.js';
|
|
|
16
16
|
import { resolveOperations, splitLayoutErrors } from '../live/apply.js';
|
|
17
17
|
import { componentListing, isRootParentId, missingContent, sectionInsertOps, sectionToInsert, variantsListing } from '../mcp/shared.js';
|
|
18
18
|
import { findSectionVersion } from '../core/sections.js';
|
|
19
|
+
import { formFieldSlug } from '../forms/blocks.js';
|
|
20
|
+
import { formFieldOps, formFieldsOf, formFieldTypes, FORM_FIELDS_GUIDE } from '../forms/fieldOps.js';
|
|
19
21
|
// ---------------------------------------------------------------------------
|
|
20
22
|
// Working copy
|
|
21
23
|
// ---------------------------------------------------------------------------
|
|
@@ -129,18 +131,22 @@ function changedIds(ops) {
|
|
|
129
131
|
}
|
|
130
132
|
return changed;
|
|
131
133
|
}
|
|
132
|
-
const plural = (n) => `${n}
|
|
134
|
+
const plural = (n, noun = 'block') => `${n} ${noun}${n === 1 ? '' : 's'}`;
|
|
135
|
+
/** "Added 2 fields, updated 1 field" for the form builder. */
|
|
136
|
+
function describeFormOps(ops) {
|
|
137
|
+
return describeOps(ops, 'field');
|
|
138
|
+
}
|
|
133
139
|
/** "Added 2 blocks, updated 1 block" for the editor. */
|
|
134
|
-
export function describeOps(ops) {
|
|
140
|
+
export function describeOps(ops, noun = 'block') {
|
|
135
141
|
const count = { insert: 0, update: 0, move: 0, remove: 0 };
|
|
136
142
|
for (const op of ops)
|
|
137
143
|
if (op.type in count)
|
|
138
144
|
count[op.type]++;
|
|
139
145
|
const parts = [
|
|
140
|
-
count.insert ? `added ${plural(count.insert)}` : '',
|
|
141
|
-
count.update ? `updated ${plural(count.update)}` : '',
|
|
142
|
-
count.move ? `moved ${plural(count.move)}` : '',
|
|
143
|
-
count.remove ? `removed ${plural(count.remove)}` : '',
|
|
146
|
+
count.insert ? `added ${plural(count.insert, noun)}` : '',
|
|
147
|
+
count.update ? `updated ${plural(count.update, noun)}` : '',
|
|
148
|
+
count.move ? `moved ${plural(count.move, noun)}` : '',
|
|
149
|
+
count.remove ? `removed ${plural(count.remove, noun)}` : '',
|
|
144
150
|
].filter(Boolean);
|
|
145
151
|
const text = parts.join(', ') || 'no changes';
|
|
146
152
|
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
@@ -231,8 +237,65 @@ const FLAT_OPERATIONS_SCHEMA = {
|
|
|
231
237
|
},
|
|
232
238
|
required: ['operations'],
|
|
233
239
|
};
|
|
240
|
+
/** The form builder's tools: the same field changes as the MCP tool editFormFields. */
|
|
241
|
+
function formToolDefinitions(env) {
|
|
242
|
+
const types = env.blocks.map((b) => formFieldSlug(b.type) ?? b.type);
|
|
243
|
+
return [
|
|
244
|
+
{
|
|
245
|
+
name: 'getForm',
|
|
246
|
+
description: 'Returns the fields of the open form in order (id, type, name, label, required, className (its classes, width included), options, message text, conditions and `shows`, the conditions in words), including your changes so far in this reply.',
|
|
247
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
248
|
+
strict: true,
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
name: 'getBlockSchema',
|
|
252
|
+
description: 'Returns the JSON Schema of the props of one field type. Its block type is "form" plus the type, e.g. "formEmail". Call it when a prop shape is unclear.',
|
|
253
|
+
inputSchema: {
|
|
254
|
+
type: 'object',
|
|
255
|
+
properties: { type: { type: 'string', enum: env.blocks.map((b) => b.type) } },
|
|
256
|
+
required: ['type'],
|
|
257
|
+
additionalProperties: false,
|
|
258
|
+
},
|
|
259
|
+
strict: true,
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
// Not strict: `values` and `conditions` are free-form. formFieldOps checks every change.
|
|
263
|
+
name: 'editFormFields',
|
|
264
|
+
description: [
|
|
265
|
+
'Changes the fields of the open form, applied in order, all or nothing. Each change appears in the form builder at once.',
|
|
266
|
+
"Changes: add { type, values?, index? }; update { field, values?, unset? } (merges values; a rename also renames the field in other fields' rules); move { field, index } (final position, 0 = first); remove { field }; setConditions { field, conditions } (null = always show). `field` is the field's name or id.",
|
|
267
|
+
FORM_FIELDS_GUIDE,
|
|
268
|
+
].join('\n\n'),
|
|
269
|
+
inputSchema: {
|
|
270
|
+
type: 'object',
|
|
271
|
+
properties: {
|
|
272
|
+
changes: {
|
|
273
|
+
type: 'array',
|
|
274
|
+
minItems: 1,
|
|
275
|
+
items: {
|
|
276
|
+
type: 'object',
|
|
277
|
+
properties: {
|
|
278
|
+
action: { type: 'string', enum: ['add', 'update', 'move', 'remove', 'setConditions'] },
|
|
279
|
+
type: { type: 'string', enum: types, description: 'add: the field type.' },
|
|
280
|
+
field: { type: 'string', description: "The field's name or id." },
|
|
281
|
+
values: { type: 'object', description: 'add, update: props, e.g. { "label": "Email", "required": true, "className": "sm:w-[calc(50%-0.5rem)]" }. Width is classes (className), never a prop.' },
|
|
282
|
+
unset: { type: 'array', items: { type: 'string' } },
|
|
283
|
+
index: { type: 'integer', minimum: 0 },
|
|
284
|
+
conditions: { type: ['object', 'null'], description: '{ match?: "all" | "any", rules: [{ field, operator, value? }] }' },
|
|
285
|
+
},
|
|
286
|
+
required: ['action'],
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
required: ['changes'],
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
];
|
|
294
|
+
}
|
|
234
295
|
/** Tool definitions in a fixed order (the order is part of the cached prompt prefix). */
|
|
235
296
|
export function toolDefinitions(env) {
|
|
297
|
+
if (env.form)
|
|
298
|
+
return formToolDefinitions(env);
|
|
236
299
|
const types = env.blocks.map((b) => b.type);
|
|
237
300
|
const saved = env.savedSections === true;
|
|
238
301
|
const sectionIds = env.sections.map((s) => s.id);
|
|
@@ -445,6 +508,8 @@ export const RUNNING_SUMMARY = {
|
|
|
445
508
|
searchMedia: 'Searching the media library',
|
|
446
509
|
generateImage: 'Generating an image',
|
|
447
510
|
getBindingSources: 'Reading document fields',
|
|
511
|
+
getForm: 'Reading the form',
|
|
512
|
+
editFormFields: 'Editing the form',
|
|
448
513
|
};
|
|
449
514
|
// ---------------------------------------------------------------------------
|
|
450
515
|
// Execution
|
|
@@ -663,6 +728,25 @@ export async function runTool(name, rawInput, workspace, env) {
|
|
|
663
728
|
switch (name) {
|
|
664
729
|
case 'getLayout':
|
|
665
730
|
return ok({ layout: workspace.view }, 'Read the page');
|
|
731
|
+
case 'getForm':
|
|
732
|
+
return ok({ fields: formFieldsOf(workspace.view), fieldTypes: formFieldTypes(env.blocks) }, 'Read the form');
|
|
733
|
+
case 'editFormFields': {
|
|
734
|
+
const changes = parseJson(input.changes);
|
|
735
|
+
if (!Array.isArray(changes) || changes.length === 0)
|
|
736
|
+
return fail('`changes` must be a non-empty list', 'Edit failed');
|
|
737
|
+
const planned = formFieldOps(workspace.layout, changes, env.blocks);
|
|
738
|
+
if (!planned.ok)
|
|
739
|
+
return fail(planned.error, 'Edit failed');
|
|
740
|
+
const result = workspace.apply(planned.ops);
|
|
741
|
+
if (!result.ok)
|
|
742
|
+
return fail(result.error, 'Edit failed', result.errors);
|
|
743
|
+
return ok({
|
|
744
|
+
ok: true,
|
|
745
|
+
fields: formFieldsOf(workspace.view),
|
|
746
|
+
...(planned.notes.length > 0 ? { notes: planned.notes } : {}),
|
|
747
|
+
...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),
|
|
748
|
+
}, describeFormOps(result.ops), result.ops);
|
|
749
|
+
}
|
|
666
750
|
case 'getBlockSchema': {
|
|
667
751
|
const def = env.blocks.find((b) => b.type === input.type);
|
|
668
752
|
if (!def)
|
|
@@ -4,6 +4,8 @@ import { classesOf, labelField, labelsField, labelsHelp } from './shared.js';
|
|
|
4
4
|
export { CAROUSEL_CLASS_MAP, CAROUSEL_LABELS, CAROUSEL_PART_CLASSES };
|
|
5
5
|
export const CAROUSEL_BLOCK = 'carousel';
|
|
6
6
|
const CAROUSEL_CLASS = 'flex flex-col gap-4';
|
|
7
|
+
/** A new slide: one full-width slide at a time, its content in a column. */
|
|
8
|
+
const SLIDE_CLASS = 'flex min-w-0 shrink-0 grow-0 basis-full flex-col gap-3';
|
|
7
9
|
/**
|
|
8
10
|
* The carousel's inner elements that take classes (`block.partClassName`), with the classes a new
|
|
9
11
|
* carousel starts with. The "slides" slot (the track) is a part too.
|
|
@@ -73,7 +75,14 @@ export function carouselBlock() {
|
|
|
73
75
|
labelsField(CAROUSEL_LABELS, LABEL_NAMES),
|
|
74
76
|
],
|
|
75
77
|
slots: {
|
|
76
|
-
slides: {
|
|
78
|
+
slides: {
|
|
79
|
+
label: 'Slides',
|
|
80
|
+
styles: true,
|
|
81
|
+
defaultClassName: CAROUSEL_PART_CLASSES.slides,
|
|
82
|
+
description: 'Each block here is one slide',
|
|
83
|
+
itemLabel: 'Slide',
|
|
84
|
+
newBlock: { type: 'stack', label: 'Slide', className: SLIDE_CLASS },
|
|
85
|
+
},
|
|
77
86
|
previous: { label: 'Previous button', allow: ARROW_CONTENT, max: 1 },
|
|
78
87
|
next: { label: 'Next button', allow: ARROW_CONTENT, max: 1 },
|
|
79
88
|
},
|
package/dist/blocks/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { defaultBlocks, FIELD_CLASS_MAP, MENU_CLASS_MAP, MENU_LABELS, type DefaultBlocksOptions } from './defaults.js';
|
|
2
2
|
export * from './builtins/index.js';
|
|
3
3
|
export { isLinkField, linkField, type BuilderCondition, type LinkFieldOptions } from './link.js';
|
|
4
|
-
export { fromPayloadBlocks, type FromPayloadBlocksOptions, type PayloadBlockOverride } from './payload.js';
|
|
4
|
+
export { BLOCK_KEY_MARKER, fromPayloadBlocks, type FromPayloadBlocksOptions, type PayloadBlockOverride } from './payload.js';
|
|
5
5
|
export { defineBlock, defineSection, type SectionBlockInput, type SectionInput, sectionsWithVariants, withDefaultClassNames, withInlineBlocks } from '../core/blocks.js';
|
|
6
6
|
export { BUILDER_CSS_CLASS, withBuilderCssClass } from '../css/marker.js';
|
|
7
7
|
export { listCollectionsOf, prepareBlocks } from '../plugin/listCollections.js';
|
package/dist/blocks/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
export { defaultBlocks, FIELD_CLASS_MAP, MENU_CLASS_MAP, MENU_LABELS } from './defaults.js';
|
|
5
5
|
export * from './builtins/index.js';
|
|
6
6
|
export { isLinkField, linkField } from './link.js';
|
|
7
|
-
export { fromPayloadBlocks } from './payload.js';
|
|
7
|
+
export { BLOCK_KEY_MARKER, fromPayloadBlocks } from './payload.js';
|
|
8
8
|
export { defineBlock, defineSection, sectionsWithVariants, withDefaultClassNames, withInlineBlocks } from '../core/blocks.js';
|
|
9
9
|
export { BUILDER_CSS_CLASS, withBuilderCssClass } from '../css/marker.js';
|
|
10
10
|
// Public since 0.4.0. 0.5.0 dropped this line by mistake; `exports.test.ts` keeps it.
|
package/dist/blocks/payload.d.ts
CHANGED
|
@@ -40,6 +40,13 @@ export type FromPayloadBlocksOptions = {
|
|
|
40
40
|
onWarning?: ((message: string) => void) | false;
|
|
41
41
|
};
|
|
42
42
|
type Config = PayloadBlockConfig;
|
|
43
|
+
/**
|
|
44
|
+
* `admin.custom.builderBlockKey` on a top-level field of a Payload block: the field stores the
|
|
45
|
+
* block's `className` (a text field) or `partClassName` (a json field). `fromPayloadBlocks` leaves
|
|
46
|
+
* the field out of the props and records it in `payload.classKeys`, so a Payload blocks field keeps
|
|
47
|
+
* the block's classes and the editor offers its Styles tab. Hide the field in Payload's admin.
|
|
48
|
+
*/
|
|
49
|
+
export declare const BLOCK_KEY_MARKER = "builderBlockKey";
|
|
43
50
|
/**
|
|
44
51
|
* Builder block definitions from Payload block configs, so a site keeps its own blocks.
|
|
45
52
|
*
|
package/dist/blocks/payload.js
CHANGED
|
@@ -3,6 +3,13 @@
|
|
|
3
3
|
import { conditionFromFunction } from '../core/conditions.js';
|
|
4
4
|
import { textOf } from '../core/fields.js';
|
|
5
5
|
import { isPlainObject } from '../core/tree.js';
|
|
6
|
+
/**
|
|
7
|
+
* `admin.custom.builderBlockKey` on a top-level field of a Payload block: the field stores the
|
|
8
|
+
* block's `className` (a text field) or `partClassName` (a json field). `fromPayloadBlocks` leaves
|
|
9
|
+
* the field out of the props and records it in `payload.classKeys`, so a Payload blocks field keeps
|
|
10
|
+
* the block's classes and the editor offers its Styles tab. Hide the field in Payload's admin.
|
|
11
|
+
*/
|
|
12
|
+
export const BLOCK_KEY_MARKER = 'builderBlockKey';
|
|
6
13
|
const ICONS = [
|
|
7
14
|
[/head|title/i, 'heading'],
|
|
8
15
|
[/video/i, 'video'],
|
|
@@ -77,6 +84,7 @@ export function fromPayloadBlocks(blocks, options = {}) {
|
|
|
77
84
|
function definitionOf(block) {
|
|
78
85
|
const notes = [];
|
|
79
86
|
const slots = {};
|
|
87
|
+
const classKeys = {};
|
|
80
88
|
const fields = adaptFields(block.fields, true, '');
|
|
81
89
|
const override = options.overrides?.[block.slug] ?? {};
|
|
82
90
|
const label = override.label ?? textOf(block.labels?.singular) ?? words(block.slug);
|
|
@@ -95,11 +103,11 @@ export function fromPayloadBlocks(blocks, options = {}) {
|
|
|
95
103
|
label,
|
|
96
104
|
fields,
|
|
97
105
|
...(hasSlots ? { slots } : {}),
|
|
98
|
-
styles: override.styles ?? options.styles ??
|
|
106
|
+
styles: override.styles ?? options.styles ?? Boolean(classKeys.className),
|
|
99
107
|
icon: override.icon ?? (hasSlots ? 'section' : (ICONS.find(([test]) => test.test(block.slug))?.[1] ?? 'block')),
|
|
100
108
|
category: override.category ?? textOf(block.admin?.group) ?? options.category ?? (hasSlots ? 'Site sections' : 'Site blocks'),
|
|
101
109
|
ai: override.ai ?? { description: `${label}: a block of the site's own design.${slotText}` },
|
|
102
|
-
payload: { slug: block.slug },
|
|
110
|
+
payload: { slug: block.slug, ...(Object.keys(classKeys).length > 0 ? { classKeys } : {}) },
|
|
103
111
|
};
|
|
104
112
|
if (override.defaultClassName)
|
|
105
113
|
def.defaultClassName = override.defaultClassName;
|
|
@@ -125,6 +133,12 @@ export function fromPayloadBlocks(blocks, options = {}) {
|
|
|
125
133
|
const name = typeof field.name === 'string' ? field.name : '';
|
|
126
134
|
const at = name ? `${path}${name}` : path;
|
|
127
135
|
readAdmin(field, at);
|
|
136
|
+
// A field that stores the block's classes is block data, not a prop.
|
|
137
|
+
const blockKey = isPlainObject(field.admin) && isPlainObject(field.admin.custom) ? field.admin.custom[BLOCK_KEY_MARKER] : undefined;
|
|
138
|
+
if (top && name && (blockKey === 'className' || blockKey === 'partClassName')) {
|
|
139
|
+
classKeys[blockKey] = name;
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
128
142
|
switch (field.type) {
|
|
129
143
|
case 'blocks': {
|
|
130
144
|
const allowed = blocksOfField(field);
|
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
export declare const DEFAULT_COMMENTS_SLUG = "builder-comments";
|
|
3
3
|
/** Server-only key in `config.custom` that holds `CommentsServerConfig`. */
|
|
4
4
|
export declare const COMMENTS_CONFIG_KEY = "websiteBuilderComments";
|
|
5
|
+
/**
|
|
6
|
+
* The builder URL's search parameter that opens one thread in comment mode:
|
|
7
|
+
* `/admin/builder/pages/12?comment=34`. The dashboard's "Open comments" links use it.
|
|
8
|
+
*/
|
|
9
|
+
export declare const COMMENT_PARAM = "comment";
|
|
5
10
|
/** Longest comment text, in characters. */
|
|
6
11
|
export declare const COMMENT_MAX = 5000;
|
|
7
12
|
/** What the editor needs: the collection it reads and writes over Payload's REST API. */
|
package/dist/comments/shared.js
CHANGED
|
@@ -5,6 +5,11 @@
|
|
|
5
5
|
export const DEFAULT_COMMENTS_SLUG = 'builder-comments';
|
|
6
6
|
/** Server-only key in `config.custom` that holds `CommentsServerConfig`. */
|
|
7
7
|
export const COMMENTS_CONFIG_KEY = 'websiteBuilderComments';
|
|
8
|
+
/**
|
|
9
|
+
* The builder URL's search parameter that opens one thread in comment mode:
|
|
10
|
+
* `/admin/builder/pages/12?comment=34`. The dashboard's "Open comments" links use it.
|
|
11
|
+
*/
|
|
12
|
+
export const COMMENT_PARAM = 'comment';
|
|
8
13
|
/** Longest comment text, in characters. */
|
|
9
14
|
export const COMMENT_MAX = 5000;
|
|
10
15
|
const text = (value) => (typeof value === 'string' && value ? value : null);
|
package/dist/core/blocks.d.ts
CHANGED
|
@@ -76,18 +76,30 @@ export declare function sectionsWithDefaultClassNames(sections: readonly Section
|
|
|
76
76
|
* block is inline.
|
|
77
77
|
*/
|
|
78
78
|
export declare function withInlineBlocks(blocks: BlockDefinition[]): BlockDefinition[];
|
|
79
|
+
/**
|
|
80
|
+
* The layout with `BlockDefinition.upgrade` run on every block (slots too, children first). The
|
|
81
|
+
* same layout when no block changes, or when no definition has an upgrade.
|
|
82
|
+
*/
|
|
83
|
+
export declare function upgradeLayout(layout: Layout, blocks: readonly BlockDefinition[]): Layout;
|
|
79
84
|
export declare function getBlockDefinition(blocks: readonly BlockDefinition[], type: string): BlockDefinition | undefined;
|
|
80
85
|
/** Slot names of a block type, in declared order. */
|
|
81
86
|
export declare function slotNames(def: BlockDefinition | undefined): string[];
|
|
82
87
|
/** The block's name for people: its own `label`, else the block type's label, else the type. */
|
|
83
88
|
export declare function blockName(block: Pick<Block, 'type' | 'label'>, blocks: readonly BlockDefinition[]): string;
|
|
89
|
+
/**
|
|
90
|
+
* Why a block (a type, or a whole block with its children) cannot sit below blocks of the types
|
|
91
|
+
* `above` (outermost first; empty for the root list) by the `ancestors` rules of its types, or
|
|
92
|
+
* `null`. Inside the placed subtree, a block's own ancestors in the subtree count too.
|
|
93
|
+
*/
|
|
94
|
+
export declare function ancestorsError(blocks: readonly BlockDefinition[], block: string | Block, above: readonly string[]): string | null;
|
|
84
95
|
/**
|
|
85
96
|
* Why `block` (a type, or a whole block with its children) cannot go into `slot` of `parentId`,
|
|
86
97
|
* or `null` when it can. Checks the direct slot's `allow` and `disallow`, and the `disallow` of
|
|
87
98
|
* every ancestor slot up to the root, against every type in the placed subtree, the placed
|
|
88
|
-
* block's own `parents` rule,
|
|
89
|
-
* moved within it, does not count as one more).
|
|
90
|
-
*
|
|
99
|
+
* block's own `parents` rule, the `ancestors` rules of every type in the subtree, and the direct
|
|
100
|
+
* slot's `max` (a block already in that slot, being moved within it, does not count as one more).
|
|
101
|
+
* The root list accepts every type without a `parents` or `ancestors` rule. The message is
|
|
102
|
+
* readable, e.g. `Button cannot go inside Link`.
|
|
91
103
|
*/
|
|
92
104
|
export declare function placementError(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string, block: string | Block, index?: Map<string, IndexedBlock>): string | null;
|
|
93
105
|
/** The slot's name for people: its `label`, else its name. */
|
|
@@ -104,6 +116,8 @@ export declare function slotFullError(blocks: readonly BlockDefinition[], owner:
|
|
|
104
116
|
* a slot without a limit, or an unknown parent.
|
|
105
117
|
*/
|
|
106
118
|
export declare function slotRoom(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string): number;
|
|
119
|
+
/** The definition of `slot` of block `parentId`. Undefined for the root list and undeclared slots. */
|
|
120
|
+
export declare function slotDefinitionAt(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string): SlotDefinition | undefined;
|
|
107
121
|
/** True when `block` (a type or a whole block) may go into `slot` of `parentId`. See `placementError`. */
|
|
108
122
|
export declare function slotAcceptsAt(blocks: readonly BlockDefinition[], layout: Layout, parentId: string | null, slot: string, block: string | Block): boolean;
|
|
109
123
|
/**
|
package/dist/core/blocks.js
CHANGED
|
@@ -203,6 +203,36 @@ export function withInlineBlocks(blocks) {
|
|
|
203
203
|
return { ...def, slots: next };
|
|
204
204
|
});
|
|
205
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* The layout with `BlockDefinition.upgrade` run on every block (slots too, children first). The
|
|
208
|
+
* same layout when no block changes, or when no definition has an upgrade.
|
|
209
|
+
*/
|
|
210
|
+
export function upgradeLayout(layout, blocks) {
|
|
211
|
+
const upgrades = new Map(blocks.flatMap((def) => (def.upgrade ? [[def.type, def.upgrade]] : [])));
|
|
212
|
+
if (upgrades.size === 0)
|
|
213
|
+
return layout;
|
|
214
|
+
const visitList = (list) => {
|
|
215
|
+
let changed = false;
|
|
216
|
+
const out = list.map((block) => {
|
|
217
|
+
const next = visit(block);
|
|
218
|
+
if (next !== block)
|
|
219
|
+
changed = true;
|
|
220
|
+
return next;
|
|
221
|
+
});
|
|
222
|
+
return changed ? out : list;
|
|
223
|
+
};
|
|
224
|
+
const visit = (block) => {
|
|
225
|
+
let next = block;
|
|
226
|
+
if (block.slots) {
|
|
227
|
+
const slots = Object.fromEntries(Object.entries(block.slots).map(([name, children]) => [name, visitList(children)]));
|
|
228
|
+
if (Object.keys(slots).some((name) => slots[name] !== block.slots?.[name]))
|
|
229
|
+
next = { ...block, slots };
|
|
230
|
+
}
|
|
231
|
+
return upgrades.get(block.type)?.(next) ?? next;
|
|
232
|
+
};
|
|
233
|
+
const list = visitList(layout.blocks);
|
|
234
|
+
return list === layout.blocks ? layout : { ...layout, blocks: list };
|
|
235
|
+
}
|
|
206
236
|
export function getBlockDefinition(blocks, type) {
|
|
207
237
|
return blocks.find((b) => b.type === type);
|
|
208
238
|
}
|
|
@@ -222,18 +252,65 @@ function subtreeTypes(block, out = new Set()) {
|
|
|
222
252
|
subtreeTypes(child, out);
|
|
223
253
|
return out;
|
|
224
254
|
}
|
|
255
|
+
/** "Email can only go inside Form", or "… inside Form or Survey". */
|
|
256
|
+
function ancestorsMessage(blocks, type) {
|
|
257
|
+
const label = (t) => getBlockDefinition(blocks, t)?.label ?? t;
|
|
258
|
+
const ancestors = getBlockDefinition(blocks, type)?.ancestors ?? [];
|
|
259
|
+
return `${label(type)} can only go inside ${ancestors.map(label).join(' or ')}`;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Why a block (a type, or a whole block with its children) cannot sit below blocks of the types
|
|
263
|
+
* `above` (outermost first; empty for the root list) by the `ancestors` rules of its types, or
|
|
264
|
+
* `null`. Inside the placed subtree, a block's own ancestors in the subtree count too.
|
|
265
|
+
*/
|
|
266
|
+
export function ancestorsError(blocks, block, above) {
|
|
267
|
+
const rootType = typeof block === 'string' ? block : block.type;
|
|
268
|
+
const label = (t) => getBlockDefinition(blocks, t)?.label ?? t;
|
|
269
|
+
const visit = (current, path) => {
|
|
270
|
+
const type = typeof current === 'string' ? current : current.type;
|
|
271
|
+
const rule = getBlockDefinition(blocks, type)?.ancestors;
|
|
272
|
+
if (rule && !rule.some((t) => path.includes(t))) {
|
|
273
|
+
return type === rootType && current === block ? ancestorsMessage(blocks, type) : `${label(rootType)} contains ${ancestorsMessage(blocks, type).replace(' can only', ', which can only')}`;
|
|
274
|
+
}
|
|
275
|
+
if (typeof current === 'string')
|
|
276
|
+
return null;
|
|
277
|
+
const inner = [...path, type];
|
|
278
|
+
for (const children of Object.values(current.slots ?? {})) {
|
|
279
|
+
for (const child of children) {
|
|
280
|
+
const error = visit(child, inner);
|
|
281
|
+
if (error)
|
|
282
|
+
return error;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
};
|
|
287
|
+
return visit(block, above);
|
|
288
|
+
}
|
|
289
|
+
/** The types of `parentId` and its ancestors, outermost first. Empty for the root list. */
|
|
290
|
+
function typesAbove(index, parentId) {
|
|
291
|
+
const out = [];
|
|
292
|
+
for (let id = parentId; id !== null;) {
|
|
293
|
+
const entry = index.get(id);
|
|
294
|
+
if (!entry)
|
|
295
|
+
break;
|
|
296
|
+
out.unshift(entry.block.type);
|
|
297
|
+
id = entry.parentId;
|
|
298
|
+
}
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
225
301
|
/**
|
|
226
302
|
* Why `block` (a type, or a whole block with its children) cannot go into `slot` of `parentId`,
|
|
227
303
|
* or `null` when it can. Checks the direct slot's `allow` and `disallow`, and the `disallow` of
|
|
228
304
|
* every ancestor slot up to the root, against every type in the placed subtree, the placed
|
|
229
|
-
* block's own `parents` rule,
|
|
230
|
-
* moved within it, does not count as one more).
|
|
231
|
-
*
|
|
305
|
+
* block's own `parents` rule, the `ancestors` rules of every type in the subtree, and the direct
|
|
306
|
+
* slot's `max` (a block already in that slot, being moved within it, does not count as one more).
|
|
307
|
+
* The root list accepts every type without a `parents` or `ancestors` rule. The message is
|
|
308
|
+
* readable, e.g. `Button cannot go inside Link`.
|
|
232
309
|
*/
|
|
233
310
|
export function placementError(blocks, layout, parentId, slot, block, index = indexLayout(layout)) {
|
|
234
311
|
const rootType = typeof block === 'string' ? block : block.type;
|
|
235
312
|
if (parentId === null)
|
|
236
|
-
return fitsParent(blocks, rootType, null) ?
|
|
313
|
+
return fitsParent(blocks, rootType, null) ? ancestorsError(blocks, block, []) : parentsMessage(blocks, rootType);
|
|
237
314
|
const types = typeof block === 'string' ? new Set([block]) : subtreeTypes(block);
|
|
238
315
|
const label = (type) => getBlockDefinition(blocks, type)?.label ?? type;
|
|
239
316
|
const skip = typeof block === 'string' ? new Set() : new Set(subtreeIds(block));
|
|
@@ -277,7 +354,7 @@ export function placementError(blocks, layout, parentId, slot, block, index = in
|
|
|
277
354
|
slotName = owner.slot;
|
|
278
355
|
ownerId = owner.parentId;
|
|
279
356
|
}
|
|
280
|
-
return
|
|
357
|
+
return ancestorsError(blocks, block, typesAbove(index, parentId));
|
|
281
358
|
}
|
|
282
359
|
/** The slot's name for people: its `label`, else its name. */
|
|
283
360
|
export function slotLabel(def, slot) {
|
|
@@ -305,13 +382,18 @@ export function slotFullError(blocks, owner, slot) {
|
|
|
305
382
|
* a slot without a limit, or an unknown parent.
|
|
306
383
|
*/
|
|
307
384
|
export function slotRoom(blocks, layout, parentId, slot) {
|
|
308
|
-
|
|
385
|
+
const max = slotDefinitionAt(blocks, layout, parentId, slot)?.max;
|
|
386
|
+
if (typeof max !== 'number')
|
|
309
387
|
return Infinity;
|
|
388
|
+
const owner = parentId === null ? null : indexLayout(layout).get(parentId)?.block;
|
|
389
|
+
return Math.max(0, max - (owner?.slots?.[slot]?.length ?? 0));
|
|
390
|
+
}
|
|
391
|
+
/** The definition of `slot` of block `parentId`. Undefined for the root list and undeclared slots. */
|
|
392
|
+
export function slotDefinitionAt(blocks, layout, parentId, slot) {
|
|
393
|
+
if (parentId === null)
|
|
394
|
+
return undefined;
|
|
310
395
|
const owner = indexLayout(layout).get(parentId)?.block;
|
|
311
|
-
|
|
312
|
-
if (!owner || typeof max !== 'number')
|
|
313
|
-
return Infinity;
|
|
314
|
-
return Math.max(0, max - (owner.slots?.[slot]?.length ?? 0));
|
|
396
|
+
return owner ? getBlockDefinition(blocks, owner.type)?.slots?.[slot] : undefined;
|
|
315
397
|
}
|
|
316
398
|
/** True when `block` (a type or a whole block) may go into `slot` of `parentId`. See `placementError`. */
|
|
317
399
|
export function slotAcceptsAt(blocks, layout, parentId, slot, block) {
|
package/dist/core/classes.d.ts
CHANGED
|
@@ -20,3 +20,8 @@ export declare function defaultPartClassNames(def: Pick<BlockDefinition, 'slots'
|
|
|
20
20
|
* in the layout.
|
|
21
21
|
*/
|
|
22
22
|
export declare function collectClasses(layout: Layout, blocks?: readonly BlockDefinition[]): string[];
|
|
23
|
+
/**
|
|
24
|
+
* The classes a block's part shows: its own (`partClassName`), else, for a part that `inherits`,
|
|
25
|
+
* the classes of that part of the nearest ancestor block of the named type. '' when it has none.
|
|
26
|
+
*/
|
|
27
|
+
export declare function partClassNameOf(layout: Layout, blockId: string, part: string, definitions: readonly BlockDefinition[]): string;
|