@perkyzz/emvb 1.3.0 → 1.4.1

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 (161) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -2
  3. package/src/admin/bulk-api.ts +5 -1
  4. package/src/admin/content-item.ts +3 -0
  5. package/src/admin/copy-rich-text.ts +99 -9
  6. package/src/admin/editor/A11yCopilot.tsx +3 -1
  7. package/src/admin/editor/Editor.tsx +28 -3
  8. package/src/admin/editor/Timeline.tsx +1 -8
  9. package/src/admin/editor/canvas/DeviceBar.tsx +7 -2
  10. package/src/admin/editor/canvas/EmptyCanvas.tsx +11 -2
  11. package/src/admin/editor/canvas/use-canvas-dnd.ts +1 -20
  12. package/src/admin/editor/canvas/vnode-react.tsx +2 -0
  13. package/src/admin/editor/co-design.ts +36 -1
  14. package/src/admin/editor/collection-previews.ts +7 -8
  15. package/src/admin/editor/dnd/dragged-source.ts +22 -0
  16. package/src/admin/editor/dnd/layer-drop.ts +141 -0
  17. package/src/admin/editor/dnd/new-element.ts +16 -0
  18. package/src/admin/editor/editor-css.ts +9 -1
  19. package/src/admin/editor/element-chrome.ts +6 -0
  20. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  21. package/src/admin/editor/extensions-context.tsx +16 -1
  22. package/src/admin/editor/feature-css.ts +27 -0
  23. package/src/admin/editor/inert-links.ts +8 -0
  24. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  25. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  26. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  27. package/src/admin/editor/panels/FontFaces.tsx +342 -0
  28. package/src/admin/editor/panels/LayersPanel.tsx +56 -6
  29. package/src/admin/editor/panels/LeftPanel.tsx +153 -29
  30. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  31. package/src/admin/editor/panels/SiteStylesDrawer.tsx +5 -0
  32. package/src/admin/editor/panels/TemplatesPanel.tsx +205 -0
  33. package/src/admin/editor/panels/TokenScales.tsx +2 -0
  34. package/src/admin/editor/panels/TriggersEditor.tsx +203 -9
  35. package/src/admin/editor/panels/VariableSection.tsx +111 -7
  36. package/src/admin/editor/panels/color-space.ts +71 -6
  37. package/src/admin/editor/panels/settings/AudienceEditor.tsx +3 -0
  38. package/src/admin/editor/panels/settings/FieldControl.tsx +33 -0
  39. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  40. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  41. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +9 -3
  42. package/src/admin/editor/panels/settings/StickyControl.tsx +97 -0
  43. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -0
  44. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  45. package/src/admin/editor/panels/settings/style-sections.ts +19 -2
  46. package/src/admin/editor/panels/url-rules.ts +43 -0
  47. package/src/admin/editor/panels/use-layers-drop.ts +232 -0
  48. package/src/admin/editor/store.ts +4 -2
  49. package/src/admin/editor/useExtensions.ts +3 -1
  50. package/src/admin/editor/useNodeActions.ts +74 -1
  51. package/src/admin/editor/useSave.ts +116 -85
  52. package/src/admin/export-api.ts +27 -2
  53. package/src/admin/extension-outputs.ts +236 -0
  54. package/src/admin/font-files-api.ts +38 -0
  55. package/src/admin/import-forms.ts +133 -0
  56. package/src/admin/pages/ImportButton.tsx +15 -4
  57. package/src/admin/pages/ImportElementorDialog.tsx +53 -187
  58. package/src/admin/pages/ImportForms.tsx +71 -0
  59. package/src/admin/pages/ImportHtmlDialog.tsx +209 -0
  60. package/src/admin/pages/ImportImageCopies.tsx +167 -0
  61. package/src/admin/pages/ImportReport.tsx +63 -0
  62. package/src/admin/pages/NewPageDialog.tsx +54 -32
  63. package/src/admin/pages/PageList.tsx +9 -0
  64. package/src/admin/pages/ThemePartList.tsx +9 -0
  65. package/src/admin/setup/plan.ts +2 -0
  66. package/src/admin/ui.ts +7 -0
  67. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  68. package/src/astro/EmVBPage.astro +5 -2
  69. package/src/astro/extension-styles.ts +35 -0
  70. package/src/astro/forms/EmVBFormsClient.astro +3 -0
  71. package/src/astro/forms/enhance.ts +107 -0
  72. package/src/astro/popups/runtime.ts +47 -2
  73. package/src/astro/render.ts +25 -4
  74. package/src/astro/resolve-theme.ts +11 -4
  75. package/src/astro/resolve.ts +2 -0
  76. package/src/astro/theme-posts.ts +17 -23
  77. package/src/astro/visitor.ts +14 -5
  78. package/src/astro/widgets/EmVBStickyRuntime.astro +9 -0
  79. package/src/astro/widgets/EmVBThemeRuntime.astro +9 -0
  80. package/src/astro/widgets/EmVBWidgetRuntimes.astro +12 -0
  81. package/src/astro/widgets/alerts.ts +16 -2
  82. package/src/astro/widgets/carousel.ts +65 -24
  83. package/src/astro/widgets/countdown.ts +18 -7
  84. package/src/astro/widgets/extension-runtimes.ts +27 -0
  85. package/src/astro/widgets/headline.ts +14 -5
  86. package/src/astro/widgets/sticky.ts +87 -0
  87. package/src/astro/widgets/theme.ts +52 -0
  88. package/src/constants.ts +1 -1
  89. package/src/core/a11y/audit.ts +150 -2
  90. package/src/core/arrange.ts +19 -1
  91. package/src/core/css/font-face.ts +72 -0
  92. package/src/core/css/generate.ts +41 -2
  93. package/src/core/css/trace.ts +8 -0
  94. package/src/core/data/bindings.ts +7 -4
  95. package/src/core/elements/dynamic-elements.ts +1 -1
  96. package/src/core/elements/element-nouns.ts +48 -0
  97. package/src/core/elements/form-elements.ts +119 -9
  98. package/src/core/elements/icon-svg.ts +14 -0
  99. package/src/core/elements/index.ts +24 -4
  100. package/src/core/elements/input-limits.ts +44 -0
  101. package/src/core/elements/menu.ts +109 -47
  102. package/src/core/elements/site.ts +108 -0
  103. package/src/core/elements/widgets.ts +13 -3
  104. package/src/core/export/runtimes.generated.ts +7 -5
  105. package/src/core/export/site.ts +53 -4
  106. package/src/core/extensions/classes.ts +114 -0
  107. package/src/core/extensions/index.ts +19 -2
  108. package/src/core/extensions/normalize.ts +13 -0
  109. package/src/core/extensions/placeholder.ts +7 -2
  110. package/src/core/extensions/registry.ts +134 -10
  111. package/src/core/extensions/render-ext.ts +115 -36
  112. package/src/core/extensions/safe-nodes.ts +67 -11
  113. package/src/core/extensions/types.ts +48 -1
  114. package/src/core/fonts/files.ts +74 -0
  115. package/src/core/fonts/google.ts +112 -0
  116. package/src/core/fonts/test-font.ts +9 -0
  117. package/src/core/import/elementor/context.ts +42 -4
  118. package/src/core/import/elementor/index.ts +55 -23
  119. package/src/core/import/elementor/widgets.ts +242 -20
  120. package/src/core/import/html/blocks.ts +602 -0
  121. package/src/core/import/html/index.ts +155 -0
  122. package/src/core/import/html/map.ts +958 -0
  123. package/src/core/import/html/parse.ts +430 -0
  124. package/src/core/index.ts +54 -0
  125. package/src/core/migrate/v18.ts +3 -0
  126. package/src/core/public-attributes.ts +17 -0
  127. package/src/core/render/extras.ts +31 -7
  128. package/src/core/render/form.ts +103 -10
  129. package/src/core/render/index.ts +165 -16
  130. package/src/core/render/section.ts +31 -1
  131. package/src/core/render/spacer-basis.ts +102 -0
  132. package/src/core/render/theme-boot.ts +16 -0
  133. package/src/core/render/vnode.ts +1 -1
  134. package/src/core/sanitize/css.ts +68 -3
  135. package/src/core/sanitize/motion.ts +12 -0
  136. package/src/core/schema/design.ts +40 -0
  137. package/src/core/schema/layout.ts +118 -6
  138. package/src/core/schema/style.ts +28 -0
  139. package/src/core/templates/index.ts +218 -0
  140. package/src/core/templates/pages.ts +29 -0
  141. package/src/core/templates/sections.ts +794 -0
  142. package/src/core/templates/types.ts +9 -0
  143. package/src/core/theme/dynamic.ts +9 -6
  144. package/src/core/theme/media-value.ts +88 -0
  145. package/src/core/theme/popup-markup.ts +21 -2
  146. package/src/core/theme/popup-rules.ts +36 -0
  147. package/src/core/theme/triggers.ts +64 -5
  148. package/src/core/translatable.ts +5 -2
  149. package/src/core/visitor-cookie.ts +91 -0
  150. package/src/extension-build.ts +331 -0
  151. package/src/index.ts +53 -4
  152. package/src/mcp/agent-defaults.ts +40 -0
  153. package/src/mcp/brief.ts +191 -0
  154. package/src/mcp/extensions.ts +138 -0
  155. package/src/mcp/prompts.ts +33 -0
  156. package/src/mcp/read.ts +84 -20
  157. package/src/mcp/tools.ts +42 -3
  158. package/src/mcp/write.ts +124 -9
  159. package/src/server/extension-routes.ts +110 -0
  160. package/src/server/font-routes.ts +301 -0
  161. package/src/server/plugin.ts +15 -0
@@ -0,0 +1,236 @@
1
+ import * as React from "react";
2
+ import { PLUGIN_ID } from "../constants.ts";
3
+ import {
4
+ extensionOutputKey,
5
+ isExtensionType,
6
+ rememberExtensionManifests,
7
+ type ExtensionManifest,
8
+ } from "../core/index.ts";
9
+ import { requestJson, type Fetcher } from "./api.ts";
10
+
11
+ /** The server renders at most this many extension elements per request (extension-routes.ts). */
12
+ const BATCH = 100;
13
+ /** Different extension elements the admin asks about for one page or export. */
14
+ const MAX_ELEMENTS = 1000;
15
+
16
+ type ExtNode = { type: string; props?: Record<string, unknown> };
17
+
18
+ /**
19
+ * W-1086: every extension element in some layouts (stored layouts may arrive as JSON text), one
20
+ * per type and props, in the order found.
21
+ */
22
+ export function extensionNodesIn(layouts: readonly unknown[]): ExtNode[] {
23
+ const found = new Map<string, ExtNode>();
24
+ const walk = (value: unknown, depth: number) => {
25
+ if (found.size >= MAX_ELEMENTS || depth > 64 || !value || typeof value !== "object") return;
26
+ const node = value as { type?: unknown; props?: unknown; children?: unknown; root?: unknown };
27
+ if (node.root) walk(node.root, depth + 1);
28
+ if (typeof node.type === "string" && isExtensionType(node.type)) {
29
+ const props =
30
+ node.props && typeof node.props === "object" && !Array.isArray(node.props)
31
+ ? (node.props as Record<string, unknown>)
32
+ : undefined;
33
+ const ext = { type: node.type, ...(props ? { props } : {}) };
34
+ found.set(extensionOutputKey(ext), ext);
35
+ }
36
+ if (Array.isArray(node.children)) for (const child of node.children) walk(child, depth + 1);
37
+ };
38
+ for (const layout of layouts) {
39
+ let value = layout;
40
+ if (typeof value === "string") {
41
+ try {
42
+ value = JSON.parse(value) as unknown;
43
+ } catch {
44
+ continue;
45
+ }
46
+ }
47
+ walk(value, 0);
48
+ }
49
+ return [...found.values()];
50
+ }
51
+
52
+ /**
53
+ * W-1086: the server-rendered output of each extension element, by `extensionOutputKey`. A
54
+ * failed request leaves its elements out (they show the placeholder). `answered`, when given,
55
+ * collects the key of every element the server answered, including those with no output.
56
+ */
57
+ export async function fetchExtensionOutputs(
58
+ fetcher: Fetcher,
59
+ nodes: readonly ExtNode[],
60
+ answered?: Set<string>,
61
+ ): Promise<Map<string, unknown>> {
62
+ const outputs = new Map<string, unknown>();
63
+ for (let start = 0; start < nodes.length; start += BATCH) {
64
+ try {
65
+ // oxlint-disable-next-line no-await-in-loop -- batches, one request at a time
66
+ const body = await requestJson<{ outputs?: { key?: unknown; nodes?: unknown }[] }>(
67
+ fetcher,
68
+ `/_emdash/api/plugins/${PLUGIN_ID}/editor/extensions/render`,
69
+ { method: "POST", body: { nodes: nodes.slice(start, start + BATCH) } },
70
+ );
71
+ for (const item of body?.outputs ?? []) {
72
+ if (typeof item.key !== "string") continue;
73
+ answered?.add(item.key);
74
+ if (Array.isArray(item.nodes)) outputs.set(item.key, item.nodes);
75
+ }
76
+ } catch {
77
+ // Leave this batch out.
78
+ }
79
+ }
80
+ return outputs;
81
+ }
82
+
83
+ /**
84
+ * W-1086: the site's extension manifests from editor/config, remembered so the admin's renderer
85
+ * has their class allowlists, stylesheets and runtimes (for the HTML export).
86
+ */
87
+ export async function loadExtensionManifests(fetcher: Fetcher): Promise<ExtensionManifest[]> {
88
+ try {
89
+ const body = await requestJson<{ extensions?: unknown }>(
90
+ fetcher,
91
+ `/_emdash/api/plugins/${PLUGIN_ID}/editor/config`,
92
+ );
93
+ const list = Array.isArray(body?.extensions) ? body.extensions : [];
94
+ rememberExtensionManifests(list);
95
+ return list.filter(
96
+ (m): m is ExtensionManifest =>
97
+ !!m &&
98
+ typeof m === "object" &&
99
+ (m as ExtensionManifest).extensionApi === 1 &&
100
+ typeof (m as ExtensionManifest).id === "string",
101
+ );
102
+ } catch {
103
+ return [];
104
+ }
105
+ }
106
+
107
+ /** Prop edits come one keystroke at a time; the canvas asks once they pause. */
108
+ export const EXTENSION_OUTPUTS_DEBOUNCE_MS = 300;
109
+ /** After a failed request the canvas asks again this much later, a few times in a row at most. */
110
+ export const EXTENSION_OUTPUTS_RETRY_MS = 1000;
111
+ const MAX_RETRIES = 3;
112
+
113
+ /**
114
+ * W-1086: extension outputs for the editor canvas. Once edits pause, asks the server for elements
115
+ * it hasn't answered (a new element, or edited props), keeps earlier answers for elements still
116
+ * on the page and drops the rest. Elements of a failed request are asked again a little later
117
+ * (a few times) and on the next change.
118
+ */
119
+ export function useExtensionOutputs(
120
+ layout: unknown,
121
+ fetcher: Fetcher,
122
+ ): ReadonlyMap<string, unknown> {
123
+ const nodes = layout ? extensionNodesIn([layout]) : [];
124
+ const key = nodes.map(extensionOutputKey).join("\u0000");
125
+ const [outputs, setOutputs] = React.useState<ReadonlyMap<string, unknown>>(() => new Map());
126
+ const asked = React.useRef(new Set<string>());
127
+ const onPage = React.useRef(new Set<string>());
128
+ const mounted = React.useRef(true);
129
+ // Bumped to ask again after a failed request; `failures` counts them in a row.
130
+ const [retry, setRetry] = React.useState(0);
131
+ const failures = React.useRef(0);
132
+ React.useEffect(() => {
133
+ mounted.current = true;
134
+ return () => {
135
+ mounted.current = false;
136
+ };
137
+ }, []);
138
+ React.useEffect(() => {
139
+ const current = new Set(nodes.map(extensionOutputKey));
140
+ onPage.current = current;
141
+ const seen = asked.current;
142
+ // Outputs of elements no longer on the page are dropped (and asked again if they come back).
143
+ for (const seenKey of seen) if (!current.has(seenKey)) seen.delete(seenKey);
144
+ setOutputs((previous) => {
145
+ if ([...previous.keys()].every((k) => current.has(k))) return previous;
146
+ return new Map([...previous].filter(([k]) => current.has(k)));
147
+ });
148
+ if (current.size === 0) return;
149
+ const timer = setTimeout(() => {
150
+ const wanted = nodes.filter((node) => !seen.has(extensionOutputKey(node)));
151
+ if (wanted.length === 0) return;
152
+ for (const node of wanted) seen.add(extensionOutputKey(node));
153
+ const answered = new Set<string>();
154
+ void fetchExtensionOutputs(fetcher, wanted, answered).then((found) => {
155
+ // A failed batch: its elements are asked again later and on the next change.
156
+ let failed = false;
157
+ for (const node of wanted) {
158
+ const wantedKey = extensionOutputKey(node);
159
+ if (answered.has(wantedKey)) continue;
160
+ seen.delete(wantedKey);
161
+ failed = true;
162
+ }
163
+ failures.current = failed ? failures.current + 1 : 0;
164
+ if (failed && failures.current <= MAX_RETRIES) {
165
+ setTimeout(() => {
166
+ if (mounted.current) setRetry((n) => n + 1);
167
+ }, EXTENSION_OUTPUTS_RETRY_MS * failures.current);
168
+ }
169
+ const keep = [...found].filter(([k]) => onPage.current.has(k));
170
+ if (!mounted.current || keep.length === 0) return;
171
+ setOutputs((previous) => new Map([...previous, ...keep]));
172
+ });
173
+ }, EXTENSION_OUTPUTS_DEBOUNCE_MS);
174
+ return () => clearTimeout(timer);
175
+ // `key` stands for `nodes`.
176
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
177
+ }, [key, fetcher, retry]);
178
+ return outputs;
179
+ }
180
+
181
+ /** W-1088: values of the sources extension panels name, by source id (`ext:<package>/<name>`). */
182
+ export type ExtensionSourceValues = ReadonlyMap<string, Readonly<Record<string, string>> | null>;
183
+
184
+ /**
185
+ * W-1088 (#36): asks the server for the values of every source an extension panel names. Values
186
+ * are plain strings (cleaned on the server); anything else in the answer is dropped. `null` for a
187
+ * source the server couldn't read; the whole map is empty when the request fails.
188
+ */
189
+ export async function fetchExtensionSourceValues(fetcher: Fetcher): Promise<ExtensionSourceValues> {
190
+ const out = new Map<string, Readonly<Record<string, string>> | null>();
191
+ try {
192
+ const body = await requestJson<{ sources?: { id?: unknown; values?: unknown }[] }>(
193
+ fetcher,
194
+ `/_emdash/api/plugins/${PLUGIN_ID}/editor/extensions/sources`,
195
+ );
196
+ for (const item of Array.isArray(body?.sources) ? body.sources : []) {
197
+ if (typeof item?.id !== "string") continue;
198
+ const raw = item.values;
199
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
200
+ out.set(item.id, null);
201
+ continue;
202
+ }
203
+ const values: Record<string, string> = {};
204
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
205
+ if (typeof value === "string") values[key] = value;
206
+ }
207
+ out.set(item.id, values);
208
+ }
209
+ } catch {
210
+ // The panels say the values couldn't be loaded.
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /**
216
+ * W-1088 (#36): source values for the extension panels, loaded once the site's manifests are in
217
+ * when a panel names a source. Undefined while loading (or when no panel names one).
218
+ */
219
+ export function useExtensionSourceValues(
220
+ fetcher: Fetcher,
221
+ manifests: readonly ExtensionManifest[],
222
+ ): ExtensionSourceValues | undefined {
223
+ const wanted = manifests.some((m) => m.panels?.some((panel) => panel.source));
224
+ const [values, setValues] = React.useState<ExtensionSourceValues | undefined>(undefined);
225
+ React.useEffect(() => {
226
+ if (!wanted) return;
227
+ let cancelled = false;
228
+ void fetchExtensionSourceValues(fetcher).then((found) => {
229
+ if (!cancelled) setValues(found);
230
+ });
231
+ return () => {
232
+ cancelled = true;
233
+ };
234
+ }, [fetcher, wanted]);
235
+ return values;
236
+ }
@@ -0,0 +1,38 @@
1
+ import { PLUGIN_ID } from "../constants.ts";
2
+ import { bytesToBase64, fontFileProblem, type FontFace } from "../core/index.ts";
3
+ import { requestJson, type Fetcher } from "./api.ts";
4
+
5
+ const BASE = `/_emdash/api/plugins/${PLUGIN_ID}`;
6
+
7
+ /**
8
+ * Uploads a WOFF2 file (W-1072). It is checked here first, so a refused file says why at once;
9
+ * the server checks it again. Answers the URL the font is served from.
10
+ */
11
+ export async function uploadFontFile(fetcher: Fetcher, file: File): Promise<{ url: string }> {
12
+ if (!/\.woff2$/i.test(file.name)) throw new Error("Choose a .woff2 font file.");
13
+ const bytes = new Uint8Array(await file.arrayBuffer());
14
+ const problem = fontFileProblem(bytes);
15
+ if (problem) throw new Error(problem);
16
+ const data = await requestJson<{ file: { url: string } }>(fetcher, `${BASE}/fonts/upload`, {
17
+ method: "POST",
18
+ body: { name: file.name, data: bytesToBase64(bytes) },
19
+ });
20
+ return { url: data.file.url };
21
+ }
22
+
23
+ /** Self-hosts one weight and style of a Google font; answers its faces (W-1072). */
24
+ export async function importGoogleFont(
25
+ fetcher: Fetcher,
26
+ request: {
27
+ family: string;
28
+ weight: number;
29
+ style: "normal" | "italic";
30
+ subsets: readonly string[];
31
+ },
32
+ ): Promise<FontFace[]> {
33
+ const data = await requestJson<{ faces: FontFace[] }>(fetcher, `${BASE}/fonts/google`, {
34
+ method: "POST",
35
+ body: request,
36
+ });
37
+ return data.faces;
38
+ }
@@ -0,0 +1,133 @@
1
+ import type { ImportedForm, ImportedFormField, Layout } from "../core/index.ts";
2
+ import type { LayoutNode } from "../core/schema/layout.ts";
3
+ import { ApiError, requestJson, type Fetcher } from "./api.ts";
4
+
5
+ const CREATE = "/_emdash/api/plugins/emdash-forms/forms/create";
6
+
7
+ /** A forms-plugin slug (`^[a-z][a-z0-9-]*$`, 100 at most) from a form's name, unique on the site. */
8
+ function formSlug(name: string, taken: ReadonlySet<string>): string {
9
+ const base =
10
+ name
11
+ .normalize("NFKD")
12
+ .replaceAll(/[̀-ͯ]/g, "")
13
+ .toLowerCase()
14
+ .replaceAll(/[^a-z0-9]+/g, "-")
15
+ .replace(/^[^a-z]+/, "")
16
+ .replace(/-+$/, "")
17
+ .slice(0, 90) || "imported-form";
18
+ let slug = base;
19
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`;
20
+ return slug;
21
+ }
22
+
23
+ /** One field as the forms plugin's `forms/create` takes it. */
24
+ function pluginField(field: ImportedFormField) {
25
+ const validation = {
26
+ ...(field.min === undefined ? {} : { min: field.min }),
27
+ ...(field.max === undefined ? {} : { max: field.max }),
28
+ };
29
+ return {
30
+ id: field.name,
31
+ type: field.type,
32
+ label: field.label,
33
+ name: field.name,
34
+ required: field.required,
35
+ width: "full",
36
+ ...(field.placeholder ? { placeholder: field.placeholder } : {}),
37
+ ...(field.options?.length ? { options: field.options } : {}),
38
+ ...(Object.keys(validation).length > 0 ? { validation } : {}),
39
+ };
40
+ }
41
+
42
+ /**
43
+ * W-1091 (#27): the body that creates an imported Elementor form in EmDash Forms (the plugin's
44
+ * admin route, plugins:manage), or null when it has no field the plugin can hold. Pages without
45
+ * fields are left out, since the plugin needs at least one field on each.
46
+ */
47
+ function formCreateBody(form: ImportedForm, slug: string) {
48
+ const pages = form.pages
49
+ .filter((page) => page.fields.length > 0)
50
+ .map((page) =>
51
+ page.title
52
+ ? { title: page.title, fields: page.fields.map(pluginField) }
53
+ : { fields: page.fields.map(pluginField) },
54
+ );
55
+ if (pages.length === 0) return null;
56
+ return {
57
+ name: form.name,
58
+ slug,
59
+ pages,
60
+ settings: {
61
+ submitLabel: form.submitLabel,
62
+ ...(form.successMessage ? { confirmationMessage: form.successMessage } : {}),
63
+ ...(pages.length > 1 && form.nextLabel ? { nextLabel: form.nextLabel } : {}),
64
+ ...(pages.length > 1 && form.prevLabel ? { prevLabel: form.prevLabel } : {}),
65
+ },
66
+ };
67
+ }
68
+
69
+ export type CreatedForms = {
70
+ /** EmVB Form node id → the new forms-plugin form id. */
71
+ ids: Map<string, string>;
72
+ /** Forms that couldn't be made (by name), with why. */
73
+ failed: { name: string; message: string }[];
74
+ };
75
+
76
+ /**
77
+ * W-1091 (#27): creates each imported form in EmDash Forms, one at a time. A refusal for lack of
78
+ * rights stops at once (nothing more would succeed) and is thrown, so the import doesn't go on
79
+ * with a half-made set; any other failure is reported and the rest go on.
80
+ */
81
+ export async function createImportedForms(
82
+ fetcher: Fetcher,
83
+ forms: readonly ImportedForm[],
84
+ takenSlugs: ReadonlySet<string>,
85
+ ): Promise<CreatedForms> {
86
+ const taken = new Set(takenSlugs);
87
+ const result: CreatedForms = { ids: new Map(), failed: [] };
88
+ for (const form of forms) {
89
+ const slug = formSlug(form.name, taken);
90
+ taken.add(slug);
91
+ const body = formCreateBody(form, slug);
92
+ if (!body) {
93
+ result.failed.push({ name: form.name, message: "it has no fields to send" });
94
+ continue;
95
+ }
96
+ try {
97
+ // oxlint-disable-next-line no-await-in-loop -- one form at a time; failures are per form
98
+ const created = await requestJson<{ id: string }>(fetcher, CREATE, {
99
+ method: "POST",
100
+ body,
101
+ });
102
+ result.ids.set(form.nodeId, created.id);
103
+ } catch (error) {
104
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
105
+ throw new ApiError(
106
+ error.status,
107
+ error.code,
108
+ "Only administrators can create forms in EmDash Forms. Untick “Create the forms in EmDash Forms” to import without them, then connect each form in its settings.",
109
+ );
110
+ }
111
+ result.failed.push({
112
+ name: form.name,
113
+ message: error instanceof Error ? error.message : String(error),
114
+ });
115
+ }
116
+ }
117
+ return result;
118
+ }
119
+
120
+ /** The layout with each created form's id on its Form element. */
121
+ export function withFormIds(layout: Layout, ids: ReadonlyMap<string, string>): Layout {
122
+ if (ids.size === 0) return layout;
123
+ const visit = (node: LayoutNode): LayoutNode => {
124
+ const formId = node.type === "form" ? ids.get(node.id) : undefined;
125
+ const children = (node as { children?: LayoutNode[] }).children;
126
+ return {
127
+ ...node,
128
+ ...(formId ? { props: { ...node.props, formId } } : {}),
129
+ ...(children ? { children: children.map(visit) } : {}),
130
+ } as LayoutNode;
131
+ };
132
+ return { ...layout, root: visit(layout.root) as Layout["root"] };
133
+ }
@@ -2,17 +2,28 @@ import { Button } from "@cloudflare/kumo";
2
2
  import { FileArrowUpIcon } from "@phosphor-icons/react";
3
3
  import { BUTTON } from "../ui.ts";
4
4
 
5
- /** Opens Import from Elementor (W-945), next to the list's New button. */
6
- export function ImportButton({ onClick }: { onClick: () => void }) {
5
+ /**
6
+ * Opens an import dialog, next to the list's New button: Import from Elementor (W-945) or
7
+ * Import HTML (W-1074, WordPress posts and HTML pages).
8
+ */
9
+ export function ImportButton({
10
+ onClick,
11
+ source = "elementor",
12
+ }: {
13
+ onClick: () => void;
14
+ source?: "elementor" | "html";
15
+ }) {
7
16
  return (
8
17
  <Button
9
18
  variant="secondary"
10
19
  className={BUTTON}
11
20
  icon={<FileArrowUpIcon aria-hidden="true" />}
12
21
  onClick={onClick}
13
- data-emvb-import-elementor=""
22
+ {...(source === "html"
23
+ ? { "data-emvb-import-html": "" }
24
+ : { "data-emvb-import-elementor": "" })}
14
25
  >
15
- Import from Elementor
26
+ {source === "html" ? "Import HTML" : "Import from Elementor"}
16
27
  </Button>
17
28
  );
18
29
  }