@perkyzz/emvb 0.2.1 → 0.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 (150) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +3 -1
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/api.ts +17 -7
  6. package/src/admin/content-api.ts +7 -51
  7. package/src/admin/content-item.ts +22 -0
  8. package/src/admin/design-api.ts +30 -0
  9. package/src/admin/editor/A11yCopilot.tsx +126 -0
  10. package/src/admin/editor/CommandPalette.tsx +118 -0
  11. package/src/admin/editor/Editor.tsx +188 -152
  12. package/src/admin/editor/EditorOverlay.tsx +9 -1
  13. package/src/admin/editor/PerfMeter.tsx +121 -0
  14. package/src/admin/editor/ShareLink.tsx +164 -0
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +287 -0
  17. package/src/admin/editor/TopBar.tsx +4 -0
  18. package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
  19. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  20. package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
  21. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  22. package/src/admin/editor/canvas/drop-line.ts +24 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  24. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  25. package/src/admin/editor/collection-previews.ts +114 -0
  26. package/src/admin/editor/editor-chrome.tsx +346 -0
  27. package/src/admin/editor/editor-commands.ts +360 -0
  28. package/src/admin/editor/editor-css.ts +5 -3
  29. package/src/admin/editor/element-chrome.ts +89 -0
  30. package/src/admin/editor/feature-css.ts +105 -0
  31. package/src/admin/editor/host.ts +35 -0
  32. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  33. package/src/admin/editor/icons/library.ts +29 -19
  34. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  35. package/src/admin/editor/live-data.tsx +71 -0
  36. package/src/admin/editor/palette-items.ts +136 -0
  37. package/src/admin/editor/palette.ts +68 -0
  38. package/src/admin/editor/panels/AddPanel.tsx +48 -68
  39. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  40. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  41. package/src/admin/editor/panels/ElementPanel.tsx +74 -102
  42. package/src/admin/editor/panels/LayersPanel.tsx +72 -63
  43. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  44. package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
  45. package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
  46. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  47. package/src/admin/editor/panels/VariableSection.tsx +10 -14
  48. package/src/admin/editor/panels/inline-error.tsx +11 -0
  49. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  50. package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -0
  51. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  52. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  53. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  54. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  55. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  56. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  57. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  58. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  59. package/src/admin/editor/panels/settings/StyleRow.tsx +26 -2
  60. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  61. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  62. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  63. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  64. package/src/admin/editor/panels/settings/length-units.ts +16 -5
  65. package/src/admin/editor/panels/settings/style-sections.ts +7 -2
  66. package/src/admin/editor/panels/style-target.ts +105 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +6 -1
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +30 -14
  74. package/src/admin/editor/useNodeActions.ts +44 -16
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/theme-api.ts +5 -18
  78. package/src/admin/ui.ts +4 -4
  79. package/src/astro/content-port.ts +24 -0
  80. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  81. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  82. package/src/astro/forms/client.ts +1 -0
  83. package/src/astro/forms-definitions.ts +24 -11
  84. package/src/astro/index.ts +1 -0
  85. package/src/astro/render-session.ts +85 -0
  86. package/src/astro/request-data.ts +109 -0
  87. package/src/astro/resolve-theme.ts +184 -64
  88. package/src/astro/resolve.ts +63 -16
  89. package/src/astro/theme-posts.ts +48 -5
  90. package/src/astro/visitor.ts +204 -0
  91. package/src/constants.ts +1 -1
  92. package/src/core/a11y/audit.ts +282 -0
  93. package/src/core/arrange.ts +150 -34
  94. package/src/core/audience/rules.ts +124 -0
  95. package/src/core/audience/variants.ts +51 -0
  96. package/src/core/canvas-styles.ts +24 -0
  97. package/src/core/clipboard.ts +11 -32
  98. package/src/core/css/generate.ts +29 -2
  99. package/src/core/css/print.ts +12 -0
  100. package/src/core/css/scope.ts +3 -3
  101. package/src/core/css/trace.ts +169 -0
  102. package/src/core/css-keywords.ts +83 -0
  103. package/src/core/data/bindings.ts +255 -0
  104. package/src/core/design/classes.ts +13 -15
  105. package/src/core/design/diff.ts +55 -0
  106. package/src/core/design/merge.ts +127 -0
  107. package/src/core/design/tokens.ts +127 -0
  108. package/src/core/design/variables.ts +25 -21
  109. package/src/core/elements/dynamic-elements.ts +117 -2
  110. package/src/core/elements/form-elements.ts +1 -0
  111. package/src/core/elements/index.ts +185 -7
  112. package/src/core/forms/binding.ts +4 -13
  113. package/src/core/history/diff.ts +152 -0
  114. package/src/core/index.ts +121 -0
  115. package/src/core/local-style.ts +27 -0
  116. package/src/core/migrate/index.ts +12 -4
  117. package/src/core/nesting.ts +4 -22
  118. package/src/core/perf/meter.ts +160 -0
  119. package/src/core/perf/scripts.ts +61 -0
  120. package/src/core/recipes/index.ts +433 -0
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +1 -2
  124. package/src/core/render/form.ts +133 -10
  125. package/src/core/render/index.ts +206 -17
  126. package/src/core/render/loop.ts +54 -7
  127. package/src/core/render/pagination.ts +9 -1
  128. package/src/core/render/vnode.ts +12 -2
  129. package/src/core/sanitize/css.ts +129 -80
  130. package/src/core/sanitize/motion.ts +129 -0
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/design.ts +29 -8
  134. package/src/core/schema/layout.ts +291 -169
  135. package/src/core/schema/motion.ts +14 -0
  136. package/src/core/schema/style.ts +101 -66
  137. package/src/core/share/link.ts +187 -0
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +242 -32
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/theme/pagination.ts +56 -0
  142. package/src/core/tree-ops.ts +57 -0
  143. package/src/index.ts +14 -2
  144. package/src/server/design-routes.ts +4 -1
  145. package/src/server/icon-routes.ts +68 -16
  146. package/src/server/plugin.ts +8 -2
  147. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  148. package/src/admin/editor/icons/sets/lucide.json +0 -1
  149. package/src/admin/editor/icons/sets/remix.json +0 -1
  150. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -19,6 +19,7 @@ import {
19
19
  nodeChildren,
20
20
  removeNode,
21
21
  starterLayout,
22
+ updateNode,
22
23
  } from "./tree-ops.ts";
23
24
 
24
25
  /** A refused operation, with the reason shown or announced to the user (R-003). */
@@ -63,6 +64,7 @@ export const REASONS = {
63
64
  onlyAccordionItems: "An accordion can only hold accordion items.",
64
65
  itemOutsideMenu: "Menu items can only go inside a Menu.",
65
66
  onlyMenuItems: "A menu can only hold menu items.",
67
+ emptyOutsideLoop: "An Empty state can only go inside a Loop.",
66
68
  } as const;
67
69
 
68
70
  const refuse = (reason: string): Refusal => ({ ok: false, reason });
@@ -118,42 +120,37 @@ function underForm(layout: Layout, parentId: string): boolean {
118
120
 
119
121
  type Drop = { layout: Layout; node: LayoutNode; into: Located; isNew: boolean };
120
122
 
121
- /** Placement rules in the order their reasons take precedence (R-003, W-034, W-074). */
123
+ /**
124
+ * Parent/child rules shared by drag-and-drop and the save-time nesting check (W-354).
125
+ * `inForm` is true when `parent` is a form or sits inside one. Depth, count and tab caps stay
126
+ * in `canDrop`.
127
+ */
128
+ export function parentChildRefusal(
129
+ parent: LayoutNode,
130
+ child: LayoutNode,
131
+ inForm: boolean,
132
+ ): string | undefined {
133
+ if (child.type === "loop-empty" && parent.type !== "loop") return REASONS.emptyOutsideLoop;
134
+ if (child.type === "tab-panel" && parent.type !== "tabs") return REASONS.tabOutsideTabs;
135
+ if (parent.type === "tabs" && child.type !== "tab-panel") return REASONS.onlyTabPanels;
136
+ if (child.type === "accordion-item" && parent.type !== "accordion") {
137
+ return REASONS.itemOutsideAccordion;
138
+ }
139
+ if (parent.type === "accordion" && child.type !== "accordion-item") {
140
+ return REASONS.onlyAccordionItems;
141
+ }
142
+ if (child.type === "menu-item" && parent.type !== "menu" && parent.type !== "menu-item") {
143
+ return REASONS.itemOutsideMenu;
144
+ }
145
+ if (parent.type === "menu" && child.type !== "menu-item") return REASONS.onlyMenuItems;
146
+ if (isFormNode(child) && inForm) return REASONS.nestedForm;
147
+ if (isFormFieldType(child.type) && !inForm) return REASONS.fieldOutsideForm;
148
+ return undefined;
149
+ }
150
+
151
+ /** Caps and the form-into-a-leaf rule. Parent/child pairs are `parentChildRefusal`. */
122
152
  const DROP_RULES: [breaks: (drop: Drop) => boolean, reason: string][] = [
123
- [
124
- ({ node, into }) => node.type === "tab-panel" && into.node.type !== "tabs",
125
- REASONS.tabOutsideTabs,
126
- ],
127
- [
128
- ({ node, into }) => into.node.type === "tabs" && node.type !== "tab-panel",
129
- REASONS.onlyTabPanels,
130
- ],
131
- [
132
- ({ node, into }) => node.type === "accordion-item" && into.node.type !== "accordion",
133
- REASONS.itemOutsideAccordion,
134
- ],
135
- [
136
- ({ node, into }) => into.node.type === "accordion" && node.type !== "accordion-item",
137
- REASONS.onlyAccordionItems,
138
- ],
139
- [
140
- ({ node, into }) =>
141
- node.type === "menu-item" && into.node.type !== "menu" && into.node.type !== "menu-item",
142
- REASONS.itemOutsideMenu,
143
- ],
144
- [
145
- ({ node, into }) => into.node.type === "menu" && node.type !== "menu-item",
146
- REASONS.onlyMenuItems,
147
- ],
148
- [
149
- ({ node, into, layout }) => isFormNode(node) && underForm(layout, into.node.id),
150
- REASONS.nestedForm,
151
- ],
152
153
  [({ node, into }) => isFormNode(node) && !isLayoutParentNode(into.node), REASONS.formIntoField],
153
- [
154
- ({ node, into, layout }) => isFormFieldType(node.type) && !underForm(layout, into.node.id),
155
- REASONS.fieldOutsideForm,
156
- ],
157
154
  // A 13th panel would be stored but never shown (W-188); moving within the same Tabs is fine.
158
155
  [
159
156
  ({ node, into }) =>
@@ -190,6 +187,8 @@ export function canDrop(layout: Layout, source: DragSource, parentId: string): A
190
187
  const moving = dragged(layout, source, parentId);
191
188
  if (!moving.ok) return moving;
192
189
  if (!isParentNode(into.node)) return refuse(REASONS.notContainer);
190
+ const placed = parentChildRefusal(into.node, moving.node, underForm(layout, into.node.id));
191
+ if (placed) return refuse(placed);
193
192
  const drop: Drop = { layout, node: moving.node, into, isNew: source.kind === "new" };
194
193
  const broken = DROP_RULES.find(([breaks]) => breaks(drop));
195
194
  return broken ? refuse(broken[1]) : { ok: true };
@@ -304,6 +303,38 @@ export function duplicateNode(
304
303
  };
305
304
  }
306
305
 
306
+ export const WRAP_TYPES = ["container", "div-block", "flexbox", "grid"] as const;
307
+ export type WrapType = (typeof WRAP_TYPES)[number];
308
+
309
+ /**
310
+ * Puts `id` inside a new box at the same place, in one step. The root cannot be wrapped.
311
+ * The new box is selected so it is obvious on the canvas.
312
+ */
313
+ export function wrapNode(
314
+ layout: Layout,
315
+ id: string,
316
+ type: WrapType,
317
+ random: () => number = Math.random,
318
+ ): Arranged {
319
+ const found = locate(layout, id);
320
+ if (!found) return refuse(REASONS.missing);
321
+ if (!found.parent) return refuse(REASONS.rootFixed);
322
+ if (size(layout.root) + 1 > MAX_NODES) return refuse(REASONS.tooMany);
323
+ const { layout: without, removed } = removeNode(layout, id);
324
+ if (!removed) return refuse(REASONS.missing);
325
+ const wrapper: LayoutNode = {
326
+ id: newNodeId(random),
327
+ type,
328
+ props: type === "grid" ? { columns: 2 } : {},
329
+ children: [removed.node],
330
+ } as LayoutNode;
331
+ return {
332
+ ok: true,
333
+ layout: insertNode(without, found.parent.id, found.index, wrapper),
334
+ selected: wrapper.id,
335
+ };
336
+ }
337
+
307
338
  /** Where click-to-add puts a new element: into a selected container, after a selected element, or at the end. */
308
339
  export function insertionPoint(layout: Layout, selectedId: string | null): Place {
309
340
  const found = selectedId ? locate(layout, selectedId) : undefined;
@@ -349,6 +380,29 @@ export function addNodeNear(
349
380
  return tried;
350
381
  }
351
382
 
383
+ /**
384
+ * Adds a whole section (a W-320 recipe): right after the outermost Section the selection is in,
385
+ * so it never lands inside another Section; with no Section around the selection, like `addNodeNear`.
386
+ */
387
+ export function addSectionNear(
388
+ layout: Layout,
389
+ node: LayoutNode,
390
+ selectedId: string | null,
391
+ ): Added | Refusal {
392
+ let outer: Located | undefined;
393
+ for (let at = selectedId ? locate(layout, selectedId) : undefined; at;) {
394
+ if (at.node.type === "layout-section") outer = at;
395
+ at = at.parent ? locate(layout, at.parent.id) : undefined;
396
+ }
397
+ const at = outer;
398
+ if (at?.parent) {
399
+ const place = { parentId: at.parent.id, index: at.index + 1 };
400
+ const added = addNode(layout, node, place);
401
+ if (added.ok) return { ...added, parentId: place.parentId };
402
+ }
403
+ return addNodeNear(layout, node, selectedId);
404
+ }
405
+
352
406
  type Child = Located & { parent: NonNullable<Located["parent"]> };
353
407
 
354
408
  /** Moves a non-root element to where `place` says, or returns the first refusal. */
@@ -446,3 +500,65 @@ export function subtreeSize(layout: Layout, id: string): number {
446
500
  const node = findNode(layout, id);
447
501
  return node ? size(node) : 0;
448
502
  }
503
+
504
+ /** The default A/B test name for an element (W-312): `test-` and its id, lowercased. */
505
+ export const defaultTestName = (id: string): string =>
506
+ `test-${
507
+ id
508
+ .toLowerCase()
509
+ .replace(/[^a-z0-9]/g, "")
510
+ .slice(0, 12) || "1"
511
+ }`;
512
+
513
+ /**
514
+ * Edge A/B testing (W-312): the element becomes arm A of a new test and a copy right after it
515
+ * becomes arm B (selected, ready to edit). Visitors see one or the other, picked on the server.
516
+ */
517
+ export function createVariantB(
518
+ layout: Layout,
519
+ id: string,
520
+ random: () => number = Math.random,
521
+ ): Arranged {
522
+ const found = locate(layout, id);
523
+ if (!found) return refuse(REASONS.missing);
524
+ if (found.node.variant) return refuse("This element is already in an A/B test.");
525
+ if (found.node.type === "loop-empty" || !found.parent) return refuse(REASONS.rootCopy);
526
+ const variant = { test: defaultTestName(found.node.id), arm: "a" as const };
527
+ const marked = updateNode(layout, id, (node) => ({ ...node, variant }) as LayoutNode);
528
+ const copied = duplicateNode(marked, id, random);
529
+ if (!copied.ok) return copied;
530
+ return {
531
+ ...copied,
532
+ layout: updateNode(
533
+ copied.layout,
534
+ copied.selected,
535
+ (node) =>
536
+ ({
537
+ ...node,
538
+ variant: { ...variant, arm: "b" },
539
+ }) as LayoutNode,
540
+ ),
541
+ };
542
+ }
543
+
544
+ /**
545
+ * Ends an A/B test (W-312): `keepId` stays, without its variant mark, and every other element of
546
+ * that test is removed.
547
+ */
548
+ export function endAbTest(layout: Layout, keepId: string): Arranged {
549
+ const kept = locate(layout, keepId);
550
+ const test = kept?.node.variant?.test;
551
+ if (!kept || !test) return refuse(REASONS.missing);
552
+ const others: string[] = [];
553
+ const walk = (node: LayoutNode): void => {
554
+ if (node.id !== keepId && node.variant?.test === test) others.push(node.id);
555
+ else for (const child of nodeChildren(node)) walk(child);
556
+ };
557
+ walk(layout.root);
558
+ let next = updateNode(layout, keepId, (node) => {
559
+ const { variant: _variant, ...rest } = node;
560
+ return rest as LayoutNode;
561
+ });
562
+ for (const id of others) next = removeNode(next, id).layout;
563
+ return { ok: true, layout: next, selected: keepId };
564
+ }
@@ -0,0 +1,124 @@
1
+ import { type Audience, type Layout, type LayoutNode } from "../schema/layout.ts";
2
+ import { knownChildren, someNode } from "../tree-ops.ts";
3
+
4
+ /** What the host knows about this visitor (W-313). Anything unknown is left out. */
5
+ export type VisitorInfo = {
6
+ /** ISO 3166 two-letter code, uppercase. */
7
+ country?: string;
8
+ device?: "mobile" | "tablet" | "desktop";
9
+ returning?: boolean;
10
+ /** The request time, epoch ms. */
11
+ now?: number;
12
+ /** Segments the host says this visitor is in (W-329), e.g. member, pro. */
13
+ segments?: readonly string[];
14
+ };
15
+
16
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
17
+
18
+ /** Hour (0–23) and weekday (0 = Sunday) at `now` in a time zone; UTC when the zone is unknown. */
19
+ export function clockIn(now: number, timeZone: string | undefined): { hour: number; day: number } {
20
+ const read = (zone: string) => {
21
+ const parts = new Intl.DateTimeFormat("en-US", {
22
+ timeZone: zone,
23
+ hour: "numeric",
24
+ hourCycle: "h23",
25
+ weekday: "short",
26
+ }).formatToParts(new Date(now));
27
+ const hour = Number(parts.find((p) => p.type === "hour")?.value ?? "0") % 24;
28
+ const day = WEEKDAYS.indexOf(parts.find((p) => p.type === "weekday")?.value ?? "Sun");
29
+ return { hour, day: Math.max(0, day) };
30
+ };
31
+ try {
32
+ return read(timeZone ?? "UTC");
33
+ } catch {
34
+ return read("UTC");
35
+ }
36
+ }
37
+
38
+ function inHours(hour: number, from: number, to: number): boolean {
39
+ if (from === to) return true;
40
+ return from < to ? hour >= from && hour < to : hour >= from || hour < to;
41
+ }
42
+
43
+ /** Whether a visitor matches every rule in the audience (W-313); unknown facts don't match. */
44
+ function matches(audience: Audience, visitor: VisitorInfo): boolean {
45
+ if (audience.countries && !(visitor.country && audience.countries.includes(visitor.country))) {
46
+ return false;
47
+ }
48
+ if (audience.devices && !(visitor.device && audience.devices.includes(visitor.device))) {
49
+ return false;
50
+ }
51
+ if (audience.visitor) {
52
+ if (visitor.returning === undefined) return false;
53
+ if ((audience.visitor === "returning") !== visitor.returning) return false;
54
+ }
55
+ if (audience.segments) {
56
+ const has = new Set(visitor.segments ?? []);
57
+ if (!audience.segments.some((segment) => has.has(segment))) return false;
58
+ }
59
+ if (audience.hours || audience.days) {
60
+ if (visitor.now === undefined) return false;
61
+ const { hour, day } = clockIn(visitor.now, audience.timeZone);
62
+ if (audience.hours && !inHours(hour, audience.hours.from, audience.hours.to)) return false;
63
+ if (audience.days && !audience.days.includes(day)) return false;
64
+ }
65
+ return true;
66
+ }
67
+
68
+ /** Whether a node shows for this visitor (W-313). No audience = everyone. */
69
+ export function audienceShows(node: LayoutNode, visitor: VisitorInfo | undefined): boolean {
70
+ const audience = node.audience;
71
+ if (!audience) return true;
72
+ const match = matches(audience, visitor ?? {});
73
+ return audience.hide ? !match : match;
74
+ }
75
+
76
+ /** Does any element in the layout have an audience? Hosts then read the visitor (W-313). */
77
+ export function layoutUsesAudience(layout: Layout): boolean {
78
+ return hasAudience(layout.root);
79
+ }
80
+
81
+ /**
82
+ * A new/returning rule is the only reason to read or set the `emvb_seen` cookie.
83
+ * Country, device and segment rules do not.
84
+ */
85
+ export function layoutUsesVisitorRule(layout: Layout): boolean {
86
+ return hasVisitorRule(layout.root);
87
+ }
88
+
89
+ const hasAudience = (node: LayoutNode): boolean =>
90
+ someNode(node, (current) => Boolean(current.audience), knownChildren);
91
+
92
+ const hasVisitorRule = (node: LayoutNode): boolean =>
93
+ someNode(node, (current) => current.audience?.visitor !== undefined, knownChildren);
94
+
95
+ /** A device from a User-Agent and the Sec-CH-UA-Mobile hint (W-313). */
96
+ export function deviceFromUserAgent(
97
+ ua: string | null | undefined,
98
+ mobileHint?: string | null,
99
+ ): VisitorInfo["device"] {
100
+ if (mobileHint === "?1") return "mobile";
101
+ if (!ua) return mobileHint === "?0" ? "desktop" : undefined;
102
+ if (/iPad|Tablet|PlayBook|Silk|Kindle|(Android(?!.*Mobile))/i.test(ua)) return "tablet";
103
+ if (/Mobi|iPhone|iPod|Android|Windows Phone|Opera Mini/i.test(ua)) return "mobile";
104
+ return "desktop";
105
+ }
106
+
107
+ const DEVICE_LABELS = { mobile: "mobile", tablet: "tablet", desktop: "desktop" } as const;
108
+
109
+ /** A short summary for the canvas and Layers, e.g. "CA, US · mobile · returning" (W-313). */
110
+ export function audienceSummary(audience: Audience): string {
111
+ const parts: string[] = [];
112
+ if (audience.countries)
113
+ parts.push(
114
+ audience.countries.slice(0, 3).join(", ") + (audience.countries.length > 3 ? "…" : ""),
115
+ );
116
+ if (audience.devices) parts.push(audience.devices.map((d) => DEVICE_LABELS[d]).join("/"));
117
+ if (audience.visitor) parts.push(audience.visitor === "new" ? "new visitors" : "returning");
118
+ if (audience.segments)
119
+ parts.push(audience.segments.slice(0, 3).join("/") + (audience.segments.length > 3 ? "…" : ""));
120
+ if (audience.hours) parts.push(`${audience.hours.from}:00–${audience.hours.to}:00`);
121
+ if (audience.days) parts.push(audience.days.map((d) => WEEKDAYS[d]).join(" "));
122
+ const who = parts.join(" · ") || "everyone";
123
+ return audience.hide ? `Hidden for ${who}` : `Only ${who}`;
124
+ }
@@ -0,0 +1,51 @@
1
+ import { AB_TEST_NAME, isParentNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
+
3
+ export type AbArm = "a" | "b";
4
+
5
+ /** An A/B test in a layout (W-312): its name and the share of visitors who see B. */
6
+ export type AbTest = { test: string; split: number };
7
+
8
+ /** The cookie that keeps a visitor on one arm of a test (W-312). */
9
+ export const abCookieName = (test: string) => `emvb_ab_${test.replaceAll("-", "_")}`;
10
+
11
+ /** Every A/B test in the layout, at most 10, with B's split (default 50 %). */
12
+ export function collectAbTests(layout: Layout): AbTest[] {
13
+ const tests = new Map<string, number>();
14
+ const walk = (node: LayoutNode): void => {
15
+ const v = node.variant;
16
+ if (v && AB_TEST_NAME.test(v.test) && (tests.has(v.test) || tests.size < 10)) {
17
+ const known = tests.get(v.test);
18
+ if (v.arm === "b" && v.split !== undefined) tests.set(v.test, v.split);
19
+ else if (known === undefined) tests.set(v.test, 50);
20
+ }
21
+ if (isParentNode(node)) for (const child of node.children) walk(child);
22
+ };
23
+ walk(layout.root);
24
+ return [...tests].map(([test, split]) => ({ test, split }));
25
+ }
26
+
27
+ /**
28
+ * The arm for one visitor (W-312): their cookie when it holds a valid arm, else a fresh pick.
29
+ * `random` is a number in [0, 1); B wins when it falls under the split.
30
+ */
31
+ export function pickArm(
32
+ test: AbTest,
33
+ cookie: string | undefined,
34
+ random: number,
35
+ ): { arm: AbArm; fresh: boolean } {
36
+ if (cookie === "a" || cookie === "b") return { arm: cookie, fresh: false };
37
+ return { arm: random * 100 < test.split ? "b" : "a", fresh: true };
38
+ }
39
+
40
+ /**
41
+ * Whether a node shows for these arms (W-312). Without a decision for its test (a host that
42
+ * doesn't run tests, or the editor), arm A shows and B stays hidden, so pages never show both.
43
+ */
44
+ export function variantShows(
45
+ node: LayoutNode,
46
+ arms: Readonly<Record<string, AbArm>> | undefined,
47
+ ): boolean {
48
+ const v = node.variant;
49
+ if (!v) return true;
50
+ return (arms?.[v.test] ?? "a") === v.arm;
51
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * W-327: stylesheets (and so fonts) a host site wants the editor canvas to load before EmVB's
3
+ * own CSS, so pages look in the editor the way the site's layout makes them look.
4
+ *
5
+ * Only `https:`/`http:` URLs and site paths (`/fonts.css`) are kept; anything else (`javascript:`,
6
+ * `data:`, `//host`, relative paths) is dropped. At most 10, each at most 2048 characters.
7
+ */
8
+ export const MAX_CANVAS_STYLES = 10;
9
+ const MAX_URL = 2048;
10
+
11
+ export function canvasStyleUrls(input: unknown): string[] {
12
+ if (!Array.isArray(input)) return [];
13
+ const out: string[] = [];
14
+ for (const item of input) {
15
+ if (typeof item !== "string") continue;
16
+ const url = item.trim();
17
+ if (!url || url.length > MAX_URL || /[\s"'<>\\]/.test(url)) continue;
18
+ const sitePath = url.startsWith("/") && !url.startsWith("//");
19
+ if (!sitePath && !/^https?:\/\/[^/]/i.test(url)) continue;
20
+ if (!out.includes(url)) out.push(url);
21
+ if (out.length === MAX_CANVAS_STYLES) break;
22
+ }
23
+ return out;
24
+ }
@@ -9,9 +9,10 @@ import {
9
9
  type Refusal,
10
10
  } from "./arrange.ts";
11
11
  import type { VariableKind } from "./design/variables.ts";
12
- import { clearVariableRefs } from "./design/variables.ts";
12
+ import { clearVariableRefs, forEachStyleRef } from "./design/variables.ts";
13
13
  import { ELEMENT_DESCRIPTORS, ELEMENTS, type ElementType } from "./elements/index.ts";
14
14
  import { MAX_LAYOUT_BYTES } from "./limits.ts";
15
+ import { isRecord } from "./record.ts";
15
16
  import { serialize } from "./render/vnode.ts";
16
17
  import { sanitizeHref } from "./sanitize/href.ts";
17
18
  import { sanitizeMediaUrl } from "./sanitize/media-url.ts";
@@ -26,6 +27,7 @@ import {
26
27
  } from "./schema/layout.ts";
27
28
  import { STYLE_STATES } from "./schema/state-names.ts";
28
29
  import type { DeviceStyles, HiddenOn, StyleProps, StyleStates } from "./schema/style.ts";
30
+ import { localStyleOf, withLocalStyle } from "./local-style.ts";
29
31
  import { findNode, nodeChildren } from "./tree-ops.ts";
30
32
  import { summarizeIssues, validateLayout } from "./validate.ts";
31
33
 
@@ -73,14 +75,7 @@ const header = () =>
73
75
  }) as const;
74
76
 
75
77
  /** The local style of a node; classes stay behind (D-033). */
76
- export function styleOf(node: LayoutNode): CopiedStyle {
77
- const copied: CopiedStyle = {};
78
- if (node.style) copied.style = structuredClone(node.style);
79
- if (node.states) copied.states = structuredClone(node.states);
80
- if (node.devices) copied.devices = structuredClone(node.devices);
81
- if (node.hiddenOn) copied.hiddenOn = structuredClone(node.hiddenOn);
82
- return copied;
83
- }
78
+ export const styleOf = localStyleOf;
84
79
 
85
80
  export const elementClip = (node: LayoutNode): ClipEnvelope => ({
86
81
  ...header(),
@@ -100,9 +95,6 @@ export type ReadClip = { ok: true; clip: Clip } | Refusal;
100
95
 
101
96
  const refuse = (reason: string): Refusal => ({ ok: false, reason });
102
97
 
103
- const isRecord = (value: unknown): value is Record<string, unknown> =>
104
- !!value && typeof value === "object" && !Array.isArray(value);
105
-
106
98
  const isCount = (value: unknown): value is number =>
107
99
  typeof value === "number" && Number.isInteger(value) && value >= 1;
108
100
 
@@ -200,15 +192,12 @@ const asRef = (value: unknown): Ref | null =>
200
192
 
201
193
  /** Every variable ref in a style: each value, plus nested colours (shadows, gradient, overlay). */
202
194
  function refsInStyle(style: StyleProps | undefined): Ref[] {
203
- if (!style) return [];
204
- const values: unknown[] = [
205
- ...Object.values(style),
206
- style.boxShadow?.color,
207
- style.iconShadow?.color,
208
- ...(style.gradient?.stops ?? []).map((stop) => stop.color),
209
- style.overlay?.color,
210
- ];
211
- return values.map(asRef).filter((ref): ref is Ref => ref !== null);
195
+ const refs: Ref[] = [];
196
+ forEachStyleRef(style, (value) => {
197
+ const ref = asRef(value);
198
+ if (ref) refs.push(ref);
199
+ });
200
+ return refs;
212
201
  }
213
202
 
214
203
  const refsOf = (owner: CopiedStyle): Ref[] => [
@@ -413,17 +402,7 @@ function styleFor(type: string, style: CopiedStyle): CopiedStyle {
413
402
  * Icon glyph keys are left out on anything but an Icon (W-292).
414
403
  */
415
404
  export function applyStyle<T extends LayoutNode>(node: T, copied: CopiedStyle): T {
416
- const style = styleFor(node.type, copied);
417
- const next = { ...node };
418
- delete next.style;
419
- delete next.states;
420
- delete next.devices;
421
- delete next.hiddenOn;
422
- if (style.style) next.style = structuredClone(style.style);
423
- if (style.states) next.states = structuredClone(style.states);
424
- if (style.devices) next.devices = structuredClone(style.devices);
425
- if (style.hiddenOn) next.hiddenOn = structuredClone(style.hiddenOn);
426
- return next;
405
+ return withLocalStyle(node, styleFor(node.type, copied));
427
406
  }
428
407
 
429
408
  export type PasteMode = "auto" | "inside";
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_FLUID_RANGE, fluidClamp } from "../design/tokens.ts";
2
+ import type { FluidRange, LengthVariable } from "../schema/design.ts";
1
3
  import type { DesignSystem } from "../schema/design.ts";
2
4
  import { DEFAULT_STYLE_TAGS } from "../schema/design.ts";
3
5
  import {
@@ -16,6 +18,7 @@ import {
16
18
  } from "../sanitize/css.ts";
17
19
  import { STYLE_STATES, type StyleStateName } from "../schema/state-names.ts";
18
20
  import { DEVICE_MEDIA, type PopupDevice } from "../theme/popup-rules.ts";
21
+ import { MOTION_KEYFRAMES } from "../sanitize/motion.ts";
19
22
 
20
23
  export type CssInput = {
21
24
  design: DesignSystem;
@@ -29,6 +32,9 @@ export type CssInput = {
29
32
  tablet?: Declaration[];
30
33
  mobile?: Declaration[];
31
34
  hiddenOn?: readonly PopupDevice[];
35
+ /** Container-query overrides (W-346). */
36
+ query?: Declaration[];
37
+ queryMin?: number;
32
38
  }>;
33
39
  /** Editor canvas only: repeat each state rule for `[data-emvb-state="<state>"]` (W-089). */
34
40
  previewStates?: boolean;
@@ -87,6 +93,12 @@ const fontStack = (value: string) => (isSafeFontStack(value) ? value : undefined
87
93
  const lengthCss = (length: { value: number; unit: string }) =>
88
94
  safe(`${length.value}${length.unit}`);
89
95
 
96
+ /** A size token: its fixed length, or a fluid `clamp()` when it has one (W-316). */
97
+ const sizeCss = (variable: LengthVariable, range: FluidRange | undefined) =>
98
+ variable.fluid
99
+ ? fluidClamp(variable.fluid.min, variable.fluid.max, range ?? DEFAULT_FLUID_RANGE)
100
+ : lengthCss(variable.value);
101
+
90
102
  /** One custom property per variable whose id and value are both safe to emit. */
91
103
  function declare<T extends { id: string }>(
92
104
  variables: readonly T[] | undefined,
@@ -100,6 +112,10 @@ function declare<T extends { id: string }>(
100
112
  });
101
113
  }
102
114
 
115
+ /** W-319: declarations that play scroll motion. */
116
+ const usesMotion = (declarations: readonly Declaration[]) =>
117
+ declarations.some((d) => d.property === "animation" && /\bemvb-m[otsrb]\b/.test(d.value));
118
+
103
119
  /**
104
120
  * Cascade order (R-021 / W-030 / W-089): variables on `.emvb-root`, base CSS, shared
105
121
  * `.emvb-k-<id>` class rules, then local `.emvb-e-<id>` (local wins). Each selector's `:hover`,
@@ -120,11 +136,13 @@ export function generateCss({
120
136
  const variables = [
121
137
  ...declare(colors, colorVariableName, (color) => safe(color.value)),
122
138
  ...declare(fonts, fontVariableName, (font) => fontStack(font.value)),
123
- ...declare(fontSizes, fontSizeVariableName, (size) => lengthCss(size.value)),
124
- ...declare(spacings, spacingVariableName, (space) => lengthCss(space.value)),
139
+ ...declare(fontSizes, fontSizeVariableName, (size) => sizeCss(size, design.fluidRange)),
140
+ ...declare(spacings, spacingVariableName, (space) => sizeCss(space, design.fluidRange)),
125
141
  ];
126
142
  const animated: string[] = [];
127
143
  const entrances: string[] = [];
144
+ /** W-319: any scroll motion on the page, so its keyframes are sent. */
145
+ let motion = false;
128
146
  const rules = (selector: string, declarations: Declaration[], states: StateDeclarations) => [
129
147
  block(selector, declarations),
130
148
  ...STYLE_STATES.map((state) =>
@@ -139,6 +157,7 @@ export function generateCss({
139
157
  const track = (selector: string, declarations: Declaration[]) => {
140
158
  if (declarations.some((d) => d.property === "transition")) animated.push(selector);
141
159
  if (declarations.some((d) => d.property === "animation")) entrances.push(selector);
160
+ if (usesMotion(declarations)) motion = true;
142
161
  return declarations;
143
162
  };
144
163
  const classes = (design.classes ?? []).flatMap((cls) => {
@@ -202,6 +221,7 @@ export function generateCss({
202
221
  );
203
222
  };
204
223
  for (const rule of responsive) {
224
+ if (usesMotion(rule.tablet) || usesMotion(rule.mobile)) motion = true;
205
225
  if (
206
226
  !entrances.includes(rule.selector) &&
207
227
  [...rule.tablet, ...rule.mobile].some((d) => d.property === "animation")
@@ -213,6 +233,7 @@ export function generateCss({
213
233
  entrances.length > 0
214
234
  ? "@keyframes emvb-fade{from{opacity:0}to{opacity:1}}@keyframes emvb-fade-up{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}@keyframes emvb-fade-down{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}@keyframes emvb-slide-up{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:none}}@keyframes emvb-slide-down{from{opacity:0;transform:translateY(-16px)}to{opacity:1;transform:none}}@keyframes emvb-scale{from{opacity:0;transform:scale(0.96)}to{opacity:1;transform:none}}"
215
235
  : "",
236
+ entrances.length > 0 && motion ? MOTION_KEYFRAMES : "",
216
237
  block(".emvb-root", variables),
217
238
  tagDefaultCss(design),
218
239
  backgroundVideo
@@ -221,6 +242,12 @@ export function generateCss({
221
242
  ...[...usedTypes].toSorted().map((type) => baseCss.get(type) ?? ""),
222
243
  ...classes,
223
244
  ...locals,
245
+ ...localRules
246
+ .filter((rule) => rule.query && rule.query.length > 0 && rule.queryMin)
247
+ .map(
248
+ (rule) =>
249
+ `@container (min-width:${rule.queryMin}px){${block(`.emvb-e-${rule.id}`, rule.query ?? [])}}`,
250
+ ),
224
251
  at(DEVICE_MEDIA.tablet, "tablet"),
225
252
  at(DEVICE_MEDIA.mobile, "mobile"),
226
253
  hide("desktop", DEVICE_MEDIA.hideDesktop),
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Print stylesheet (W-335). Chrome that only makes sense on screen is hidden.
3
+ * Appended after scoped page CSS so the selectors stay global: a header, float or popup
4
+ * is not inside the page's scope wrapper.
5
+ */
6
+ export function printCss(): string {
7
+ return (
8
+ "@media print{" +
9
+ ".emvb-theme-header,.emvb-theme-footer,.emvb-float,.emvb-popup{display:none!important}" +
10
+ "}"
11
+ );
12
+ }
@@ -22,9 +22,9 @@ export function scopeWrapperCss(): string {
22
22
  return `:where(.${WRAPPER_CLASS}){display:contents}`;
23
23
  }
24
24
 
25
- /** The wrapper's class attribute for a scope token. */
26
- export function scopeAttribute(token: string): string {
27
- return `class="${WRAPPER_CLASS} ${scopeClass(token)}"`;
25
+ /** Classes on the scope wrapper. The editor's vnode and the public HTML both use them. */
26
+ export function scopeClassName(token: string): string {
27
+ return `${WRAPPER_CLASS} ${scopeClass(token)}`;
28
28
  }
29
29
 
30
30
  function splitSelectors(prelude: string): string[] {