@elementor/editor-canvas 4.5.0-1178 → 4.5.0-1180

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.
@@ -0,0 +1,240 @@
1
+ import { getCurrentDocument } from '@elementor/editor-documents';
2
+ import { createElement, deleteElement, getContainer, getCurrentDocumentContainer } from '@elementor/editor-elements';
3
+ import { undoable } from '@elementor/editor-v1-adapters';
4
+ import { httpService } from '@elementor/http-client';
5
+
6
+ import { initBuildCompositionTool } from '../tool';
7
+
8
+ jest.mock( '@elementor/http-client', () => ( {
9
+ httpService: jest.fn(),
10
+ AxiosError: class AxiosError extends Error {},
11
+ } ) );
12
+
13
+ jest.mock( '@elementor/editor-documents', () => ( {
14
+ getCurrentDocument: jest.fn(),
15
+ } ) );
16
+
17
+ jest.mock( '@elementor/editor-elements', () => ( {
18
+ createElement: jest.fn( ( { model } ) => ( { id: model.id } ) ),
19
+ deleteElement: jest.fn(),
20
+ getContainer: jest.fn(),
21
+ getCurrentDocumentContainer: jest.fn(),
22
+ } ) );
23
+
24
+ type UndoableActions = {
25
+ do: () => unknown;
26
+ undo: ( payload: undefined, result: unknown ) => void;
27
+ };
28
+
29
+ let lastUndoable: { actions: UndoableActions; result: unknown } | null = null;
30
+
31
+ jest.mock( '@elementor/editor-v1-adapters', () => ( {
32
+ undoable: jest.fn( ( actions: UndoableActions ) => () => {
33
+ const result = actions.do();
34
+ lastUndoable = { actions, result };
35
+
36
+ return result;
37
+ } ),
38
+ } ) );
39
+
40
+ type ToolConfig = {
41
+ handler: ( input: Record< string, unknown > ) => Promise< Record< string, unknown > >;
42
+ };
43
+
44
+ const POST_ID = 12;
45
+ const CURRENT_TREE = [ { id: 'unsaved1', elType: 'e-div-block', elements: [] } ];
46
+ const PLANNED_ELEMENT = {
47
+ id: 'a1b2c3',
48
+ elType: 'e-div-block',
49
+ settings: {},
50
+ elements: [ { id: 'd4e5f6', elType: 'widget', widgetType: 'e-heading', settings: {}, elements: [] } ],
51
+ };
52
+
53
+ const documentContainer = {
54
+ id: 'document',
55
+ model: {
56
+ get: () => ( { toJSON: () => CURRENT_TREE } ),
57
+ },
58
+ };
59
+
60
+ const captureTool = (): ToolConfig => {
61
+ const addTool = jest.fn();
62
+ initBuildCompositionTool( { addTool, resource: jest.fn() } as never );
63
+
64
+ return addTool.mock.calls[ 0 ][ 0 ] as ToolConfig;
65
+ };
66
+
67
+ const givenServerPlan = ( plan: Record< string, unknown > ) => {
68
+ const post = jest.fn().mockResolvedValue( { data: { data: plan } } );
69
+ jest.mocked( httpService ).mockReturnValue( { post } as never );
70
+
71
+ return post;
72
+ };
73
+
74
+ describe( 'build-composition tool', () => {
75
+ beforeEach( () => {
76
+ jest.clearAllMocks();
77
+ lastUndoable = null;
78
+ jest.mocked( getCurrentDocument ).mockReturnValue( { id: POST_ID } as never );
79
+ jest.mocked( getCurrentDocumentContainer ).mockReturnValue( documentContainer as never );
80
+ } );
81
+
82
+ it( 'plans in dry run against the live editor tree and inserts the planned elements locally', async () => {
83
+ // Arrange.
84
+ const post = givenServerPlan( {
85
+ root_element_ids: [ 'a1b2c3' ],
86
+ resolved_xml: '<e-div-block id="a1b2c3"></e-div-block>',
87
+ elements: [ PLANNED_ELEMENT ],
88
+ } );
89
+
90
+ // Act.
91
+ const result = await captureTool().handler( { xml_structure: '<e-div-block configuration-id="hero"/>' } );
92
+
93
+ // Assert.
94
+ expect( post ).toHaveBeenCalledWith( 'elementor/v1/mcp-proxy', {
95
+ tool: 'build-composition',
96
+ input: {
97
+ xml_structure: '<e-div-block configuration-id="hero"/>',
98
+ post_id: POST_ID,
99
+ parent_id: 'document',
100
+ mode: 'append',
101
+ dry_run: true,
102
+ document_elements: CURRENT_TREE,
103
+ },
104
+ } );
105
+ expect( createElement ).toHaveBeenCalledWith( {
106
+ container: documentContainer,
107
+ model: PLANNED_ELEMENT,
108
+ options: { useHistory: false },
109
+ } );
110
+ expect( deleteElement ).not.toHaveBeenCalled();
111
+ expect( undoable ).toHaveBeenCalledTimes( 1 );
112
+ expect( result ).toEqual( {
113
+ root_element_ids: [ 'a1b2c3' ],
114
+ resolved_xml: '<e-div-block id="a1b2c3"></e-div-block>',
115
+ } );
116
+ } );
117
+
118
+ it( 'replaces the children in a single undo step', async () => {
119
+ // Arrange.
120
+ const parentContainer = { id: 'parent1' };
121
+ const oldChildren: Record< string, unknown > = {
122
+ old1: {
123
+ id: 'old1',
124
+ parent: parentContainer,
125
+ model: { toJSON: () => ( { id: 'old1' } ) },
126
+ view: { _index: 0 },
127
+ },
128
+ old2: {
129
+ id: 'old2',
130
+ parent: parentContainer,
131
+ model: { toJSON: () => ( { id: 'old2' } ) },
132
+ view: { _index: 1 },
133
+ },
134
+ };
135
+ jest.mocked( getContainer ).mockImplementation(
136
+ ( id: string ) => ( id === 'parent1' ? parentContainer : oldChildren[ id ] ?? null ) as never
137
+ );
138
+ givenServerPlan( {
139
+ root_element_ids: [ 'a1b2c3' ],
140
+ removed_element_ids: [ 'old1', 'old2' ],
141
+ elements: [ PLANNED_ELEMENT ],
142
+ } );
143
+
144
+ // Act.
145
+ await captureTool().handler( {
146
+ xml_structure: '<e-div-block configuration-id="hero"/>',
147
+ parent_id: 'parent1',
148
+ mode: 'replace_children',
149
+ } );
150
+
151
+ // Assert.
152
+ expect( undoable ).toHaveBeenCalledTimes( 1 );
153
+ expect( undoable ).toHaveBeenCalledWith( expect.anything(), { title: 'Build composition' } );
154
+ expect( deleteElement ).toHaveBeenCalledWith( { container: oldChildren.old1, options: { useHistory: false } } );
155
+ expect( deleteElement ).toHaveBeenCalledWith( { container: oldChildren.old2, options: { useHistory: false } } );
156
+ expect( createElement ).toHaveBeenCalledWith( {
157
+ container: parentContainer,
158
+ model: PLANNED_ELEMENT,
159
+ options: { useHistory: false },
160
+ } );
161
+ } );
162
+
163
+ it( 'undo removes the created elements and restores the replaced children in place', async () => {
164
+ // Arrange.
165
+ const parentContainer = { id: 'parent1' };
166
+ const created = { id: 'a1b2c3' };
167
+ const old1 = {
168
+ id: 'old1',
169
+ parent: parentContainer,
170
+ model: { toJSON: () => ( { id: 'old1' } ) },
171
+ view: { _index: 2 },
172
+ };
173
+ const containers: Record< string, unknown > = { parent1: parentContainer, old1 };
174
+ jest.mocked( getContainer ).mockImplementation( ( id: string ) => ( containers[ id ] ?? null ) as never );
175
+ givenServerPlan( {
176
+ root_element_ids: [ 'a1b2c3' ],
177
+ removed_element_ids: [ 'old1' ],
178
+ elements: [ PLANNED_ELEMENT ],
179
+ } );
180
+ await captureTool().handler( {
181
+ xml_structure: '<e-div-block configuration-id="hero"/>',
182
+ parent_id: 'parent1',
183
+ mode: 'replace_children',
184
+ } );
185
+ containers.a1b2c3 = created;
186
+ jest.mocked( createElement ).mockClear();
187
+ jest.mocked( deleteElement ).mockClear();
188
+
189
+ // Act.
190
+ lastUndoable?.actions.undo( undefined, lastUndoable.result );
191
+
192
+ // Assert.
193
+ expect( deleteElement ).toHaveBeenCalledWith( { container: created, options: { useHistory: false } } );
194
+ expect( createElement ).toHaveBeenCalledWith( {
195
+ container: parentContainer,
196
+ model: { id: 'old1' },
197
+ options: { useHistory: false, at: 2 },
198
+ } );
199
+ } );
200
+
201
+ it( 'does not remove anything when the plan has no elements', async () => {
202
+ // Arrange.
203
+ jest.mocked( getContainer ).mockReturnValue( { id: 'parent1' } as never );
204
+ givenServerPlan( { root_element_ids: [], removed_element_ids: [ 'old1' ] } );
205
+
206
+ // Act & Assert.
207
+ await expect(
208
+ captureTool().handler( {
209
+ xml_structure: '<e-div-block configuration-id="hero"/>',
210
+ parent_id: 'parent1',
211
+ mode: 'replace_children',
212
+ } )
213
+ ).rejects.toThrow( 'The planned composition has no elements to build' );
214
+ expect( deleteElement ).not.toHaveBeenCalled();
215
+ expect( undoable ).not.toHaveBeenCalled();
216
+ } );
217
+
218
+ it( 'fails without calling the server when the parent is not in the editor', async () => {
219
+ // Arrange.
220
+ jest.mocked( getContainer ).mockReturnValue( null );
221
+ const post = givenServerPlan( {} );
222
+
223
+ // Act & Assert.
224
+ await expect(
225
+ captureTool().handler( { xml_structure: '<e-div-block configuration-id="hero"/>', parent_id: 'missing' } )
226
+ ).rejects.toThrow( 'Parent element not found: missing' );
227
+ expect( post ).not.toHaveBeenCalled();
228
+ } );
229
+
230
+ it( 'changes nothing in the editor when the server rejects the composition', async () => {
231
+ // Arrange.
232
+ const post = jest.fn().mockRejectedValue( new Error( 'invalid_xml' ) );
233
+ jest.mocked( httpService ).mockReturnValue( { post } as never );
234
+
235
+ // Act & Assert.
236
+ await expect( captureTool().handler( { xml_structure: '<broken' } ) ).rejects.toThrow( 'invalid_xml' );
237
+ expect( createElement ).not.toHaveBeenCalled();
238
+ expect( deleteElement ).not.toHaveBeenCalled();
239
+ } );
240
+ } );
@@ -0,0 +1,236 @@
1
+ import { getCurrentDocument } from '@elementor/editor-documents';
2
+ import {
3
+ createElement,
4
+ type CreateElementParams,
5
+ deleteElement,
6
+ getContainer,
7
+ getCurrentDocumentContainer,
8
+ type V1Element,
9
+ } from '@elementor/editor-elements';
10
+ import { type MCPRegistryEntry } from '@elementor/editor-mcp';
11
+ import { undoable } from '@elementor/editor-v1-adapters';
12
+ import { type HttpResponse, httpService } from '@elementor/http-client';
13
+ import { z } from '@elementor/schema';
14
+ import { __ } from '@wordpress/i18n';
15
+
16
+ import { getMcpErrorMessage } from '../../utils/get-mcp-error-message';
17
+
18
+ const MCP_PROXY_URL = 'elementor/v1/mcp-proxy';
19
+ const TOOL_NAME = 'build-composition';
20
+ const DOCUMENT_ROOT = 'document';
21
+ const ELEMENTS_TO_JSON_OPTIONS = { remove: [ 'default', 'editSettings', 'defaultEditSettings' ] };
22
+
23
+ export const BUILD_COMPOSITION_GUIDE_URI = 'elementor://tools/build-composition-guide';
24
+
25
+ type PlannedElement = NonNullable< CreateElementParams[ 'model' ] >;
26
+
27
+ type BuildCompositionResponse = {
28
+ root_element_ids: string[];
29
+ removed_element_ids?: string[];
30
+ resolved_xml?: string;
31
+ warnings?: string[];
32
+ warning_details?: unknown[];
33
+ pro_features_discovery?: Array< { message: string; upgrade_url: string } >;
34
+ elements: PlannedElement[];
35
+ };
36
+
37
+ type ElementsCollection = { toJSON: ( options: typeof ELEMENTS_TO_JSON_OPTIONS ) => unknown[] };
38
+
39
+ export const initBuildCompositionTool = ( reg: MCPRegistryEntry ) => {
40
+ const { addTool, resource } = reg;
41
+
42
+ resource(
43
+ 'build-composition-guide',
44
+ BUILD_COMPOSITION_GUIDE_URI,
45
+ {
46
+ title: 'Build Composition Guide',
47
+ description: 'Full guide for the build-composition tool',
48
+ mimeType: 'text/markdown',
49
+ },
50
+ async ( uri: URL ) => {
51
+ const { data } = await httpService().get< HttpResponse< string > >( MCP_PROXY_URL, {
52
+ params: { uri: uri.href },
53
+ } );
54
+
55
+ return {
56
+ contents: [ { uri: uri.href, mimeType: 'text/markdown', text: data.data } ],
57
+ };
58
+ }
59
+ );
60
+
61
+ addTool( {
62
+ name: TOOL_NAME,
63
+ description:
64
+ 'Build a V4 layout on the open page from an XML structure in one call. Read the build-composition guide resource before use. ' +
65
+ 'Every element in xml_structure needs a unique configuration-id; element_config, style, classes and interactions are keyed by it. ' +
66
+ 'The elements are added to the editor (unsaved, undoable) and their new element ids are returned in resolved_xml and root_element_ids.',
67
+ schema: {
68
+ xml_structure: z
69
+ .string()
70
+ .describe(
71
+ 'Raw XML of Elementor widget tags, e.g. <e-div-block configuration-id="hero"><e-heading configuration-id="hero-title"></e-heading></e-div-block>. No other attributes, ids, classes or text nodes.'
72
+ ),
73
+ element_config: z
74
+ .record( z.string(), z.any() )
75
+ .optional()
76
+ .describe( 'configuration-id → plain widget settings matching elementor://widgets/schema/{type}.' ),
77
+ editor_settings: z
78
+ .record( z.string(), z.any() )
79
+ .optional()
80
+ .describe( 'configuration-id → editor-only fields.' ),
81
+ style: z
82
+ .record( z.string(), z.string() )
83
+ .optional()
84
+ .describe(
85
+ 'configuration-id → plain CSS string. Supports &:hover/&:focus/&:active nesting and @media(--breakpoint) blocks.'
86
+ ),
87
+ classes: z
88
+ .record( z.string(), z.array( z.string() ) )
89
+ .optional()
90
+ .describe( 'configuration-id → existing global class labels to attach.' ),
91
+ interactions: z
92
+ .record( z.string(), z.array( z.record( z.string(), z.any() ) ) )
93
+ .optional()
94
+ .describe( 'configuration-id → interaction items. See elementor://interactions/schema.' ),
95
+ parent_id: z
96
+ .string()
97
+ .optional()
98
+ .describe( 'Element id of the parent container. Omit to insert at the document root.' ),
99
+ mode: z
100
+ .enum( [ 'append', 'replace_children' ] )
101
+ .optional()
102
+ .describe(
103
+ 'append (default) or replace_children, which removes the existing children of parent_id first.'
104
+ ),
105
+ },
106
+ outputSchema: {
107
+ root_element_ids: z.array( z.string() ).describe( 'Ids of the created root-level elements.' ),
108
+ resolved_xml: z.string().optional().describe( 'The XML with the new element ids embedded.' ),
109
+ removed_element_ids: z.array( z.string() ).optional(),
110
+ warnings: z.array( z.string() ).optional(),
111
+ warning_details: z.array( z.any() ).optional(),
112
+ pro_features_discovery: z.array( z.object( { message: z.string(), upgrade_url: z.string() } ) ).optional(),
113
+ },
114
+ requiredResources: [
115
+ { uri: BUILD_COMPOSITION_GUIDE_URI, description: 'Full guide for XML structure, ids, layouts and styles' },
116
+ ],
117
+ handler: async ( { parent_id: parentId = DOCUMENT_ROOT, mode = 'append', ...input } ) => {
118
+ const postId = getCurrentDocument()?.id;
119
+ const documentContainer = getCurrentDocumentContainer();
120
+
121
+ if ( ! postId || ! documentContainer ) {
122
+ throw new Error( 'No active document found.' );
123
+ }
124
+
125
+ const parentContainer = parentId === DOCUMENT_ROOT ? documentContainer : getContainer( parentId );
126
+
127
+ if ( ! parentContainer ) {
128
+ throw new Error( `Parent element not found: ${ parentId }` );
129
+ }
130
+
131
+ let plan: BuildCompositionResponse;
132
+
133
+ try {
134
+ const { data } = await httpService().post< HttpResponse< BuildCompositionResponse > >( MCP_PROXY_URL, {
135
+ tool: TOOL_NAME,
136
+ input: {
137
+ ...input,
138
+ post_id: postId,
139
+ parent_id: parentId,
140
+ mode,
141
+ dry_run: true,
142
+ document_elements: serializeElements( documentContainer ),
143
+ },
144
+ } );
145
+
146
+ plan = data.data;
147
+ } catch ( error ) {
148
+ throw new Error( getMcpErrorMessage( error, TOOL_NAME ) );
149
+ }
150
+
151
+ applyPlan( parentContainer, plan );
152
+
153
+ const { elements, ...result } = plan;
154
+
155
+ return result;
156
+ },
157
+ } );
158
+ };
159
+
160
+ function serializeElements( container: V1Element ): unknown[] {
161
+ const elements = container.model.get( 'elements' ) as ElementsCollection | undefined;
162
+
163
+ return elements?.toJSON( ELEMENTS_TO_JSON_OPTIONS ) ?? [];
164
+ }
165
+
166
+ type RemovedElement = {
167
+ model: PlannedElement;
168
+ parentId: string;
169
+ at: number;
170
+ };
171
+
172
+ type AppliedPlan = {
173
+ removed: RemovedElement[];
174
+ createdIds: string[];
175
+ };
176
+
177
+ function applyPlan(
178
+ parentContainer: V1Element,
179
+ { elements, removed_element_ids: removedIds = [] }: BuildCompositionResponse
180
+ ) {
181
+ if ( ! Array.isArray( elements ) || ! elements.length ) {
182
+ throw new Error( 'The planned composition has no elements to build' );
183
+ }
184
+
185
+ const apply = (): AppliedPlan => {
186
+ const removed: RemovedElement[] = [];
187
+
188
+ removedIds.forEach( ( id ) => {
189
+ const container = getContainer( id );
190
+
191
+ if ( ! container?.parent ) {
192
+ return;
193
+ }
194
+
195
+ removed.push( {
196
+ model: container.model.toJSON() as PlannedElement,
197
+ parentId: container.parent.id,
198
+ at: container.view?._index ?? 0,
199
+ } );
200
+
201
+ deleteElement( { container, options: { useHistory: false } } );
202
+ } );
203
+
204
+ const target = parentContainer.lookup?.() ?? parentContainer;
205
+ const createdIds = elements.map(
206
+ ( model ) => createElement( { container: target, model, options: { useHistory: false } } ).id
207
+ );
208
+
209
+ return { removed, createdIds };
210
+ };
211
+
212
+ undoable(
213
+ {
214
+ do: apply,
215
+ undo: ( _: undefined, { removed, createdIds }: AppliedPlan ) => {
216
+ [ ...createdIds ].reverse().forEach( ( id ) => {
217
+ const container = getContainer( id );
218
+
219
+ if ( container ) {
220
+ deleteElement( { container, options: { useHistory: false } } );
221
+ }
222
+ } );
223
+
224
+ [ ...removed ].reverse().forEach( ( { model, parentId, at } ) => {
225
+ const parent = getContainer( parentId );
226
+
227
+ if ( parent ) {
228
+ createElement( { container: parent, model, options: { useHistory: false, at } } );
229
+ }
230
+ } );
231
+ },
232
+ redo: apply,
233
+ },
234
+ { title: __( 'Build composition', 'elementor' ) }
235
+ )();
236
+ }