@perkyzz/emvb 1.0.0 → 1.1.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 (80) hide show
  1. package/README.md +9 -0
  2. package/package.json +2 -2
  3. package/src/admin/bulk-api.ts +67 -0
  4. package/src/admin/content-api.ts +10 -6
  5. package/src/admin/copy-rich-text.ts +119 -0
  6. package/src/admin/dialog-tab-wrap.ts +78 -0
  7. package/src/admin/editor/A11yCopilot.tsx +2 -0
  8. package/src/admin/editor/Editor.tsx +18 -6
  9. package/src/admin/editor/Timeline.tsx +6 -2
  10. package/src/admin/editor/TopBar.tsx +27 -7
  11. package/src/admin/editor/canvas/CanvasFrame.tsx +7 -2
  12. package/src/admin/editor/canvas/DeviceBar.tsx +22 -9
  13. package/src/admin/editor/canvas/canvas-scale.ts +3 -3
  14. package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
  15. package/src/admin/editor/dnd/new-element.ts +22 -0
  16. package/src/admin/editor/editor-chrome.tsx +7 -5
  17. package/src/admin/editor/editor-commands.ts +10 -4
  18. package/src/admin/editor/editor-css.ts +2 -1
  19. package/src/admin/editor/panels/ElementPanel.tsx +29 -16
  20. package/src/admin/editor/panels/SettingsPanel.tsx +2 -2
  21. package/src/admin/editor/panels/settings/EffectsControls.tsx +79 -1
  22. package/src/admin/editor/panels/settings/IconControls.tsx +11 -0
  23. package/src/admin/editor/panels/settings/LengthRow.tsx +36 -3
  24. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +18 -0
  25. package/src/admin/editor/panels/settings/StyleRow.tsx +7 -0
  26. package/src/admin/editor/panels/settings/length-units.ts +15 -3
  27. package/src/admin/editor/panels/settings/style-sections.ts +1 -0
  28. package/src/admin/editor/panels/style-target.ts +17 -4
  29. package/src/admin/editor/section-templates.ts +26 -4
  30. package/src/admin/editor/store.ts +8 -2
  31. package/src/admin/editor/useEditorCommands.ts +7 -5
  32. package/src/admin/editor/useNodeActions.ts +4 -2
  33. package/src/admin/export-api.ts +221 -0
  34. package/src/admin/index.tsx +6 -1
  35. package/src/admin/pages/ExportDialog.tsx +395 -0
  36. package/src/admin/pages/PageList.tsx +67 -2
  37. package/src/admin/pages/ThemePartList.tsx +37 -1
  38. package/src/admin/pages/bulk.tsx +303 -0
  39. package/src/admin/search.ts +20 -0
  40. package/src/admin/theme-api.ts +4 -0
  41. package/src/admin/ui.ts +11 -2
  42. package/src/admin/widgets/CanvasField.tsx +8 -0
  43. package/src/admin/widgets/ConvertToRichText.tsx +136 -0
  44. package/src/admin/widgets/ExportEntryHtml.tsx +92 -0
  45. package/src/admin/widgets/convert-body.ts +73 -2
  46. package/src/astro/render.ts +6 -6
  47. package/src/astro/resolve-theme.ts +11 -7
  48. package/src/astro/tabs/runtime.ts +16 -6
  49. package/src/constants.ts +1 -1
  50. package/src/core/a11y/audit.ts +2 -1
  51. package/src/core/contract.ts +22 -2
  52. package/src/core/css/generate.ts +83 -21
  53. package/src/core/css/scope.ts +10 -2
  54. package/src/core/css/trace.ts +33 -8
  55. package/src/core/design/classes.ts +25 -5
  56. package/src/core/design/devices.ts +78 -2
  57. package/src/core/design/variables.ts +14 -1
  58. package/src/core/export/runtimes.generated.ts +9 -0
  59. package/src/core/export/site.ts +562 -0
  60. package/src/core/export/zip.ts +95 -0
  61. package/src/core/history/diff.ts +25 -0
  62. package/src/core/import/elementor/atomic.ts +22 -9
  63. package/src/core/import/elementor/index.ts +22 -4
  64. package/src/core/import/elementor/style.ts +21 -1
  65. package/src/core/index.ts +14 -0
  66. package/src/core/json-schema.ts +8 -1
  67. package/src/core/perf/meter.ts +37 -19
  68. package/src/core/portable-text-export.ts +243 -0
  69. package/src/core/public-attributes.ts +30 -0
  70. package/src/core/render/index.ts +88 -9
  71. package/src/core/render/tabs.ts +18 -11
  72. package/src/core/sanitize/css.ts +26 -0
  73. package/src/core/schema/design.ts +2 -2
  74. package/src/core/schema/layout.ts +11 -3
  75. package/src/core/schema/style.ts +47 -0
  76. package/src/core/search-text.ts +70 -0
  77. package/src/core/theme/float.ts +1 -0
  78. package/src/core/theme/popup-rules.ts +16 -0
  79. package/src/mcp/read.ts +2 -3
  80. package/src/server/icon-routes.ts +52 -12
@@ -721,9 +721,10 @@ function convert(props: Settings, snap: AtomicSnapshots, ctx: ImportContext): Co
721
721
  return out;
722
722
  }
723
723
 
724
- const DEVICE_OF: Record<string, "desktop" | "laptop" | "tablet" | "mobile"> = {
724
+ const DEVICE_OF: Record<string, "wide" | "desktop" | "laptop" | "tablet" | "mobile"> = {
725
725
  desktop: "desktop",
726
- widescreen: "desktop",
726
+ // W-959: EmVB has a Wide screen device (2400 px and up), like Elementor's.
727
+ widescreen: "wide",
727
728
  // W-956: EmVB has a Laptop device (up to 1366 px), like Elementor's.
728
729
  laptop: "laptop",
729
730
  tablet_extra: "tablet",
@@ -746,7 +747,7 @@ type AtomicStyle = {
746
747
  style: Style;
747
748
  devices: { laptop?: Style; tablet?: Style; mobile?: Style };
748
749
  states: { hover?: Style; focus?: Style; active?: Style };
749
- display: { desktop?: string; laptop?: string; tablet?: string; mobile?: string };
750
+ display: { wide?: string; desktop?: string; laptop?: string; tablet?: string; mobile?: string };
750
751
  columns: { desktop?: number; tablet?: number; mobile?: number };
751
752
  tracks: { desktop?: string[]; tablet?: string[]; mobile?: string[] };
752
753
  fullRow: boolean;
@@ -917,7 +918,8 @@ function atomicStyle(
917
918
  /** W-958: only these classes, without Elementor's base styles (a class's own look). */
918
919
  only?: readonly ClassDef[],
919
920
  ): AtomicStyle {
920
- const layers: Record<"desktop" | "laptop" | "tablet" | "mobile", Style> = {
921
+ const layers: Record<"wide" | "desktop" | "laptop" | "tablet" | "mobile", Style> = {
922
+ wide: {},
921
923
  desktop: {},
922
924
  laptop: {},
923
925
  tablet: {},
@@ -954,7 +956,7 @@ function atomicStyle(
954
956
  unsupported.add(`${breakpoint} breakpoint`);
955
957
  continue;
956
958
  }
957
- if (breakpoint !== device) folded = true;
959
+ if (breakpoint !== device && breakpoint !== "widescreen") folded = true;
958
960
  const converted = convert(isRecord(variant.props) ? variant.props : {}, snap, ctx);
959
961
  if (variant.custom_css) {
960
962
  const raw = isRecord(variant.custom_css) ? variant.custom_css["raw"] : undefined;
@@ -985,7 +987,9 @@ function atomicStyle(
985
987
  if (converted.columns && device === "laptop") {
986
988
  // EmVB's grid columns have no laptop value: laptops keep the desktop columns.
987
989
  unsupported.add("grid columns for laptops (laptops use the desktop columns)");
988
- } else if (converted.columns && device !== "laptop") {
990
+ } else if (converted.columns && device === "wide") {
991
+ unsupported.add("grid columns for wide screens (wide screens use the desktop columns)");
992
+ } else if (converted.columns && device !== "laptop" && device !== "wide") {
989
993
  columns[device] = converted.columns;
990
994
  if (converted.tracks) tracks[device] = converted.tracks;
991
995
  else delete tracks[device];
@@ -995,7 +999,7 @@ function atomicStyle(
995
999
  ctx.note(
996
1000
  "approximated",
997
1001
  "Breakpoints",
998
- "Extra breakpoints were folded into Tablet and Mobile, and Widescreen into Desktop.",
1002
+ "Extra breakpoints were folded into Tablet and Mobile.",
999
1003
  );
1000
1004
  if (Object.keys(phoneFromFluid).length > 0 && !quiet) {
1001
1005
  ctx.note(
@@ -1007,8 +1011,10 @@ function atomicStyle(
1007
1011
  for (const what of quiet ? [] : unsupported) {
1008
1012
  ctx.note("approximated", name, `Left out a style EmVB has no setting for: ${what}.`);
1009
1013
  }
1010
- for (const layer of [layers.desktop, layers.laptop, layers.tablet, layers.mobile])
1014
+ for (const layer of [layers.wide, layers.desktop, layers.laptop, layers.tablet, layers.mobile])
1011
1015
  finishBorders(layer);
1016
+ // W-959: Wide screen values build on Desktop's and sit in the style's `wide` record.
1017
+ const wideScreen = changedKeys(layers.desktop, layers.wide);
1012
1018
  const mobile = { ...narrowFromWidth, ...phoneFromFluid, ...layers.mobile };
1013
1019
  const laptop = changedKeys(layers.desktop, layers.laptop);
1014
1020
  const wide = { ...layers.desktop, ...laptop };
@@ -1029,7 +1035,8 @@ function atomicStyle(
1029
1035
  tracks[device] = Array.from({ length: count }, () => "1fr");
1030
1036
  wider = tracks[device] ?? wider;
1031
1037
  }
1032
- return { style: layers.desktop, devices, states: statesOut, display, columns, tracks, fullRow };
1038
+ const style = isEmptyStyle(wideScreen) ? layers.desktop : { ...layers.desktop, wide: wideScreen };
1039
+ return { style, devices, states: statesOut, display, columns, tracks, fullRow };
1033
1040
  }
1034
1041
 
1035
1042
  // ---------------------------------------------------------------------------------------------
@@ -1130,6 +1137,12 @@ function applyStyle(n: N, s: AtomicStyle): N {
1130
1137
  (d) => shown[d] === "none",
1131
1138
  );
1132
1139
  if (hidden.length > 0) n["hiddenOn"] = hidden;
1140
+ // W-959: a widescreen display that hides or shows unlike Desktop.
1141
+ if (s.display.wide !== undefined && (s.display.wide === "none") !== hidden.includes("desktop")) {
1142
+ const style = { ...(n["style"] as Style | undefined) };
1143
+ style["wide"] = { ...(style["wide"] as Style | undefined), hidden: s.display.wide === "none" };
1144
+ n["style"] = style;
1145
+ }
1133
1146
  return n;
1134
1147
  }
1135
1148
 
@@ -19,8 +19,11 @@ import {
19
19
  deviceStyles,
20
20
  entrance,
21
21
  flexReader,
22
+ type Device,
22
23
  hiddenOn,
24
+ mergeStyles,
23
25
  type Style,
26
+ wideHidden,
24
27
  widthReader,
25
28
  } from "./style.ts";
26
29
  import { isRecord, num, type Settings, slider, str } from "./values.ts";
@@ -318,6 +321,12 @@ class Walker {
318
321
  }
319
322
  const hidden = hiddenOn(s);
320
323
  if (hidden) target["hiddenOn"] = hidden;
324
+ const wide = wideHidden(s);
325
+ if (wide !== undefined) {
326
+ const style = { ...(target["style"] as Style | undefined) };
327
+ style["wide"] = { ...(style["wide"] as Style | undefined), hidden: wide };
328
+ target["style"] = style;
329
+ }
321
330
  const id = str(s["_element_id"]) ?? str(s["css_id"]);
322
331
  if (id) {
323
332
  if (isValidHtmlId(id) && !ctx.htmlIds.has(id) && !target["htmlId"]) {
@@ -566,7 +575,7 @@ class Walker {
566
575
  const layoutDevices = layoutDs.devices;
567
576
 
568
577
  if (!boxed) {
569
- const style = { ...outerStyle, ...innerStyle };
578
+ const style = mergeStyles(outerStyle, innerStyle);
570
579
  const n = grid
571
580
  ? node(
572
581
  ctx,
@@ -582,6 +591,14 @@ class Walker {
582
591
  const boxedWidth = slider(s["boxed_width"]) ?? { value: 1140, unit: "px" as const };
583
592
  const minHeight = innerStyle["minHeight"];
584
593
  delete innerStyle["minHeight"];
594
+ // W-959: and its Wide screen min height, like the other devices' below.
595
+ const innerWide = innerStyle["wide"] as Style | undefined;
596
+ if (innerWide && "minHeight" in innerWide) {
597
+ const { minHeight: wideMin, ...rest } = innerWide;
598
+ outerStyle["wide"] = { ...(outerStyle["wide"] as Style | undefined), minHeight: wideMin };
599
+ if (Object.keys(rest).length > 0) innerStyle["wide"] = rest;
600
+ else delete innerStyle["wide"];
601
+ }
585
602
  const inner = grid
586
603
  ? node(ctx, "grid", gridProps(columns), {
587
604
  style: {
@@ -610,8 +627,9 @@ class Walker {
610
627
  );
611
628
  // Min height belongs to the outer box on every device, as on desktop.
612
629
  const outerDevices = { ...outerDs.devices };
613
- const innerDevices: { tablet?: Style; mobile?: Style } = {};
614
- for (const key of ["tablet", "mobile"] as const) {
630
+ const innerDevices: { laptop?: Style; tablet?: Style; mobile?: Style } = {};
631
+ // W-956: Laptop's layout values (direction, gap) go to the inner box too; they were dropped.
632
+ for (const key of ["laptop", "tablet", "mobile"] as const) {
615
633
  const layout = layoutDevices?.[key];
616
634
  if (!layout) continue;
617
635
  const { minHeight: deviceMin, ...rest } = layout;
@@ -705,7 +723,7 @@ function verticalOf(style: Style, grid: boolean): string {
705
723
  }
706
724
 
707
725
  /** Grid gaps and minimum height per device (column counts are props, see gridColumns). */
708
- const gridReader = (s: Settings, d: "" | "_laptop" | "_tablet" | "_mobile"): Style => {
726
+ const gridReader = (s: Settings, d: Device): Style => {
709
727
  const style: Style = {};
710
728
  const gaps = s[`grid_gaps${d}`];
711
729
  const gap = isRecord(gaps)
@@ -25,7 +25,7 @@ import {
25
25
  } from "./values.ts";
26
26
 
27
27
  export type Style = Record<string, unknown>;
28
- export type Device = "" | "_laptop" | "_tablet" | "_mobile";
28
+ export type Device = "" | "_widescreen" | "_laptop" | "_tablet" | "_mobile";
29
29
 
30
30
  /** Reads one device's style from a widget's settings. */
31
31
  export type Reader = (s: Settings, d: Device, ctx: ImportContext, el: string) => Style;
@@ -39,6 +39,8 @@ export function deviceStyles(
39
39
  ): { style?: Style; devices?: { laptop?: Style; tablet?: Style; mobile?: Style } } {
40
40
  const read = (d: Device) => Object.assign({}, ...readers.map((r) => r(s, d, ctx, el))) as Style;
41
41
  const desktop = read("");
42
+ // W-959: Elementor's widescreen values (`key_widescreen`), on Desktop's, in `style.wide`.
43
+ const wide = changedKeys(desktop, read("_widescreen"));
42
44
  // W-956: Elementor's laptop values (`key_laptop`), between desktop and tablet.
43
45
  const laptop = changedKeys(desktop, read("_laptop"));
44
46
  const tablet = changedKeys({ ...desktop, ...laptop }, read("_tablet"));
@@ -47,6 +49,7 @@ export function deviceStyles(
47
49
  if (!isEmptyStyle(laptop)) devices.laptop = laptop;
48
50
  if (!isEmptyStyle(tablet)) devices.tablet = tablet;
49
51
  if (!isEmptyStyle(mobile)) devices.mobile = mobile;
52
+ if (!isEmptyStyle(wide)) desktop["wide"] = wide;
50
53
  return {
51
54
  ...(isEmptyStyle(desktop) ? {} : { style: desktop }),
52
55
  ...(Object.keys(devices).length > 0 ? { devices } : {}),
@@ -398,6 +401,23 @@ export function entrance(s: Settings, ctx: ImportContext, el: string): Style | u
398
401
  * without Elementor's laptop breakpoint (no `hide_laptop` setting) hides "desktop" from 1025 px,
399
402
  * laptops included.
400
403
  */
404
+ /**
405
+ * W-959: `hide_widescreen` when the site has Elementor's widescreen breakpoint and it hides or
406
+ * shows unlike Desktop (`style.wide.hidden`); undefined when Wide screen follows Desktop.
407
+ */
408
+ export function wideHidden(s: Settings): boolean | undefined {
409
+ if (!("hide_widescreen" in s)) return undefined;
410
+ const wide = !!str(s["hide_widescreen"]);
411
+ return wide === !!str(s["hide_desktop"]) ? undefined : wide;
412
+ }
413
+
414
+ /** Two styles one after the other; their Wide screen records merge too (W-959). */
415
+ export function mergeStyles(a: Style | undefined, b: Style | undefined): Style {
416
+ const out: Style = { ...a, ...b };
417
+ if (isRecord(a?.["wide"]) && isRecord(b?.["wide"])) out["wide"] = { ...a["wide"], ...b["wide"] };
418
+ return out;
419
+ }
420
+
401
421
  export function hiddenOn(s: Settings): ("desktop" | "laptop" | "tablet" | "mobile")[] | undefined {
402
422
  const out: ("desktop" | "laptop" | "tablet" | "mobile")[] = [];
403
423
  const laptopActive = "hide_laptop" in s;
package/src/core/index.ts CHANGED
@@ -93,6 +93,7 @@ export {
93
93
  plainTextOf,
94
94
  withPlainText,
95
95
  } from "./elements/plain-text.ts";
96
+ export { layoutSearchText } from "./search-text.ts";
96
97
  export {
97
98
  StyleProps,
98
99
  FlatStyleProps,
@@ -100,6 +101,8 @@ export {
100
101
  type StylePatch,
101
102
  StyleStates,
102
103
  DeviceStyles,
104
+ OwnStyle,
105
+ WideStyle,
103
106
  HiddenOn,
104
107
  ColorValue,
105
108
  Length,
@@ -217,13 +220,20 @@ export {
217
220
  type ImportLosses,
218
221
  } from "./design/transfer.ts";
219
222
  export {
223
+ hiddenOnDevice,
224
+ hiddenOnEveryDevice,
220
225
  patchClassDevices,
226
+ patchClassWide,
221
227
  patchDeviceStyle,
228
+ patchWideStyle,
222
229
  toggleHidden,
230
+ toggleHiddenOn,
231
+ wideHideIsOwn,
223
232
  type ResponsiveDevice,
224
233
  } from "./design/devices.ts";
225
234
  export {
226
235
  renderPage,
236
+ sharedPartCss,
227
237
  type RenderMode,
228
238
  type RenderResult,
229
239
  type RenderWarning,
@@ -379,6 +389,10 @@ export {
379
389
  POPUP_DEVICES,
380
390
  DEVICES,
381
391
  type Device,
392
+ EDITOR_DEVICES,
393
+ type EditorDevice,
394
+ WIDE_MIN_PX,
395
+ WIDE_PREVIEW_PX,
382
396
  STYLE_DEVICES,
383
397
  type StyleDevice,
384
398
  DEVICE_MEDIA,
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { DESIGN_SCHEMA_VERSION, DesignSystem } from "./schema/design.ts";
3
3
  import { CONTRACT_VERSION, KNOWN_NODE_SCHEMAS, LAYOUT_SCHEMA_VERSION } from "./schema/layout.ts";
4
- import { DeviceStyles, StyleProps, StyleStates } from "./schema/style.ts";
4
+ import { DeviceStyles, OwnStyle, StyleProps, StyleStates, WideStyle } from "./schema/style.ts";
5
5
 
6
6
  /**
7
7
  * JSON Schema (2020-12) exports of the stored formats (W-925, contract 1.0). They describe the
@@ -46,8 +46,15 @@ function styleDefs(): { defs: Json; shared: Map<string, string> } {
46
46
  states: withRefs(states, inner),
47
47
  devices: withRefs(devices, inner),
48
48
  };
49
+ // W-959: an element's or class's own style carries `wide`, the Wide screen record.
50
+ const wide = toJson(WideStyle);
51
+ const own = toJson(OwnStyle);
52
+ defs["wideStyle"] = wide;
53
+ defs["ownStyle"] = withRefs(own, new Map([[JSON.stringify(wide), "wideStyle"]]));
49
54
  const shared = new Map([
50
55
  ...inner,
56
+ [JSON.stringify(own), "ownStyle"],
57
+ [JSON.stringify(wide), "wideStyle"],
51
58
  [JSON.stringify(states), "states"],
52
59
  [JSON.stringify(devices), "devices"],
53
60
  ]);
@@ -74,15 +74,16 @@ const isPlayerEmbed = (node: LayoutNode): boolean => {
74
74
  return typeof url === "string" && resolveEmbedUrl(url)?.kind === "iframe";
75
75
  };
76
76
 
77
+ type Weight = { images: number; bytes: number; embeds: number };
78
+ const zero = (): Weight => ({ images: 0, bytes: 0, embeds: 0 });
79
+ const add = (a: Weight, b: Weight) => {
80
+ a.images += b.images;
81
+ a.bytes += b.bytes;
82
+ a.embeds += b.embeds;
83
+ };
84
+
77
85
  /** Images and embeds under a node, with their estimated weight. */
78
- function media(
79
- node: LayoutNode,
80
- bgClasses: Set<string>,
81
- dynamic?: ThemeDynamicData,
82
- ): { images: number; bytes: number; embeds: number } {
83
- let images = 0;
84
- let bytes = 0;
85
- let embeds = 0;
86
+ function media(node: LayoutNode, bgClasses: Set<string>, dynamic?: ThemeDynamicData): Weight {
86
87
  const seen = new Set<Layout>();
87
88
  /** W-671: a synced section or Loop Item part the canvas loaded is weighed with the page. */
88
89
  const part = (n: LayoutNode): Layout | undefined => {
@@ -97,30 +98,47 @@ function media(
97
98
  seen.add(found);
98
99
  return found;
99
100
  };
100
- const walk = (n: LayoutNode): void => {
101
+ // W-973: a visitor sees one arm of an A/B test, so only the heavier arm's media count.
102
+ const arms = new Map<string, Map<string, Weight>>();
103
+ const walk = (n: LayoutNode): Weight => {
104
+ const own = zero();
101
105
  const template = part(n);
102
- if (template) walk(template.root);
106
+ if (template) add(own, walk(template.root));
103
107
  if (n.type === "image" || n.type === "post-image") {
104
108
  const src = (n.props as { src?: unknown }).src;
105
109
  if (n.type === "post-image" || (typeof src === "string" && src.trim())) {
106
- images += 1;
107
- bytes += imageBytes(n);
110
+ own.images += 1;
111
+ own.bytes += imageBytes(n);
108
112
  }
109
113
  }
110
114
  if (hasBackgroundImage(n, bgClasses)) {
111
- images += 1;
112
- bytes += IMAGE_GUESS;
115
+ own.images += 1;
116
+ own.bytes += IMAGE_GUESS;
113
117
  }
114
118
  // W-508: only a YouTube or Vimeo player is a third-party embed; a media-library video loads
115
119
  // its metadata only, and a missing or refused URL renders nothing.
116
120
  if (n.type === "video" && isPlayerEmbed(n)) {
117
- embeds += 1;
118
- bytes += EMBED_BYTES;
121
+ own.embeds += 1;
122
+ own.bytes += EMBED_BYTES;
119
123
  }
120
- if (isParentNode(n)) for (const child of n.children) walk(child);
124
+ if (isParentNode(n)) for (const child of n.children) add(own, walk(child));
125
+ const variant = n.variant;
126
+ if (variant) {
127
+ const test = arms.get(variant.test) ?? new Map<string, Weight>();
128
+ const arm = test.get(variant.arm) ?? zero();
129
+ add(arm, own);
130
+ test.set(variant.arm, arm);
131
+ arms.set(variant.test, test);
132
+ return zero();
133
+ }
134
+ return own;
121
135
  };
122
- walk(node);
123
- return { images, bytes, embeds };
136
+ const total = walk(node);
137
+ for (const test of arms.values()) {
138
+ const heaviest = [...test.values()].reduce((a, b) => (b.bytes > a.bytes ? b : a), zero());
139
+ add(total, heaviest);
140
+ }
141
+ return total;
124
142
  }
125
143
 
126
144
  const kb = (bytes: number) => `${Math.round(bytes / 1000)} KB`;
@@ -0,0 +1,243 @@
1
+ // oxlint-disable no-underscore-dangle -- Portable Text names its fields _type, _key and _ref.
2
+ import type { Layout, LayoutNode, TextMark } from "./schema/layout.ts";
3
+ import { nodeChildren } from "./tree-ops.ts";
4
+ import { sanitizeUrl } from "./sanitize/url.ts";
5
+
6
+ /**
7
+ * W-963: the reverse of Convert to EmVB. A layout becomes EmDash rich text (Portable Text): the
8
+ * words, headings, lists, links and images, in reading order, without the design. What can't be
9
+ * rich text (forms, embeds, icons, dividers, loops) is counted by type, never guessed at.
10
+ */
11
+
12
+ type Span = { _type: "span"; _key: string; text: string; marks: string[] };
13
+ type LinkDef = { _type: "link"; _key: string; href: string; blank?: true };
14
+ export type PortableTextBlock =
15
+ | {
16
+ _type: "block";
17
+ _key: string;
18
+ style: string;
19
+ children: Span[];
20
+ markDefs: LinkDef[];
21
+ listItem?: "bullet" | "number";
22
+ level?: number;
23
+ }
24
+ | {
25
+ _type: "image";
26
+ _key: string;
27
+ asset: { url: string; _ref?: string };
28
+ alt?: string;
29
+ width?: number;
30
+ height?: number;
31
+ };
32
+
33
+ export type PortableTextExport = {
34
+ body: PortableTextBlock[];
35
+ /** Elements that became blocks. */
36
+ converted: number;
37
+ /** Elements left out, by element type (`form: 2`). */
38
+ skipped: Record<string, number>;
39
+ };
40
+
41
+ const LINK_SCHEMES: ReadonlySet<string> = new Set(["https:", "http:", "mailto:", "tel:"]);
42
+ const IMAGE_SCHEMES: ReadonlySet<string> = new Set(["https:", "http:"]);
43
+
44
+ /** Boxes whose children are read in order; they add nothing of their own. */
45
+ const BOXES = new Set([
46
+ "container",
47
+ "flexbox",
48
+ "grid",
49
+ "div",
50
+ "div-block",
51
+ "layout-section",
52
+ "accordion",
53
+ "tabs",
54
+ ]);
55
+
56
+ /** Leaves with no words (or nothing that rich text can hold), left out without a count. */
57
+ const QUIET = new Set(["spacer"]);
58
+
59
+ /** A relative site path is kept as is; anything else must be a safe absolute URL. */
60
+ function safeHref(raw: string | undefined, schemes = LINK_SCHEMES): string | undefined {
61
+ const href = raw?.trim();
62
+ if (!href) return undefined;
63
+ if (href.startsWith("/") && !href.startsWith("//")) return href;
64
+ if (href.startsWith("#")) return href;
65
+ return sanitizeUrl(href, schemes);
66
+ }
67
+
68
+ export function layoutToPortableText(
69
+ layout: Layout,
70
+ options: {
71
+ /** Synced section layouts by part id, so their words come across too. */
72
+ sectionTemplates?: Readonly<Record<string, Layout>>;
73
+ /** Stable keys for tests. */
74
+ key?: () => string;
75
+ } = {},
76
+ ): PortableTextExport {
77
+ let counter = 0;
78
+ const key = options.key ?? (() => `k${(counter++).toString(36)}`);
79
+ const body: PortableTextBlock[] = [];
80
+ const skipped: Record<string, number> = {};
81
+ let converted = 0;
82
+ const skip = (type: string) => {
83
+ skipped[type] = (skipped[type] ?? 0) + 1;
84
+ };
85
+
86
+ const block = (
87
+ text: string,
88
+ style = "normal",
89
+ marks: readonly TextMark[] = [],
90
+ whole?: { href: string; newTab?: boolean },
91
+ ) => {
92
+ const markDefs: LinkDef[] = [];
93
+ const linkKey = (href: string, newTab?: boolean) => {
94
+ const def: LinkDef = { _type: "link", _key: key(), href, ...(newTab ? { blank: true } : {}) };
95
+ markDefs.push(def);
96
+ return def._key;
97
+ };
98
+ const wholeKey = whole ? linkKey(whole.href, whole.newTab) : undefined;
99
+ const usable = marks.filter((m) => m.end > m.start && m.start < text.length);
100
+ const cuts = new Set([0, text.length]);
101
+ for (const m of usable) {
102
+ cuts.add(Math.min(m.start, text.length));
103
+ cuts.add(Math.min(m.end, text.length));
104
+ }
105
+ const points = [...cuts].toSorted((a, b) => a - b);
106
+ const markKeys = new Map<TextMark, string>();
107
+ const children: Span[] = [];
108
+ for (let i = 0; i < points.length - 1; i += 1) {
109
+ const from = points[i] ?? 0;
110
+ const to = points[i + 1] ?? 0;
111
+ if (to <= from) continue;
112
+ const names: string[] = wholeKey ? [wholeKey] : [];
113
+ for (const m of usable) {
114
+ if (m.start > from || m.end < to) continue;
115
+ if (m.bold) names.push("strong");
116
+ if (m.italic) names.push("em");
117
+ const href = wholeKey ? undefined : safeHref(m.href);
118
+ if (href) {
119
+ let k = markKeys.get(m);
120
+ if (!k) {
121
+ k = linkKey(href, m.newTab);
122
+ markKeys.set(m, k);
123
+ }
124
+ names.push(k);
125
+ }
126
+ }
127
+ children.push({ _type: "span", _key: key(), text: text.slice(from, to), marks: names });
128
+ }
129
+ if (children.length === 0) children.push({ _type: "span", _key: key(), text: "", marks: [] });
130
+ body.push({ _type: "block", _key: key(), style, children, markDefs });
131
+ };
132
+
133
+ const visit = (node: LayoutNode, seen: ReadonlySet<string>) => {
134
+ // An A/B test's B element repeats what A says; A is kept.
135
+ if (node.variant?.arm === "b") {
136
+ skip("A/B test variant");
137
+ return;
138
+ }
139
+ const props = (node.props ?? {}) as Record<string, unknown>;
140
+ const text = typeof props["text"] === "string" ? props["text"].trim() : "";
141
+ const marks = Array.isArray(props["marks"]) ? (props["marks"] as TextMark[]) : [];
142
+ switch (node.type) {
143
+ case "heading": {
144
+ if (!text) return;
145
+ const href = safeHref(props["href"] as string | undefined);
146
+ block(
147
+ text,
148
+ `h${Number(props["level"]) || 2}`,
149
+ href ? [] : marks,
150
+ href ? { href, newTab: props["newTab"] === true } : undefined,
151
+ );
152
+ converted++;
153
+ return;
154
+ }
155
+ case "text":
156
+ case "label":
157
+ case "span": {
158
+ if (!text) return;
159
+ block(text, "normal", marks);
160
+ converted++;
161
+ return;
162
+ }
163
+ case "link":
164
+ case "button": {
165
+ if (!text) return;
166
+ const href = safeHref(props["href"] as string | undefined);
167
+ block(text, "normal", [], href ? { href, newTab: props["newTab"] === true } : undefined);
168
+ converted++;
169
+ return;
170
+ }
171
+ case "list": {
172
+ const items = Array.isArray(props["items"]) ? props["items"] : [];
173
+ const ordered =
174
+ props["ordered"] === true ||
175
+ (typeof props["marker"] === "string" &&
176
+ !["disc", "circle", "square", "none"].includes(props["marker"]));
177
+ let any = false;
178
+ for (const item of items) {
179
+ if (typeof item !== "string" || !item.trim()) continue;
180
+ block(item.trim());
181
+ const last = body.at(-1);
182
+ if (last?._type === "block") {
183
+ last.listItem = ordered ? "number" : "bullet";
184
+ last.level = 1;
185
+ }
186
+ any = true;
187
+ }
188
+ if (any) converted++;
189
+ return;
190
+ }
191
+ case "image": {
192
+ const src = safeHref(props["src"] as string | undefined, IMAGE_SCHEMES);
193
+ if (!src) {
194
+ skip("image");
195
+ return;
196
+ }
197
+ const alt = typeof props["alt"] === "string" ? props["alt"] : "";
198
+ const mediaId = typeof props["mediaId"] === "string" ? props["mediaId"] : undefined;
199
+ body.push({
200
+ _type: "image",
201
+ _key: key(),
202
+ asset: { url: src, ...(mediaId ? { _ref: mediaId } : {}) },
203
+ ...(alt && props["decorative"] !== true ? { alt } : {}),
204
+ ...(typeof props["width"] === "number" ? { width: props["width"] } : {}),
205
+ ...(typeof props["height"] === "number" ? { height: props["height"] } : {}),
206
+ });
207
+ converted++;
208
+ if (typeof props["caption"] === "string" && props["caption"].trim())
209
+ block(props["caption"].trim());
210
+ return;
211
+ }
212
+ case "accordion-item":
213
+ case "tab-panel": {
214
+ const title = node.type === "accordion-item" ? props["summary"] : props["label"];
215
+ if (typeof title === "string" && title.trim()) {
216
+ block(title.trim(), "h3");
217
+ converted++;
218
+ }
219
+ for (const child of nodeChildren(node)) visit(child, seen);
220
+ return;
221
+ }
222
+ case "part-ref": {
223
+ const partId = typeof props["partId"] === "string" ? props["partId"] : "";
224
+ const synced = options.sectionTemplates?.[partId];
225
+ if (synced && !seen.has(partId)) {
226
+ visit(synced.root, new Set([...seen, partId]));
227
+ return;
228
+ }
229
+ for (const child of nodeChildren(node)) visit(child, seen);
230
+ return;
231
+ }
232
+ default: {
233
+ if (BOXES.has(node.type)) {
234
+ for (const child of nodeChildren(node)) visit(child, seen);
235
+ return;
236
+ }
237
+ if (!QUIET.has(node.type)) skip(node.type);
238
+ }
239
+ }
240
+ };
241
+ visit(layout.root, new Set());
242
+ return { body, converted, skipped };
243
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The `data-emvb-*` attributes public HTML may carry: hooks a public runtime or host reads, never
3
+ * editor state. docs/system/layout-format.md ("Rendered output") lists the same names; a test
4
+ * keeps the two in step. Editor attributes such as `data-emvb-id` never reach public output.
5
+ */
6
+ export const PUBLIC_DATA_ATTRIBUTES: readonly string[] = [
7
+ "data-emvb-theme-part",
8
+ "data-emvb-loop-item",
9
+ "data-emvb-popup",
10
+ "data-emvb-popup-config",
11
+ "data-emvb-popup-dismiss",
12
+ "data-emvb-float",
13
+ "data-emvb-float-dismiss",
14
+ "data-emvb-float-edge",
15
+ ];
16
+
17
+ /**
18
+ * The `data-emvb-*` attribute names on the tags of `html` (not inside `<style>` or `<script>`)
19
+ * that aren't public hooks, each once.
20
+ */
21
+ export function editorAttributesIn(html: string): string[] {
22
+ const tags = html.replace(/<(style|script)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
23
+ const found = new Set<string>();
24
+ for (const tag of tags.match(/<[a-z][^>]*>/gi) ?? []) {
25
+ for (const [, name] of tag.matchAll(/\s(data-emvb-[a-z0-9-]+)(?=[\s=>/])/gi)) {
26
+ if (name && !PUBLIC_DATA_ATTRIBUTES.includes(name)) found.add(name);
27
+ }
28
+ }
29
+ return [...found];
30
+ }