@perkyzz/emvb 1.3.0 → 1.4.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 (134) 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/editor/A11yCopilot.tsx +3 -1
  5. package/src/admin/editor/Editor.tsx +22 -2
  6. package/src/admin/editor/Timeline.tsx +1 -8
  7. package/src/admin/editor/canvas/DeviceBar.tsx +7 -2
  8. package/src/admin/editor/canvas/EmptyCanvas.tsx +11 -2
  9. package/src/admin/editor/canvas/use-canvas-dnd.ts +1 -20
  10. package/src/admin/editor/canvas/vnode-react.tsx +2 -0
  11. package/src/admin/editor/co-design.ts +36 -1
  12. package/src/admin/editor/dnd/dragged-source.ts +22 -0
  13. package/src/admin/editor/dnd/layer-drop.ts +141 -0
  14. package/src/admin/editor/dnd/new-element.ts +16 -0
  15. package/src/admin/editor/editor-css.ts +9 -1
  16. package/src/admin/editor/element-chrome.ts +6 -0
  17. package/src/admin/editor/feature-css.ts +22 -0
  18. package/src/admin/editor/inert-links.ts +8 -0
  19. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  20. package/src/admin/editor/panels/FontFaces.tsx +342 -0
  21. package/src/admin/editor/panels/LayersPanel.tsx +56 -6
  22. package/src/admin/editor/panels/LeftPanel.tsx +153 -29
  23. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  24. package/src/admin/editor/panels/SiteStylesDrawer.tsx +5 -0
  25. package/src/admin/editor/panels/TemplatesPanel.tsx +205 -0
  26. package/src/admin/editor/panels/TokenScales.tsx +2 -0
  27. package/src/admin/editor/panels/TriggersEditor.tsx +203 -9
  28. package/src/admin/editor/panels/VariableSection.tsx +111 -7
  29. package/src/admin/editor/panels/color-space.ts +71 -6
  30. package/src/admin/editor/panels/settings/AudienceEditor.tsx +3 -0
  31. package/src/admin/editor/panels/settings/FieldControl.tsx +18 -0
  32. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +9 -3
  33. package/src/admin/editor/panels/settings/StickyControl.tsx +97 -0
  34. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -0
  35. package/src/admin/editor/panels/settings/style-sections.ts +19 -2
  36. package/src/admin/editor/panels/url-rules.ts +43 -0
  37. package/src/admin/editor/panels/use-layers-drop.ts +232 -0
  38. package/src/admin/editor/store.ts +4 -2
  39. package/src/admin/editor/useExtensions.ts +3 -1
  40. package/src/admin/editor/useNodeActions.ts +74 -1
  41. package/src/admin/editor/useSave.ts +116 -85
  42. package/src/admin/export-api.ts +25 -2
  43. package/src/admin/extension-outputs.ts +179 -0
  44. package/src/admin/font-files-api.ts +38 -0
  45. package/src/admin/pages/ImportButton.tsx +15 -4
  46. package/src/admin/pages/ImportElementorDialog.tsx +22 -188
  47. package/src/admin/pages/ImportHtmlDialog.tsx +209 -0
  48. package/src/admin/pages/ImportImageCopies.tsx +167 -0
  49. package/src/admin/pages/ImportReport.tsx +63 -0
  50. package/src/admin/pages/NewPageDialog.tsx +54 -32
  51. package/src/admin/pages/PageList.tsx +9 -0
  52. package/src/admin/pages/ThemePartList.tsx +9 -0
  53. package/src/astro/EmVBPage.astro +5 -2
  54. package/src/astro/extension-styles.ts +35 -0
  55. package/src/astro/forms/EmVBFormsClient.astro +3 -0
  56. package/src/astro/forms/enhance.ts +107 -0
  57. package/src/astro/popups/runtime.ts +47 -2
  58. package/src/astro/render.ts +19 -4
  59. package/src/astro/resolve-theme.ts +11 -4
  60. package/src/astro/widgets/EmVBStickyRuntime.astro +9 -0
  61. package/src/astro/widgets/EmVBThemeRuntime.astro +9 -0
  62. package/src/astro/widgets/EmVBWidgetRuntimes.astro +12 -0
  63. package/src/astro/widgets/alerts.ts +16 -2
  64. package/src/astro/widgets/carousel.ts +65 -24
  65. package/src/astro/widgets/countdown.ts +18 -7
  66. package/src/astro/widgets/extension-runtimes.ts +27 -0
  67. package/src/astro/widgets/headline.ts +14 -5
  68. package/src/astro/widgets/sticky.ts +87 -0
  69. package/src/astro/widgets/theme.ts +52 -0
  70. package/src/constants.ts +1 -1
  71. package/src/core/a11y/audit.ts +150 -2
  72. package/src/core/arrange.ts +19 -1
  73. package/src/core/css/font-face.ts +72 -0
  74. package/src/core/css/generate.ts +35 -1
  75. package/src/core/elements/form-elements.ts +119 -9
  76. package/src/core/elements/icon-svg.ts +14 -0
  77. package/src/core/elements/index.ts +24 -4
  78. package/src/core/elements/input-limits.ts +44 -0
  79. package/src/core/elements/menu.ts +109 -47
  80. package/src/core/elements/site.ts +108 -0
  81. package/src/core/elements/widgets.ts +13 -3
  82. package/src/core/export/runtimes.generated.ts +7 -5
  83. package/src/core/export/site.ts +50 -4
  84. package/src/core/extensions/classes.ts +114 -0
  85. package/src/core/extensions/index.ts +17 -2
  86. package/src/core/extensions/normalize.ts +13 -0
  87. package/src/core/extensions/registry.ts +134 -10
  88. package/src/core/extensions/render-ext.ts +66 -21
  89. package/src/core/extensions/safe-nodes.ts +67 -11
  90. package/src/core/extensions/types.ts +48 -1
  91. package/src/core/fonts/files.ts +74 -0
  92. package/src/core/fonts/google.ts +112 -0
  93. package/src/core/fonts/test-font.ts +9 -0
  94. package/src/core/import/elementor/context.ts +13 -4
  95. package/src/core/import/elementor/index.ts +32 -21
  96. package/src/core/import/elementor/widgets.ts +114 -12
  97. package/src/core/import/html/blocks.ts +602 -0
  98. package/src/core/import/html/index.ts +155 -0
  99. package/src/core/import/html/map.ts +958 -0
  100. package/src/core/import/html/parse.ts +430 -0
  101. package/src/core/index.ts +45 -0
  102. package/src/core/migrate/v18.ts +3 -0
  103. package/src/core/public-attributes.ts +17 -0
  104. package/src/core/render/extras.ts +31 -7
  105. package/src/core/render/form.ts +103 -10
  106. package/src/core/render/index.ts +151 -15
  107. package/src/core/render/section.ts +31 -1
  108. package/src/core/render/spacer-basis.ts +102 -0
  109. package/src/core/render/theme-boot.ts +16 -0
  110. package/src/core/render/vnode.ts +1 -1
  111. package/src/core/sanitize/css.ts +68 -3
  112. package/src/core/sanitize/motion.ts +12 -0
  113. package/src/core/schema/design.ts +40 -0
  114. package/src/core/schema/layout.ts +114 -5
  115. package/src/core/schema/style.ts +28 -0
  116. package/src/core/templates/index.ts +218 -0
  117. package/src/core/templates/pages.ts +29 -0
  118. package/src/core/templates/sections.ts +794 -0
  119. package/src/core/templates/types.ts +9 -0
  120. package/src/core/theme/dynamic.ts +9 -6
  121. package/src/core/theme/popup-markup.ts +21 -2
  122. package/src/core/theme/popup-rules.ts +36 -0
  123. package/src/core/theme/triggers.ts +64 -5
  124. package/src/core/translatable.ts +5 -2
  125. package/src/extension-build.ts +331 -0
  126. package/src/index.ts +25 -3
  127. package/src/mcp/brief.ts +191 -0
  128. package/src/mcp/prompts.ts +33 -0
  129. package/src/mcp/read.ts +29 -1
  130. package/src/mcp/tools.ts +40 -1
  131. package/src/mcp/write.ts +41 -1
  132. package/src/server/extension-routes.ts +73 -0
  133. package/src/server/font-routes.ts +301 -0
  134. package/src/server/plugin.ts +9 -0
@@ -3,7 +3,6 @@ import { FileArrowUpIcon } from "@phosphor-icons/react";
3
3
  import * as React from "react";
4
4
  import {
5
5
  type ElementorImport,
6
- type ImportNote,
7
6
  importElementor,
8
7
  mergeSectionClasses,
9
8
  remapClassIds,
@@ -15,7 +14,6 @@ import {
15
14
  import { THEME_PARTS_COLLECTION } from "../../constants.ts";
16
15
  import { ApiError, type Fetcher } from "../api.ts";
17
16
  import { createPage, listPages, type PageSummary } from "../content-api.ts";
18
- import { uploadImage } from "../media-api.ts";
19
17
  import { loadSiteMenus } from "../menus-api.ts";
20
18
  import type { MenuLink } from "../../core/import/elementor/context.ts";
21
19
  import { editorUrl } from "../editor/exit.ts";
@@ -25,6 +23,8 @@ import { saveDesign } from "../design-api.ts";
25
23
  import { loadDesign } from "../editor/useEditorData.ts";
26
24
  import { BUTTON, FIELD } from "../ui.ts";
27
25
  import { CreateDialog } from "./CreateDialog.tsx";
26
+ import { ImportReport } from "./ImportReport.tsx";
27
+ import { type Copy, fileNameOf, ImportImageCopies } from "./ImportImageCopies.tsx";
28
28
  import {
29
29
  ImportPageLinks,
30
30
  type PageLinks,
@@ -43,61 +43,24 @@ function loadIcons(): Promise<IconMap> {
43
43
  );
44
44
  }
45
45
 
46
- const GROUPS: { kind: ImportNote["kind"]; title: string }[] = [
47
- { kind: "unmapped", title: "Not recognised" },
48
- { kind: "skipped", title: "Left out" },
49
- { kind: "approximated", title: "Changed to fit EmVB" },
50
- ];
51
-
52
- /** What the import will do, before anything is created. */
53
- function ImportReport({
46
+ /** The Elementor report: Elementor elements, and the fonts the page uses. */
47
+ function ElementorReport({
54
48
  result,
55
49
  partType,
56
50
  }: {
57
51
  result: ElementorImport | undefined;
58
52
  partType?: ThemePartType;
59
53
  }) {
60
- if (!result) return null;
61
- if (!result.ok) {
62
- return (
63
- <p className="emvb-inline-error" role="alert" data-emvb-import-error="">
64
- {result.error}
65
- </p>
66
- );
67
- }
54
+ const summary = result?.ok
55
+ ? `Ready to import ${result.mapped} of ${result.elements} Elementor elements` +
56
+ (partType ? ` as a ${THEME_PART_TYPE_LABELS[partType].toLowerCase()}.` : ".")
57
+ : "";
68
58
  return (
69
- <section
70
- className="emvb-import-report"
71
- aria-label="Import report"
72
- // The report can be long; it scrolls on its own and must be reachable by keyboard.
73
- tabIndex={0}
74
- data-emvb-import-report=""
75
- >
76
- <p className="emvb-import-summary" role="status">
77
- {`Ready to import ${result.mapped} of ${result.elements} Elementor elements`}
78
- {partType ? ` as a ${THEME_PART_TYPE_LABELS[partType].toLowerCase()}.` : "."}
79
- </p>
80
- {result.fonts.length > 0 && (
59
+ <ImportReport result={result} summary={summary}>
60
+ {result?.ok && result.fonts.length > 0 && (
81
61
  <p className="emvb-helper">{`Fonts used: ${result.fonts.join(", ")}. Make sure your site loads them.`}</p>
82
62
  )}
83
- {GROUPS.map(({ kind, title }) => {
84
- const notes = result.notes.filter((note) => note.kind === kind);
85
- if (notes.length === 0) return null;
86
- return (
87
- <details key={kind} open={kind !== "approximated"} data-emvb-import-group={kind}>
88
- <summary>{`${title} (${notes.length})`}</summary>
89
- <ul>
90
- {notes.map((note) => (
91
- <li key={`${note.element}:${note.message}`}>
92
- <strong>{note.element}:</strong> {note.message}
93
- {note.count > 1 ? ` (${note.count}×)` : ""}
94
- </li>
95
- ))}
96
- </ul>
97
- </details>
98
- );
99
- })}
100
- </section>
63
+ </ImportReport>
101
64
  );
102
65
  }
103
66
 
@@ -106,16 +69,6 @@ const MAX_SVG_FILE = 65_536;
106
69
  /** Files fetched in one go; an export with more names them in the report. */
107
70
  const MAX_SVG_FETCHES = 100;
108
71
 
109
- /** A URL's file name, decoded and lower-cased, to match a chosen file to the export's address (W-951, W-958). */
110
- export function fileNameOf(url: string): string {
111
- const last = url.split(/[?#]/)[0]?.split("/").pop() ?? "";
112
- try {
113
- return decodeURIComponent(last).toLowerCase();
114
- } catch {
115
- return last.toLowerCase();
116
- }
117
- }
118
-
119
72
  /** Fetches an SVG file without cookies; undefined when the site refuses (CORS) or it's too big. */
120
73
  async function fetchSvg(url: string): Promise<string | undefined> {
121
74
  try {
@@ -132,44 +85,6 @@ async function fetchSvg(url: string): Promise<string | undefined> {
132
85
  }
133
86
  }
134
87
 
135
- /** W-958: an image copied into the media library is at most this large. */
136
- const MAX_IMAGE_FILE = 20 * 1024 * 1024;
137
-
138
- /** Fetches an old-site image without cookies; undefined when refused (CORS), not an image or too big. */
139
- async function fetchImage(url: string): Promise<File | undefined> {
140
- try {
141
- const response = await fetch(url, {
142
- credentials: "omit",
143
- redirect: "follow",
144
- signal: AbortSignal.timeout(20_000),
145
- });
146
- if (!response.ok) return undefined;
147
- const blob = await response.blob();
148
- if (!blob.type.startsWith("image/") || blob.size > MAX_IMAGE_FILE) return undefined;
149
- return new File([blob], fileNameOf(url) || "image", { type: blob.type });
150
- } catch {
151
- return undefined;
152
- }
153
- }
154
-
155
- /** Runs `run` on every item, at most `limit` at a time. */
156
- async function eachLimited<T>(
157
- items: readonly T[],
158
- limit: number,
159
- run: (item: T) => Promise<void>,
160
- ): Promise<void> {
161
- let next = 0;
162
- const worker = async (): Promise<void> => {
163
- const index = next++;
164
- if (index >= items.length) return;
165
- await run(items[index] as T);
166
- return worker();
167
- };
168
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
169
- }
170
-
171
- type Copy = { url: string; id: string };
172
-
173
88
  /** Reads a chosen file as text, refusing one larger than the importer reads. */
174
89
  async function readJsonFile(file: File): Promise<string> {
175
90
  if (file.size > MAX_IMPORT_CHARS)
@@ -213,9 +128,8 @@ export function ImportElementorDialog({
213
128
  const [pages, setPages] = React.useState<PageSummary[]>();
214
129
  // W-958: old-site images copied into the media library, by their old address.
215
130
  const [copies, setCopies] = React.useState<ReadonlyMap<string, Copy>>(new Map());
216
- const [imageStatus, setImageStatus] = React.useState<string>();
217
- const [copying, setCopying] = React.useState(false);
218
- const imageRef = React.useRef<HTMLInputElement>(null);
131
+ // A new import starts the image copy row afresh (its status line and file input).
132
+ const [session, setSession] = React.useState(0);
219
133
  // W-1026: the site's own menus (from its WordPress import) for imported Nav Menus, by name.
220
134
  // A menu the site doesn't have is kept as no links, so it is asked for once.
221
135
  const [siteMenus, setSiteMenus] = React.useState<ReadonlyMap<string, MenuLink[]>>(new Map());
@@ -240,7 +154,7 @@ export function ImportElementorDialog({
240
154
  setSvgStatus(undefined);
241
155
  setPageLinks(readPageLinks());
242
156
  setCopies(new Map());
243
- setImageStatus(undefined);
157
+ setSession((n) => n + 1);
244
158
  setSiteMenus(new Map());
245
159
  }
246
160
  }
@@ -279,54 +193,6 @@ export function ImportElementorDialog({
279
193
  const linkedPages = result?.ok ? result.pageLinks : [];
280
194
  const oldImages = result?.ok ? result.images.filter((url) => !copies.has(url)) : [];
281
195
 
282
- const upload = async (url: string, file: File, done: [string, Copy][]) => {
283
- try {
284
- const item = await uploadImage(fetcher, file);
285
- done.push([url, { url: item.url, id: item.id }]);
286
- } catch {
287
- // Counted as not copied below.
288
- }
289
- };
290
-
291
- const copyImages = async () => {
292
- setCopying(true);
293
- const done: [string, Copy][] = [];
294
- const urls = [...oldImages];
295
- await eachLimited(urls, 4, async (url) => {
296
- const file = await fetchImage(url);
297
- if (file) await upload(url, file, done);
298
- });
299
- setCopies((current) => new Map([...current, ...done]));
300
- const failed = urls.length - done.length;
301
- setImageStatus(
302
- failed === 0
303
- ? `Copied ${done.length} ${done.length === 1 ? "image" : "images"} to the media library.`
304
- : `Copied ${done.length} of ${urls.length}. The rest couldn't be read from your old site from here: download them from its media library and add them with Add image files.`,
305
- );
306
- setCopying(false);
307
- };
308
-
309
- const addImages = async (files: readonly File[]) => {
310
- setCopying(true);
311
- const wanted = new Map(oldImages.map((url) => [fileNameOf(url), url]));
312
- const usable = (file: File) =>
313
- file.size <= MAX_IMAGE_FILE &&
314
- file.type.startsWith("image/") &&
315
- wanted.has(file.name.toLowerCase());
316
- const unused = files.filter((file) => !usable(file)).map((file) => file.name);
317
- const done: [string, Copy][] = [];
318
- await eachLimited(files.filter(usable), 4, (file) =>
319
- upload(wanted.get(file.name.toLowerCase()) ?? "", file, done),
320
- );
321
- setCopies((current) => new Map([...current, ...done]));
322
- setImageStatus(
323
- `Copied ${done.length} ${done.length === 1 ? "image" : "images"} to the media library.` +
324
- (unused.length > 0
325
- ? ` Not used (not in this export, not an image, or over 20 MB): ${unused.join(", ")}.`
326
- : ""),
327
- );
328
- setCopying(false);
329
- };
330
196
  // W-1026: fetch each menu the export's Nav Menus name once; the import re-runs with them.
331
197
  const wantedMenus = (result?.ok ? result.menus : []).filter((name) => !siteMenus.has(name));
332
198
  const wantedKey = wantedMenus.join("\u0000");
@@ -612,45 +478,13 @@ export function ImportElementorDialog({
612
478
  />
613
479
  </div>
614
480
  )}
615
- {(oldImages.length > 0 || imageStatus) && (
616
- <div className="emvb-import-row" data-emvb-import-images="">
617
- <Button
618
- type="button"
619
- variant="secondary"
620
- className={BUTTON}
621
- disabled={copying || oldImages.length === 0}
622
- onClick={() => void copyImages()}
623
- >
624
- {copying ? "Copying…" : "Copy images"}
625
- </Button>
626
- <Button
627
- type="button"
628
- variant="secondary"
629
- className={BUTTON}
630
- disabled={copying || oldImages.length === 0}
631
- onClick={() => imageRef.current?.click()}
632
- >
633
- Add image files
634
- </Button>
635
- <span className="emvb-helper" role="status">
636
- {imageStatus ??
637
- `${oldImages.length} ${oldImages.length === 1 ? "image loads" : "images load"} from your old site. Copy them to your media library (copies stay there even if you don't import), or add the files.`}
638
- </span>
639
- <input
640
- ref={imageRef}
641
- type="file"
642
- accept="image/*"
643
- multiple
644
- hidden
645
- data-emvb-elementor-images=""
646
- onChange={(event) => {
647
- const files = [...(event.target.files ?? [])];
648
- event.target.value = "";
649
- if (files.length > 0) void addImages(files);
650
- }}
651
- />
652
- </div>
653
- )}
481
+ <ImportImageCopies
482
+ key={session}
483
+ fetcher={fetcher}
484
+ images={oldImages}
485
+ onCopied={(done) => setCopies((current) => new Map([...current, ...done]))}
486
+ dataAttribute="data-emvb-elementor-images"
487
+ />
654
488
  <ImportPageLinks
655
489
  ids={linkedPages}
656
490
  links={pageLinks}
@@ -686,7 +520,7 @@ export function ImportElementorDialog({
686
520
  ))}
687
521
  </Select>
688
522
  )}
689
- <ImportReport result={result} {...(target === "part" ? { partType } : {})} />
523
+ <ElementorReport result={result} {...(target === "part" ? { partType } : {})} />
690
524
  </div>
691
525
  </CreateDialog>
692
526
  );
@@ -0,0 +1,209 @@
1
+ import { Button, Select } from "@cloudflare/kumo";
2
+ import { FileArrowUpIcon } from "@phosphor-icons/react";
3
+ import * as React from "react";
4
+ import {
5
+ importHtml,
6
+ MAX_HTML_IMPORT_CHARS,
7
+ THEME_PART_TYPE_LABELS,
8
+ THEME_PART_TYPES,
9
+ type ThemePartType,
10
+ } from "../../core/index.ts";
11
+ import { THEME_PARTS_COLLECTION } from "../../constants.ts";
12
+ import { ApiError, type Fetcher } from "../api.ts";
13
+ import { createPage } from "../content-api.ts";
14
+ import { editorUrl } from "../editor/exit.ts";
15
+ import { createThemePart } from "../theme-api.ts";
16
+ import { BUTTON, FIELD } from "../ui.ts";
17
+ import { CreateDialog } from "./CreateDialog.tsx";
18
+ import { type Copy, ImportImageCopies } from "./ImportImageCopies.tsx";
19
+ import { ImportReport } from "./ImportReport.tsx";
20
+
21
+ /** Reads a chosen file as text, refusing one larger than the importer reads. */
22
+ async function readHtmlFile(file: File): Promise<string> {
23
+ if (file.size > MAX_HTML_IMPORT_CHARS)
24
+ throw new Error("This file is larger than 4 MB. Import one page at a time.");
25
+ return file.text();
26
+ }
27
+
28
+ /**
29
+ * Import HTML (W-1074): paste a WordPress post's block markup (Code editor) or choose or paste
30
+ * any HTML page, see what will be kept, changed or left out, then create a draft page (or theme
31
+ * part) and open it. Nothing is fetched from an address: the person pastes or uploads it.
32
+ */
33
+ export function ImportHtmlDialog({
34
+ fetcher,
35
+ open,
36
+ onOpenChange,
37
+ target,
38
+ }: {
39
+ fetcher: Fetcher;
40
+ open: boolean;
41
+ onOpenChange: (open: boolean) => void;
42
+ target: "page" | "part";
43
+ }) {
44
+ const [html, setHtml] = React.useState("");
45
+ const [fileName, setFileName] = React.useState<string>();
46
+ const [fileError, setFileError] = React.useState<string>();
47
+ const [partType, setPartType] = React.useState<ThemePartType>("section");
48
+ const [copies, setCopies] = React.useState<ReadonlyMap<string, Copy>>(new Map());
49
+ const [session, setSession] = React.useState(0);
50
+ const fileRef = React.useRef<HTMLInputElement>(null);
51
+
52
+ const [wasOpen, setWasOpen] = React.useState(open);
53
+ if (open !== wasOpen) {
54
+ setWasOpen(open);
55
+ if (open) {
56
+ setHtml("");
57
+ setFileName(undefined);
58
+ setFileError(undefined);
59
+ setPartType("section");
60
+ setCopies(new Map());
61
+ setSession((n) => n + 1);
62
+ }
63
+ }
64
+
65
+ const run = React.useCallback(
66
+ () => importHtml(html, { media: (url: string) => copies.get(url) }),
67
+ [html, copies],
68
+ );
69
+ const result = React.useMemo(() => (html.trim() ? run() : undefined), [html, run]);
70
+ const oldImages = result?.ok ? result.images.filter((url) => !copies.has(url)) : [];
71
+
72
+ const create = async (title: string, slug: string) => {
73
+ const imported = html.trim() ? run() : undefined;
74
+ if (!imported?.ok) {
75
+ throw new ApiError(
76
+ 400,
77
+ "IMPORT_EMPTY",
78
+ imported ? imported.error : "Choose or paste some HTML first.",
79
+ );
80
+ }
81
+ if (target === "part") {
82
+ const id = await createThemePart(fetcher, { title, slug, partType, layout: imported.layout });
83
+ return editorUrl(id, THEME_PARTS_COLLECTION);
84
+ }
85
+ return editorUrl(await createPage(fetcher, { title, slug, layout: imported.layout }));
86
+ };
87
+
88
+ return (
89
+ <CreateDialog
90
+ name="import-html"
91
+ heading="Import from WordPress or HTML"
92
+ noun={target === "part" ? "theme part" : "page"}
93
+ emptyTitle="Enter a title."
94
+ slugPrefix={target === "part" ? `${partType}-` : ""}
95
+ slugHint={
96
+ target === "part"
97
+ ? "Tells theme parts apart. Theme parts have no public address."
98
+ : "The page's address on your site."
99
+ }
100
+ submitLabel="Import"
101
+ open={open}
102
+ onOpenChange={onOpenChange}
103
+ create={create}
104
+ {...(result?.ok && result.title ? { suggestedTitle: result.title } : {})}
105
+ >
106
+ <div className="emvb-import-source">
107
+ <p className="emvb-helper">
108
+ From WordPress, open the post or page, switch to the Code editor (⋮ → Code editor) and
109
+ copy everything. Or choose an .html file, or paste any page&apos;s source. You see what
110
+ will be kept before anything is created.
111
+ </p>
112
+ <div className="emvb-import-row">
113
+ <Button
114
+ type="button"
115
+ variant="secondary"
116
+ className={BUTTON}
117
+ icon={<FileArrowUpIcon aria-hidden="true" />}
118
+ onClick={() => fileRef.current?.click()}
119
+ >
120
+ Choose file
121
+ </Button>
122
+ <span className="emvb-helper" data-emvb-import-file="">
123
+ {fileName ?? "No file chosen"}
124
+ </span>
125
+ <input
126
+ ref={fileRef}
127
+ type="file"
128
+ accept="text/html,.html,.htm,text/plain,.txt"
129
+ hidden
130
+ data-emvb-html-file=""
131
+ onChange={(event) => {
132
+ const file = event.target.files?.[0];
133
+ event.target.value = "";
134
+ if (!file) return;
135
+ setFileError(undefined);
136
+ readHtmlFile(file).then(
137
+ (text) => {
138
+ setFileName(file.name);
139
+ setHtml(text);
140
+ },
141
+ (failure: unknown) =>
142
+ setFileError(
143
+ failure instanceof Error ? failure.message : "Couldn't read that file.",
144
+ ),
145
+ );
146
+ }}
147
+ />
148
+ </div>
149
+ {fileError && (
150
+ <p className="emvb-inline-error" role="alert">
151
+ {fileError}
152
+ </p>
153
+ )}
154
+ <label htmlFor="emvb-import-html" className="emvb-import-label">
155
+ Or paste the HTML
156
+ </label>
157
+ <textarea
158
+ id="emvb-import-html"
159
+ className={`${FIELD} emvb-import-json`}
160
+ rows={4}
161
+ spellCheck={false}
162
+ value={html}
163
+ placeholder="<!-- wp:paragraph --><p>…</p><!-- /wp:paragraph -->"
164
+ onChange={(event) => {
165
+ setFileName(undefined);
166
+ setHtml(event.target.value);
167
+ }}
168
+ />
169
+ <ImportImageCopies
170
+ key={session}
171
+ fetcher={fetcher}
172
+ images={oldImages}
173
+ onCopied={(done) => setCopies((current) => new Map([...current, ...done]))}
174
+ dataAttribute="data-emvb-html-images"
175
+ />
176
+ {target === "part" && (
177
+ <Select
178
+ label="Type"
179
+ className={FIELD}
180
+ value={partType}
181
+ onValueChange={(value) =>
182
+ setPartType(THEME_PART_TYPES.find((type) => type === value) ?? "section")
183
+ }
184
+ renderValue={(value: unknown) =>
185
+ THEME_PART_TYPE_LABELS[value as ThemePartType] ?? String(value)
186
+ }
187
+ >
188
+ {THEME_PART_TYPES.map((type) => (
189
+ <Select.Option key={type} value={type}>
190
+ {THEME_PART_TYPE_LABELS[type]}
191
+ </Select.Option>
192
+ ))}
193
+ </Select>
194
+ )}
195
+ <ImportReport
196
+ result={result}
197
+ summary={
198
+ result?.ok
199
+ ? `Ready to import ${result.mapped} of ${result.elements} ${result.source === "wordpress" ? "WordPress blocks" : "HTML elements"}` +
200
+ (target === "part"
201
+ ? ` as a ${THEME_PART_TYPE_LABELS[partType].toLowerCase()}.`
202
+ : ".")
203
+ : ""
204
+ }
205
+ />
206
+ </div>
207
+ </CreateDialog>
208
+ );
209
+ }
@@ -0,0 +1,167 @@
1
+ import { Button } from "@cloudflare/kumo";
2
+ import * as React from "react";
3
+ import type { Fetcher } from "../api.ts";
4
+ import { uploadImage } from "../media-api.ts";
5
+ import { BUTTON } from "../ui.ts";
6
+
7
+ /** An old-site image's copy in the media library. */
8
+ export type Copy = { url: string; id: string };
9
+
10
+ /** A URL's file name, decoded and lower-cased, to match a chosen file to the export's address (W-951, W-958). */
11
+ export function fileNameOf(url: string): string {
12
+ const last = url.split(/[?#]/)[0]?.split("/").pop() ?? "";
13
+ try {
14
+ return decodeURIComponent(last).toLowerCase();
15
+ } catch {
16
+ return last.toLowerCase();
17
+ }
18
+ }
19
+
20
+ /** W-958: an image copied into the media library is at most this large. */
21
+ const MAX_IMAGE_FILE = 20 * 1024 * 1024;
22
+
23
+ /** Fetches an old-site image without cookies; undefined when refused (CORS), not an image or too big. */
24
+ async function fetchImage(url: string): Promise<File | undefined> {
25
+ try {
26
+ const response = await fetch(url, {
27
+ credentials: "omit",
28
+ redirect: "follow",
29
+ signal: AbortSignal.timeout(20_000),
30
+ });
31
+ if (!response.ok) return undefined;
32
+ const blob = await response.blob();
33
+ if (!blob.type.startsWith("image/") || blob.size > MAX_IMAGE_FILE) return undefined;
34
+ return new File([blob], fileNameOf(url) || "image", { type: blob.type });
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ /** Runs `run` on every item, at most `limit` at a time. */
41
+ async function eachLimited<T>(
42
+ items: readonly T[],
43
+ limit: number,
44
+ run: (item: T) => Promise<void>,
45
+ ): Promise<void> {
46
+ let next = 0;
47
+ const worker = async (): Promise<void> => {
48
+ const index = next++;
49
+ if (index >= items.length) return;
50
+ await run(items[index] as T);
51
+ return worker();
52
+ };
53
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
54
+ }
55
+
56
+ /**
57
+ * W-958 (shared with W-1074): the import dialogs' **Copy images** row. The browser fetches each
58
+ * old-site image (without cookies) and uploads it to the media library; images the old site
59
+ * won't let it read can be added as files, matched by file name. Nothing is fetched by the server.
60
+ */
61
+ export function ImportImageCopies({
62
+ fetcher,
63
+ images,
64
+ onCopied,
65
+ dataAttribute,
66
+ }: {
67
+ fetcher: Fetcher;
68
+ /** Old-site image addresses not copied yet. */
69
+ images: readonly string[];
70
+ onCopied: (done: [string, Copy][]) => void;
71
+ /** Marks the hidden file input for tests (`data-emvb-elementor-images`, …). */
72
+ dataAttribute: string;
73
+ }) {
74
+ const [status, setStatus] = React.useState<string>();
75
+ const [copying, setCopying] = React.useState(false);
76
+ const inputRef = React.useRef<HTMLInputElement>(null);
77
+
78
+ const upload = async (url: string, file: File, done: [string, Copy][]) => {
79
+ try {
80
+ const item = await uploadImage(fetcher, file);
81
+ done.push([url, { url: item.url, id: item.id }]);
82
+ } catch {
83
+ // Counted as not copied below.
84
+ }
85
+ };
86
+
87
+ const copyImages = async () => {
88
+ setCopying(true);
89
+ const done: [string, Copy][] = [];
90
+ const urls = [...images];
91
+ await eachLimited(urls, 4, async (url) => {
92
+ const file = await fetchImage(url);
93
+ if (file) await upload(url, file, done);
94
+ });
95
+ onCopied(done);
96
+ const failed = urls.length - done.length;
97
+ setStatus(
98
+ failed === 0
99
+ ? `Copied ${done.length} ${done.length === 1 ? "image" : "images"} to the media library.`
100
+ : `Copied ${done.length} of ${urls.length}. The rest couldn't be read from your old site from here: download them from its media library and add them with Add image files.`,
101
+ );
102
+ setCopying(false);
103
+ };
104
+
105
+ const addImages = async (files: readonly File[]) => {
106
+ setCopying(true);
107
+ const wanted = new Map(images.map((url) => [fileNameOf(url), url]));
108
+ const usable = (file: File) =>
109
+ file.size <= MAX_IMAGE_FILE &&
110
+ file.type.startsWith("image/") &&
111
+ wanted.has(file.name.toLowerCase());
112
+ const unused = files.filter((file) => !usable(file)).map((file) => file.name);
113
+ const done: [string, Copy][] = [];
114
+ await eachLimited(files.filter(usable), 4, (file) =>
115
+ upload(wanted.get(file.name.toLowerCase()) ?? "", file, done),
116
+ );
117
+ onCopied(done);
118
+ setStatus(
119
+ `Copied ${done.length} ${done.length === 1 ? "image" : "images"} to the media library.` +
120
+ (unused.length > 0
121
+ ? ` Not used (not in this export, not an image, or over 20 MB): ${unused.join(", ")}.`
122
+ : ""),
123
+ );
124
+ setCopying(false);
125
+ };
126
+
127
+ if (images.length === 0 && !status) return null;
128
+ return (
129
+ <div className="emvb-import-row" data-emvb-import-images="">
130
+ <Button
131
+ type="button"
132
+ variant="secondary"
133
+ className={BUTTON}
134
+ disabled={copying || images.length === 0}
135
+ onClick={() => void copyImages()}
136
+ >
137
+ {copying ? "Copying…" : "Copy images"}
138
+ </Button>
139
+ <Button
140
+ type="button"
141
+ variant="secondary"
142
+ className={BUTTON}
143
+ disabled={copying || images.length === 0}
144
+ onClick={() => inputRef.current?.click()}
145
+ >
146
+ Add image files
147
+ </Button>
148
+ <span className="emvb-helper" role="status">
149
+ {status ??
150
+ `${images.length} ${images.length === 1 ? "image loads" : "images load"} from your old site. Copy them to your media library (copies stay there even if you don't import), or add the files.`}
151
+ </span>
152
+ <input
153
+ ref={inputRef}
154
+ type="file"
155
+ accept="image/*"
156
+ multiple
157
+ hidden
158
+ {...{ [dataAttribute]: "" }}
159
+ onChange={(event) => {
160
+ const files = [...(event.target.files ?? [])];
161
+ event.target.value = "";
162
+ if (files.length > 0) void addImages(files);
163
+ }}
164
+ />
165
+ </div>
166
+ );
167
+ }