@perkyzz/emvb 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/README.md +3 -3
  2. package/package.json +4 -4
  3. package/src/admin/agents-api.ts +45 -0
  4. package/src/admin/editor/A11yCopilot.tsx +1 -1
  5. package/src/admin/editor/Editor.tsx +325 -239
  6. package/src/admin/editor/FieldPreview.tsx +164 -0
  7. package/src/admin/editor/Timeline.tsx +2 -1
  8. package/src/admin/editor/TopBar.tsx +36 -3
  9. package/src/admin/editor/canvas/CanvasFrame.tsx +2 -2
  10. package/src/admin/editor/canvas/DeviceBar.tsx +17 -9
  11. package/src/admin/editor/canvas/canvas-scale.ts +2 -2
  12. package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
  13. package/src/admin/editor/co-design.ts +190 -0
  14. package/src/admin/editor/dnd/new-element.ts +26 -4
  15. package/src/admin/editor/editor-chrome.tsx +3 -3
  16. package/src/admin/editor/editor-commands.ts +8 -3
  17. package/src/admin/editor/editor-css.ts +3 -0
  18. package/src/admin/editor/element-chrome.ts +3 -1
  19. package/src/admin/editor/extension-manifests.ts +20 -0
  20. package/src/admin/editor/extensions/ExtensionPanels.tsx +26 -0
  21. package/src/admin/editor/extensions-context.tsx +27 -0
  22. package/src/admin/editor/feature-css.ts +17 -0
  23. package/src/admin/editor/host.ts +6 -0
  24. package/src/admin/editor/palette-items.ts +2 -2
  25. package/src/admin/editor/panels/AddPanel.tsx +31 -1
  26. package/src/admin/editor/panels/AgentRequestBox.tsx +116 -0
  27. package/src/admin/editor/panels/ClassesSection.tsx +9 -6
  28. package/src/admin/editor/panels/CoDesignPanel.tsx +170 -0
  29. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  30. package/src/admin/editor/panels/ElementPanel.tsx +53 -15
  31. package/src/admin/editor/panels/LanguagesSection.tsx +152 -0
  32. package/src/admin/editor/panels/LayersPanel.tsx +10 -6
  33. package/src/admin/editor/panels/LeftPanel.tsx +33 -5
  34. package/src/admin/editor/panels/PageSettings.tsx +4 -0
  35. package/src/admin/editor/panels/SettingsPanel.tsx +21 -2
  36. package/src/admin/editor/panels/SiteStylesDrawer.tsx +7 -7
  37. package/src/admin/editor/panels/settings/BackgroundControls.tsx +76 -20
  38. package/src/admin/editor/panels/settings/BackgroundFill.tsx +8 -6
  39. package/src/admin/editor/panels/settings/BoxControl.tsx +5 -5
  40. package/src/admin/editor/panels/settings/EffectsControls.tsx +104 -9
  41. package/src/admin/editor/panels/settings/FieldControl.tsx +9 -3
  42. package/src/admin/editor/panels/settings/IconControls.tsx +14 -11
  43. package/src/admin/editor/panels/settings/LengthRow.tsx +27 -16
  44. package/src/admin/editor/panels/settings/LoopControl.tsx +269 -0
  45. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
  46. package/src/admin/editor/panels/settings/MediaPicker.tsx +5 -5
  47. package/src/admin/editor/panels/settings/MotionControl.tsx +12 -11
  48. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +7 -4
  49. package/src/admin/editor/panels/settings/StyleRow.tsx +113 -13
  50. package/src/admin/editor/panels/settings/TextMarksControl.tsx +247 -0
  51. package/src/admin/editor/panels/settings/VariableBinding.tsx +2 -2
  52. package/src/admin/editor/panels/settings/background-mode.ts +14 -11
  53. package/src/admin/editor/panels/settings/box-link-name.ts +1 -1
  54. package/src/admin/editor/panels/settings/box-sides.ts +22 -14
  55. package/src/admin/editor/panels/settings/heading-warning.ts +5 -1
  56. package/src/admin/editor/panels/settings/length-units.ts +55 -2
  57. package/src/admin/editor/panels/settings/query-style.ts +3 -3
  58. package/src/admin/editor/panels/settings/style-sections.ts +51 -10
  59. package/src/admin/editor/panels/style-target.ts +9 -7
  60. package/src/admin/editor/presence.ts +60 -0
  61. package/src/admin/editor/store.ts +6 -2
  62. package/src/admin/editor/useCoDesign.ts +177 -0
  63. package/src/admin/editor/useEditorCommands.ts +4 -4
  64. package/src/admin/editor/useExtensions.ts +45 -0
  65. package/src/admin/editor/useNodeActions.ts +15 -6
  66. package/src/admin/editor/useProposals.ts +81 -0
  67. package/src/admin/index.tsx +5 -1
  68. package/src/admin/languages-api.ts +61 -0
  69. package/src/admin/media-api.ts +27 -0
  70. package/src/admin/pages/AgentSetup.tsx +148 -0
  71. package/src/admin/pages/AgentsPage.tsx +11 -28
  72. package/src/admin/pages/CollectionsPage.tsx +215 -0
  73. package/src/admin/pages/CreateDialog.tsx +15 -0
  74. package/src/admin/pages/ImportButton.tsx +18 -0
  75. package/src/admin/pages/ImportElementorDialog.tsx +669 -0
  76. package/src/admin/pages/ImportPageLinks.tsx +86 -0
  77. package/src/admin/pages/PageList.tsx +15 -1
  78. package/src/admin/pages/ThemePartList.tsx +15 -1
  79. package/src/admin/pages/section-head.tsx +27 -0
  80. package/src/admin/proposals-api.ts +91 -0
  81. package/src/admin/setup/host-collections.ts +100 -0
  82. package/src/admin/ui.ts +39 -2
  83. package/src/admin/widgets/CanvasField.tsx +202 -0
  84. package/src/admin/widgets/convert-body.ts +54 -0
  85. package/src/admin/widgets/field-fetcher.ts +79 -0
  86. package/src/astro/content-port.ts +14 -1
  87. package/src/astro/index.ts +2 -0
  88. package/src/astro/page-count.ts +77 -0
  89. package/src/astro/resolve-theme.ts +58 -3
  90. package/src/astro/resolve.ts +128 -5
  91. package/src/astro/responsive-images.ts +99 -0
  92. package/src/constants.ts +1 -1
  93. package/src/core/a11y/audit.ts +44 -14
  94. package/src/core/arrange.ts +5 -1
  95. package/src/core/bounded-array.ts +31 -0
  96. package/src/core/canvas-collections.ts +20 -0
  97. package/src/core/clipboard.ts +9 -0
  98. package/src/core/contract.ts +285 -0
  99. package/src/core/css/generate.ts +89 -20
  100. package/src/core/css/trace.ts +18 -9
  101. package/src/core/css-keywords.ts +51 -1
  102. package/src/core/design/cascade.ts +12 -9
  103. package/src/core/design/classes.ts +4 -5
  104. package/src/core/design/devices.ts +13 -13
  105. package/src/core/design/states.ts +5 -3
  106. package/src/core/design/transfer.ts +5 -0
  107. package/src/core/design/variables.ts +17 -4
  108. package/src/core/elements/dynamic-elements.ts +19 -4
  109. package/src/core/elements/index.ts +73 -9
  110. package/src/core/extensions/define.ts +13 -0
  111. package/src/core/extensions/index.ts +41 -0
  112. package/src/core/extensions/namespace.ts +82 -0
  113. package/src/core/extensions/normalize.ts +141 -0
  114. package/src/core/extensions/placeholder.ts +41 -0
  115. package/src/core/extensions/registry.ts +94 -0
  116. package/src/core/extensions/render-ext.ts +118 -0
  117. package/src/core/extensions/safe-nodes.ts +93 -0
  118. package/src/core/extensions/schema.ts +112 -0
  119. package/src/core/extensions/types.ts +159 -0
  120. package/src/core/forms/binding.ts +1 -1
  121. package/src/core/history/diff.ts +1 -1
  122. package/src/core/import/elementor/atomic.ts +1595 -0
  123. package/src/core/import/elementor/classes.ts +127 -0
  124. package/src/core/import/elementor/context.ts +429 -0
  125. package/src/core/import/elementor/counter-steps.ts +72 -0
  126. package/src/core/import/elementor/css.ts +445 -0
  127. package/src/core/import/elementor/html.ts +500 -0
  128. package/src/core/import/elementor/index.ts +949 -0
  129. package/src/core/import/elementor/inline-marks.ts +81 -0
  130. package/src/core/import/elementor/snapshots.ts +48 -0
  131. package/src/core/import/elementor/style.ts +409 -0
  132. package/src/core/import/elementor/values.ts +241 -0
  133. package/src/core/import/elementor/widgets.ts +1897 -0
  134. package/src/core/index.ts +84 -0
  135. package/src/core/json-schema.ts +107 -0
  136. package/src/core/limits.ts +19 -0
  137. package/src/core/migrate/index.ts +6 -1
  138. package/src/core/migrate/v18.ts +222 -0
  139. package/src/core/perf/meter.ts +5 -5
  140. package/src/core/portable-text.ts +127 -0
  141. package/src/core/proposals-safety.ts +102 -0
  142. package/src/core/proposals.ts +357 -0
  143. package/src/core/recipes/index.ts +2 -2
  144. package/src/core/render/extras.ts +3 -3
  145. package/src/core/render/index.ts +140 -20
  146. package/src/core/render/loop.ts +1 -1
  147. package/src/core/render/pagination.ts +20 -1
  148. package/src/core/render/section.ts +4 -4
  149. package/src/core/render/vnode.ts +1 -1
  150. package/src/core/sanitize/css.ts +125 -10
  151. package/src/core/sanitize/motion.ts +116 -0
  152. package/src/core/saved-sections.ts +6 -0
  153. package/src/core/schema/descriptors.ts +3 -1
  154. package/src/core/schema/design.ts +2 -1
  155. package/src/core/schema/layout.ts +87 -14
  156. package/src/core/schema/style.ts +251 -114
  157. package/src/core/text-marks.ts +227 -0
  158. package/src/core/theme/dynamic.ts +9 -4
  159. package/src/core/theme/float.ts +1 -0
  160. package/src/core/theme/pagination.ts +9 -0
  161. package/src/core/theme/popup-rules.ts +17 -1
  162. package/src/core/translatable.ts +34 -0
  163. package/src/core/validate.ts +13 -1
  164. package/src/index.ts +35 -1
  165. package/src/mcp/errors.ts +3 -1
  166. package/src/mcp/ports.ts +67 -0
  167. package/src/mcp/prompts.ts +1 -11
  168. package/src/mcp/proposals.ts +281 -0
  169. package/src/mcp/read.ts +10 -9
  170. package/src/mcp/tools.ts +71 -3
  171. package/src/mcp/write.ts +66 -11
  172. package/src/server/agent-settings.ts +21 -2
  173. package/src/server/hooks.ts +81 -0
  174. package/src/server/mcp-routes.ts +15 -0
  175. package/src/server/plugin.ts +53 -5
  176. package/src/server/presence.ts +78 -0
  177. package/src/server/proposals.ts +261 -0
  178. package/src/server/requests.ts +196 -0
  179. package/src/server/tools-served.ts +45 -0
@@ -0,0 +1,1595 @@
1
+ /**
2
+ * Elementor 4 "atomic" elements (W-945): e-flexbox, e-div-block, e-heading, e-paragraph,
3
+ * e-button, e-image, e-svg, e-form…, e-accordion…, e-tabs…. Their styles are CSS properties
4
+ * with typed values (`{ $$type, value }`) in classes, each class a list of variants by
5
+ * breakpoint and state. A template export carries the global classes and variables it uses
6
+ * (`global_classes`, `global_variables`); their styles are inlined on each element, so an
7
+ * import never rewrites the site's own design system.
8
+ */
9
+ import {
10
+ ALIGN_ITEMS,
11
+ BORDER_STYLES,
12
+ FLEX_DIRECTIONS,
13
+ FLEX_WRAPS,
14
+ JUSTIFY_CONTENT,
15
+ LENGTH_UNITS,
16
+ OBJECT_FITS,
17
+ OVERFLOWS,
18
+ POSITIONS,
19
+ TEXT_ALIGNS,
20
+ TEXT_DECORATIONS,
21
+ TEXT_TRANSFORMS,
22
+ } from "../../css-keywords.ts";
23
+ import { FIELD_NAME_PATTERN, type TextMark } from "../../schema/layout.ts";
24
+ import { sanitizeHref } from "../../sanitize/href.ts";
25
+ import { sanitizeMediaUrl } from "../../sanitize/media-url.ts";
26
+ import { type ImportContext, type ImportedClass, svgFileId } from "./context.ts";
27
+ import { combineLayers, inlineOver, type Layers, STATE_NAMES } from "./classes.ts";
28
+ import { declarations, decodeRawCss, finishBorders } from "./css.ts";
29
+ import { cleanText, decodeEntities, embedVideoUrl, inlineMarks, splitLong } from "./html.ts";
30
+ import type { Style } from "./style.ts";
31
+ import {
32
+ altFromUrl,
33
+ changedKeys,
34
+ color,
35
+ fontWeight,
36
+ isEmptyStyle,
37
+ isRecord,
38
+ type Settings,
39
+ str,
40
+ } from "./values.ts";
41
+ import type { AtomicSnapshots, ClassDef, Value, ClassVariant } from "./snapshots.ts";
42
+ import { type Env, type N, node } from "./widgets.ts";
43
+
44
+ /** `{ $$type, value }` → value; plain values pass through. */
45
+ const un = (v: unknown): unknown => (isRecord(v) && "$$type" in v ? (v as Value).value : v);
46
+ const typeOf = (v: unknown) =>
47
+ isRecord(v) && typeof v["$$type"] === "string" ? (v["$$type"] as string) : undefined;
48
+
49
+ const UNITS = new Set<string>(LENGTH_UNITS);
50
+ type Len = { value: number; unit: string };
51
+
52
+ /**
53
+ * A size. Fluid Elementor values `max(A, min(B, …))` become B (the large-screen value) with A
54
+ * offered for phones; a bare number with the custom unit is returned as a number.
55
+ */
56
+ function size(
57
+ v: unknown,
58
+ opts: { negative?: boolean } = {},
59
+ ): { len?: Len | "auto"; small?: Len; number?: number; fluid?: boolean } {
60
+ const raw = un(v);
61
+ if (!isRecord(raw)) return {};
62
+ const unit = str(raw["unit"]) ?? "px";
63
+ const amount = raw["size"];
64
+ if (unit === "auto") return { len: "auto" };
65
+ if (unit === "custom") {
66
+ const text = str(amount)?.trim() ?? "";
67
+ if (/^-?\d+(?:\.\d+)?$/.test(text)) return { number: Number(text) };
68
+ const plainLen = cssLen(text, opts.negative);
69
+ if (plainLen) return { len: plainLen };
70
+ const fluid =
71
+ /^max\(\s*([^,]+?)\s*,\s*min\(\s*([^,]+?)\s*,/.exec(text) ??
72
+ /^clamp\(\s*([^,]+?)\s*,[^,]+,\s*([^)]+?)\s*\)$/.exec(text);
73
+ if (fluid) {
74
+ const small = cssLen(fluid[1] ?? "", opts.negative);
75
+ const large = cssLen(fluid[2] ?? "", opts.negative);
76
+ if (large) return { len: large, ...(small ? { small } : {}), fluid: true };
77
+ }
78
+ return { fluid: true };
79
+ }
80
+ const n =
81
+ typeof amount === "number"
82
+ ? amount
83
+ : /^-?\d+(?:\.\d+)?$/.test(str(amount) ?? "")
84
+ ? Number(amount)
85
+ : undefined;
86
+ if (n === undefined || !UNITS.has(unit) || Math.abs(n) > 10_000 || (!opts.negative && n < 0))
87
+ return {};
88
+ return { len: { value: n, unit } };
89
+ }
90
+
91
+ function cssLen(text: string, negative = false): Len | undefined {
92
+ const m = /^(-?\d+(?:\.\d+)?)(px|rem|em|%|vw|vh|ch)$/.exec(text.trim());
93
+ if (!m) return undefined;
94
+ const value = Number(m[1]);
95
+ if ((!negative && value < 0) || Math.abs(value) > 10_000) return undefined;
96
+ return { value, unit: m[2] ?? "px" };
97
+ }
98
+
99
+ const SIDES: Record<string, string> = {
100
+ "block-start": "Top",
101
+ "inline-end": "Right",
102
+ "block-end": "Bottom",
103
+ "inline-start": "Left",
104
+ };
105
+ const CORNERS: Record<string, string> = {
106
+ "start-start": "borderTopLeftRadius",
107
+ "start-end": "borderTopRightRadius",
108
+ "end-end": "borderBottomRightRadius",
109
+ "end-start": "borderBottomLeftRadius",
110
+ };
111
+ const pick = (list: readonly string[], v: unknown) => {
112
+ const s = str(un(v));
113
+ return s && list.includes(s) ? s : undefined;
114
+ };
115
+
116
+ /** What one variant's props become: base style, phone-only values from fluid sizes, and notes. */
117
+ type Converted = {
118
+ style: Style;
119
+ phone: Style;
120
+ /** Applies on tablet and phone (a capped wrapper's side gutters). */
121
+ narrow?: Style;
122
+ display?: string;
123
+ columns?: number;
124
+ tracks?: string[];
125
+ /** `grid-column: 1 / -1`: spans every column of the parent grid. */
126
+ fullRow?: boolean;
127
+ unsupported: string[];
128
+ };
129
+
130
+ function colorOf(v: unknown, snap: AtomicSnapshots): string | undefined {
131
+ if (typeOf(v) === "global-color-variable") {
132
+ const variable = snap.variables.get(str(un(v)) ?? "");
133
+ return color(isRecord(variable?.value) ? un(variable.value) : variable?.value);
134
+ }
135
+ return color(un(v));
136
+ }
137
+
138
+ /** Top-level tokens of a track list (commas and spaces inside parentheses stay put). */
139
+ function topLevel(text: string, separator: RegExp): string[] {
140
+ const out: string[] = [];
141
+ let depth = 0;
142
+ let current = "";
143
+ for (const ch of text) {
144
+ if (ch === "(") depth++;
145
+ if (ch === ")") depth = Math.max(0, depth - 1);
146
+ if (depth === 0 && separator.test(ch)) {
147
+ if (current.trim()) out.push(current.trim());
148
+ current = "";
149
+ } else current += ch;
150
+ }
151
+ if (current.trim()) out.push(current.trim());
152
+ return out;
153
+ }
154
+
155
+ const EMVB_TRACK =
156
+ /^(?:1fr|2fr|3fr|auto|min-content|max-content|0|\d+(?:\.\d+)?(?:px|rem|em|%|vw|vh|ch))$/;
157
+
158
+ /** One CSS track → an EmVB track (`minmax` takes its larger side, fractions round to 1–3fr). */
159
+ function emvbTrack(track: string): string | undefined {
160
+ const minmax = /^minmax\(\s*([^,]+?)\s*,\s*(.+?)\s*\)$/.exec(track);
161
+ const value = minmax ? (minmax[2] ?? "") : track;
162
+ const fr = /^(\d*\.?\d+)fr$/.exec(value);
163
+ if (fr) return `${Math.min(3, Math.max(1, Math.round(Number(fr[1]))))}fr`;
164
+ return EMVB_TRACK.test(value) ? value : undefined;
165
+ }
166
+
167
+ /** `grid-template-columns` → a column count and, when the columns differ, EmVB tracks. */
168
+ function gridTracks(template: string): { count: number; tracks?: string[] } | undefined {
169
+ const tracks: string[] = [];
170
+ for (const token of topLevel(template.trim(), /\s/)) {
171
+ const repeat = /^repeat\(\s*(\d{1,2})\s*,\s*(.+)\)$/.exec(token);
172
+ const times = repeat ? Number(repeat[1]) : 1;
173
+ const inner = repeat ? topLevel(repeat[2] ?? "", /\s/) : [token];
174
+ for (let i = 0; i < times && tracks.length <= 12; i++) {
175
+ for (const one of inner) {
176
+ const mapped = emvbTrack(one);
177
+ if (!mapped) return undefined;
178
+ tracks.push(mapped);
179
+ }
180
+ }
181
+ }
182
+ if (tracks.length === 0 || tracks.length > 12) return undefined;
183
+ const equal =
184
+ tracks.every((t) => t === tracks[0]) && (tracks[0] === "1fr" || tracks.length === 1);
185
+ return equal ? { count: tracks.length } : { count: tracks.length, tracks };
186
+ }
187
+
188
+ /** W-955: style keys that keep a fluid size exactly, as EmVB's `{ fluid: { min, max } }`. */
189
+ const FLUID_KEYS = new Set([
190
+ "fontSize",
191
+ "gap",
192
+ "width",
193
+ "minWidth",
194
+ "maxWidth",
195
+ "height",
196
+ "minHeight",
197
+ "maxHeight",
198
+ "paddingTop",
199
+ "paddingRight",
200
+ "paddingBottom",
201
+ "paddingLeft",
202
+ "marginTop",
203
+ "marginRight",
204
+ "marginBottom",
205
+ "marginLeft",
206
+ ]);
207
+
208
+ const toPx = (l: Len): number | undefined =>
209
+ l.unit === "px" ? l.value : l.unit === "rem" ? l.value * 16 : undefined;
210
+
211
+ /**
212
+ * W-955: `max(A, min(B, …))` or `clamp(A, …, B)` in px or rem as a fluid size from A to B, when
213
+ * the key takes one; otherwise the caller keeps B with A for phones.
214
+ */
215
+ function fluidOf(
216
+ key: string,
217
+ s: { len?: Len | "auto"; small?: Len },
218
+ ): { fluid: { min: number; max: number } } | undefined {
219
+ if (!FLUID_KEYS.has(key) || !s.small || !s.len || s.len === "auto") return undefined;
220
+ const min = toPx(s.small);
221
+ const max = toPx(s.len);
222
+ if (min === undefined || max === undefined || min < 0 || max < 0) return undefined;
223
+ if (min > 10_000 || max > 10_000) return undefined;
224
+ return { fluid: { min: Math.round(min * 100) / 100, max: Math.round(max * 100) / 100 } };
225
+ }
226
+
227
+ /** One variant's props → EmVB style keys. */
228
+ function convert(props: Settings, snap: AtomicSnapshots, ctx: ImportContext): Converted {
229
+ const out: Converted = { style: {}, phone: {}, unsupported: [] };
230
+ const { style, phone } = out;
231
+ const putSize = (key: string, v: unknown, allowAuto = false, negative = false) => {
232
+ const s = size(v, { negative });
233
+ if (s.len === "auto") {
234
+ if (allowAuto) style[key] = "auto";
235
+ return;
236
+ }
237
+ const fluid = fluidOf(key, s);
238
+ if (fluid) {
239
+ style[key] = fluid;
240
+ return;
241
+ }
242
+ if (s.len) style[key] = s.len;
243
+ if (s.small) phone[key] = s.small;
244
+ if (!s.len && s.fluid) out.unsupported.push(key);
245
+ };
246
+ const putBox = (prefix: "padding" | "margin" | "border", v: unknown, suffix = "") => {
247
+ const raw = un(v);
248
+ const sides = isRecord(raw) && !("size" in raw) ? raw : undefined;
249
+ const entries: [string, unknown][] = sides
250
+ ? Object.entries(sides)
251
+ .filter(([k]) => k in SIDES)
252
+ .map(([k, s]) => [SIDES[k] ?? "", s])
253
+ : ["Top", "Right", "Bottom", "Left"].map((side) => [side, v]);
254
+ for (const [side, s] of entries) {
255
+ const sz = size(s, { negative: prefix === "margin" });
256
+ const key = `${prefix}${side}${suffix}`;
257
+ const fluid = fluidOf(key, sz);
258
+ if (fluid) {
259
+ style[key] = fluid;
260
+ continue;
261
+ }
262
+ if (sz.len === "auto") {
263
+ if (prefix === "margin") style[key] = "auto";
264
+ } else if (sz.len) style[key] = sz.len;
265
+ if (sz.small) phone[key] = sz.small;
266
+ }
267
+ };
268
+ for (const [prop, v] of Object.entries(props)) {
269
+ switch (prop) {
270
+ case "color": {
271
+ const c = colorOf(v, snap);
272
+ if (c) style["color"] = c;
273
+ break;
274
+ }
275
+ case "background": {
276
+ const bg = un(v);
277
+ if (!isRecord(bg)) break;
278
+ const c = colorOf(bg["color"], snap);
279
+ if (c) style["backgroundColor"] = c;
280
+ const overlays = un(bg["background-overlay"]);
281
+ if (Array.isArray(overlays) && overlays.length > 0) {
282
+ const kinds = overlays.map((layer) => typeOf(layer));
283
+ const imageAt = kinds.indexOf("background-image-overlay");
284
+ for (const [index, layer] of overlays.entries()) {
285
+ const t = typeOf(layer);
286
+ const body = un(layer);
287
+ if (t === "background-image-overlay" && isRecord(body)) {
288
+ const image = un(body["image"]);
289
+ const src = isRecord(image) ? un(image["src"]) : undefined;
290
+ const url = isRecord(src) ? str(un(src["url"])) : undefined;
291
+ const safe = url ? sanitizeMediaUrl(url) : undefined;
292
+ if (safe && !/[()\\\s"'`]/.test(safe)) {
293
+ ctx.externalImage(safe);
294
+ style["backgroundImage"] = safe;
295
+ const sizeKw = str(un(body["size"]));
296
+ if (sizeKw === "cover" || sizeKw === "contain" || sizeKw === "auto")
297
+ style["backgroundSize"] = sizeKw;
298
+ } else out.unsupported.push("background image");
299
+ } else if (t === "background-color-overlay" && isRecord(body)) {
300
+ const overlay = colorOf(body["color"], snap);
301
+ if (overlay) style["overlay"] = { color: overlay, opacity: 1 };
302
+ } else if (t === "background-gradient-overlay" && isRecord(body)) {
303
+ const stops = (
304
+ Array.isArray(un(body["stops"])) ? (un(body["stops"]) as unknown[]) : []
305
+ )
306
+ .map((stop) => un(stop))
307
+ .filter(isRecord)
308
+ .map((stop) => ({
309
+ color: colorOf(stop["color"], snap),
310
+ at: Number(un(stop["offset"])),
311
+ }))
312
+ .filter(
313
+ (stop): stop is { color: string; at: number } =>
314
+ Boolean(stop.color) && Number.isFinite(stop.at),
315
+ )
316
+ .slice(0, 10)
317
+ .map((stop) => ({
318
+ color: stop.color,
319
+ at: Math.min(100, Math.max(0, Math.round(stop.at))),
320
+ }));
321
+ if (stops.length >= 2) {
322
+ const radial = str(un(body["type"])) === "radial";
323
+ const angle = Number(un(body["angle"]));
324
+ const gradient = {
325
+ type: radial ? "radial" : "linear",
326
+ ...(radial
327
+ ? {}
328
+ : {
329
+ angle: Number.isFinite(angle)
330
+ ? ((Math.round(angle) % 360) + 360) % 360
331
+ : 180,
332
+ }),
333
+ stops,
334
+ };
335
+ // CSS draws the first layer on top: a gradient before the image is a scrim,
336
+ // EmVB's gradient overlay (W-949); after it, the gradient under the image.
337
+ if (imageAt > index) style["overlay"] = { gradient };
338
+ else style["gradient"] = gradient;
339
+ } else out.unsupported.push("background gradient");
340
+ } else {
341
+ out.unsupported.push("background layer");
342
+ }
343
+ }
344
+ }
345
+ break;
346
+ }
347
+ case "display": {
348
+ const d = str(un(v));
349
+ if (d) out.display = d;
350
+ break;
351
+ }
352
+ case "grid-template-columns": {
353
+ const grid = gridTracks(str(un(v)) ?? "");
354
+ if (grid) {
355
+ out.columns = grid.count;
356
+ if (grid.tracks) out.tracks = grid.tracks;
357
+ } else out.unsupported.push("grid-template-columns");
358
+ break;
359
+ }
360
+ case "font-size":
361
+ case "letter-spacing":
362
+ case "min-width":
363
+ case "min-height":
364
+ case "max-width":
365
+ case "max-height":
366
+ putSize(
367
+ {
368
+ "font-size": "fontSize",
369
+ "letter-spacing": "letterSpacing",
370
+ "min-width": "minWidth",
371
+ "min-height": "minHeight",
372
+ "max-width": "maxWidth",
373
+ "max-height": "maxHeight",
374
+ }[prop] ?? prop,
375
+ v,
376
+ false,
377
+ prop === "letter-spacing",
378
+ );
379
+ break;
380
+ case "width": {
381
+ const raw = un(v);
382
+ const textValue =
383
+ isRecord(raw) && raw["unit"] === "custom" ? (str(raw["size"])?.trim() ?? "") : "";
384
+ // Centred wrappers: min(1180px, calc(100% - 48px)) and calc(100% - 32px).
385
+ const capped =
386
+ /^min\(\s*(\d+(?:\.\d+)?)px\s*,\s*calc\(\s*100%\s*-\s*(\d+(?:\.\d+)?)px\s*\)\s*\)$/.exec(
387
+ textValue,
388
+ );
389
+ const gutter = /^calc\(\s*100%\s*-\s*(\d+(?:\.\d+)?)px\s*\)$/.exec(textValue);
390
+ if (capped) {
391
+ const half = { value: Number(capped[2]) / 2, unit: "px" };
392
+ style["width"] = { value: 100, unit: "%" };
393
+ style["maxWidth"] = { value: Number(capped[1]), unit: "px" };
394
+ out.narrow = { width: "auto", marginLeft: half, marginRight: half };
395
+ break;
396
+ }
397
+ if (gutter) {
398
+ const half = { value: Number(gutter[1]) / 2, unit: "px" };
399
+ style["width"] = "auto";
400
+ style["marginLeft"] = half;
401
+ style["marginRight"] = half;
402
+ break;
403
+ }
404
+ putSize(prop, v, true);
405
+ break;
406
+ }
407
+ case "height":
408
+ putSize(prop, v, true);
409
+ break;
410
+ case "line-height": {
411
+ const s = size(v);
412
+ if (s.number !== undefined && s.number >= 0 && s.number <= 100)
413
+ style["lineHeight"] = s.number;
414
+ else if (s.len && s.len !== "auto")
415
+ style["lineHeight"] = s.len.unit === "em" ? s.len.value : s.len;
416
+ if (s.small) phone["lineHeight"] = s.small;
417
+ break;
418
+ }
419
+ case "padding":
420
+ putBox("padding", v);
421
+ break;
422
+ case "margin":
423
+ putBox("margin", v);
424
+ break;
425
+ case "border-width": {
426
+ const raw = un(v);
427
+ if (isRecord(raw) && !("size" in raw)) putBox("border", v, "Width");
428
+ else {
429
+ const s = size(v);
430
+ if (s.len && s.len !== "auto") style["borderWidth"] = s.len;
431
+ }
432
+ break;
433
+ }
434
+ case "border-radius": {
435
+ const raw = un(v);
436
+ if (isRecord(raw) && !("size" in raw)) {
437
+ for (const [corner, key] of Object.entries(CORNERS)) {
438
+ const s = size(raw[corner]);
439
+ if (s.len && s.len !== "auto") style[key] = s.len;
440
+ }
441
+ } else {
442
+ const s = size(v);
443
+ if (s.len && s.len !== "auto") style["borderRadius"] = s.len;
444
+ if (s.small) phone["borderRadius"] = s.small;
445
+ }
446
+ break;
447
+ }
448
+ case "border-color": {
449
+ const c = colorOf(v, snap);
450
+ if (c) style["borderColor"] = c;
451
+ break;
452
+ }
453
+ case "border-style": {
454
+ const s = pick(BORDER_STYLES, v);
455
+ if (s) style["borderStyle"] = s;
456
+ break;
457
+ }
458
+ case "font-family": {
459
+ const name =
460
+ typeOf(v) === "global-font-variable"
461
+ ? str(snap.variables.get(str(un(v)) ?? "")?.value)
462
+ : str(un(v));
463
+ const stack = ctx.useFont(name);
464
+ if (stack) style["fontFamily"] = stack;
465
+ break;
466
+ }
467
+ case "font-weight": {
468
+ const w = fontWeight(un(v));
469
+ if (w !== undefined) style["fontWeight"] = w;
470
+ break;
471
+ }
472
+ case "gap": {
473
+ const raw = un(v);
474
+ const s = isRecord(raw) && "column" in raw ? size(raw["column"]) : size(v);
475
+ const fluid = fluidOf("gap", s);
476
+ if (fluid) {
477
+ style["gap"] = fluid;
478
+ break;
479
+ }
480
+ if (s.len && s.len !== "auto") style["gap"] = s.len;
481
+ if (s.small) phone["gap"] = s.small;
482
+ break;
483
+ }
484
+ case "align-items":
485
+ case "justify-content":
486
+ case "flex-direction":
487
+ case "flex-wrap":
488
+ case "text-transform":
489
+ case "text-align":
490
+ case "text-decoration":
491
+ case "overflow":
492
+ case "object-fit":
493
+ case "position": {
494
+ const lists: Record<string, readonly string[]> = {
495
+ "align-items": ALIGN_ITEMS,
496
+ "justify-content": JUSTIFY_CONTENT,
497
+ "flex-direction": FLEX_DIRECTIONS,
498
+ "flex-wrap": FLEX_WRAPS,
499
+ "text-transform": TEXT_TRANSFORMS,
500
+ "text-align": TEXT_ALIGNS,
501
+ "text-decoration": TEXT_DECORATIONS,
502
+ overflow: OVERFLOWS,
503
+ "object-fit": OBJECT_FITS,
504
+ position: POSITIONS,
505
+ };
506
+ const raw = str(un(v));
507
+ const mapped = raw === "start" ? "flex-start" : raw === "end" ? "flex-end" : raw;
508
+ const value =
509
+ pick(lists[prop] ?? [], mapped) ??
510
+ (prop === "text-align" && (raw === "start" || raw === "end")
511
+ ? raw === "start"
512
+ ? "left"
513
+ : "right"
514
+ : undefined);
515
+ const key = prop.replace(/-([a-z])/g, (_m, c: string) => c.toUpperCase());
516
+ if (value) style[key] = value;
517
+ else out.unsupported.push(`${prop}: ${raw ?? "?"}`);
518
+ break;
519
+ }
520
+ case "inset-block-start":
521
+ case "inset-inline-end":
522
+ case "inset-block-end":
523
+ case "inset-inline-start": {
524
+ const key = {
525
+ "inset-block-start": "top",
526
+ "inset-inline-end": "right",
527
+ "inset-block-end": "bottom",
528
+ "inset-inline-start": "left",
529
+ }[prop];
530
+ if (key) putSize(key, v, true, true);
531
+ break;
532
+ }
533
+ case "z-index": {
534
+ const n = Number(un(v));
535
+ if (Number.isInteger(n) && Math.abs(n) <= 9999) style["zIndex"] = n;
536
+ break;
537
+ }
538
+ case "opacity": {
539
+ const s = size(v);
540
+ if (s.len && s.len !== "auto")
541
+ style["opacity"] = Math.min(
542
+ 1,
543
+ Math.max(0, s.len.unit === "%" ? s.len.value / 100 : s.len.value),
544
+ );
545
+ else if (s.number !== undefined) style["opacity"] = Math.min(1, Math.max(0, s.number));
546
+ break;
547
+ }
548
+ case "aspect-ratio": {
549
+ const m = /^\s*(\d{1,4})\s*\/\s*(\d{1,4})\s*$/.exec(str(un(v)) ?? "");
550
+ if (m && Number(m[1]) > 0 && Number(m[2]) > 0) style["aspectRatio"] = `${m[1]}/${m[2]}`;
551
+ break;
552
+ }
553
+ case "cursor": {
554
+ const c = str(un(v));
555
+ if (c === "pointer" || c === "default") style["cursor"] = c;
556
+ break;
557
+ }
558
+ case "box-shadow": {
559
+ const list = un(v);
560
+ const first = Array.isArray(list) ? un(list[0]) : undefined;
561
+ if (!isRecord(first)) break;
562
+ const n = (key: string, lo: number, hi: number) => {
563
+ const s = size(first[key], { negative: true });
564
+ return s.len && s.len !== "auto" ? Math.min(hi, Math.max(lo, s.len.value)) : 0;
565
+ };
566
+ const c = colorOf(first["color"], snap);
567
+ style["boxShadow"] = {
568
+ x: n("hOffset", -1000, 1000),
569
+ y: n("vOffset", -1000, 1000),
570
+ blur: n("blur", 0, 1000),
571
+ spread: n("spread", -1000, 1000),
572
+ ...(c ? { color: c } : {}),
573
+ ...(str(un(first["position"])) === "inset" ? { inset: true } : {}),
574
+ };
575
+ break;
576
+ }
577
+ case "transition": {
578
+ const list = un(v);
579
+ const items = (Array.isArray(list) ? list : []).map((item) => un(item)).filter(isRecord);
580
+ const targets = new Set<string>();
581
+ let ms = 0;
582
+ for (const item of items) {
583
+ const selection = un(item["selection"]);
584
+ const key = isRecord(selection) ? str(un(selection["key"])) : undefined;
585
+ const amount = un(item["size"]);
586
+ if (isRecord(amount)) {
587
+ const n = Number(amount["size"]);
588
+ const unitName = str(amount["unit"]);
589
+ if (Number.isFinite(n)) ms = Math.max(ms, unitName === "s" ? n * 1000 : n);
590
+ }
591
+ const mapped =
592
+ key === "opacity"
593
+ ? "opacity"
594
+ : key === "box-shadow"
595
+ ? "shadow"
596
+ : key === "filter"
597
+ ? "filter"
598
+ : key && /color/.test(key)
599
+ ? "colors"
600
+ : "all";
601
+ targets.add(mapped);
602
+ }
603
+ if (items.length > 0) {
604
+ style["motion"] = {
605
+ transition: {
606
+ property: targets.size === 1 ? [...targets][0] : "all",
607
+ duration: Math.min(2000, Math.max(0, Math.round(ms))),
608
+ easing: "ease",
609
+ },
610
+ };
611
+ }
612
+ break;
613
+ }
614
+ case "grid-column": {
615
+ const span = str(un(v))?.replace(/\s+/g, "");
616
+ if (span === "1/-1" || span === "span-1" || span === "1/span-1") out.fullRow = true;
617
+ else out.unsupported.push(`grid-column: ${span ?? "?"}`);
618
+ break;
619
+ }
620
+ case "flex": {
621
+ // W-954: `{ flexGrow?, flexShrink?, flexBasis? }`.
622
+ const raw = un(v);
623
+ if (!isRecord(raw)) break;
624
+ const grow = Number(un(raw["flexGrow"]));
625
+ const shrink = Number(un(raw["flexShrink"]));
626
+ if (raw["flexGrow"] !== undefined && Number.isFinite(grow) && grow >= 0 && grow <= 100)
627
+ style["flexGrow"] = grow;
628
+ if (
629
+ raw["flexShrink"] !== undefined &&
630
+ Number.isFinite(shrink) &&
631
+ shrink >= 0 &&
632
+ shrink <= 100
633
+ )
634
+ style["flexShrink"] = shrink;
635
+ if (raw["flexBasis"] !== undefined) {
636
+ const basis = size(raw["flexBasis"]);
637
+ if (basis.len) style["flexBasis"] = basis.len;
638
+ }
639
+ break;
640
+ }
641
+ case "align-self":
642
+ case "order": {
643
+ const { style: mapped } = declarations(`${prop}: ${str(un(v)) ?? String(un(v))}`);
644
+ if (Object.keys(mapped).length > 0) Object.assign(style, mapped);
645
+ else out.unsupported.push(prop);
646
+ break;
647
+ }
648
+ case "transform": {
649
+ // W-953: move, scale and rotate; skew and 3D parts are left out.
650
+ const fns = un(isRecord(un(v)) ? (un(v) as Settings)["transform-functions"] : undefined);
651
+ const out3: Record<string, number> = {};
652
+ for (const fn of Array.isArray(fns) ? fns : []) {
653
+ const kind = typeOf(fn);
654
+ const body = un(fn);
655
+ if (!isRecord(body)) continue;
656
+ if (kind === "transform-move") {
657
+ for (const axis of ["x", "y"] as const) {
658
+ const sz = size(body[axis], { negative: true });
659
+ if (sz.len && sz.len !== "auto" && sz.len.unit === "px" && sz.len.value !== 0) {
660
+ out3[axis] = Math.round(Math.min(2000, Math.max(-2000, sz.len.value)));
661
+ }
662
+ }
663
+ } else if (kind === "transform-scale") {
664
+ const x = Number(un(body["x"]));
665
+ if (Number.isFinite(x) && x !== 1)
666
+ out3["scale"] = Math.round(Math.min(4, Math.max(0.1, x)) * 100);
667
+ } else if (kind === "transform-rotate") {
668
+ const z = un(body["z"]);
669
+ const amount = isRecord(z) ? Number(z["size"]) : Number.NaN;
670
+ const unit = isRecord(z) ? str(z["unit"]) : undefined;
671
+ const perUnit: Record<string, number> = {
672
+ deg: 1,
673
+ turn: 360,
674
+ rad: 180 / Math.PI,
675
+ grad: 0.9,
676
+ };
677
+ const deg =
678
+ Number.isFinite(amount) && unit && perUnit[unit]
679
+ ? amount * (perUnit[unit] ?? 1)
680
+ : undefined;
681
+ if (deg !== undefined && deg !== 0)
682
+ out3["rotate"] = Math.round(Math.min(360, Math.max(-360, deg)));
683
+ } else out.unsupported.push(kind ?? "transform");
684
+ }
685
+ if (Object.keys(out3).length > 0) style["transform"] = out3;
686
+ break;
687
+ }
688
+ case "font-style":
689
+ case "white-space":
690
+ case "overflow-wrap":
691
+ case "object-position":
692
+ case "overflow-x":
693
+ case "overflow-y": {
694
+ const raw = str(un(v));
695
+ const { style: mapped } = declarations(`${prop}: ${raw ?? ""}`);
696
+ if (Object.keys(mapped).length > 0) Object.assign(style, mapped);
697
+ else out.unsupported.push(`${prop}: ${raw ?? "?"}`);
698
+ break;
699
+ }
700
+ case "backdrop-filter": {
701
+ const list = un(v);
702
+ const blur = (Array.isArray(list) ? list : [])
703
+ .map((f) => un(f))
704
+ .filter(isRecord)
705
+ .find((f) => str(un(f["func"])) === "blur");
706
+ // `{ func: "blur", args: { $$type: "blur", value: { size: <size> } } }`
707
+ const args = blur ? un(blur["args"]) : undefined;
708
+ const radius = isRecord(args) ? size(args["size"]) : {};
709
+ const px =
710
+ radius.len && radius.len !== "auto" && radius.len.unit === "px"
711
+ ? radius.len.value
712
+ : undefined;
713
+ if (px !== undefined && px >= 0 && px <= 100) style["backdropFilter"] = { blur: px };
714
+ else out.unsupported.push("backdrop-filter");
715
+ break;
716
+ }
717
+ default:
718
+ out.unsupported.push(prop);
719
+ }
720
+ }
721
+ return out;
722
+ }
723
+
724
+ const DEVICE_OF: Record<string, "desktop" | "laptop" | "tablet" | "mobile"> = {
725
+ desktop: "desktop",
726
+ widescreen: "desktop",
727
+ // W-956: EmVB has a Laptop device (up to 1366 px), like Elementor's.
728
+ laptop: "laptop",
729
+ tablet_extra: "tablet",
730
+ tablet: "tablet",
731
+ mobile_extra: "mobile",
732
+ mobile: "mobile",
733
+ };
734
+ /** Elementor's desktop-first cascade, narrowest last: later entries win. */
735
+ const BREAKPOINT_ORDER = [
736
+ "widescreen",
737
+ "desktop",
738
+ "laptop",
739
+ "tablet_extra",
740
+ "tablet",
741
+ "mobile_extra",
742
+ "mobile",
743
+ ];
744
+
745
+ type AtomicStyle = {
746
+ style: Style;
747
+ devices: { laptop?: Style; tablet?: Style; mobile?: Style };
748
+ states: { hover?: Style; focus?: Style; active?: Style };
749
+ display: { desktop?: string; laptop?: string; tablet?: string; mobile?: string };
750
+ columns: { desktop?: number; tablet?: number; mobile?: number };
751
+ tracks: { desktop?: string[]; tablet?: string[]; mobile?: string[] };
752
+ fullRow: boolean;
753
+ };
754
+
755
+ /**
756
+ * W-958: with "Add Elementor's classes" on, an element points at its Elementor global classes as
757
+ * EmVB classes and keeps inline only what makes it look exactly as before (see `inlineOver`).
758
+ * When the classes can't give that look (a class sets something the element doesn't have, two
759
+ * classes disagree, or a class isn't valid), the element keeps its full inline style.
760
+ */
761
+ function useClasses(n: N, el: Settings, snap: AtomicSnapshots, ctx: ImportContext): N {
762
+ if (!ctx.useClasses) return n;
763
+ const ids = un(settingsOf(el)["classes"]);
764
+ const globals = (Array.isArray(ids) ? ids : []).filter(
765
+ (id): id is string => typeof id === "string" && snap.classes.has(id),
766
+ );
767
+ if (globals.length === 0) return n;
768
+ const made = globals.map((id) =>
769
+ ctx.importedClass(id, () => classLook(id, snap, ctx), snap.classes.get(id)?.label),
770
+ );
771
+ if (made.some((l) => l === undefined)) return n;
772
+ // A class whose look is only visibility or grid placement carries nothing as an EmVB class.
773
+ const layers = made.filter((c) =>
774
+ Object.values((c as ImportedClass).layers).some((layer) => !isEmptyStyle(layer)),
775
+ );
776
+ if (layers.length === 0) return n;
777
+ const combined = combineLayers(layers.map((l) => (l as ImportedClass).layers));
778
+ if (!combined) return n;
779
+ const states = n["states"] as Record<string, Style> | undefined;
780
+ const want: Layers = {
781
+ desktop: (n["style"] as Style | undefined) ?? {},
782
+ laptop: (n["devices"] as Record<string, Style> | undefined)?.["laptop"] ?? {},
783
+ tablet: (n["devices"] as Record<string, Style> | undefined)?.["tablet"] ?? {},
784
+ mobile: (n["devices"] as Record<string, Style> | undefined)?.["mobile"] ?? {},
785
+ hover: states?.["hover"] ?? {},
786
+ focus: states?.["focus"] ?? {},
787
+ active: states?.["active"] ?? {},
788
+ };
789
+ const inline = inlineOver(want, combined);
790
+ if (!inline) return n;
791
+ delete n["style"];
792
+ delete n["devices"];
793
+ delete n["states"];
794
+ if (!isEmptyStyle(inline.desktop)) n["style"] = inline.desktop;
795
+ const devices: Record<string, Style> = {};
796
+ if (!isEmptyStyle(inline.laptop)) devices["laptop"] = inline.laptop;
797
+ if (!isEmptyStyle(inline.tablet)) devices["tablet"] = inline.tablet;
798
+ if (!isEmptyStyle(inline.mobile)) devices["mobile"] = inline.mobile;
799
+ if (Object.keys(devices).length > 0) n["devices"] = devices;
800
+ const stateStyles: Record<string, Style> = {};
801
+ for (const s of STATE_NAMES) if (!isEmptyStyle(inline[s])) stateStyles[s] = inline[s];
802
+ if (Object.keys(stateStyles).length > 0) n["states"] = stateStyles;
803
+ n["classes"] = layers.map((l) => (l as ImportedClass).id);
804
+ return n;
805
+ }
806
+
807
+ /** One Elementor global class's own look, as EmVB layers. */
808
+ function classLook(id: string, snap: AtomicSnapshots, ctx: ImportContext): Layers {
809
+ const def = snap.classes.get(id) as ClassDef;
810
+ const look = atomicStyle("", {}, snap, ctx, id, true, [def]);
811
+ return {
812
+ desktop: look.style,
813
+ laptop: look.devices.laptop ?? {},
814
+ tablet: look.devices.tablet ?? {},
815
+ mobile: look.devices.mobile ?? {},
816
+ hover: look.states.hover ?? {},
817
+ focus: look.states.focus ?? {},
818
+ active: look.states.active ?? {},
819
+ };
820
+ }
821
+
822
+ /**
823
+ * W-950: emphasised and bold words take what the site's CSS gives them inside the element's
824
+ * classes (the gold, upright word of a hero title).
825
+ */
826
+ function styleWords(
827
+ marks: TextMark[],
828
+ el: Settings,
829
+ snap: AtomicSnapshots,
830
+ ctx: ImportContext,
831
+ ): TextMark[] {
832
+ if (marks.length === 0 || ctx.wordRules.size === 0) return marks;
833
+ const ids = un(settingsOf(el)["classes"]);
834
+ const names = (Array.isArray(ids) ? ids : []).flatMap((id) =>
835
+ typeof id === "string" ? [id, snap.classes.get(id)?.label ?? ""] : [],
836
+ );
837
+ const ruleFor = (tag: "em" | "strong") =>
838
+ names.map((name) => ctx.wordRules.get(`${name} ${tag}`)).findLast(Boolean);
839
+ const em = ruleFor("em");
840
+ const strong = ruleFor("strong");
841
+ if (!em && !strong) return marks;
842
+ return marks.flatMap((mark) => {
843
+ const next: TextMark = { ...mark };
844
+ for (const [rule, on] of [
845
+ [em, mark.italic],
846
+ [strong, mark.bold],
847
+ ] as const) {
848
+ if (!rule || !on) continue;
849
+ if (rule.color && next.color === undefined) next.color = rule.color;
850
+ if (rule.italic === false) delete next.italic;
851
+ if (rule.italic === true) next.italic = true;
852
+ if (rule.bold === false) delete next.bold;
853
+ if (rule.bold === true) next.bold = true;
854
+ }
855
+ return next.bold || next.italic || next.color || next.href ? [next] : [];
856
+ });
857
+ }
858
+
859
+ /** Base styles Elementor gives each atomic element before any class. */
860
+ const BASE: Record<string, Settings> = {
861
+ "e-flexbox": {
862
+ display: "flex",
863
+ "flex-direction": "row",
864
+ padding: { $$type: "size", value: { size: 10, unit: "px" } },
865
+ },
866
+ "e-div-block": {
867
+ display: "block",
868
+ padding: { $$type: "size", value: { size: 10, unit: "px" } },
869
+ "min-width": { $$type: "size", value: { size: 30, unit: "px" } },
870
+ },
871
+ "e-button": {
872
+ background: { $$type: "background", value: { color: { $$type: "color", value: "#375EFB" } } },
873
+ color: { $$type: "color", value: "#ffffff" },
874
+ padding: {
875
+ $$type: "dimensions",
876
+ value: {
877
+ "block-start": { $$type: "size", value: { size: 12, unit: "px" } },
878
+ "inline-end": { $$type: "size", value: { size: 24, unit: "px" } },
879
+ "block-end": { $$type: "size", value: { size: 12, unit: "px" } },
880
+ "inline-start": { $$type: "size", value: { size: 24, unit: "px" } },
881
+ },
882
+ },
883
+ "border-radius": { $$type: "size", value: { size: 2, unit: "px" } },
884
+ "border-style": { $$type: "string", value: "none" },
885
+ "text-align": { $$type: "string", value: "center" },
886
+ },
887
+ "e-svg": {
888
+ width: { $$type: "size", value: { size: 65, unit: "px" } },
889
+ height: { $$type: "size", value: { size: 65, unit: "px" } },
890
+ },
891
+ };
892
+
893
+ /** The classes an atomic element uses, in the order their styles apply (last wins). */
894
+ function classesOf(el: Settings, snap: AtomicSnapshots): ClassDef[] {
895
+ const settings = isRecord(el["settings"]) ? el["settings"] : {};
896
+ const ids = un(settings["classes"]);
897
+ const local = isRecord(el["styles"]) ? el["styles"] : {};
898
+ const list = Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
899
+ const globals = list
900
+ .filter((id) => snap.classes.has(id))
901
+ // Elementor: a class higher in the Class Manager order wins, so it is applied last.
902
+ .toSorted((a, b) => (snap.rank.get(b) ?? 0) - (snap.rank.get(a) ?? 0))
903
+ .map((id) => snap.classes.get(id) as ClassDef);
904
+ const locals = list.filter((id) => isRecord(local[id])).map((id) => local[id] as ClassDef);
905
+ return [...globals, ...locals];
906
+ }
907
+
908
+ /** Every class and base style of an element, folded into EmVB style, devices and states. */
909
+ function atomicStyle(
910
+ type: string,
911
+ el: Settings,
912
+ snap: AtomicSnapshots,
913
+ ctx: ImportContext,
914
+ name: string,
915
+ /** Read again for one value: don't repeat the notes. */
916
+ quiet = false,
917
+ /** W-958: only these classes, without Elementor's base styles (a class's own look). */
918
+ only?: readonly ClassDef[],
919
+ ): AtomicStyle {
920
+ const layers: Record<"desktop" | "laptop" | "tablet" | "mobile", Style> = {
921
+ desktop: {},
922
+ laptop: {},
923
+ tablet: {},
924
+ mobile: {},
925
+ };
926
+ const phoneFromFluid: Style = {};
927
+ const narrowFromWidth: Style = {};
928
+ const states: AtomicStyle["states"] = {};
929
+ const display: AtomicStyle["display"] = {};
930
+ const columns: AtomicStyle["columns"] = {};
931
+ const tracks: AtomicStyle["tracks"] = {};
932
+ let fullRow = false;
933
+ const unsupported = new Set<string>();
934
+ const variants: ClassVariant[] = [];
935
+ if (BASE[type] && !only)
936
+ variants.push({ meta: { breakpoint: "desktop", state: null }, props: BASE[type] });
937
+ for (const def of only ?? classesOf(el, snap)) {
938
+ const own = Array.isArray(def.variants) ? def.variants : [];
939
+ // Within a class, wider breakpoints first so narrower ones override them.
940
+ variants.push(
941
+ ...own.toSorted(
942
+ (a, b) =>
943
+ BREAKPOINT_ORDER.indexOf(a.meta?.breakpoint ?? "desktop") -
944
+ BREAKPOINT_ORDER.indexOf(b.meta?.breakpoint ?? "desktop"),
945
+ ),
946
+ );
947
+ }
948
+ let folded = false;
949
+ for (const variant of variants) {
950
+ const breakpoint = variant.meta?.breakpoint ?? "desktop";
951
+ const state = variant.meta?.state ?? null;
952
+ const device = DEVICE_OF[breakpoint];
953
+ if (!device) {
954
+ unsupported.add(`${breakpoint} breakpoint`);
955
+ continue;
956
+ }
957
+ if (breakpoint !== device) folded = true;
958
+ const converted = convert(isRecord(variant.props) ? variant.props : {}, snap, ctx);
959
+ if (variant.custom_css) {
960
+ const raw = isRecord(variant.custom_css) ? variant.custom_css["raw"] : undefined;
961
+ const css = decodeRawCss(raw);
962
+ if (css === undefined) unsupported.add("custom CSS");
963
+ else {
964
+ const extra = declarations(css);
965
+ Object.assign(converted.style, extra.style);
966
+ for (const prop of extra.unmapped) unsupported.add(prop);
967
+ }
968
+ }
969
+ for (const u of converted.unsupported) unsupported.add(u);
970
+ if (state) {
971
+ const key = state === "focus-visible" ? "focus" : state;
972
+ if ((key === "hover" || key === "focus" || key === "active") && device === "desktop") {
973
+ states[key] = { ...states[key], ...converted.style };
974
+ } else unsupported.add(`${state} state`);
975
+ continue;
976
+ }
977
+ // A fluid value set for phones uses its small bound there (narrow phones get it in Elementor).
978
+ Object.assign(layers[device], converted.style, device === "mobile" ? converted.phone : {});
979
+ if (device === "desktop") Object.assign(phoneFromFluid, converted.phone);
980
+ if (converted.narrow && device === "desktop") {
981
+ Object.assign(narrowFromWidth, converted.narrow);
982
+ }
983
+ if (converted.display) display[device] = converted.display;
984
+ if (converted.fullRow) fullRow = true;
985
+ if (converted.columns && device === "laptop") {
986
+ // EmVB's grid columns have no laptop value: laptops keep the desktop columns.
987
+ unsupported.add("grid columns for laptops (laptops use the desktop columns)");
988
+ } else if (converted.columns && device !== "laptop") {
989
+ columns[device] = converted.columns;
990
+ if (converted.tracks) tracks[device] = converted.tracks;
991
+ else delete tracks[device];
992
+ }
993
+ }
994
+ if (folded && !quiet)
995
+ ctx.note(
996
+ "approximated",
997
+ "Breakpoints",
998
+ "Extra breakpoints were folded into Tablet and Mobile, and Widescreen into Desktop.",
999
+ );
1000
+ if (Object.keys(phoneFromFluid).length > 0 && !quiet) {
1001
+ ctx.note(
1002
+ "approximated",
1003
+ "Fluid sizes",
1004
+ "Fluid sizes use their large value on desktop and their small value on phones.",
1005
+ );
1006
+ }
1007
+ for (const what of quiet ? [] : unsupported) {
1008
+ ctx.note("approximated", name, `Left out a style EmVB has no setting for: ${what}.`);
1009
+ }
1010
+ for (const layer of [layers.desktop, layers.laptop, layers.tablet, layers.mobile])
1011
+ finishBorders(layer);
1012
+ const mobile = { ...narrowFromWidth, ...phoneFromFluid, ...layers.mobile };
1013
+ const laptop = changedKeys(layers.desktop, layers.laptop);
1014
+ const wide = { ...layers.desktop, ...laptop };
1015
+ const tablet = changedKeys(wide, { ...narrowFromWidth, ...layers.tablet });
1016
+ const devices: AtomicStyle["devices"] = {};
1017
+ if (!isEmptyStyle(laptop)) devices.laptop = laptop;
1018
+ if (!isEmptyStyle(tablet)) devices.tablet = tablet;
1019
+ const mobileChanged = changedKeys({ ...wide, ...layers.tablet }, mobile);
1020
+ if (!isEmptyStyle(mobileChanged)) devices.mobile = mobileChanged;
1021
+ const statesOut: AtomicStyle["states"] = {};
1022
+ for (const [k, v] of Object.entries(states))
1023
+ if (!isEmptyStyle(v)) statesOut[k as keyof AtomicStyle["states"]] = v;
1024
+ // A narrower device with only a count must not inherit a wider device's custom tracks.
1025
+ let wider = tracks.desktop;
1026
+ for (const device of ["tablet", "mobile"] as const) {
1027
+ const count = columns[device];
1028
+ if (count && !tracks[device] && wider)
1029
+ tracks[device] = Array.from({ length: count }, () => "1fr");
1030
+ wider = tracks[device] ?? wider;
1031
+ }
1032
+ return { style: layers.desktop, devices, states: statesOut, display, columns, tracks, fullRow };
1033
+ }
1034
+
1035
+ // ---------------------------------------------------------------------------------------------
1036
+ // Elements
1037
+
1038
+ const settingsOf = (el: Settings): Settings => (isRecord(el["settings"]) ? el["settings"] : {});
1039
+ const text = (v: unknown) =>
1040
+ cleanText(
1041
+ decodeEntities((str(un(v)) ?? "").replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]*>/g, "")),
1042
+ true,
1043
+ );
1044
+
1045
+ /** An atomic link: a URL, or a page or dynamic link that can't be resolved here (noted). */
1046
+ function linkOf(v: unknown, ctx: ImportContext, name: string): { href?: string; newTab?: boolean } {
1047
+ const raw = un(v);
1048
+ if (!isRecord(raw)) return {};
1049
+ const destination = raw["destination"];
1050
+ const kind = typeOf(destination);
1051
+ const newTab = un(raw["isTargetBlank"]) === true;
1052
+ if (kind === "url" || typeof destination === "string") {
1053
+ const safe = ctx.href(str(un(destination)) ?? "");
1054
+ return safe ? { href: safe, ...(newTab ? { newTab: true } : {}) } : {};
1055
+ }
1056
+ if (kind === "query") {
1057
+ // W-958: a link to a WordPress page by its id; the import dialog asks where it goes.
1058
+ const target = un(destination);
1059
+ const id = isRecord(target) ? un(target["id"]) : undefined;
1060
+ if (typeof id === "number" && Number.isInteger(id) && id > 0) {
1061
+ const safe = ctx.pageLink(id);
1062
+ if (safe) return { href: safe, ...(newTab ? { newTab: true } : {}) };
1063
+ ctx.note(
1064
+ "skipped",
1065
+ "Links",
1066
+ "Links to WordPress pages were left out; choose where each page goes under Page links in the import dialog.",
1067
+ );
1068
+ return {};
1069
+ }
1070
+ }
1071
+ if (kind)
1072
+ ctx.note(
1073
+ "approximated",
1074
+ name,
1075
+ "Links to WordPress pages or dynamic values were left out; set them in the editor.",
1076
+ );
1077
+ return {};
1078
+ }
1079
+
1080
+ /** An Elementor 4 `svg-src` that names only a WordPress media id (W-951). */
1081
+ function mediaId(v: unknown): number | undefined {
1082
+ const source = un(v);
1083
+ const id = isRecord(source) ? un(source["id"]) : undefined;
1084
+ return typeof id === "number" && Number.isInteger(id) && id > 0 ? id : undefined;
1085
+ }
1086
+
1087
+ /**
1088
+ * An Elementor 4 SVG as an Icon (W-951): sized from its width in px (the svg fills the box), named
1089
+ * by its link when it has one, decorative otherwise. Without markup the icon is an empty slot.
1090
+ */
1091
+ function svgIcon(
1092
+ styled: (n: N) => N,
1093
+ ctx: ImportContext,
1094
+ iconId: string,
1095
+ markup: string | undefined,
1096
+ linkProps: { href?: string; newTab?: boolean },
1097
+ title: string,
1098
+ ): N {
1099
+ const n = styled(
1100
+ node(ctx, "icon", {
1101
+ iconId,
1102
+ ...(markup ? { iconSvg: markup } : {}),
1103
+ ...(linkProps.href ? { ...linkProps, title } : { decorative: true }),
1104
+ }),
1105
+ );
1106
+ const width = (n["style"] as Style | undefined)?.width;
1107
+ if (isRecord(width) && width["unit"] === "px" && typeof width["value"] === "number") {
1108
+ const px = Math.round(width["value"]);
1109
+ if (px > 0 && px <= 512) (n["props"] as Record<string, unknown>)["size"] = px;
1110
+ }
1111
+ return n;
1112
+ }
1113
+
1114
+ function imageUrl(v: unknown): string | undefined {
1115
+ const image = un(v);
1116
+ const src = isRecord(image) && "src" in image ? un(image["src"]) : image;
1117
+ const url = isRecord(src) ? str(un(src["url"])) : undefined;
1118
+ return url ? sanitizeMediaUrl(url) : undefined;
1119
+ }
1120
+
1121
+ const LABEL_FOR = (el: Settings) => str(un(settingsOf(el)["input-id"]));
1122
+
1123
+ function applyStyle(n: N, s: AtomicStyle): N {
1124
+ if (!isEmptyStyle(s.style)) n["style"] = { ...(n["style"] as Style | undefined), ...s.style };
1125
+ if (s.devices.laptop || s.devices.tablet || s.devices.mobile) n["devices"] = s.devices;
1126
+ if (Object.keys(s.states).length > 0) n["states"] = s.states;
1127
+ // W-956: a laptop shows what desktop shows unless a laptop variant says otherwise.
1128
+ const shown = { ...s.display, laptop: s.display.laptop ?? s.display.desktop };
1129
+ const hidden = (["desktop", "laptop", "tablet", "mobile"] as const).filter(
1130
+ (d) => shown[d] === "none",
1131
+ );
1132
+ if (hidden.length > 0) n["hiddenOn"] = hidden;
1133
+ return n;
1134
+ }
1135
+
1136
+ const CONTAINER_TAGS = new Set([
1137
+ "section",
1138
+ "header",
1139
+ "footer",
1140
+ "main",
1141
+ "article",
1142
+ "aside",
1143
+ "nav",
1144
+ "div",
1145
+ ]);
1146
+
1147
+ /** Maps Elementor 4 elements; returns undefined for types it doesn't know. */
1148
+ export function atomicElement(
1149
+ el: Settings,
1150
+ ctx: ImportContext,
1151
+ snap: AtomicSnapshots,
1152
+ env: Env,
1153
+ ): N[] | undefined {
1154
+ const nodes = elementNodes(el, ctx, snap, env);
1155
+ const [first] = nodes ?? [];
1156
+ const grid = env.grid;
1157
+ if (first && grid && nodes?.length === 1) {
1158
+ const type = str(el["widgetType"]) ?? str(el["elType"]) ?? "";
1159
+ if (atomicStyle(type, el, snap, ctx, labelOf(type), true).fullRow) {
1160
+ // `grid-column: 1 / -1` spans the parent's columns on each device.
1161
+ first["style"] = { ...(first["style"] as Style | undefined), gridColumnSpan: grid.desktop };
1162
+ const devices = { ...(first["devices"] as Record<string, Style> | undefined) };
1163
+ if (grid.tablet && grid.tablet !== grid.desktop)
1164
+ devices["tablet"] = { ...devices["tablet"], gridColumnSpan: grid.tablet };
1165
+ if (grid.mobile && grid.mobile !== (grid.tablet ?? grid.desktop))
1166
+ devices["mobile"] = { ...devices["mobile"], gridColumnSpan: grid.mobile };
1167
+ if (Object.keys(devices).length > 0) first["devices"] = devices;
1168
+ }
1169
+ }
1170
+ return nodes;
1171
+ }
1172
+
1173
+ function elementNodes(
1174
+ el: Settings,
1175
+ ctx: ImportContext,
1176
+ snap: AtomicSnapshots,
1177
+ env: Env,
1178
+ ): N[] | undefined {
1179
+ const { walk, form } = env;
1180
+ const type = str(el["widgetType"]) ?? str(el["elType"]) ?? "";
1181
+ const s = settingsOf(el);
1182
+ const name = labelOf(type);
1183
+ const styled = (n: N) =>
1184
+ useClasses(applyStyle(n, atomicStyle(type, el, snap, ctx, name)), el, snap, ctx);
1185
+ const kids = (next: Partial<Env> = {}) => {
1186
+ const { grid: _grid, ...rest } = env;
1187
+ return walk(el["elements"], { ...rest, depth: env.depth + 1, ...next });
1188
+ };
1189
+ const editorLabel = isRecord(el["editor_settings"])
1190
+ ? str(el["editor_settings"]["title"])?.trim().slice(0, 80)
1191
+ : undefined;
1192
+ const label = (n: N) => {
1193
+ if (editorLabel) n["editorLabel"] = editorLabel;
1194
+ const id = str(un(s["_cssid"]));
1195
+ if (id && /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(id) && !ctx.htmlIds.has(id)) {
1196
+ ctx.htmlIds.add(id);
1197
+ n["htmlId"] = id;
1198
+ }
1199
+ return n;
1200
+ };
1201
+
1202
+ switch (type) {
1203
+ case "e-flexbox":
1204
+ case "e-div-block":
1205
+ case "e-form-success-message":
1206
+ case "e-form-error-message": {
1207
+ if (type === "e-form-success-message" || type === "e-form-error-message") {
1208
+ ctx.note(
1209
+ "approximated",
1210
+ "Form",
1211
+ "Form success and error messages come from the forms plugin; Elementor's were left out.",
1212
+ );
1213
+ return [];
1214
+ }
1215
+ const st = atomicStyle(type, el, snap, ctx, name);
1216
+ const d = st.display.desktop ?? (type === "e-flexbox" ? "flex" : "block");
1217
+ const tag = str(un(s["tag"]));
1218
+ const linkProps = linkOf(s["link"], ctx, name);
1219
+ let n: N;
1220
+ if (d === "grid") {
1221
+ const tablet = st.columns.tablet;
1222
+ const mobile = st.columns.mobile;
1223
+ n = node(
1224
+ ctx,
1225
+ "grid",
1226
+ {
1227
+ columns: st.columns.desktop ?? 1,
1228
+ ...(tablet ? { columnsTablet: tablet } : {}),
1229
+ ...(mobile ? { columnsMobile: mobile } : {}),
1230
+ ...(st.tracks.desktop ? { columnTracks: st.tracks.desktop } : {}),
1231
+ ...(st.tracks.tablet ? { columnTracksTablet: st.tracks.tablet } : {}),
1232
+ ...(st.tracks.mobile ? { columnTracksMobile: st.tracks.mobile } : {}),
1233
+ ...linkProps,
1234
+ },
1235
+ {
1236
+ children: kids({
1237
+ parentRow: true,
1238
+ grid: {
1239
+ desktop: st.columns.desktop ?? 1,
1240
+ ...(tablet ? { tablet } : {}),
1241
+ ...(mobile ? { mobile } : {}),
1242
+ },
1243
+ }),
1244
+ },
1245
+ );
1246
+ } else if (
1247
+ d === "flex" ||
1248
+ d === "inline-flex" ||
1249
+ (tag && CONTAINER_TAGS.has(tag) && tag !== "div")
1250
+ ) {
1251
+ const row =
1252
+ d.includes("flex") && (st.style["flexDirection"] ?? "row").toString().startsWith("row");
1253
+ n = node(
1254
+ ctx,
1255
+ "container",
1256
+ { ...(tag && CONTAINER_TAGS.has(tag) ? { tag } : {}), ...linkProps },
1257
+ {
1258
+ style: { flexDirection: d.includes("flex") ? "row" : "column" },
1259
+ children: kids({ parentRow: row }),
1260
+ },
1261
+ );
1262
+ // Block on desktop, flex elsewhere is rare; a block box is shown as a column.
1263
+ } else {
1264
+ n = node(ctx, "div-block", linkProps, { children: kids({ parentRow: false }) });
1265
+ }
1266
+ applyStyle(n, st);
1267
+ // A container that turns into a block on a device stacks its children there.
1268
+ for (const device of ["tablet", "mobile"] as const) {
1269
+ const dd = st.display[device];
1270
+ if (n.type === "container" && dd === "block") {
1271
+ const devices = { ...(n["devices"] as Record<string, Style> | undefined) };
1272
+ devices[device] = { ...devices[device], flexDirection: "column" };
1273
+ n["devices"] = devices;
1274
+ }
1275
+ }
1276
+ return [label(useClasses(n, el, snap, ctx))];
1277
+ }
1278
+ case "e-heading": {
1279
+ const tag = str(un(s["tag"])) ?? "h2";
1280
+ const level = /^h([1-6])$/.exec(tag)?.[1];
1281
+ const t = text(s["title"]).replace(/\n+/g, " ");
1282
+ if (!t) return [];
1283
+ const linkProps = linkOf(s["link"], ctx, name);
1284
+ // W-950: bold, italic, coloured and linked words stay formatted (the gold word in a title).
1285
+ const found = styleWords(
1286
+ inlineMarks(str(un(s["title"])) ?? "", (url) => ctx.href(url), t),
1287
+ el,
1288
+ snap,
1289
+ ctx,
1290
+ );
1291
+ const marks = linkProps.href ? found.filter((m) => m.bold || m.italic || m.color) : found;
1292
+ const withMarks = marks.length > 0 ? { marks } : {};
1293
+ if (level)
1294
+ return splitLong(t).map((part) =>
1295
+ label(
1296
+ styled(
1297
+ node(ctx, "heading", {
1298
+ text: part,
1299
+ level: Number(level),
1300
+ ...linkProps,
1301
+ ...withMarks,
1302
+ }),
1303
+ ),
1304
+ ),
1305
+ );
1306
+ return splitLong(t).map((part) =>
1307
+ label(
1308
+ styled(node(ctx, "text", { text: part, tag: tag === "div" ? "div" : "p", ...withMarks })),
1309
+ ),
1310
+ );
1311
+ }
1312
+ case "e-paragraph": {
1313
+ const t = text(s["paragraph"]);
1314
+ if (!t) return [];
1315
+ const linkProps = linkOf(s["link"], ctx, name);
1316
+ if (linkProps.href)
1317
+ return [label(styled(node(ctx, "link", { text: t.slice(0, 2000), ...linkProps })))];
1318
+ const tag = str(un(s["tag"]));
1319
+ const marks = styleWords(
1320
+ inlineMarks(str(un(s["paragraph"])) ?? "", (url) => ctx.href(url), t),
1321
+ el,
1322
+ snap,
1323
+ ctx,
1324
+ );
1325
+ return splitLong(t).map((part) =>
1326
+ label(
1327
+ styled(
1328
+ node(ctx, "text", {
1329
+ text: part,
1330
+ ...(tag === "div" ? { tag: "div" } : {}),
1331
+ ...(marks.length > 0 ? { marks } : {}),
1332
+ }),
1333
+ ),
1334
+ ),
1335
+ );
1336
+ }
1337
+ case "e-button": {
1338
+ const t = text(s["text"]).replace(/\n+/g, " ") || "Button";
1339
+ return [
1340
+ label(
1341
+ styled(node(ctx, "button", { text: t.slice(0, 2000), ...linkOf(s["link"], ctx, name) })),
1342
+ ),
1343
+ ];
1344
+ }
1345
+ case "e-image": {
1346
+ const url = imageUrl(s["image"]);
1347
+ if (!url) {
1348
+ ctx.note("skipped", name, "An image without an address in the export was left out.");
1349
+ return [];
1350
+ }
1351
+ ctx.externalImage(url);
1352
+ const alt = text(s["alt"]) || "";
1353
+ if (!alt)
1354
+ ctx.note(
1355
+ "approximated",
1356
+ name,
1357
+ "Images without alt text got one from their file name; check it.",
1358
+ );
1359
+ return [
1360
+ label(
1361
+ styled(
1362
+ node(ctx, "image", {
1363
+ src: url,
1364
+ alt: alt || altFromUrl(url),
1365
+ ...linkOf(s["link"], ctx, name),
1366
+ }),
1367
+ ),
1368
+ ),
1369
+ ];
1370
+ }
1371
+ case "e-svg": {
1372
+ const url = imageUrl(s["svg"]);
1373
+ const linkProps = linkOf(s["link"], ctx, name);
1374
+ // W-951: with the file's markup the SVG is inline, so CSS colour reaches currentColor.
1375
+ const markup = url ? ctx.svgMarkup(url) : undefined;
1376
+ if (url && markup)
1377
+ return [label(svgIcon(styled, ctx, svgFileId(url), markup, linkProps, altFromUrl(url)))];
1378
+ if (!url) {
1379
+ // Elementor exports name an uploaded SVG by its WordPress media id only.
1380
+ const media = mediaId(s["svg"]);
1381
+ if (media === undefined) return [];
1382
+ ctx.note(
1383
+ "skipped",
1384
+ name,
1385
+ "SVG files aren't in Elementor exports, so these are empty Icon elements at their size; pick each file again in the editor (Icon → My uploads).",
1386
+ );
1387
+ return [label(svgIcon(styled, ctx, `wp-media:${media}`, undefined, linkProps, "Icon"))];
1388
+ }
1389
+ ctx.externalImage(url);
1390
+ ctx.note(
1391
+ "approximated",
1392
+ name,
1393
+ "SVG files that couldn't be read are shown as images, so colours can't change them; add the .svg files in the import dialog to make them recolourable icons.",
1394
+ );
1395
+ return [
1396
+ label(
1397
+ styled(
1398
+ node(ctx, "image", {
1399
+ src: url,
1400
+ alt: linkProps.href ? altFromUrl(url) : "",
1401
+ ...(linkProps.href ? linkProps : { decorative: true }),
1402
+ }),
1403
+ ),
1404
+ ),
1405
+ ];
1406
+ }
1407
+ case "e-divider":
1408
+ return [label(styled(node(ctx, "divider", {})))];
1409
+ case "e-youtube": {
1410
+ const url = embedVideoUrl(str(un(s["source"])) ?? "") ?? str(un(s["source"]));
1411
+ const safe = url ? sanitizeHref(url) : undefined;
1412
+ return safe ? [label(styled(node(ctx, "video", { url: safe, title: "Video" })))] : [];
1413
+ }
1414
+ case "e-accordion": {
1415
+ const items = (Array.isArray(el["elements"]) ? el["elements"] : []).filter(isRecord);
1416
+ const first = str(un(s["default_state"])) === "first_expanded";
1417
+ const children = items.map((item, i) => {
1418
+ const parts = (Array.isArray(item["elements"]) ? item["elements"] : []).filter(isRecord);
1419
+ const header = parts.find((p) => p["elType"] === "e-accordion-item-header");
1420
+ const content = parts.find((p) => p["elType"] === "e-accordion-item-content");
1421
+ const summary = (collectText(header) || "Item").slice(0, 200);
1422
+ return node(
1423
+ ctx,
1424
+ "accordion-item",
1425
+ { summary, ...(first && i === 0 ? { open: true } : {}) },
1426
+ {
1427
+ children: content
1428
+ ? walk(content["elements"], { ...env, parentRow: false, depth: env.depth + 2 })
1429
+ : [],
1430
+ },
1431
+ );
1432
+ });
1433
+ return children.length > 0 ? [label(styled(node(ctx, "accordion", {}, { children })))] : [];
1434
+ }
1435
+ case "e-tabs": {
1436
+ const panels: N[] = [];
1437
+ const menu = findAll(el, "e-tab");
1438
+ const contents = findAll(el, "e-tab-content");
1439
+ menu.slice(0, 12).forEach((tab, i) => {
1440
+ const content = contents[i];
1441
+ panels.push(
1442
+ node(
1443
+ ctx,
1444
+ "tab-panel",
1445
+ { label: (collectText(tab) || `Tab ${i + 1}`).slice(0, 2000) },
1446
+ {
1447
+ children: content
1448
+ ? walk(content["elements"], { ...env, parentRow: false, depth: env.depth + 2 })
1449
+ : [],
1450
+ },
1451
+ ),
1452
+ );
1453
+ });
1454
+ return panels.length > 0 ? [label(styled(node(ctx, "tabs", {}, { children: panels })))] : [];
1455
+ }
1456
+ case "e-form": {
1457
+ const labels = new Map<string, string>();
1458
+ const byField = new Map<Settings, string>();
1459
+ for (const l of findAll(el, "e-form-label")) {
1460
+ const id = LABEL_FOR(l);
1461
+ if (id) labels.set(id, text(settingsOf(l)["text"]).replace(/\n+/g, " ").slice(0, 200));
1462
+ }
1463
+ // A label without `input-id` names the field beside it in the same box.
1464
+ pairSiblingLabels(el, byField);
1465
+ ctx.note(
1466
+ "approximated",
1467
+ "Form",
1468
+ "Connect each imported form to a form in the forms plugin; Elementor's submit actions weren't imported.",
1469
+ );
1470
+ const n = node(
1471
+ ctx,
1472
+ "form",
1473
+ { formId: "" },
1474
+ {
1475
+ children: kids({ form: { labels, byField }, parentRow: false }),
1476
+ },
1477
+ );
1478
+ return [label(styled(n))];
1479
+ }
1480
+ case "e-form-label":
1481
+ return form
1482
+ ? []
1483
+ : [label(styled(node(ctx, "text", { text: text(settingsOf(el)["text"]) || "Label" })))];
1484
+ case "e-form-input":
1485
+ case "e-form-textarea":
1486
+ case "e-form-select":
1487
+ case "e-form-checkbox": {
1488
+ if (!form) {
1489
+ ctx.note("skipped", name, "A form field outside a form was left out.");
1490
+ return [];
1491
+ }
1492
+ const id = str(un(s["_cssid"]));
1493
+ let field = str(un(s["name"])) ?? id ?? "";
1494
+ field = field.replace(/[^A-Za-z0-9_-]/g, "_");
1495
+ if (!FIELD_NAME_PATTERN.test(field) || field.length > 80) field = `field_${ctx.nodes + 1}`;
1496
+ const fieldLabel =
1497
+ (id ? form.labels.get(id) : undefined) ??
1498
+ form.byField?.get(el) ??
1499
+ (text(s["label"]) || (type === "e-form-checkbox" ? text(s["value"]) : ""));
1500
+ const placeholder = text(s["placeholder"]).slice(0, 200);
1501
+ const kind =
1502
+ type === "e-form-textarea"
1503
+ ? "textarea"
1504
+ : type === "e-form-select"
1505
+ ? "select"
1506
+ : type === "e-form-checkbox"
1507
+ ? "checkbox"
1508
+ : "text-input";
1509
+ if (kind === "select")
1510
+ ctx.note(
1511
+ "approximated",
1512
+ "Form",
1513
+ "Select options come from the forms plugin form; Elementor's options weren't imported.",
1514
+ );
1515
+ return [
1516
+ node(ctx, kind, {
1517
+ field,
1518
+ ...(fieldLabel ? { label: fieldLabel.slice(0, 200) } : {}),
1519
+ ...(placeholder && kind !== "checkbox" ? { placeholder } : {}),
1520
+ }),
1521
+ ];
1522
+ }
1523
+ case "e-form-submit-button": {
1524
+ if (!form) return [];
1525
+ const t = text(s["text"]).replace(/\n+/g, " ").slice(0, 80);
1526
+ return [label(styled(node(ctx, "submit", t ? { label: t } : {})))];
1527
+ }
1528
+ default:
1529
+ return undefined;
1530
+ }
1531
+ }
1532
+
1533
+ const FIELD_TYPES = new Set([
1534
+ "e-form-input",
1535
+ "e-form-textarea",
1536
+ "e-form-select",
1537
+ "e-form-checkbox",
1538
+ ]);
1539
+
1540
+ function pairSiblingLabels(el: Settings, into: Map<Settings, string>, depth = 0): void {
1541
+ if (depth > 12) return;
1542
+ const kids = (Array.isArray(el["elements"]) ? el["elements"] : []).filter(isRecord);
1543
+ kids.forEach((child, i) => {
1544
+ if (child["widgetType"] === "e-form-label" && !LABEL_FOR(child)) {
1545
+ const isField = (n: Settings | undefined) =>
1546
+ n !== undefined && FIELD_TYPES.has(str(n["widgetType"]) ?? "");
1547
+ const target =
1548
+ isField(kids[i - 1]) && !into.has(kids[i - 1] as Settings)
1549
+ ? kids[i - 1]
1550
+ : isField(kids[i + 1])
1551
+ ? kids[i + 1]
1552
+ : undefined;
1553
+ if (target)
1554
+ into.set(target, text(settingsOf(child)["text"]).replace(/\n+/g, " ").slice(0, 200));
1555
+ }
1556
+ pairSiblingLabels(child, into, depth + 1);
1557
+ });
1558
+ }
1559
+
1560
+ function findAll(el: Settings, type: string, out: Settings[] = [], depth = 0): Settings[] {
1561
+ if (depth > 12) return out;
1562
+ for (const child of Array.isArray(el["elements"]) ? el["elements"] : []) {
1563
+ if (!isRecord(child)) continue;
1564
+ if (child["elType"] === type || child["widgetType"] === type) out.push(child);
1565
+ else findAll(child, type, out, depth + 1);
1566
+ }
1567
+ return out;
1568
+ }
1569
+
1570
+ /** The text of an element subtree (accordion and tab titles). */
1571
+ function collectText(el: Settings | undefined): string {
1572
+ if (!el) return "";
1573
+ const parts: string[] = [];
1574
+ const visit = (n: Settings, depth: number) => {
1575
+ if (depth > 8) return;
1576
+ const s = settingsOf(n);
1577
+ for (const key of ["title", "paragraph", "text"])
1578
+ if (s[key] !== undefined) parts.push(text(s[key]));
1579
+ for (const child of Array.isArray(n["elements"]) ? n["elements"] : [])
1580
+ if (isRecord(child)) visit(child, depth + 1);
1581
+ };
1582
+ visit(el, 0);
1583
+ return cleanText(parts.join(" ").replace(/[▸▾►▼]\s*/g, ""));
1584
+ }
1585
+
1586
+ function labelOf(type: string): string {
1587
+ return (
1588
+ type
1589
+ .replace(/^e-/, "")
1590
+ .split("-")
1591
+ .filter(Boolean)
1592
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1593
+ .join(" ") || "Element"
1594
+ );
1595
+ }