@elementor/editor-canvas 3.33.0-98 → 3.35.0-324

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 (58) hide show
  1. package/dist/index.d.mts +133 -10
  2. package/dist/index.d.ts +133 -10
  3. package/dist/index.js +1409 -212
  4. package/dist/index.mjs +1393 -179
  5. package/package.json +18 -14
  6. package/src/__tests__/settings-props-resolver.test.ts +0 -40
  7. package/src/__tests__/styles-prop-resolver.test.ts +13 -0
  8. package/src/components/__tests__/__snapshots__/style-renderer.test.tsx.snap +2 -6
  9. package/src/components/__tests__/elements-overlays.test.tsx +96 -12
  10. package/src/components/__tests__/inline-editor-overlay.test.tsx +245 -0
  11. package/src/components/__tests__/style-renderer.test.tsx +2 -2
  12. package/src/components/elements-overlays.tsx +33 -10
  13. package/src/components/inline-editor-overlay.tsx +79 -0
  14. package/src/components/interactions-renderer.tsx +33 -0
  15. package/src/components/{element-overlay.tsx → outline-overlay.tsx} +8 -7
  16. package/src/components/style-renderer.tsx +2 -4
  17. package/src/hooks/__tests__/use-has-overlapping.test.ts +187 -0
  18. package/src/hooks/use-floating-on-element.ts +11 -8
  19. package/src/hooks/use-has-overlapping.ts +21 -0
  20. package/src/hooks/use-interactions-items.ts +108 -0
  21. package/src/hooks/use-style-items.ts +34 -8
  22. package/src/index.ts +9 -0
  23. package/src/init-settings-transformers.ts +4 -0
  24. package/src/init.tsx +18 -0
  25. package/src/legacy/create-templated-element-type.ts +67 -42
  26. package/src/legacy/init-legacy-views.ts +27 -5
  27. package/src/legacy/types.ts +44 -4
  28. package/src/mcp/canvas-mcp.ts +17 -0
  29. package/src/mcp/mcp-description.ts +40 -0
  30. package/src/mcp/resources/widgets-schema-resource.ts +173 -0
  31. package/src/mcp/tools/build-composition/prompt.ts +128 -0
  32. package/src/mcp/tools/build-composition/schema.ts +31 -0
  33. package/src/mcp/tools/build-composition/tool.ts +163 -0
  34. package/src/mcp/tools/configure-element/prompt.ts +93 -0
  35. package/src/mcp/tools/configure-element/schema.ts +25 -0
  36. package/src/mcp/tools/configure-element/tool.ts +67 -0
  37. package/src/mcp/tools/get-element-config/tool.ts +69 -0
  38. package/src/mcp/utils/do-update-element-property.ts +129 -0
  39. package/src/mcp/utils/generate-available-tags.ts +23 -0
  40. package/src/renderers/__tests__/__snapshots__/create-styles-renderer.test.ts.snap +2 -0
  41. package/src/renderers/__tests__/create-styles-renderer.test.ts +25 -0
  42. package/src/renderers/create-styles-renderer.ts +20 -9
  43. package/src/renderers/errors.ts +6 -0
  44. package/src/sync/drag-element-from-panel.ts +49 -0
  45. package/src/sync/types.ts +32 -1
  46. package/src/transformers/settings/__tests__/attributes-transformer.test.ts +15 -0
  47. package/src/transformers/settings/__tests__/classes-transformer.test.ts +83 -0
  48. package/src/transformers/settings/attributes-transformer.ts +1 -23
  49. package/src/transformers/settings/classes-transformer.ts +21 -21
  50. package/src/transformers/settings/date-time-transformer.ts +12 -0
  51. package/src/transformers/settings/query-transformer.ts +10 -0
  52. package/src/transformers/styles/__tests__/transform-origin-transformer.test.ts +24 -0
  53. package/src/transformers/styles/__tests__/transition-transformer.test.ts +52 -0
  54. package/src/transformers/styles/background-transformer.ts +3 -1
  55. package/src/transformers/styles/transform-origin-transformer.ts +12 -2
  56. package/src/transformers/styles/transition-transformer.ts +34 -4
  57. package/src/types/element-overlay.ts +18 -0
  58. package/src/utils/inline-editing-utils.ts +43 -0
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // src/init.tsx
2
2
  import { injectIntoLogic, injectIntoTop } from "@elementor/editor";
3
+ import { init as initInteractionsRepository } from "@elementor/editor-interactions";
4
+ import { getMCPByDomain } from "@elementor/editor-mcp";
3
5
 
4
6
  // src/components/classes-rename.tsx
5
7
  import { useEffect } from "react";
@@ -44,24 +46,108 @@ var renameClass = (oldClassName, newClassName) => {
44
46
  };
45
47
 
46
48
  // src/components/elements-overlays.tsx
47
- import * as React2 from "react";
49
+ import * as React3 from "react";
48
50
  import { getElements, useSelectedElement } from "@elementor/editor-elements";
49
51
  import {
50
52
  __privateUseIsRouteActive as useIsRouteActive,
51
53
  __privateUseListenTo as useListenTo,
54
+ isExperimentActive,
52
55
  useEditMode,
53
56
  windowEvent
54
57
  } from "@elementor/editor-v1-adapters";
55
58
 
56
- // src/components/element-overlay.tsx
59
+ // src/utils/inline-editing-utils.ts
60
+ import { getContainer, getElementType } from "@elementor/editor-elements";
61
+ var WIDGET_PROPERTY_MAP = {
62
+ "e-heading": "title",
63
+ "e-paragraph": "paragraph"
64
+ };
65
+ var getHtmlPropertyName = (container) => {
66
+ const widgetType = container?.model?.get("widgetType") ?? container?.model?.get("elType");
67
+ if (!widgetType) {
68
+ return "";
69
+ }
70
+ if (WIDGET_PROPERTY_MAP[widgetType]) {
71
+ return WIDGET_PROPERTY_MAP[widgetType];
72
+ }
73
+ const propsSchema = getElementType(widgetType)?.propsSchema;
74
+ if (!propsSchema) {
75
+ return "";
76
+ }
77
+ const entry = Object.entries(propsSchema).find(([, propType]) => propType.key === "html");
78
+ return entry?.[0] ?? "";
79
+ };
80
+ var hasInlineEditableProperty = (containerId) => {
81
+ const container = getContainer(containerId);
82
+ const widgetType = container?.model?.get("widgetType") ?? container?.model?.get("elType");
83
+ if (!widgetType) {
84
+ return false;
85
+ }
86
+ return widgetType in WIDGET_PROPERTY_MAP;
87
+ };
88
+ var getInlineEditablePropertyName = (container) => {
89
+ return getHtmlPropertyName(container);
90
+ };
91
+
92
+ // src/components/inline-editor-overlay.tsx
93
+ import * as React2 from "react";
94
+ import { InlineEditor } from "@elementor/editor-controls";
95
+ import { getContainer as getContainer2, updateElementSettings, useElementSetting } from "@elementor/editor-elements";
96
+ import { htmlPropTypeUtil } from "@elementor/editor-props";
97
+ import { Box as Box2 } from "@elementor/ui";
98
+ import { debounce } from "@elementor/utils";
99
+ import { FloatingPortal as FloatingPortal2 } from "@floating-ui/react";
100
+
101
+ // src/hooks/use-floating-on-element.ts
102
+ import { useEffect as useEffect2, useState } from "react";
103
+ import { autoUpdate, offset, size, useFloating } from "@floating-ui/react";
104
+ function useFloatingOnElement({ element, isSelected }) {
105
+ const [isOpen, setIsOpen] = useState(false);
106
+ const sizeModifier = 2;
107
+ const { refs, floatingStyles, context } = useFloating({
108
+ // Must be controlled for interactions (like hover) to work.
109
+ open: isOpen || isSelected,
110
+ onOpenChange: setIsOpen,
111
+ whileElementsMounted: autoUpdate,
112
+ middleware: [
113
+ // Match the floating element's size to the reference element.
114
+ size(() => {
115
+ return {
116
+ apply({ elements, rects }) {
117
+ Object.assign(elements.floating.style, {
118
+ width: `${rects.reference.width + sizeModifier}px`,
119
+ height: `${rects.reference.height + sizeModifier}px`
120
+ });
121
+ }
122
+ };
123
+ }),
124
+ // Center the floating element on the reference element.
125
+ offset(({ rects }) => -rects.reference.height / 2 - rects.floating.height / 2)
126
+ ]
127
+ });
128
+ useEffect2(() => {
129
+ refs.setReference(element);
130
+ }, [element, refs]);
131
+ return {
132
+ isVisible: isOpen || isSelected,
133
+ context,
134
+ floating: {
135
+ setRef: refs.setFloating,
136
+ ref: refs.floating,
137
+ styles: floatingStyles
138
+ }
139
+ };
140
+ }
141
+
142
+ // src/components/outline-overlay.tsx
57
143
  import * as React from "react";
58
144
  import { Box, styled } from "@elementor/ui";
59
145
  import { FloatingPortal, useHover, useInteractions } from "@floating-ui/react";
60
146
 
61
147
  // src/hooks/use-bind-react-props-to-element.ts
62
- import { useEffect as useEffect2 } from "react";
148
+ import { useEffect as useEffect3 } from "react";
63
149
  function useBindReactPropsToElement(element, getProps) {
64
- useEffect2(() => {
150
+ useEffect3(() => {
65
151
  const el = element;
66
152
  const { events, attrs } = groupProps(getProps());
67
153
  events.forEach(([eventName, listener]) => el.addEventListener(eventName, listener));
@@ -92,45 +178,24 @@ function groupProps(props) {
92
178
  );
93
179
  }
94
180
 
95
- // src/hooks/use-floating-on-element.ts
96
- import { useEffect as useEffect3, useState } from "react";
97
- import { autoUpdate, offset, size, useFloating } from "@floating-ui/react";
98
- function useFloatingOnElement({ element, isSelected }) {
99
- const [isOpen, setIsOpen] = useState(false);
100
- const { refs, floatingStyles, context } = useFloating({
101
- // Must be controlled for interactions (like hover) to work.
102
- open: isOpen || isSelected,
103
- onOpenChange: setIsOpen,
104
- whileElementsMounted: autoUpdate,
105
- middleware: [
106
- // Match the floating element's size to the reference element.
107
- size({
108
- apply({ elements, rects }) {
109
- Object.assign(elements.floating.style, {
110
- width: `${rects.reference.width + 2}px`,
111
- height: `${rects.reference.height + 2}px`
112
- });
113
- }
114
- }),
115
- // Center the floating element on the reference element.
116
- offset(({ rects }) => -rects.reference.height / 2 - rects.floating.height / 2)
117
- ]
118
- });
119
- useEffect3(() => {
120
- refs.setReference(element);
121
- }, [element, refs]);
122
- return {
123
- isVisible: isOpen || isSelected,
124
- context,
125
- floating: {
126
- setRef: refs.setFloating,
127
- ref: refs.floating,
128
- styles: floatingStyles
129
- }
130
- };
131
- }
181
+ // src/hooks/use-has-overlapping.ts
182
+ var possibleOverlappingSelectors = [".e-off-canvas"];
183
+ var useHasOverlapping = () => {
184
+ const preview = window.elementor?.$preview?.[0];
185
+ if (!preview) {
186
+ return false;
187
+ }
188
+ const hasOverlapping = possibleOverlappingSelectors.map((selector) => Array.from(preview?.contentWindow?.document.body.querySelectorAll(selector) ?? [])).flat().some(
189
+ (elem) => elem.checkVisibility({
190
+ opacityProperty: true,
191
+ visibilityProperty: true,
192
+ contentVisibilityAuto: true
193
+ })
194
+ );
195
+ return hasOverlapping;
196
+ };
132
197
 
133
- // src/components/element-overlay.tsx
198
+ // src/components/outline-overlay.tsx
134
199
  var CANVAS_WRAPPER_ID = "elementor-preview-responsive-wrapper";
135
200
  var OverlayBox = styled(Box, {
136
201
  shouldForwardProp: (prop) => prop !== "isSelected" && prop !== "isSmallerOffset"
@@ -139,12 +204,13 @@ var OverlayBox = styled(Box, {
139
204
  outlineOffset: isSelected && !isSmallerOffset ? "-2px" : "-1px",
140
205
  pointerEvents: "none"
141
206
  }));
142
- function ElementOverlay({ element, isSelected, id }) {
207
+ var OutlineOverlay = ({ element, isSelected, id }) => {
143
208
  const { context, floating, isVisible } = useFloatingOnElement({ element, isSelected });
144
209
  const { getFloatingProps, getReferenceProps } = useInteractions([useHover(context)]);
210
+ const hasOverlapping = useHasOverlapping();
145
211
  useBindReactPropsToElement(element, getReferenceProps);
146
212
  const isSmallerOffset = element.offsetHeight <= 1;
147
- return isVisible && /* @__PURE__ */ React.createElement(FloatingPortal, { id: CANVAS_WRAPPER_ID }, /* @__PURE__ */ React.createElement(
213
+ return isVisible && !hasOverlapping && /* @__PURE__ */ React.createElement(FloatingPortal, { id: CANVAS_WRAPPER_ID }, /* @__PURE__ */ React.createElement(
148
214
  OverlayBox,
149
215
  {
150
216
  ref: floating.setRef,
@@ -156,9 +222,75 @@ function ElementOverlay({ element, isSelected, id }) {
156
222
  ...getFloatingProps()
157
223
  }
158
224
  ));
159
- }
225
+ };
226
+
227
+ // src/components/inline-editor-overlay.tsx
228
+ var OVERLAY_Z_INDEX = 1e3;
229
+ var DEBOUNCE_DELAY = 100;
230
+ var InlineEditorOverlay = ({ element, isSelected, id }) => {
231
+ const { floating, isVisible } = useFloatingOnElement({ element, isSelected });
232
+ const propertyName = React2.useMemo(() => {
233
+ const container = getContainer2(id);
234
+ return getInlineEditablePropertyName(container);
235
+ }, [id]);
236
+ const contentProp = useElementSetting(id, propertyName);
237
+ const value = React2.useMemo(() => htmlPropTypeUtil.extract(contentProp) || "", [contentProp]);
238
+ const debouncedUpdateRef = React2.useRef(null);
239
+ const lastValueRef = React2.useRef("");
240
+ React2.useEffect(() => {
241
+ debouncedUpdateRef.current = debounce((newValue) => {
242
+ const textContent = newValue.replace(/<[^>]*>/g, "").trim();
243
+ const valueToSave = textContent === "" ? "&nbsp;" : newValue;
244
+ updateElementSettings({
245
+ id,
246
+ props: {
247
+ [propertyName]: htmlPropTypeUtil.create(valueToSave)
248
+ },
249
+ withHistory: true
250
+ });
251
+ }, DEBOUNCE_DELAY);
252
+ return () => {
253
+ debouncedUpdateRef.current?.cancel?.();
254
+ };
255
+ }, [id, propertyName]);
256
+ const handleValueChange = React2.useCallback((newValue) => {
257
+ lastValueRef.current = newValue;
258
+ debouncedUpdateRef.current?.(newValue);
259
+ }, []);
260
+ React2.useEffect(() => {
261
+ if (!isVisible && debouncedUpdateRef.current?.pending?.()) {
262
+ debouncedUpdateRef.current.flush(lastValueRef.current);
263
+ }
264
+ }, [isVisible]);
265
+ if (!isVisible) {
266
+ return null;
267
+ }
268
+ return /* @__PURE__ */ React2.createElement(FloatingPortal2, { id: CANVAS_WRAPPER_ID }, /* @__PURE__ */ React2.createElement(
269
+ Box2,
270
+ {
271
+ ref: floating.setRef,
272
+ style: {
273
+ ...floating.styles,
274
+ zIndex: OVERLAY_Z_INDEX,
275
+ pointerEvents: "auto"
276
+ }
277
+ },
278
+ /* @__PURE__ */ React2.createElement(InlineEditor, { value, setValue: handleValueChange, showToolbar: isSelected })
279
+ ));
280
+ };
160
281
 
161
282
  // src/components/elements-overlays.tsx
283
+ var ELEMENTS_DATA_ATTR = "atomic";
284
+ var overlayRegistry = [
285
+ {
286
+ component: OutlineOverlay,
287
+ shouldRender: () => true
288
+ },
289
+ {
290
+ component: InlineEditorOverlay,
291
+ shouldRender: ({ id, isSelected }) => isSelected && hasInlineEditableProperty(id) && isExperimentActive("v4-inline-text-editing")
292
+ }
293
+ ];
162
294
  function ElementsOverlays() {
163
295
  const selected = useSelectedElement();
164
296
  const elements = useElementsDom();
@@ -166,9 +298,16 @@ function ElementsOverlays() {
166
298
  const isEditMode = currentEditMode === "edit";
167
299
  const isKitRouteActive = useIsRouteActive("panel/global");
168
300
  const isActive = isEditMode && !isKitRouteActive;
169
- return isActive && elements.map(([id, element]) => /* @__PURE__ */ React2.createElement(ElementOverlay, { key: id, id, element, isSelected: selected.element?.id === id }));
301
+ if (!isActive) {
302
+ return null;
303
+ }
304
+ return elements.map(([id, element]) => {
305
+ const isSelected = selected.element?.id === id;
306
+ return overlayRegistry.map(
307
+ ({ shouldRender, component: Overlay }, index) => shouldRender({ id, element, isSelected }) && /* @__PURE__ */ React3.createElement(Overlay, { key: `${id}-${index}`, id, element, isSelected })
308
+ );
309
+ });
170
310
  }
171
- var ELEMENTS_DATA_ATTR = "atomic";
172
311
  function useElementsDom() {
173
312
  return useListenTo(
174
313
  [windowEvent("elementor/editor/element-rendered"), windowEvent("elementor/editor/element-destroyed")],
@@ -178,13 +317,100 @@ function useElementsDom() {
178
317
  );
179
318
  }
180
319
 
181
- // src/components/style-renderer.tsx
182
- import * as React3 from "react";
183
- import { __privateUseListenTo as useListenTo3, commandEndEvent as commandEndEvent2 } from "@elementor/editor-v1-adapters";
320
+ // src/components/interactions-renderer.tsx
321
+ import * as React4 from "react";
322
+ import { __privateUseListenTo as useListenTo2, commandEndEvent } from "@elementor/editor-v1-adapters";
184
323
  import { Portal } from "@elementor/ui";
185
324
 
186
- // src/hooks/use-documents-css-links.ts
187
- import { __privateUseListenTo as useListenTo2, commandEndEvent } from "@elementor/editor-v1-adapters";
325
+ // src/hooks/use-interactions-items.ts
326
+ import { useEffect as useEffect6, useMemo as useMemo2, useState as useState2 } from "react";
327
+ import { interactionsRepository } from "@elementor/editor-interactions";
328
+ import { registerDataHook } from "@elementor/editor-v1-adapters";
329
+
330
+ // src/hooks/use-on-mount.ts
331
+ import { useEffect as useEffect5, useRef as useRef2 } from "react";
332
+ function useOnMount(cb) {
333
+ const mounted = useRef2(false);
334
+ useEffect5(() => {
335
+ if (!mounted.current) {
336
+ mounted.current = true;
337
+ cb();
338
+ }
339
+ }, []);
340
+ }
341
+
342
+ // src/hooks/use-interactions-items.ts
343
+ function useInteractionsItems() {
344
+ const [interactionItems, setInteractionItems] = useState2({});
345
+ const providerAndSubscribers = useMemo2(() => {
346
+ try {
347
+ const providers = interactionsRepository.getProviders();
348
+ const mapped = providers.map((provider) => {
349
+ return {
350
+ provider,
351
+ subscriber: createProviderSubscriber({
352
+ provider,
353
+ setInteractionItems
354
+ })
355
+ };
356
+ });
357
+ return mapped;
358
+ } catch {
359
+ return [];
360
+ }
361
+ }, []);
362
+ useEffect6(() => {
363
+ if (providerAndSubscribers.length === 0) {
364
+ return;
365
+ }
366
+ const unsubscribes = providerAndSubscribers.map(({ provider, subscriber }) => {
367
+ const safeSubscriber = () => {
368
+ try {
369
+ subscriber();
370
+ } catch {
371
+ }
372
+ };
373
+ const unsubscribe = provider.subscribe(safeSubscriber);
374
+ return unsubscribe;
375
+ });
376
+ return () => {
377
+ unsubscribes.forEach((unsubscribe) => unsubscribe());
378
+ };
379
+ }, [providerAndSubscribers]);
380
+ useOnMount(() => {
381
+ if (providerAndSubscribers.length === 0) {
382
+ return;
383
+ }
384
+ registerDataHook("after", "editor/documents/attach-preview", async () => {
385
+ providerAndSubscribers.forEach(({ subscriber }) => {
386
+ try {
387
+ subscriber();
388
+ } catch {
389
+ }
390
+ });
391
+ });
392
+ });
393
+ return useMemo2(() => {
394
+ const result = Object.values(interactionItems).sort(sortByProviderPriority).flatMap(({ items }) => items);
395
+ return result;
396
+ }, [interactionItems]);
397
+ }
398
+ function sortByProviderPriority({ provider: providerA }, { provider: providerB }) {
399
+ return providerA.priority - providerB.priority;
400
+ }
401
+ function createProviderSubscriber({ provider, setInteractionItems }) {
402
+ return () => {
403
+ try {
404
+ const items = provider.actions.all();
405
+ const providerKey = provider.getKey();
406
+ setInteractionItems((prev) => ({
407
+ ...prev,
408
+ [providerKey]: { provider, items }
409
+ }));
410
+ } catch {
411
+ }
412
+ };
413
+ }
188
414
 
189
415
  // src/sync/get-canvas-iframe-document.ts
190
416
  function getCanvasIframeDocument() {
@@ -192,13 +418,42 @@ function getCanvasIframeDocument() {
192
418
  return extendedWindow.elementor?.$preview?.[0]?.contentDocument;
193
419
  }
194
420
 
421
+ // src/components/interactions-renderer.tsx
422
+ function InteractionsRenderer() {
423
+ const container = usePortalContainer();
424
+ const interactionItems = useInteractionsItems();
425
+ if (!container) {
426
+ return null;
427
+ }
428
+ const interactionsData = JSON.stringify(Array.isArray(interactionItems) ? interactionItems : []);
429
+ return /* @__PURE__ */ React4.createElement(Portal, { container }, /* @__PURE__ */ React4.createElement(
430
+ "script",
431
+ {
432
+ type: "application/json",
433
+ "data-e-interactions": "true",
434
+ dangerouslySetInnerHTML: {
435
+ __html: interactionsData
436
+ }
437
+ }
438
+ ));
439
+ }
440
+ function usePortalContainer() {
441
+ return useListenTo2(commandEndEvent("editor/documents/attach-preview"), () => getCanvasIframeDocument()?.head);
442
+ }
443
+
444
+ // src/components/style-renderer.tsx
445
+ import * as React5 from "react";
446
+ import { __privateUseListenTo as useListenTo4, commandEndEvent as commandEndEvent3 } from "@elementor/editor-v1-adapters";
447
+ import { Portal as Portal2 } from "@elementor/ui";
448
+
195
449
  // src/hooks/use-documents-css-links.ts
450
+ import { __privateUseListenTo as useListenTo3, commandEndEvent as commandEndEvent2 } from "@elementor/editor-v1-adapters";
196
451
  var REMOVED_ATTR = "data-e-removed";
197
452
  var DOCUMENT_WRAPPER_ATTR = "data-elementor-id";
198
453
  var CSS_LINK_ID_PREFIX = "elementor-post-";
199
454
  var CSS_LINK_ID_SUFFIX = "-css";
200
455
  function useDocumentsCssLinks() {
201
- return useListenTo2(commandEndEvent("editor/documents/attach-preview"), () => {
456
+ return useListenTo3(commandEndEvent2("editor/documents/attach-preview"), () => {
202
457
  const iframeDocument = getCanvasIframeDocument();
203
458
  if (!iframeDocument) {
204
459
  return [];
@@ -239,10 +494,11 @@ function getLinkAttrs(el) {
239
494
  }
240
495
 
241
496
  // src/hooks/use-style-items.ts
242
- import { useEffect as useEffect5, useMemo as useMemo3, useState as useState2 } from "react";
497
+ import { useEffect as useEffect7, useMemo as useMemo5, useState as useState3 } from "react";
243
498
  import { getBreakpoints } from "@elementor/editor-responsive";
499
+ import { isClassState as isClassState2 } from "@elementor/editor-styles";
244
500
  import { stylesRepository as stylesRepository2 } from "@elementor/editor-styles-repository";
245
- import { registerDataHook } from "@elementor/editor-v1-adapters";
501
+ import { registerDataHook as registerDataHook2 } from "@elementor/editor-v1-adapters";
246
502
 
247
503
  // src/utils/abort-previous-runs.ts
248
504
  function abortPreviousRuns(cb) {
@@ -275,20 +531,8 @@ function signalizedProcess(signal, steps = []) {
275
531
  };
276
532
  }
277
533
 
278
- // src/hooks/use-on-mount.ts
279
- import { useEffect as useEffect4, useRef } from "react";
280
- function useOnMount(cb) {
281
- const mounted = useRef(false);
282
- useEffect4(() => {
283
- if (!mounted.current) {
284
- mounted.current = true;
285
- cb();
286
- }
287
- }, []);
288
- }
289
-
290
534
  // src/hooks/use-style-prop-resolver.ts
291
- import { useMemo } from "react";
535
+ import { useMemo as useMemo3 } from "react";
292
536
  import { getStylesSchema } from "@elementor/editor-styles";
293
537
 
294
538
  // src/renderers/create-props-resolver.ts
@@ -313,10 +557,10 @@ var getMultiPropsValue = (multiProps) => {
313
557
  // src/renderers/create-props-resolver.ts
314
558
  var TRANSFORM_DEPTH_LIMIT = 3;
315
559
  function createPropsResolver({ transformers, schema: initialSchema, onPropResolve }) {
316
- async function resolve({ props, schema, signal }) {
317
- schema = schema ?? initialSchema;
560
+ async function resolve({ props, schema: schema2, signal }) {
561
+ schema2 = schema2 ?? initialSchema;
318
562
  const promises = Promise.all(
319
- Object.entries(schema).map(async ([key, type]) => {
563
+ Object.entries(schema2).map(async ([key, type]) => {
320
564
  const value = props[key] ?? type.default;
321
565
  const transformed = await transform({ value, key, type, signal });
322
566
  onPropResolve?.({ key, value: transformed });
@@ -412,7 +656,7 @@ var enqueueFont = (fontFamily, context = "preview") => {
412
656
 
413
657
  // src/hooks/use-style-prop-resolver.ts
414
658
  function useStylePropResolver() {
415
- return useMemo(() => {
659
+ return useMemo3(() => {
416
660
  return createPropsResolver({
417
661
  transformers: styleTransformersRegistry,
418
662
  schema: getStylesSchema(),
@@ -427,11 +671,14 @@ function useStylePropResolver() {
427
671
  }
428
672
 
429
673
  // src/hooks/use-style-renderer.ts
430
- import { useMemo as useMemo2 } from "react";
674
+ import { useMemo as useMemo4 } from "react";
431
675
  import { useBreakpointsMap } from "@elementor/editor-responsive";
432
676
 
433
677
  // src/renderers/create-styles-renderer.ts
434
- import { EXPERIMENTAL_FEATURES, isExperimentActive } from "@elementor/editor-v1-adapters";
678
+ import {
679
+ isClassState,
680
+ isPseudoState
681
+ } from "@elementor/editor-styles";
435
682
  import { decodeString } from "@elementor/utils";
436
683
 
437
684
  // src/renderers/errors.ts
@@ -440,6 +687,10 @@ var UnknownStyleTypeError = createError({
440
687
  code: "unknown_style_type",
441
688
  message: "Unknown style type"
442
689
  });
690
+ var UnknownStyleStateError = createError({
691
+ code: "unknown_style_state",
692
+ message: "Unknown style state"
693
+ });
443
694
 
444
695
  // src/renderers/create-styles-renderer.ts
445
696
  var SELECTORS_MAP = {
@@ -457,7 +708,8 @@ function createStylesRenderer({ resolve, breakpoints, selectorPrefix = "" }) {
457
708
  return {
458
709
  id: style.id,
459
710
  breakpoint: style?.variants[0]?.meta?.breakpoint || "desktop",
460
- value: variantsCss.join("")
711
+ value: variantsCss.join(""),
712
+ state: style?.variants[0]?.meta?.state || null
461
713
  };
462
714
  });
463
715
  return await Promise.all(stylesCssPromises);
@@ -473,7 +725,18 @@ function createStyleWrapper(value = "", wrapper) {
473
725
  return createStyleWrapper(`${value}${symbol}${cssName}`, wrapper);
474
726
  },
475
727
  withPrefix: (prefix) => createStyleWrapper([prefix, value].filter(Boolean).join(" "), wrapper),
476
- withState: (state) => createStyleWrapper(state ? `${value}:${state}` : value, wrapper),
728
+ withState: (state) => {
729
+ if (!state) {
730
+ return createStyleWrapper(value, wrapper);
731
+ }
732
+ if (isClassState(state)) {
733
+ return createStyleWrapper(`${value}.${state}`, wrapper);
734
+ }
735
+ if (isPseudoState(state)) {
736
+ return createStyleWrapper(`${value}:${state}`, wrapper);
737
+ }
738
+ throw new UnknownStyleStateError({ context: { state } });
739
+ },
477
740
  withMediaQuery: (breakpoint) => {
478
741
  if (!breakpoint?.type) {
479
742
  return createStyleWrapper(value, wrapper);
@@ -501,10 +764,7 @@ async function propsToCss({ props, resolve, signal }) {
501
764
  }, []).join("");
502
765
  }
503
766
  function customCssToString(customCss) {
504
- if (!isExperimentActive(EXPERIMENTAL_FEATURES.CUSTOM_CSS) || !customCss?.raw) {
505
- return "";
506
- }
507
- const decoded = decodeString(customCss.raw);
767
+ const decoded = decodeString(customCss?.raw || "");
508
768
  if (!decoded.trim()) {
509
769
  return "";
510
770
  }
@@ -515,7 +775,7 @@ function customCssToString(customCss) {
515
775
  var SELECTOR_PREFIX = ".elementor";
516
776
  function useStyleRenderer(resolve) {
517
777
  const breakpoints = useBreakpointsMap();
518
- return useMemo2(() => {
778
+ return useMemo4(() => {
519
779
  return createStylesRenderer({
520
780
  selectorPrefix: SELECTOR_PREFIX,
521
781
  breakpoints,
@@ -528,12 +788,12 @@ function useStyleRenderer(resolve) {
528
788
  function useStyleItems() {
529
789
  const resolve = useStylePropResolver();
530
790
  const renderStyles = useStyleRenderer(resolve);
531
- const [styleItems, setStyleItems] = useState2({});
532
- const providerAndSubscribers = useMemo3(() => {
791
+ const [styleItems, setStyleItems] = useState3({});
792
+ const providerAndSubscribers = useMemo5(() => {
533
793
  return stylesRepository2.getProviders().map((provider) => {
534
794
  return {
535
795
  provider,
536
- subscriber: createProviderSubscriber({
796
+ subscriber: createProviderSubscriber2({
537
797
  provider,
538
798
  renderStyles,
539
799
  setStyleItems
@@ -541,7 +801,7 @@ function useStyleItems() {
541
801
  };
542
802
  });
543
803
  }, [renderStyles]);
544
- useEffect5(() => {
804
+ useEffect7(() => {
545
805
  const unsubscribes = providerAndSubscribers.map(
546
806
  ({ provider, subscriber }) => provider.subscribe(subscriber)
547
807
  );
@@ -550,22 +810,34 @@ function useStyleItems() {
550
810
  };
551
811
  }, [providerAndSubscribers]);
552
812
  useOnMount(() => {
553
- registerDataHook("after", "editor/documents/attach-preview", async () => {
813
+ registerDataHook2("after", "editor/documents/attach-preview", async () => {
554
814
  const promises = providerAndSubscribers.map(async ({ subscriber }) => subscriber());
555
815
  await Promise.all(promises);
556
816
  });
557
817
  });
558
818
  const breakpointsOrder = getBreakpoints().map((breakpoint) => breakpoint.id);
559
- return useMemo3(
560
- () => Object.values(styleItems).sort(({ provider: providerA }, { provider: providerB }) => providerA.priority - providerB.priority).flatMap(({ items }) => items).sort(({ breakpoint: breakpointA }, { breakpoint: breakpointB }) => {
561
- return breakpointsOrder.indexOf(breakpointA) - breakpointsOrder.indexOf(breakpointB);
562
- }),
563
- // eslint-disable-next-line
819
+ return useMemo5(
820
+ () => Object.values(styleItems).sort(sortByProviderPriority2).flatMap(({ items }) => items).sort(sortByStateType).sort(sortByBreakpoint(breakpointsOrder)),
564
821
  // eslint-disable-next-line react-hooks/exhaustive-deps
565
822
  [styleItems, breakpointsOrder.join("-")]
566
823
  );
567
824
  }
568
- function createProviderSubscriber({ provider, renderStyles, setStyleItems }) {
825
+ function sortByProviderPriority2({ provider: providerA }, { provider: providerB }) {
826
+ return providerA.priority - providerB.priority;
827
+ }
828
+ function sortByBreakpoint(breakpointsOrder) {
829
+ return ({ breakpoint: breakpointA }, { breakpoint: breakpointB }) => breakpointsOrder.indexOf(breakpointA) - breakpointsOrder.indexOf(breakpointB);
830
+ }
831
+ function sortByStateType({ state: stateA }, { state: stateB }) {
832
+ if (isClassState2(stateA) && !isClassState2(stateB)) {
833
+ return -1;
834
+ }
835
+ if (!isClassState2(stateA) && isClassState2(stateB)) {
836
+ return 1;
837
+ }
838
+ return 0;
839
+ }
840
+ function createProviderSubscriber2({ provider, renderStyles, setStyleItems }) {
569
841
  return abortPreviousRuns(
570
842
  (abortController) => signalizedProcess(abortController.signal).then((_, signal) => {
571
843
  const styles = provider.actions.all().map((__5, index, items) => {
@@ -611,16 +883,16 @@ function createProviderSubscriber({ provider, renderStyles, setStyleItems }) {
611
883
 
612
884
  // src/components/style-renderer.tsx
613
885
  function StyleRenderer() {
614
- const container = usePortalContainer();
886
+ const container = usePortalContainer2();
615
887
  const styleItems = useStyleItems();
616
888
  const linksAttrs = useDocumentsCssLinks();
617
889
  if (!container) {
618
890
  return null;
619
891
  }
620
- return /* @__PURE__ */ React3.createElement(Portal, { container }, styleItems.map((item) => /* @__PURE__ */ React3.createElement("style", { "data-e-style-id": item.id, key: `${item.id}-${item.breakpoint}` }, item.value)), linksAttrs.map((attrs) => /* @__PURE__ */ React3.createElement("link", { ...attrs, key: attrs.id })));
892
+ return /* @__PURE__ */ React5.createElement(Portal2, { container }, styleItems.map((item, i) => /* @__PURE__ */ React5.createElement("style", { key: `${item.id}-${i}-${item.breakpoint}` }, item.value)), linksAttrs.map((attrs) => /* @__PURE__ */ React5.createElement("link", { ...attrs, key: attrs.id })));
621
893
  }
622
- function usePortalContainer() {
623
- return useListenTo3(commandEndEvent2("editor/documents/attach-preview"), () => getCanvasIframeDocument()?.head);
894
+ function usePortalContainer2() {
895
+ return useListenTo4(commandEndEvent3("editor/documents/attach-preview"), () => getCanvasIframeDocument()?.head);
624
896
  }
625
897
 
626
898
  // src/settings-transformers-registry.ts
@@ -632,48 +904,39 @@ function createTransformer(cb) {
632
904
  }
633
905
 
634
906
  // src/transformers/settings/attributes-transformer.ts
635
- function escapeHtmlAttribute(value) {
636
- const specialChars = {
637
- "&": "&amp;",
638
- "<": "&lt;",
639
- ">": "&gt;",
640
- "'": "&#39;",
641
- '"': "&quot;"
642
- };
643
- return value.replace(/[&<>'"]/g, (char) => specialChars[char] || char);
644
- }
645
- var attributesTransformer = createTransformer((values) => {
646
- return values.map((value) => {
647
- if (!value.key || !value.value) {
648
- return "";
649
- }
650
- const escapedValue = escapeHtmlAttribute(value.value);
651
- return `${value.key}="${escapedValue}"`;
652
- }).join(" ");
653
- });
907
+ var attributesTransformer = createTransformer(() => "");
654
908
 
655
909
  // src/transformers/settings/classes-transformer.ts
656
910
  import { stylesRepository as stylesRepository3 } from "@elementor/editor-styles-repository";
911
+ function transformClassId(id, cache) {
912
+ if (!cache.has(id)) {
913
+ const provider2 = stylesRepository3.getProviders().find((p) => {
914
+ return p.actions.all().find((style) => style.id === id);
915
+ });
916
+ if (!provider2) {
917
+ return id;
918
+ }
919
+ cache.set(id, provider2.getKey());
920
+ }
921
+ const providerKey = cache.get(id);
922
+ const provider = stylesRepository3.getProviderByKey(providerKey);
923
+ return provider?.actions.resolveCssName(id) ?? id;
924
+ }
657
925
  function createClassesTransformer() {
658
926
  const cache = /* @__PURE__ */ new Map();
659
927
  return createTransformer((value) => {
660
- return value.map((id) => {
661
- if (!cache.has(id)) {
662
- cache.set(id, getCssName(id));
663
- }
664
- return cache.get(id);
665
- }).filter(Boolean);
928
+ return value.map((id) => transformClassId(id, cache)).filter(Boolean);
666
929
  });
667
930
  }
668
- function getCssName(id) {
669
- const provider = stylesRepository3.getProviders().find((p) => {
670
- return p.actions.all().find((style) => style.id === id);
671
- });
672
- if (!provider) {
673
- return id;
674
- }
675
- return provider.actions.resolveCssName(id);
676
- }
931
+
932
+ // src/transformers/settings/date-time-transformer.ts
933
+ var dateTimeTransformer = createTransformer((values) => {
934
+ return values.map((value) => {
935
+ const date = (value.date || "").trim();
936
+ const time = (value.time || "").trim();
937
+ return !date && !time ? "" : `${date} ${time}`.trim();
938
+ }).join(" ");
939
+ });
677
940
 
678
941
  // src/transformers/settings/link-transformer.ts
679
942
  var linkTransformer = createTransformer(({ destination, isTargetBlank }) => {
@@ -684,6 +947,11 @@ var linkTransformer = createTransformer(({ destination, isTargetBlank }) => {
684
947
  };
685
948
  });
686
949
 
950
+ // src/transformers/settings/query-transformer.ts
951
+ var queryTransformer = createTransformer(({ id }) => {
952
+ return id ?? null;
953
+ });
954
+
687
955
  // src/transformers/shared/image-src-transformer.ts
688
956
  var imageSrcTransformer = createTransformer((value) => ({
689
957
  id: value.id ?? null,
@@ -723,7 +991,7 @@ var plainTransformer = createTransformer((value) => {
723
991
 
724
992
  // src/init-settings-transformers.ts
725
993
  function initSettingsTransformers() {
726
- settingsTransformersRegistry.register("classes", createClassesTransformer()).register("link", linkTransformer).register("image", imageTransformer).register("image-src", imageSrcTransformer).register("attributes", attributesTransformer).registerFallback(plainTransformer);
994
+ settingsTransformersRegistry.register("classes", createClassesTransformer()).register("link", linkTransformer).register("query", queryTransformer).register("image", imageTransformer).register("image-src", imageSrcTransformer).register("attributes", attributesTransformer).register("date-time", dateTimeTransformer).registerFallback(plainTransformer);
727
995
  }
728
996
 
729
997
  // src/transformers/styles/background-color-overlay-transformer.ts
@@ -821,10 +1089,11 @@ function getValuesString(items, prop, defaultValue, preventUnification = false)
821
1089
 
822
1090
  // src/transformers/styles/background-transformer.ts
823
1091
  var backgroundTransformer = createTransformer((value) => {
824
- const { color = null, "background-overlay": overlays = null } = value;
1092
+ const { color = null, "background-overlay": overlays = null, clip = null } = value;
825
1093
  return createMultiPropsValue({
826
1094
  ...overlays,
827
- "background-color": color
1095
+ "background-color": color,
1096
+ "background-clip": clip
828
1097
  });
829
1098
  });
830
1099
 
@@ -950,11 +1219,19 @@ var transformMoveTransformer = createTransformer((value) => {
950
1219
 
951
1220
  // src/transformers/styles/transform-origin-transformer.ts
952
1221
  var EMPTY_VALUE = "0px";
1222
+ var DEFAULT_XY = "50%";
1223
+ var DEFAULT_Z = EMPTY_VALUE;
953
1224
  function getVal2(val) {
954
1225
  return `${val ?? EMPTY_VALUE}`;
955
1226
  }
956
1227
  var transformOriginTransformer = createTransformer((value) => {
957
- return `${getVal2(value.x)} ${getVal2(value.y)} ${getVal2(value.z)}`;
1228
+ const x = getVal2(value.x);
1229
+ const y = getVal2(value.y);
1230
+ const z4 = getVal2(value.z);
1231
+ if (x === DEFAULT_XY && y === DEFAULT_XY && z4 === DEFAULT_Z) {
1232
+ return null;
1233
+ }
1234
+ return `${x} ${y} ${z4}`;
958
1235
  });
959
1236
 
960
1237
  // src/transformers/styles/transform-rotate-transformer.ts
@@ -982,17 +1259,36 @@ var transformSkewTransformer = createTransformer((value) => {
982
1259
  });
983
1260
 
984
1261
  // src/transformers/styles/transition-transformer.ts
1262
+ import { transitionProperties } from "@elementor/editor-controls";
1263
+ var getAllowedProperties = () => {
1264
+ const allowedProperties = /* @__PURE__ */ new Set();
1265
+ transitionProperties.forEach((category) => {
1266
+ category.properties.forEach((property) => {
1267
+ allowedProperties.add(property.value);
1268
+ });
1269
+ });
1270
+ return allowedProperties;
1271
+ };
985
1272
  var transitionTransformer = createTransformer((transitionValues) => {
986
1273
  if (transitionValues?.length < 1) {
987
1274
  return null;
988
1275
  }
989
- return transitionValues.filter(Boolean).map(mapToTransitionString).join(", ");
1276
+ const allowedProperties = getAllowedProperties();
1277
+ const validTransitions = transitionValues.map((value) => mapToTransitionString(value, allowedProperties)).filter(Boolean);
1278
+ if (validTransitions.length === 0) {
1279
+ return null;
1280
+ }
1281
+ return validTransitions.join(", ");
990
1282
  });
991
- var mapToTransitionString = (value) => {
1283
+ var mapToTransitionString = (value, allowedProperties) => {
992
1284
  if (!value.selection || !value.size) {
993
1285
  return "";
994
1286
  }
995
- return `${value.selection.value} ${value.size}`;
1287
+ const property = value.selection.value;
1288
+ if (!allowedProperties.has(property)) {
1289
+ return "";
1290
+ }
1291
+ return `${property} ${value.size}`;
996
1292
  };
997
1293
 
998
1294
  // src/init-style-transformers.ts
@@ -1153,26 +1449,21 @@ function createElementViewClassDeclaration() {
1153
1449
  }
1154
1450
 
1155
1451
  // src/legacy/create-templated-element-type.ts
1156
- function createTemplatedElementType({ type, renderer, element }) {
1452
+ function createTemplatedElementType({
1453
+ type,
1454
+ renderer,
1455
+ element
1456
+ }) {
1157
1457
  const legacyWindow = window;
1158
- Object.entries(element.twig_templates).forEach(([key, template]) => {
1159
- renderer.register(key, template);
1160
- });
1161
- const propsResolver = createPropsResolver({
1162
- transformers: settingsTransformersRegistry,
1163
- schema: element.atomic_props_schema
1164
- });
1165
1458
  return class extends legacyWindow.elementor.modules.elements.types.Widget {
1166
1459
  getType() {
1167
1460
  return type;
1168
1461
  }
1169
1462
  getView() {
1170
- return createTemplatedElementViewClassDeclaration({
1463
+ return createTemplatedElementView({
1171
1464
  type,
1172
1465
  renderer,
1173
- propsResolver,
1174
- baseStylesDictionary: element.base_styles_dictionary,
1175
- templateKey: element.twig_main_template
1466
+ element
1176
1467
  });
1177
1468
  }
1178
1469
  };
@@ -1180,14 +1471,21 @@ function createTemplatedElementType({ type, renderer, element }) {
1180
1471
  function canBeTemplated(element) {
1181
1472
  return !!(element.atomic_props_schema && element.twig_templates && element.twig_main_template && element.base_styles_dictionary);
1182
1473
  }
1183
- function createTemplatedElementViewClassDeclaration({
1474
+ function createTemplatedElementView({
1184
1475
  type,
1185
1476
  renderer,
1186
- propsResolver: resolveProps,
1187
- templateKey,
1188
- baseStylesDictionary
1477
+ element
1189
1478
  }) {
1190
1479
  const BaseView = createElementViewClassDeclaration();
1480
+ const templateKey = element.twig_main_template;
1481
+ const baseStylesDictionary = element.base_styles_dictionary;
1482
+ Object.entries(element.twig_templates).forEach(([key, template]) => {
1483
+ renderer.register(key, template);
1484
+ });
1485
+ const resolveProps = createPropsResolver({
1486
+ transformers: settingsTransformersRegistry,
1487
+ schema: element.atomic_props_schema
1488
+ });
1191
1489
  return class extends BaseView {
1192
1490
  #abortController = null;
1193
1491
  getTemplateType() {
@@ -1196,41 +1494,63 @@ function createTemplatedElementViewClassDeclaration({
1196
1494
  renderOnChange() {
1197
1495
  this.render();
1198
1496
  }
1199
- // Overriding Marionette original render method to inject our renderer.
1200
- async _renderTemplate() {
1201
- this.#beforeRenderTemplate();
1497
+ // Override `render` function to support async `_renderTemplate`
1498
+ // Note that `_renderChildren` asynchronity is still NOT supported, so only the parent element rendering can be async
1499
+ render() {
1202
1500
  this.#abortController?.abort();
1203
1501
  this.#abortController = new AbortController();
1204
- const process = signalizedProcess(this.#abortController.signal).then((_, signal) => {
1502
+ const process = signalizedProcess(this.#abortController.signal).then(() => this.#beforeRender()).then(() => this._renderTemplate()).then(() => {
1503
+ this._renderChildren();
1504
+ this.#afterRender();
1505
+ });
1506
+ return process.execute();
1507
+ }
1508
+ // Overriding Marionette original `_renderTemplate` method to inject our renderer.
1509
+ async _renderTemplate() {
1510
+ this.triggerMethod("before:render:template");
1511
+ const process = signalizedProcess(this.#abortController?.signal).then((_, signal) => {
1205
1512
  const settings = this.model.get("settings").toJSON();
1206
1513
  return resolveProps({
1207
1514
  props: settings,
1208
1515
  signal
1209
1516
  });
1210
- }).then((resolvedSettings) => {
1517
+ }).then((settings) => {
1518
+ return this.afterSettingsResolve(settings);
1519
+ }).then(async (settings) => {
1211
1520
  const context = {
1212
1521
  id: this.model.get("id"),
1213
1522
  type,
1214
- settings: resolvedSettings,
1523
+ settings,
1215
1524
  base_styles: baseStylesDictionary
1216
1525
  };
1217
1526
  return renderer.render(templateKey, context);
1218
1527
  }).then((html) => this.$el.html(html));
1219
1528
  await process.execute();
1220
- this.#afterRenderTemplate();
1221
- }
1222
- // Emulating the original Marionette behavior.
1223
- #beforeRenderTemplate() {
1224
- this.triggerMethod("before:render:template");
1225
- }
1226
- #afterRenderTemplate() {
1227
1529
  this.bindUIElements();
1228
1530
  this.triggerMethod("render:template");
1229
1531
  }
1532
+ afterSettingsResolve(settings) {
1533
+ return settings;
1534
+ }
1535
+ #beforeRender() {
1536
+ this._ensureViewIsIntact();
1537
+ this._isRendering = true;
1538
+ this.resetChildViewContainer();
1539
+ this.triggerMethod("before:render", this);
1540
+ }
1541
+ #afterRender() {
1542
+ this._isRendering = false;
1543
+ this.isRendered = true;
1544
+ this.triggerMethod("render", this);
1545
+ }
1230
1546
  };
1231
1547
  }
1232
1548
 
1233
1549
  // src/legacy/init-legacy-views.ts
1550
+ var elementsLegacyTypes = {};
1551
+ function registerElementType(type, elementTypeGenerator) {
1552
+ elementsLegacyTypes[type] = elementTypeGenerator;
1553
+ }
1234
1554
  function initLegacyViews() {
1235
1555
  __privateListenTo(v1ReadyEvent(), () => {
1236
1556
  const config = getWidgetsCache() ?? {};
@@ -1240,12 +1560,856 @@ function initLegacyViews() {
1240
1560
  if (!element.atomic) {
1241
1561
  return;
1242
1562
  }
1243
- const ElementType = canBeTemplated(element) ? createTemplatedElementType({ type, renderer, element }) : createElementType(type);
1563
+ let ElementType;
1564
+ if (!!elementsLegacyTypes[type] && canBeTemplated(element)) {
1565
+ ElementType = elementsLegacyTypes[type]({ type, renderer, element });
1566
+ } else if (canBeTemplated(element)) {
1567
+ ElementType = createTemplatedElementType({ type, renderer, element });
1568
+ } else {
1569
+ ElementType = createElementType(type);
1570
+ }
1244
1571
  legacyWindow.elementor.elementsManager.registerElementType(new ElementType());
1245
1572
  });
1246
1573
  });
1247
1574
  }
1248
1575
 
1576
+ // src/mcp/resources/widgets-schema-resource.ts
1577
+ import { getWidgetsCache as getWidgetsCache2 } from "@elementor/editor-elements";
1578
+ import { ResourceTemplate } from "@elementor/editor-mcp";
1579
+ import {
1580
+ Schema
1581
+ } from "@elementor/editor-props";
1582
+ import { getStylesSchema as getStylesSchema2 } from "@elementor/editor-styles";
1583
+ var WIDGET_SCHEMA_URI = "elementor://widgets/schema/{widgetType}";
1584
+ var STYLE_SCHEMA_URI = "elementor://styles/schema/{category}";
1585
+ var BEST_PRACTICES_URI = "elementor://styles/best-practices";
1586
+ var initWidgetsSchemaResource = (reg) => {
1587
+ const { mcpServer } = reg;
1588
+ mcpServer.resource("styles-best-practices", BEST_PRACTICES_URI, async () => {
1589
+ return {
1590
+ contents: [
1591
+ {
1592
+ uri: BEST_PRACTICES_URI,
1593
+ text: `# Styling best practices
1594
+ Prefer using "em" and "rem" values for text-related sizes, padding and spacing. Use percentages for dynamic sizing relative to parent containers.
1595
+ This flexboxes are by default "flex" with "stretch" alignment. To ensure proper layout, define the "justify-content" and "align-items" as in the schema, or in custom_css, depends on your needs.
1596
+
1597
+ When applicable for styles, use the "custom_css" property for free-form CSS styling. This property accepts a string of CSS rules that will be applied directly to the element.
1598
+ The css string must follow standard CSS syntax, with properties and values separated by semicolons, no selectors, or nesting rules allowed.`
1599
+ }
1600
+ ]
1601
+ };
1602
+ });
1603
+ mcpServer.resource(
1604
+ "styles-schema",
1605
+ new ResourceTemplate(STYLE_SCHEMA_URI, {
1606
+ list: () => {
1607
+ const categories = [...Object.keys(getStylesSchema2()), "custom_css"];
1608
+ return {
1609
+ resources: categories.map((category) => ({
1610
+ uri: `elementor://styles/schema/${category}`,
1611
+ name: "Style schema for " + category
1612
+ }))
1613
+ };
1614
+ }
1615
+ }),
1616
+ {
1617
+ description: "Common styles schema for the specified category"
1618
+ },
1619
+ async (uri, variables) => {
1620
+ const category = typeof variables.category === "string" ? variables.category : variables.category?.[0];
1621
+ if (category === "custom_css") {
1622
+ return {
1623
+ contents: [
1624
+ {
1625
+ uri: uri.toString(),
1626
+ text: "Free style inline CSS string of properties and their values. Applicable for a single element, only the properties and values are accepted. Use this as a last resort for properties that are not covered with the schema."
1627
+ }
1628
+ ]
1629
+ };
1630
+ }
1631
+ const stylesSchema = getStylesSchema2()[category];
1632
+ if (!stylesSchema) {
1633
+ throw new Error(`No styles schema found for category: ${category}`);
1634
+ }
1635
+ const cleanedupPropSchema = cleanupPropType(stylesSchema);
1636
+ const asJson = Schema.propTypeToJsonSchema(cleanedupPropSchema);
1637
+ return {
1638
+ contents: [
1639
+ {
1640
+ uri: uri.toString(),
1641
+ text: JSON.stringify(asJson)
1642
+ }
1643
+ ]
1644
+ };
1645
+ }
1646
+ );
1647
+ mcpServer.resource(
1648
+ "widget-schema-by-type",
1649
+ new ResourceTemplate(WIDGET_SCHEMA_URI, {
1650
+ list: () => {
1651
+ const cache = getWidgetsCache2() || {};
1652
+ const availableWidgets = Object.keys(cache || {}).filter(
1653
+ (widgetType) => cache[widgetType]?.atomic_props_schema
1654
+ );
1655
+ return {
1656
+ resources: availableWidgets.map((widgetType) => ({
1657
+ uri: `elementor://widgets/schema/${widgetType}`,
1658
+ name: "Widget schema for " + widgetType
1659
+ }))
1660
+ };
1661
+ }
1662
+ }),
1663
+ {
1664
+ description: "PropType schema for the specified widget type"
1665
+ },
1666
+ async (uri, variables) => {
1667
+ const widgetType = typeof variables.widgetType === "string" ? variables.widgetType : variables.widgetType?.[0];
1668
+ const propSchema = getWidgetsCache2()?.[widgetType]?.atomic_props_schema;
1669
+ if (!propSchema) {
1670
+ throw new Error(`No prop schema found for element type: ${widgetType}`);
1671
+ }
1672
+ const cleanedupPropSchema = cleanupPropSchema(propSchema);
1673
+ const asJson = Object.fromEntries(
1674
+ Object.entries(cleanedupPropSchema).map(([key, propType]) => [
1675
+ key,
1676
+ Schema.propTypeToJsonSchema(propType)
1677
+ ])
1678
+ );
1679
+ Schema.nonConfigurablePropKeys.forEach((key) => {
1680
+ delete asJson[key];
1681
+ });
1682
+ return {
1683
+ contents: [
1684
+ {
1685
+ uri: uri.toString(),
1686
+ text: JSON.stringify(asJson)
1687
+ }
1688
+ ]
1689
+ };
1690
+ }
1691
+ );
1692
+ };
1693
+ function cleanupPropSchema(propSchema) {
1694
+ const result = {};
1695
+ Object.keys(propSchema).forEach((propName) => {
1696
+ result[propName] = cleanupPropType(propSchema[propName]);
1697
+ });
1698
+ return result;
1699
+ }
1700
+ function cleanupPropType(propType) {
1701
+ const result = {};
1702
+ Object.keys(propType).forEach((property) => {
1703
+ switch (property) {
1704
+ case "key":
1705
+ case "kind":
1706
+ result[property] = propType[property];
1707
+ break;
1708
+ case "meta":
1709
+ case "settings":
1710
+ {
1711
+ if (Object.keys(propType[property] || {}).length > 0) {
1712
+ result[property] = propType[property];
1713
+ }
1714
+ }
1715
+ break;
1716
+ }
1717
+ });
1718
+ if (result.kind === "plain") {
1719
+ Object.defineProperty(result, "kind", { value: "string" });
1720
+ } else if (result.kind === "array") {
1721
+ result.item_prop_type = cleanupPropType(propType.item_prop_type);
1722
+ } else if (result.kind === "object") {
1723
+ const shape = propType.shape;
1724
+ const cleanedShape = cleanupPropSchema(shape);
1725
+ result.shape = cleanedShape;
1726
+ } else if (result.kind === "union") {
1727
+ const propTypes = propType.prop_types;
1728
+ const cleanedPropTypes = {};
1729
+ Object.keys(propTypes).forEach((key) => {
1730
+ cleanedPropTypes[key] = cleanupPropType(propTypes[key]);
1731
+ });
1732
+ result.prop_types = cleanedPropTypes;
1733
+ }
1734
+ return result;
1735
+ }
1736
+
1737
+ // src/mcp/tools/build-composition/tool.ts
1738
+ import {
1739
+ createElement as createElement6,
1740
+ deleteElement,
1741
+ generateElementId,
1742
+ getContainer as getContainer3,
1743
+ getWidgetsCache as getWidgetsCache4
1744
+ } from "@elementor/editor-elements";
1745
+
1746
+ // src/mcp/utils/do-update-element-property.ts
1747
+ import {
1748
+ createElementStyle,
1749
+ getElementStyles,
1750
+ getWidgetsCache as getWidgetsCache3,
1751
+ updateElementSettings as updateElementSettings2,
1752
+ updateElementStyle
1753
+ } from "@elementor/editor-elements";
1754
+ import {
1755
+ getPropSchemaFromCache,
1756
+ Schema as Schema2,
1757
+ stringPropTypeUtil
1758
+ } from "@elementor/editor-props";
1759
+ import { getStylesSchema as getStylesSchema3 } from "@elementor/editor-styles";
1760
+ function resolvePropValue(value, forceKey) {
1761
+ return Schema2.adjustLlmPropValueSchema(value, forceKey);
1762
+ }
1763
+ var doUpdateElementProperty = (params) => {
1764
+ const { elementId, propertyName, propertyValue, elementType } = params;
1765
+ if (propertyName === "_styles") {
1766
+ const elementStyles = getElementStyles(elementId) || {};
1767
+ const propertyMapValue = propertyValue;
1768
+ const styleSchema = getStylesSchema3();
1769
+ const transformedStyleValues = Object.fromEntries(
1770
+ Object.entries(propertyMapValue).map(([key, val]) => {
1771
+ if (key === "custom_css") {
1772
+ return [key, val];
1773
+ }
1774
+ const { key: propKey, kind } = styleSchema?.[key] || {};
1775
+ if (!propKey && kind !== "union") {
1776
+ throw new Error(`_styles property ${key} is not supported.`);
1777
+ }
1778
+ return [key, resolvePropValue(val, propKey)];
1779
+ })
1780
+ );
1781
+ let customCss;
1782
+ Object.keys(propertyMapValue).forEach((stylePropName) => {
1783
+ const propertyRawSchema = styleSchema[stylePropName];
1784
+ if (stylePropName === "custom_css") {
1785
+ let customCssValue = propertyMapValue[stylePropName];
1786
+ if (typeof customCssValue === "object") {
1787
+ customCssValue = stringPropTypeUtil.extract(customCssValue) || customCssValue?.value || "";
1788
+ }
1789
+ customCss = {
1790
+ raw: btoa(customCssValue)
1791
+ };
1792
+ return;
1793
+ }
1794
+ const isSupported = !!propertyRawSchema;
1795
+ if (!isSupported) {
1796
+ throw new Error(`_styles property ${stylePropName} is not supported.`);
1797
+ }
1798
+ if (propertyRawSchema.kind === "plain") {
1799
+ if (typeof propertyMapValue[stylePropName] !== "object") {
1800
+ const propUtil = getPropSchemaFromCache(propertyRawSchema.key);
1801
+ if (propUtil) {
1802
+ const plainValue = propUtil.create(propertyMapValue[stylePropName]);
1803
+ propertyMapValue[stylePropName] = plainValue;
1804
+ }
1805
+ }
1806
+ }
1807
+ });
1808
+ const localStyle = Object.values(elementStyles).find((style) => style.label === "local");
1809
+ if (!localStyle) {
1810
+ createElementStyle({
1811
+ elementId,
1812
+ ...typeof customCss !== "undefined" ? { custom_css: customCss } : {},
1813
+ classesProp: "classes",
1814
+ label: "local",
1815
+ meta: {
1816
+ breakpoint: "desktop",
1817
+ state: null
1818
+ },
1819
+ props: {
1820
+ ...transformedStyleValues
1821
+ }
1822
+ });
1823
+ } else {
1824
+ updateElementStyle({
1825
+ elementId,
1826
+ styleId: localStyle.id,
1827
+ meta: {
1828
+ breakpoint: "desktop",
1829
+ state: null
1830
+ },
1831
+ ...typeof customCss !== "undefined" ? { custom_css: customCss } : {},
1832
+ props: {
1833
+ ...transformedStyleValues
1834
+ }
1835
+ });
1836
+ }
1837
+ return;
1838
+ }
1839
+ const elementPropSchema = getWidgetsCache3()?.[elementType]?.atomic_props_schema;
1840
+ if (!elementPropSchema) {
1841
+ throw new Error(`No prop schema found for element type: ${elementType}`);
1842
+ }
1843
+ if (!elementPropSchema[propertyName]) {
1844
+ const propertyNames = Object.keys(elementPropSchema);
1845
+ throw new Error(
1846
+ `Property "${propertyName}" does not exist on element type "${elementType}". Available properties are: ${propertyNames.join(
1847
+ ", "
1848
+ )}`
1849
+ );
1850
+ }
1851
+ const value = resolvePropValue(propertyValue);
1852
+ updateElementSettings2({
1853
+ id: elementId,
1854
+ props: {
1855
+ [propertyName]: value
1856
+ },
1857
+ withHistory: false
1858
+ });
1859
+ };
1860
+
1861
+ // src/mcp/tools/build-composition/prompt.ts
1862
+ import { toolPrompts } from "@elementor/editor-mcp";
1863
+ var generatePrompt = () => {
1864
+ const buildCompositionsToolPrompt = toolPrompts("build-compositions");
1865
+ buildCompositionsToolPrompt.description(`
1866
+ Build entire elementor widget comositions representing complex structures of nested elements.
1867
+
1868
+ # When to use this tool
1869
+ Always prefer this tool when the user requires to build a composition of elements, such as cards, heros, or inspired from other pages or HTML compositions.
1870
+ Prefer this tool over any other tool for building HTML structure, unless you are specified to use a different tool.
1871
+
1872
+ # **CRITICAL - REQUIRED RESOURCES (Must read before using this tool)**
1873
+ 1. [${WIDGET_SCHEMA_URI}]
1874
+ Required to understand which widgets are available, and what are their configuration schemas.
1875
+ Every widgetType (i.e. e-heading, e-button) that is supported has it's own property schema, that you must follow in order to apply property values correctly.
1876
+ 2. [${STYLE_SCHEMA_URI}]
1877
+ Required to understand the styles schema for the widgets. All widgets share the same styles schema.
1878
+ 3. List of allowed custom tags for building the structure is derived from the list of widgets schema resources.
1879
+
1880
+ # Instructions
1881
+ 1. Understand the user requirements carefully.
1882
+ 2. Build a valid XML structure using only the allowed custom tags provided. For example, if you
1883
+ use the "e-button" element, it would be represented as <e-button></e-button> in the XML structure.
1884
+ 3. Plan the configuration for each element according to the user requirements, using the configuration schema provided for each custom tag.
1885
+ Every widget type has it's own configuration schema, retreivable from the resource [${WIDGET_SCHEMA_URI}].
1886
+ PropValues must follow the exact PropType schema provided in the resource.
1887
+ 4. For every element, provide a "configuration-id" attribute. For example:
1888
+ \`<e-flexbox configuration-id="flex1"><e-heading configuration-id="heading2"></e-heading></e-flexbox>\`
1889
+ In the elementConfig property, provide the actual configuration object for each configuration-id used in the XML structure.
1890
+ In the stylesConfig property, provide the actual styles configuration object for each configuration-id used in the XML structure.
1891
+ 5. Ensure the XML structure is valid and parsable.
1892
+ 6. Do not add any attribute nodes, classes, id's, and no text nodes allowed.
1893
+ Layout properties, such as margin, padding, align, etc. must be applied using the [${STYLE_SCHEMA_URI}] PropValues.
1894
+ 7. Some elements allow nesting of other elements, and most of the DO NOT. The allowed elements that can have nested children are "e-div-block" and "e-flexbox".
1895
+ 8. Make sure that non-container elements do NOT have any nested elements.
1896
+ 9. Unsless the user specifically requires structure only, BE EXPRESSIVE AND VISUALLY CREATIVE AS POSSIBLE IN APPLYING STYLE CONFIGURATION.
1897
+ In the case of doubt, prefer adding more styles to make the composition visually appealing.
1898
+
1899
+ # Additional Guidelines
1900
+ - Most users expect the structure to be well designed and visually appealing.
1901
+ - Use layout properties, ensure "white space" design approach is followed, and make sure the composition is visually balanced.
1902
+ - Use appropriate spacing, alignment, and sizing to create a harmonious layout.
1903
+ - Consider the visual hierarchy of elements to guide the user's attention effectively.
1904
+ - You are encouraged to use colors, typography, and other style properties to enhance the visual appeal, as long as they are part of the configuration schema for the elements used.
1905
+ - Always aim for a clean and professional look that aligns with modern design principles.
1906
+ - When you are required to create placeholder texts, use texts that have a length that fits the goal. When long texts are required, use longer placeholder texts. When the user specifies exact texts, use the exact texts.
1907
+ - Image size does not affect the actual size on the screen, only which quality to use. If you use images, specifically add _styles PropValues to define the image sizes.
1908
+ - Attempt to use layout, margin, padding, size properties from the styles schema.
1909
+ - If your elements library is limited, encourage use of nesting containers to achieve complex layouts.
1910
+
1911
+ # CONSTRAINTS
1912
+ When a tool execution fails, retry up to 10 more times, read the error message carefully, and adjust the XML structure or the configurations accordingly.
1913
+ If a "$$type" is missing, update the invalid object, if the XML has parsing errors, fix it, etc. and RETRY.
1914
+ VALIDATE the XML structure before delivering it as the final result.
1915
+ VALIDATE the JSON structure used in the "configuration" attributes for each element before delivering the final result. The configuration must MATCH the PropValue schemas.
1916
+ NO LINKS ALLOWED. Never apply links to elements, even if they appear in the PropType schema.
1917
+ elementConfig values must align with the widget's PropType schema, available at the resource [${WIDGET_SCHEMA_URI}].
1918
+ stylesConfig values must align with the common styles PropType schema, available at the resource [${STYLE_SCHEMA_URI}].
1919
+
1920
+ # Parameters
1921
+ All parameters are MANDATORY.
1922
+ - xmlStructure
1923
+ - elementConfig
1924
+ - stylesConfig
1925
+
1926
+ If unsure about the configuration of a specific property, read the schema resources carefully.
1927
+
1928
+
1929
+ `);
1930
+ buildCompositionsToolPrompt.example(`
1931
+ A Heading and a button inside a flexbox
1932
+ {
1933
+ xmlStructure: "<e-flexbox configuration-id="flex1"><e-heading configuration-id="heading1"></e-heading><e-button configuration-id="button1"></e-button></e-flexbox>"
1934
+ elementConfig: {
1935
+ "flex1": {
1936
+ "tag": {
1937
+ "$$type": "string",
1938
+ "value": "section"
1939
+ },
1940
+ },
1941
+ stylesConfig: {
1942
+ "heading1": {
1943
+ "font-size": {
1944
+ "$$type": "size",
1945
+ "value": {
1946
+ "size": { "$$type": "number", "value": 24 },
1947
+ "unit": { "$$type": "string", "value": "px" }
1948
+ }
1949
+ },
1950
+ "color": {
1951
+ "$$type": "color",
1952
+ "value": { "$$type": "string", "value": "#333" }
1953
+ }
1954
+ }
1955
+ },
1956
+ }
1957
+ `);
1958
+ buildCompositionsToolPrompt.parameter(
1959
+ "xmlStructure",
1960
+ `**MANDATORY** A valid XML structure representing the composition to be built, using custom elementor tags, styling and configuration PropValues.`
1961
+ );
1962
+ buildCompositionsToolPrompt.parameter(
1963
+ "elementConfig",
1964
+ `**MANDATORY** A record mapping configuration IDs to their corresponding configuration objects, defining the PropValues for each element created.`
1965
+ );
1966
+ buildCompositionsToolPrompt.parameter(
1967
+ "stylesConfig",
1968
+ `**MANDATORY** A record mapping style PropTypes to their corresponding style configuration objects, defining the PropValues for styles to be applied to elements.`
1969
+ );
1970
+ buildCompositionsToolPrompt.instruction(
1971
+ `You will be provided the XML structure with element IDs. These IDs represent the actual elementor widgets created on the page/post.
1972
+ You should use these IDs as reference for further configuration, styling or changing elements later on.`
1973
+ );
1974
+ buildCompositionsToolPrompt.instruction(
1975
+ `You must use styles/variables/classes that are available in the project resources, you should prefer using them over inline styles, and you are welcome to execute relevant tools AFTER this tool execution, to apply global classes to the created elements.`
1976
+ );
1977
+ return buildCompositionsToolPrompt.prompt();
1978
+ };
1979
+
1980
+ // src/mcp/tools/build-composition/schema.ts
1981
+ import { z } from "@elementor/schema";
1982
+ var inputSchema = {
1983
+ xmlStructure: z.string().describe("The XML structure representing the composition to be built"),
1984
+ elementConfig: z.record(
1985
+ z.string().describe("The configuration id"),
1986
+ z.record(z.string().describe("property name"), z.any().describe("The PropValue for the property"))
1987
+ ).describe("A record mapping element IDs to their configuration objects. REQUIRED"),
1988
+ stylesConfig: z.record(
1989
+ z.string().describe("The configuration id"),
1990
+ z.record(
1991
+ z.string().describe("_styles property name"),
1992
+ z.any().describe("The PropValue for the style property. MANDATORY")
1993
+ )
1994
+ ).describe(
1995
+ `A record mapping element IDs to their styles configuration objects. Use the actual styles schema from [${STYLE_SCHEMA_URI}].`
1996
+ ).default({})
1997
+ };
1998
+ var outputSchema = {
1999
+ errors: z.string().describe("Error message if the composition building failed").optional(),
2000
+ xmlStructure: z.string().describe("The built XML structure as a string").optional(),
2001
+ llmInstructions: z.string().describe("Instructions used to further actions for you").optional()
2002
+ };
2003
+
2004
+ // src/mcp/tools/build-composition/tool.ts
2005
+ var initBuildCompositionsTool = (reg) => {
2006
+ const { addTool } = reg;
2007
+ addTool({
2008
+ name: "build-compositions",
2009
+ description: generatePrompt(),
2010
+ schema: inputSchema,
2011
+ outputSchema,
2012
+ handler: async (params) => {
2013
+ let xml = null;
2014
+ const { xmlStructure, elementConfig, stylesConfig } = params;
2015
+ const errors = [];
2016
+ const softErrors = [];
2017
+ const rootContainers = [];
2018
+ const widgetsCache = getWidgetsCache4() || {};
2019
+ const documentContainer = getContainer3("document");
2020
+ try {
2021
+ const parser = new DOMParser();
2022
+ xml = parser.parseFromString(xmlStructure, "application/xml");
2023
+ const errorNode = xml.querySelector("parsererror");
2024
+ if (errorNode) {
2025
+ throw new Error("Failed to parse XML structure: " + errorNode.textContent);
2026
+ }
2027
+ const children = Array.from(xml.children);
2028
+ const iterate = (node, containerElement = documentContainer) => {
2029
+ const elementTag = node.tagName;
2030
+ if (!widgetsCache[elementTag]) {
2031
+ errors.push(new Error(`Unknown widget type: ${elementTag}`));
2032
+ }
2033
+ const isContainer = elementTag === "e-flexbox" || elementTag === "e-div-block";
2034
+ const newElement = isContainer ? createElement6({
2035
+ containerId: containerElement.id,
2036
+ model: {
2037
+ elType: elementTag,
2038
+ id: generateElementId()
2039
+ },
2040
+ options: { useHistory: false }
2041
+ }) : createElement6({
2042
+ containerId: containerElement.id,
2043
+ model: {
2044
+ elType: "widget",
2045
+ widgetType: elementTag,
2046
+ id: generateElementId()
2047
+ },
2048
+ options: { useHistory: false }
2049
+ });
2050
+ if (containerElement === documentContainer) {
2051
+ rootContainers.push(newElement);
2052
+ }
2053
+ node.setAttribute("id", newElement.id);
2054
+ const configId = node.getAttribute("configuration-id") || "";
2055
+ try {
2056
+ const configObject = elementConfig[configId] || {};
2057
+ const styleObject = stylesConfig[configId] || {};
2058
+ configObject._styles = styleObject;
2059
+ for (const [propertyName, propertyValue] of Object.entries(configObject)) {
2060
+ const widgetSchema = widgetsCache[elementTag];
2061
+ if (!widgetSchema?.atomic_props_schema?.[propertyName] && propertyName !== "_styles" && propertyName !== "custom_css") {
2062
+ softErrors.push(
2063
+ new Error(
2064
+ `Property "${propertyName}" does not exist on element type "${elementTag}".`
2065
+ )
2066
+ );
2067
+ continue;
2068
+ }
2069
+ try {
2070
+ doUpdateElementProperty({
2071
+ elementId: newElement.id,
2072
+ propertyName,
2073
+ propertyValue: propertyName === "custom_css" ? { _styles: propertyValue } : propertyValue,
2074
+ elementType: elementTag
2075
+ });
2076
+ } catch (error) {
2077
+ softErrors.push(error);
2078
+ }
2079
+ }
2080
+ if (isContainer) {
2081
+ for (const child of node.children) {
2082
+ iterate(child, newElement);
2083
+ }
2084
+ } else {
2085
+ node.innerHTML = "";
2086
+ node.removeAttribute("configuration");
2087
+ }
2088
+ } finally {
2089
+ }
2090
+ };
2091
+ for (const childNode of children) {
2092
+ iterate(childNode, documentContainer);
2093
+ try {
2094
+ } catch (error) {
2095
+ errors.push(error);
2096
+ }
2097
+ }
2098
+ } catch (error) {
2099
+ errors.push(error);
2100
+ }
2101
+ if (errors.length) {
2102
+ rootContainers.forEach((rootContainer) => {
2103
+ deleteElement({
2104
+ elementId: rootContainer.id,
2105
+ options: { useHistory: false }
2106
+ });
2107
+ });
2108
+ }
2109
+ if (errors.length > 0) {
2110
+ const errorText = `Failed to build composition with the following errors:
2111
+
2112
+
2113
+ ${errors.map((e) => typeof e === "string" ? e : e.message).join("\n\n")}
2114
+ "Missing $$type" errors indicate that the configuration objects are invalid. Try again and apply **ALL** object entries with correct $$type.
2115
+ Now that you have these errors, fix them and try again. Errors regarding configuration objects, please check again the PropType schemas`;
2116
+ throw new Error(errorText);
2117
+ }
2118
+ if (!xml) {
2119
+ throw new Error("XML structure is null after parsing.");
2120
+ }
2121
+ return {
2122
+ xmlStructure: new XMLSerializer().serializeToString(xml),
2123
+ llmInstructions: (softErrors.length ? `The composition was built successfully, but there were some issues with the provided configurations:
2124
+
2125
+ ${softErrors.map((e) => `- ${e.message}`).join("\n")}
2126
+
2127
+ Please use confiugure-element tool to fix these issues. Now that you have information about these issues, use the configure-element tool to fix them!` : "") + `
2128
+ Next Steps:
2129
+ - Use "apply-global-class" tool as there may be global styles ready to be applied to elements.
2130
+ - Use "configure-element" tool to further configure elements as needed, including styles.
2131
+ `
2132
+ };
2133
+ }
2134
+ });
2135
+ };
2136
+
2137
+ // src/mcp/tools/configure-element/prompt.ts
2138
+ var configureElementToolPrompt = `Configure an existing element on the page.
2139
+
2140
+ # **CRITICAL - REQUIRED INFORMATION (Must read before using this tool)**
2141
+ 1. [${WIDGET_SCHEMA_URI}]
2142
+ Required to understand which widgets are available, and what are their configuration schemas.
2143
+ Every widgetType (i.e. e-heading, e-button) that is supported has it's own property schema, that you must follow in order to apply property values correctly.
2144
+ 2. [${STYLE_SCHEMA_URI}]
2145
+ Required to understand the styles schema for the widgets. All widgets share the same styles schema, grouped by categories.
2146
+ Use this resource to understand which style properties are available for each element, and how to structure the "_styles" configuration property.
2147
+ 3. If not sure about the PropValues schema, you can use the "get-element-configuration-values" tool to retreive the current PropValues configuration of the element.
2148
+
2149
+ Before using this tool, check the definitions of the elements PropTypes at the resource "widget-schema-by-type" at editor-canvas__elementor://widgets/schema/{widgetType}
2150
+ All widgets share a common _style property for styling, which uses the common styles schema.
2151
+ Retreive and check the common styles schema at the resource list "styles-schema" at editor-canvas__elementor://styles/schema/{category}
2152
+
2153
+ # Parameters
2154
+ - propertiesToChange: An object containing the properties to change, with their new values. MANDATORY
2155
+ - elementId: The ID of the element to configure. MANDATORY
2156
+ - elementType: The type of the element to configure (i.e. e-heading, e-button). MANDATORY
2157
+
2158
+ # When to use this tool
2159
+ When a user requires to change anything in an element, such as updating text, colors, sizes, or other configurable properties.
2160
+ This tool handles elements of type "widget".
2161
+ This tool handles styling elements, using the _styles property in the configuration.
2162
+
2163
+ The element's schema must be known before using this tool.
2164
+
2165
+ Attached resource link describing how PropType schema should be parsed as PropValue for this tool.
2166
+
2167
+ Read carefully the PropType Schema of the element and it's styles, then apply correct PropValue according to the schema.
2168
+
2169
+ PropValue structure:
2170
+ {
2171
+ "$$type": string, // MANDATORY as defined in the PropType schema under the "key" property
2172
+ value: unknown // The value according to the PropType schema for kinds of "array", use array with PropValues items inside. For "object", read the shape property of the PropType schema. For "plain", use strings.
2173
+ }
2174
+
2175
+ <IMPORTANT>
2176
+ ALWAYS MAKE SURE you have the PropType schemas for the element you are configuring, and the common-styles schema for styling. If you are not sure, retreive the schema from the resources mentioned above.
2177
+ </IMPORTANT>
2178
+
2179
+ You can use multiple property changes at once by providing multiple entries in the propertiesToChange object, including _style alongside non-style props.
2180
+ Some properties are nested, use the root property name, then objects with nested values inside, as the complete schema suggests.
2181
+ Nested properties, such as for the _styles, should include a "_styles" property with object containing the definitions to change.
2182
+
2183
+ Make sure you have the "widget-schema-by-type" resource available to retreive the PropType schema for the element type you are configuring.
2184
+
2185
+ # How to configure elements
2186
+ We use a dedicated PropType Schema for configuring elements, including styles. When you configure an element, you must use the EXACT PropType Value as defined in the schema.
2187
+ For _styles, use the style schema provided, as it also uses the PropType format.
2188
+ For all non-primitive types, provide the key property as defined in the schema as $$type in the generated objecct, as it is MANDATORY for parsing.
2189
+
2190
+ Use the EXACT "PROP-TYPE" Schema given, and ALWAYS include the "key" property from the original configuration for every property you are changing.
2191
+
2192
+ # Example
2193
+ \`\`\`json
2194
+ {
2195
+ propertiesToChange: {
2196
+ // List of properties TO CHANGE, following the PropType schema for the element as defined in the resource [${WIDGET_SCHEMA_URI}]
2197
+ title: {
2198
+ $$type: 'string',
2199
+ value: 'New Title Text'
2200
+ },
2201
+ border: {
2202
+ $$type: 'boolean',
2203
+ value: false
2204
+ },
2205
+ _styles: {
2206
+ // List of available keys available at the [${STYLE_SCHEMA_URI}] dynamic resource
2207
+ 'line-height': {
2208
+ $$type: 'size', // MANDATORY do not forget to include the correct $$type for every property
2209
+ value: {
2210
+ size: {
2211
+ $$type: 'number',
2212
+ value: 20
2213
+ },
2214
+ unit: {
2215
+ $$type: 'string',
2216
+ value: 'px'
2217
+ }
2218
+ }
2219
+ }
2220
+ }
2221
+ }
2222
+ };
2223
+ \`\`\`
2224
+
2225
+ <IMPORTANT>
2226
+ The $$type property is MANDATORY for every value, it is required to parse the value and apply application-level effects.
2227
+ </IMPORTANT>
2228
+ `;
2229
+
2230
+ // src/mcp/tools/configure-element/schema.ts
2231
+ import { z as z2 } from "@elementor/schema";
2232
+ var inputSchema2 = {
2233
+ propertiesToChange: z2.record(
2234
+ z2.string().describe(
2235
+ "The property name. If nested property, provide the root property name, and the object delta only."
2236
+ ),
2237
+ z2.any().describe("The property's value")
2238
+ ).describe("An object record containing property names and their new values to be set on the element").optional(),
2239
+ elementType: z2.string().describe("The type of the element to retreive the schema"),
2240
+ elementId: z2.string().describe("The unique id of the element to configure")
2241
+ };
2242
+ var outputSchema2 = {
2243
+ success: z2.boolean().describe(
2244
+ "Whether the configuration change was successful, only if propertyName and propertyValue are provided"
2245
+ )
2246
+ };
2247
+
2248
+ // src/mcp/tools/configure-element/tool.ts
2249
+ var initConfigureElementTool = (reg) => {
2250
+ const { addTool } = reg;
2251
+ addTool({
2252
+ name: "configure-element",
2253
+ description: configureElementToolPrompt,
2254
+ schema: inputSchema2,
2255
+ outputSchema: outputSchema2,
2256
+ handler: ({ elementId, propertiesToChange, elementType }) => {
2257
+ if (!propertiesToChange) {
2258
+ throw new Error(
2259
+ "propertiesToChange is required to configure an element. Now that you have this information, ensure you have the schema and try again."
2260
+ );
2261
+ }
2262
+ const toUpdate = Object.entries(propertiesToChange);
2263
+ for (const [propertyName, propertyValue] of toUpdate) {
2264
+ if (!propertyName && !elementId && !elementType) {
2265
+ throw new Error(
2266
+ "propertyName, elementId, elementType are required to configure an element. If you want to retreive the schema, use the get-element-configuration-schema tool."
2267
+ );
2268
+ }
2269
+ try {
2270
+ doUpdateElementProperty({
2271
+ elementId,
2272
+ elementType,
2273
+ propertyName,
2274
+ propertyValue
2275
+ });
2276
+ } catch (error) {
2277
+ const errorMessage = createUpdateErrorMessage({
2278
+ propertyName,
2279
+ elementId,
2280
+ elementType,
2281
+ error
2282
+ });
2283
+ throw new Error(errorMessage);
2284
+ }
2285
+ }
2286
+ return {
2287
+ success: true
2288
+ };
2289
+ }
2290
+ });
2291
+ };
2292
+ function createUpdateErrorMessage(opts) {
2293
+ const { propertyName, elementId, elementType, error } = opts;
2294
+ return `Failed to update property "${propertyName}" on element "${elementId}": ${error.message}.
2295
+ Check the element's PropType schema at the resource [${WIDGET_SCHEMA_URI.replace(
2296
+ "{widgetType}",
2297
+ elementType
2298
+ )}] for type "${elementType}" to ensure the property exists and the value matches the expected PropType.
2299
+ Now that you have this information, ensure you have the schema and try again.`;
2300
+ }
2301
+
2302
+ // src/mcp/tools/get-element-config/tool.ts
2303
+ import { getContainer as getContainer4, getElementStyles as getElementStyles2, getWidgetsCache as getWidgetsCache5 } from "@elementor/editor-elements";
2304
+ import { Schema as Schema3 } from "@elementor/editor-props";
2305
+ import { z as z3 } from "@elementor/schema";
2306
+ var schema = {
2307
+ elementId: z3.string()
2308
+ };
2309
+ var outputSchema3 = {
2310
+ propValues: z3.record(z3.string(), z3.any()).describe(
2311
+ "A record mapping PropTypes to their corresponding PropValues, with _styles record for style-related PropValues"
2312
+ )
2313
+ };
2314
+ var initGetElementConfigTool = (reg) => {
2315
+ const { addTool } = reg;
2316
+ addTool({
2317
+ name: "get-element-configuration-values",
2318
+ description: "Retrieve the element's configuration PropValues for a specific element by unique ID.",
2319
+ schema,
2320
+ outputSchema: outputSchema3,
2321
+ handler: async ({ elementId }) => {
2322
+ const element = getContainer4(elementId);
2323
+ if (!element) {
2324
+ throw new Error(`Element with ID ${elementId} not found.`);
2325
+ }
2326
+ const elementRawSettings = element.settings;
2327
+ const propSchema = getWidgetsCache5()?.[element.model.get("widgetType") || ""]?.atomic_props_schema;
2328
+ if (!elementRawSettings || !propSchema) {
2329
+ throw new Error(`No settings or prop schema found for element ID: ${elementId}`);
2330
+ }
2331
+ const propValues = {};
2332
+ const stylePropValues = {};
2333
+ Schema3.configurableKeys(propSchema).forEach((key) => {
2334
+ propValues[key] = structuredClone(elementRawSettings.get(key));
2335
+ });
2336
+ const elementStyles = getElementStyles2(elementId) || {};
2337
+ const localStyle = Object.values(elementStyles).find((style) => style.label === "local");
2338
+ if (localStyle) {
2339
+ const defaultVariant = localStyle.variants.find(
2340
+ (variant) => variant.meta.breakpoint === "desktop" && !variant.meta.state
2341
+ );
2342
+ if (defaultVariant) {
2343
+ const styleProps = defaultVariant.props || {};
2344
+ Object.keys(styleProps).forEach((stylePropName) => {
2345
+ if (typeof styleProps[stylePropName] !== "undefined") {
2346
+ stylePropValues[stylePropName] = structuredClone(styleProps[stylePropName]);
2347
+ }
2348
+ });
2349
+ }
2350
+ }
2351
+ return {
2352
+ propValues: {
2353
+ ...propValues,
2354
+ _styles: stylePropValues
2355
+ }
2356
+ };
2357
+ }
2358
+ });
2359
+ };
2360
+
2361
+ // src/mcp/canvas-mcp.ts
2362
+ var initCanvasMcp = (reg) => {
2363
+ const { setMCPDescription } = reg;
2364
+ setMCPDescription(
2365
+ 'Everything related to creative design, layout, styling and building the pages, specifically element of type "widget"'
2366
+ );
2367
+ initWidgetsSchemaResource(reg);
2368
+ initBuildCompositionsTool(reg);
2369
+ initGetElementConfigTool(reg);
2370
+ initConfigureElementTool(reg);
2371
+ };
2372
+
2373
+ // src/mcp/mcp-description.ts
2374
+ var mcpDescription = `Canvas MCP - Working with widgets and styles: how to use the PropType schemas and generate PropValue structures
2375
+
2376
+ # Elementor's PropValue configuration system
2377
+
2378
+ Every widget in Elementor has a set of properties that can be configured, defined in a STRICT SCHEMA we call "PropType".
2379
+ All widget configuration values are represented using a structure we call "PropValue".
2380
+
2381
+ To correctly configure a widget's properties, FOLLOW THE PropType schema defined for that widget. This schema outlines the expected structure and types for each property, ensuring that the values you provide are valid and can be properly interpreted by Elementor.
2382
+ Every widget has it's own PropType schema, retreivable from the resource [${WIDGET_SCHEMA_URI}].
2383
+ ALL WIDGETS share a common _styles property with a uniform styles schema, retreivable from the resource [${STYLE_SCHEMA_URI}].
2384
+ The style schema is grouped by categories, such as "typography", "background", "border", etc.
2385
+
2386
+ # Tools and usage
2387
+ - Use the "get-element-configuration-values" tool to retrieve the current configuration of a specific element, including its PropValues and styles. It is recommended to use this tool when you are required to make changes to an existing element, to ensure you have the correct current configuration schema.
2388
+ If a PropValue changes it's type (only on union PropTypes), read the new schema from the resources mentioned above, and adjust the PropValue structure accordingly.
2389
+ - Use the "build-composition" tool to create a NEW ELEMENTS in a composition on the page. You can use this tool to also create a new single element.
2390
+ - Use the "configure-element" tool to update the configuration of an EXISTING element on the page.
2391
+
2392
+ All array types that can receive union types, are typed as mixed array, which means that each item in the array can be of any of the allowed types defined in the PropType schema.
2393
+ Example: the "background" can have a background-overlay property, which can contain multiple overlays, such as color, gradient, image, etc. Each item in the array must follow the PropType schema for each overlay type.
2394
+ All _style properties are OPTIONAL. When a _style is defined, we MERGE the values with existing styles, so only the properties you define will be changed, and the rest will remain as is.
2395
+
2396
+ # Styling best practices
2397
+ Prefer using "em" and "rem" values for text-related sizes, padding and spacing. Use percentages for dynamic sizing relative to parent containers.
2398
+ This flexboxes are by default "flex" with "stretch" alignment. To ensure proper layout, define the "justify-content" and "align-items" as in the schema.
2399
+
2400
+ Additionaly, some PropTypes have metadata information (meta property) that can help in understaind the PropType usage, such as description or other useful information.
2401
+
2402
+ Example of null values:
2403
+ {
2404
+ $$type: 'as-defined-for-propValue',
2405
+ value: null
2406
+ }
2407
+
2408
+ Example of "image" PropValue structure:
2409
+ {$$type:'image',value:{src:{$$type:'image-src',value:{url:{$$type:'url',value:'https://example.com/image.jpg'}}},size:{$$type:'string',value:'full'}}}
2410
+
2411
+ `;
2412
+
1249
2413
  // src/prevent-link-in-link-commands.ts
1250
2414
  import {
1251
2415
  getAnchoredAncestorId,
@@ -1342,17 +2506,17 @@ import {
1342
2506
 
1343
2507
  // src/style-commands/undoable-actions/paste-element-style.ts
1344
2508
  import {
1345
- createElementStyle,
2509
+ createElementStyle as createElementStyle2,
1346
2510
  deleteElementStyle,
1347
- getElementStyles,
1348
- updateElementStyle
2511
+ getElementStyles as getElementStyles3,
2512
+ updateElementStyle as updateElementStyle2
1349
2513
  } from "@elementor/editor-elements";
1350
2514
  import { ELEMENTS_STYLES_RESERVED_LABEL } from "@elementor/editor-styles-repository";
1351
2515
  import { undoable } from "@elementor/editor-v1-adapters";
1352
2516
  import { __ as __3 } from "@wordpress/i18n";
1353
2517
 
1354
2518
  // src/style-commands/utils.ts
1355
- import { getElementLabel, getWidgetsCache as getWidgetsCache2 } from "@elementor/editor-elements";
2519
+ import { getElementLabel, getWidgetsCache as getWidgetsCache6 } from "@elementor/editor-elements";
1356
2520
  import { CLASSES_PROP_KEY } from "@elementor/editor-props";
1357
2521
  import { __ as __2 } from "@wordpress/i18n";
1358
2522
  function hasAtomicWidgets(args) {
@@ -1377,7 +2541,7 @@ function getClassesProp(container) {
1377
2541
  }
1378
2542
  function getContainerSchema(container) {
1379
2543
  const type = container?.model.get("widgetType") || container?.model.get("elType");
1380
- const widgetsCache = getWidgetsCache2();
2544
+ const widgetsCache = getWidgetsCache6();
1381
2545
  const elementType = widgetsCache?.[type];
1382
2546
  return elementType?.atomic_props_schema ?? null;
1383
2547
  }
@@ -1403,7 +2567,7 @@ var undoablePasteElementStyle = () => undoable(
1403
2567
  if (!classesProp) {
1404
2568
  return null;
1405
2569
  }
1406
- const originalStyles = getElementStyles(container.id);
2570
+ const originalStyles = getElementStyles3(container.id);
1407
2571
  const [styleId, styleDef] = Object.entries(originalStyles ?? {})[0] ?? [];
1408
2572
  const originalStyle = Object.keys(styleDef ?? {}).length ? styleDef : null;
1409
2573
  const revertData = {
@@ -1412,7 +2576,7 @@ var undoablePasteElementStyle = () => undoable(
1412
2576
  };
1413
2577
  if (styleId) {
1414
2578
  newStyle.variants.forEach(({ meta, props, custom_css: customCss }) => {
1415
- updateElementStyle({
2579
+ updateElementStyle2({
1416
2580
  elementId,
1417
2581
  styleId,
1418
2582
  meta,
@@ -1423,7 +2587,7 @@ var undoablePasteElementStyle = () => undoable(
1423
2587
  } else {
1424
2588
  const [firstVariant] = newStyle.variants;
1425
2589
  const additionalVariants = newStyle.variants.slice(1);
1426
- revertData.styleId = createElementStyle({
2590
+ revertData.styleId = createElementStyle2({
1427
2591
  elementId,
1428
2592
  classesProp,
1429
2593
  label: ELEMENTS_STYLES_RESERVED_LABEL,
@@ -1450,7 +2614,7 @@ var undoablePasteElementStyle = () => undoable(
1450
2614
  }
1451
2615
  const [firstVariant] = revertData.originalStyle.variants;
1452
2616
  const additionalVariants = revertData.originalStyle.variants.slice(1);
1453
- createElementStyle({
2617
+ createElementStyle2({
1454
2618
  elementId: container.id,
1455
2619
  classesProp,
1456
2620
  label: ELEMENTS_STYLES_RESERVED_LABEL,
@@ -1506,7 +2670,7 @@ import {
1506
2670
  } from "@elementor/editor-v1-adapters";
1507
2671
 
1508
2672
  // src/style-commands/undoable-actions/reset-element-style.ts
1509
- import { createElementStyle as createElementStyle2, deleteElementStyle as deleteElementStyle2, getElementStyles as getElementStyles2 } from "@elementor/editor-elements";
2673
+ import { createElementStyle as createElementStyle3, deleteElementStyle as deleteElementStyle2, getElementStyles as getElementStyles4 } from "@elementor/editor-elements";
1510
2674
  import { ELEMENTS_STYLES_RESERVED_LABEL as ELEMENTS_STYLES_RESERVED_LABEL2 } from "@elementor/editor-styles-repository";
1511
2675
  import { undoable as undoable2 } from "@elementor/editor-v1-adapters";
1512
2676
  import { __ as __4 } from "@wordpress/i18n";
@@ -1515,7 +2679,7 @@ var undoableResetElementStyle = () => undoable2(
1515
2679
  do: ({ containers }) => {
1516
2680
  return containers.map((container) => {
1517
2681
  const elementId = container.model.get("id");
1518
- const containerStyles = getElementStyles2(elementId);
2682
+ const containerStyles = getElementStyles4(elementId);
1519
2683
  Object.keys(containerStyles ?? {}).forEach(
1520
2684
  (styleId) => deleteElementStyle2(elementId, styleId)
1521
2685
  );
@@ -1533,7 +2697,7 @@ var undoableResetElementStyle = () => undoable2(
1533
2697
  Object.entries(containerStyles ?? {}).forEach(([styleId, style]) => {
1534
2698
  const [firstVariant] = style.variants;
1535
2699
  const additionalVariants = style.variants.slice(1);
1536
- createElementStyle2({
2700
+ createElementStyle3({
1537
2701
  elementId,
1538
2702
  classesProp,
1539
2703
  styleId,
@@ -1585,6 +2749,7 @@ function init() {
1585
2749
  initLinkInLinkPrevention();
1586
2750
  initLegacyViews();
1587
2751
  initSettingsTransformers();
2752
+ initInteractionsRepository();
1588
2753
  injectIntoTop({
1589
2754
  id: "elements-overlays",
1590
2755
  component: ElementsOverlays
@@ -1593,17 +2758,66 @@ function init() {
1593
2758
  id: "canvas-style-render",
1594
2759
  component: StyleRenderer
1595
2760
  });
2761
+ injectIntoTop({
2762
+ id: "canvas-interactions-render",
2763
+ component: InteractionsRenderer
2764
+ });
1596
2765
  injectIntoLogic({
1597
2766
  id: "classes-rename",
1598
2767
  component: ClassesRename
1599
2768
  });
2769
+ initCanvasMcp(
2770
+ getMCPByDomain("canvas", {
2771
+ instructions: mcpDescription
2772
+ })
2773
+ );
1600
2774
  }
2775
+
2776
+ // src/sync/drag-element-from-panel.ts
2777
+ var startDragElementFromPanel = (props) => {
2778
+ const channels = getElementorChannels();
2779
+ channels?.editor.reply("element:dragged", null);
2780
+ channels?.panelElements.reply("element:selected", getLegacyPanelElementView(props)).trigger("element:drag:start");
2781
+ };
2782
+ var endDragElementFromPanel = () => {
2783
+ getElementorChannels()?.panelElements?.trigger("element:drag:end");
2784
+ };
2785
+ var getElementorChannels = () => {
2786
+ const extendedWindow = window;
2787
+ const channels = extendedWindow.elementor?.channels;
2788
+ if (!channels) {
2789
+ throw new Error(
2790
+ "Elementor channels not found: Elementor editor is not initialized or channels are unavailable."
2791
+ );
2792
+ }
2793
+ return channels;
2794
+ };
2795
+ var getLegacyPanelElementView = ({ settings, ...rest }) => {
2796
+ const extendedWindow = window;
2797
+ const LegacyElementModel = extendedWindow.elementor?.modules?.elements?.models?.Element;
2798
+ if (!LegacyElementModel) {
2799
+ throw new Error("Elementor legacy Element model not found in editor modules");
2800
+ }
2801
+ const elementModel = new LegacyElementModel({
2802
+ ...rest,
2803
+ custom: {
2804
+ isPreset: !!settings,
2805
+ preset_settings: settings
2806
+ }
2807
+ });
2808
+ return { model: elementModel };
2809
+ };
1601
2810
  export {
1602
2811
  createPropsResolver,
2812
+ createTemplatedElementView,
1603
2813
  createTransformer,
1604
2814
  createTransformersRegistry,
2815
+ endDragElementFromPanel,
2816
+ getCanvasIframeDocument,
1605
2817
  init,
2818
+ registerElementType,
1606
2819
  settingsTransformersRegistry,
2820
+ startDragElementFromPanel,
1607
2821
  styleTransformersRegistry
1608
2822
  };
1609
2823
  //# sourceMappingURL=index.mjs.map