@perkyzz/emvb 0.3.0 → 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 (121) 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 +1 -1
  10. package/src/admin/editor/Editor.tsx +106 -332
  11. package/src/admin/editor/EditorOverlay.tsx +3 -1
  12. package/src/admin/editor/PerfMeter.tsx +1 -1
  13. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  14. package/src/admin/editor/Timeline.tsx +16 -3
  15. package/src/admin/editor/canvas/CanvasFrame.tsx +51 -368
  16. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  17. package/src/admin/editor/canvas/SelectionOverlay.tsx +86 -46
  18. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  19. package/src/admin/editor/canvas/drop-line.ts +24 -0
  20. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  21. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  22. package/src/admin/editor/collection-previews.ts +28 -5
  23. package/src/admin/editor/editor-chrome.tsx +346 -0
  24. package/src/admin/editor/editor-commands.ts +360 -0
  25. package/src/admin/editor/element-chrome.ts +89 -0
  26. package/src/admin/editor/feature-css.ts +15 -15
  27. package/src/admin/editor/host.ts +33 -0
  28. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  29. package/src/admin/editor/icons/library.ts +29 -19
  30. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  31. package/src/admin/editor/palette-items.ts +36 -5
  32. package/src/admin/editor/palette.ts +3 -2
  33. package/src/admin/editor/panels/AddPanel.tsx +2 -67
  34. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  35. package/src/admin/editor/panels/ElementPanel.tsx +40 -99
  36. package/src/admin/editor/panels/LayersPanel.tsx +34 -62
  37. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  38. package/src/admin/editor/panels/SiteStylesDrawer.tsx +16 -10
  39. package/src/admin/editor/panels/VariableSection.tsx +1 -10
  40. package/src/admin/editor/panels/inline-error.tsx +11 -0
  41. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  42. package/src/admin/editor/panels/settings/AudienceEditor.tsx +73 -3
  43. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  44. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  45. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  46. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -2
  47. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  48. package/src/admin/editor/panels/settings/length-units.ts +15 -4
  49. package/src/admin/editor/panels/settings/style-sections.ts +5 -1
  50. package/src/admin/editor/panels/style-target.ts +105 -0
  51. package/src/admin/editor/section-templates.ts +43 -21
  52. package/src/admin/editor/shortcuts.ts +4 -0
  53. package/src/admin/editor/store.ts +10 -1
  54. package/src/admin/editor/useClipboardActions.ts +1 -1
  55. package/src/admin/editor/useEditorCommands.ts +61 -13
  56. package/src/admin/editor/useEditorData.ts +7 -1
  57. package/src/admin/editor/useEditorShortcuts.ts +23 -15
  58. package/src/admin/editor/useNodeActions.ts +6 -1
  59. package/src/admin/forms-api.ts +17 -6
  60. package/src/admin/icon-uploads-api.ts +18 -0
  61. package/src/admin/theme-api.ts +5 -18
  62. package/src/astro/content-port.ts +24 -0
  63. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  64. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  65. package/src/astro/forms/client.ts +1 -0
  66. package/src/astro/forms-definitions.ts +24 -11
  67. package/src/astro/index.ts +1 -0
  68. package/src/astro/render-session.ts +85 -0
  69. package/src/astro/request-data.ts +20 -8
  70. package/src/astro/resolve-theme.ts +166 -76
  71. package/src/astro/resolve.ts +57 -16
  72. package/src/astro/theme-posts.ts +16 -5
  73. package/src/astro/visitor.ts +67 -5
  74. package/src/constants.ts +1 -1
  75. package/src/core/arrange.ts +63 -38
  76. package/src/core/audience/rules.ts +22 -2
  77. package/src/core/canvas-styles.ts +24 -0
  78. package/src/core/clipboard.ts +11 -32
  79. package/src/core/css/generate.ts +9 -0
  80. package/src/core/css/print.ts +12 -0
  81. package/src/core/css/scope.ts +3 -3
  82. package/src/core/css-keywords.ts +83 -0
  83. package/src/core/data/bindings.ts +4 -6
  84. package/src/core/design/classes.ts +13 -15
  85. package/src/core/design/diff.ts +55 -0
  86. package/src/core/design/merge.ts +127 -0
  87. package/src/core/design/variables.ts +25 -21
  88. package/src/core/elements/dynamic-elements.ts +30 -0
  89. package/src/core/elements/form-elements.ts +1 -0
  90. package/src/core/elements/index.ts +183 -7
  91. package/src/core/forms/binding.ts +4 -13
  92. package/src/core/index.ts +10 -0
  93. package/src/core/local-style.ts +27 -0
  94. package/src/core/migrate/index.ts +9 -4
  95. package/src/core/nesting.ts +4 -23
  96. package/src/core/perf/scripts.ts +9 -6
  97. package/src/core/record.ts +3 -0
  98. package/src/core/render/context.ts +2 -0
  99. package/src/core/render/dynamic-post.ts +1 -2
  100. package/src/core/render/form.ts +133 -10
  101. package/src/core/render/index.ts +155 -13
  102. package/src/core/render/vnode.ts +12 -2
  103. package/src/core/sanitize/css.ts +90 -77
  104. package/src/core/sanitize/svg.ts +8 -3
  105. package/src/core/sanitize/url.ts +10 -1
  106. package/src/core/schema/design.ts +5 -7
  107. package/src/core/schema/layout.ts +153 -181
  108. package/src/core/schema/style.ts +53 -63
  109. package/src/core/share/link.ts +68 -28
  110. package/src/core/tabs/presence.ts +7 -17
  111. package/src/core/theme/dynamic.ts +200 -39
  112. package/src/core/theme/float.ts +1 -1
  113. package/src/core/tree-ops.ts +57 -0
  114. package/src/index.ts +14 -2
  115. package/src/server/design-routes.ts +4 -1
  116. package/src/server/icon-routes.ts +68 -16
  117. package/src/server/plugin.ts +8 -2
  118. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  119. package/src/admin/editor/icons/sets/lucide.json +0 -1
  120. package/src/admin/editor/icons/sets/remix.json +0 -1
  121. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -1,13 +1,13 @@
1
- import { decodeSlug, getEmDashEntry } from "emdash";
2
- import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
3
1
  import { PAGES_COLLECTION } from "../constants.ts";
4
- import { formIdsInLayout, loadFormDefinitions } from "./forms-definitions.ts";
5
- import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
2
+ import { emdashContent, type ContentPort } from "./content-port.ts";
3
+ import { formIdsInLayouts } from "./forms-definitions.ts";
4
+ import { readLayout, renderStored, type RenderedPage } from "./render.ts";
5
+ import { designFor, formsFor } from "./render-session.ts";
6
6
  import { bindingDataFor } from "./request-data.ts";
7
- import type { VisitorAstro } from "./visitor.ts";
8
- import { sectionTemplatesFor } from "./resolve-theme.ts";
7
+ import type { HostVisitor, VisitorAstro } from "./visitor.ts";
8
+ import { referencedTemplatesFor } from "./resolve-theme.ts";
9
9
 
10
- type EmDashEntry = NonNullable<Awaited<ReturnType<typeof getEmDashEntry>>["entry"]>;
10
+ type EmDashEntry = NonNullable<Awaited<ReturnType<ContentPort["getEntry"]>>["entry"]>;
11
11
 
12
12
  export type ResolvedEmVBPage = RenderedPage & {
13
13
  /** The EmDash entry, for `getSeoMeta` and the host's layout. */
@@ -27,16 +27,37 @@ type AstroLike = VisitorAstro & {
27
27
  /**
28
28
  * Looks up the published EmVB page for this request's slug (or its draft under a preview token),
29
29
  * so a host route can try EmVB first and fall through to its own content (R-030, R-052).
30
+ * A fixed route such as `/` passes the page's slug explicitly: `{ slug: "home" }`.
30
31
  */
31
32
  export async function resolveEmVBPage(
32
33
  astro: AstroLike,
33
- options: { param?: string } = {},
34
+ options: {
35
+ /** The route parameter that holds the URL-encoded slug (default `"slug"`). */
36
+ param?: string;
37
+ /** The page's slug, used as-is (not URL-decoded) in place of the route parameter. */
38
+ slug?: string;
39
+ /** What the host knows about the visitor: segments and facts Visitors rules use (W-329). */
40
+ visitor?: HostVisitor;
41
+ } = {},
34
42
  ): Promise<ResolvedEmVBPage | null> {
35
- const slug = decodeSlug(astro.params[options.param ?? "slug"]);
43
+ return resolveEmVBPageWith(emdashContent, astro, options);
44
+ }
45
+
46
+ /** Same as `resolveEmVBPage`, with a content port so tests can pass a fake (W-359). */
47
+ export async function resolveEmVBPageWith(
48
+ content: ContentPort,
49
+ astro: AstroLike,
50
+ options: {
51
+ param?: string;
52
+ slug?: string;
53
+ visitor?: HostVisitor;
54
+ } = {},
55
+ ): Promise<ResolvedEmVBPage | null> {
56
+ const slug = options.slug ?? content.decodeSlug(astro.params[options.param ?? "slug"]);
36
57
  if (!slug) return null;
37
- let found: Awaited<ReturnType<typeof getEmDashEntry>>;
58
+ let found: Awaited<ReturnType<ContentPort["getEntry"]>>;
38
59
  try {
39
- found = await getEmDashEntry(PAGES_COLLECTION, slug);
60
+ found = await content.getEntry(PAGES_COLLECTION, slug);
40
61
  } catch {
41
62
  // No emvb_pages collection yet (EmVB not set up): not an EmVB page.
42
63
  return null;
@@ -44,16 +65,36 @@ export async function resolveEmVBPage(
44
65
  const entry = found.entry;
45
66
  if (!entry) return null;
46
67
  const data = entry.data as Record<string, unknown>;
47
- const handler = getPublicPluginApiRouteHandler(astro.locals as never);
48
- const design = await loadDesign(handler, astro.url);
68
+ const handler = content.pluginHandler(astro.locals as never);
69
+ const design = await designFor(astro, handler, astro.url);
49
70
  const layout = readLayout(data["layout"]);
71
+ const referenced = layout
72
+ ? await referencedTemplatesFor(layout, content, astro)
73
+ : { sectionTemplates: {}, loopTemplates: {} };
74
+ const { sectionTemplates, loopTemplates } = referenced;
50
75
  const formDefinitions = layout
51
- ? await loadFormDefinitions(handler, astro.url, formIdsInLayout(layout))
76
+ ? await formsFor(
77
+ astro,
78
+ handler,
79
+ astro.url,
80
+ formIdsInLayouts([
81
+ layout,
82
+ ...Object.values(sectionTemplates),
83
+ ...Object.values(loopTemplates),
84
+ ]),
85
+ )
52
86
  : undefined;
53
- const sectionTemplates = layout ? await sectionTemplatesFor(layout) : {};
54
87
  const dynamic = {
55
88
  ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
56
- ...(await bindingDataFor(layout, astro.url, astro, Object.values(sectionTemplates))),
89
+ ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
90
+ ...(await bindingDataFor(
91
+ layout,
92
+ astro.url,
93
+ astro,
94
+ Object.values(sectionTemplates),
95
+ options.visitor ? { visitor: options.visitor } : {},
96
+ content,
97
+ )),
57
98
  };
58
99
  return {
59
100
  ...renderStored(
@@ -1,4 +1,4 @@
1
- import type { ThemePostFields } from "../core/index.ts";
1
+ import { loopPermalink, type ThemePostFields } from "../core/index.ts";
2
2
 
3
3
  type MediaLike = {
4
4
  src?: unknown;
@@ -42,7 +42,15 @@ export function entryTimestamp(value: unknown): string | undefined {
42
42
  */
43
43
  export function themePostFromEntry(
44
44
  entry: { id?: string; data?: Record<string, unknown> } | Record<string, unknown>,
45
- options: { permalinkPrefix?: string } = {},
45
+ options: {
46
+ permalinkPrefix?: string;
47
+ /** W-330: a Loop's link pattern, e.g. `/team/{slug}`. */
48
+ permalinkPattern?: string;
49
+ /** W-330: the field with the entry's image, instead of `featured_image`. */
50
+ imageField?: string;
51
+ /** W-330: the field with the entry's excerpt, instead of `excerpt`. */
52
+ excerptField?: string;
53
+ } = {},
46
54
  ): ThemePostFields | null {
47
55
  const data =
48
56
  "data" in entry && entry.data && typeof entry.data === "object"
@@ -52,11 +60,14 @@ export function themePostFromEntry(
52
60
  const slug = typeof data["slug"] === "string" ? data["slug"] : id;
53
61
  if (!slug && !id) return null;
54
62
  const title = typeof data["title"] === "string" ? data["title"] : "";
55
- const excerpt = typeof data["excerpt"] === "string" ? data["excerpt"] : "";
63
+ const excerptValue = data[options.excerptField ?? "excerpt"];
64
+ const excerpt = typeof excerptValue === "string" ? excerptValue : "";
56
65
  const content = data["content"] ?? "";
57
66
  const prefix = options.permalinkPrefix ?? "/posts";
58
- const permalink = `${prefix.replace(/\/$/, "")}/${slug || id}`;
59
- const media = mediaFieldsFrom(data["featured_image"]);
67
+ const permalink = options.permalinkPattern
68
+ ? loopPermalink(options.permalinkPattern, { slug: slug || id, id: id || slug })
69
+ : `${prefix.replace(/\/$/, "")}/${slug || id}`;
70
+ const media = mediaFieldsFrom(data[options.imageField ?? "featured_image"]);
60
71
  // W-303: EmDash's own publish date is `data.publishedAt`, a `Date`; a custom field may be text.
61
72
  const publishedAt = ["published_at", "publishedAt", "date"]
62
73
  .map((key) => entryTimestamp(data[key]))
@@ -1,8 +1,10 @@
1
1
  import {
2
+ AUDIENCE_SEGMENT,
2
3
  abCookieName,
3
4
  collectAbTests,
4
5
  deviceFromUserAgent,
5
6
  layoutUsesAudience,
7
+ layoutUsesVisitorRule,
6
8
  pickArm,
7
9
  type AbArm,
8
10
  type Layout,
@@ -86,6 +88,25 @@ export function abArmsFor(
86
88
  const SEEN_COOKIE = "emvb_seen";
87
89
  const SEEN_DAYS = 365;
88
90
 
91
+ /**
92
+ * One cookie as the browser sent it, decoded as `Astro.cookies.get` would. Unlike that getter, it
93
+ * ignores a cookie set earlier in this request, so the page and its theme parts agree on a first
94
+ * visit.
95
+ */
96
+ function requestCookie(astro: VisitorAstro, name: string): string | undefined {
97
+ for (const pair of astro.request?.headers.get("cookie")?.split(";") ?? []) {
98
+ const at = pair.indexOf("=");
99
+ if (at < 0 || pair.slice(0, at).trim() !== name) continue;
100
+ const raw = pair.slice(at + 1).trim();
101
+ try {
102
+ return decodeURIComponent(raw);
103
+ } catch {
104
+ return raw;
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+
89
110
  const COUNTRY = /^[A-Z]{2}$/;
90
111
 
91
112
  /**
@@ -108,12 +129,53 @@ function countryOf(astro: VisitorAstro): string | undefined {
108
129
  return undefined;
109
130
  }
110
131
 
132
+ /**
133
+ * What the host site knows about this visitor (W-329), passed as
134
+ * `resolveEmVBPage(Astro, { visitor })` or `resolveThemeParts(Astro, ctx, { visitor })`:
135
+ * segments (`member`, `pro`) that Visitors rules match, and facts that replace what EmVB detects.
136
+ */
137
+ export type HostVisitor = {
138
+ segments?: readonly string[];
139
+ country?: string;
140
+ device?: VisitorInfo["device"];
141
+ returning?: boolean;
142
+ };
143
+
144
+ const MAX_SEGMENTS = 50;
145
+
146
+ /** The host's visitor facts EmVB can use; bad values are left out (W-329). */
147
+ export function hostVisitorFacts(host: HostVisitor | undefined): Partial<VisitorInfo> {
148
+ if (!host || typeof host !== "object") return {};
149
+ const facts: Partial<VisitorInfo> = {};
150
+ if (Array.isArray(host.segments)) {
151
+ const segments = [
152
+ ...new Set(
153
+ host.segments
154
+ .filter((s): s is string => typeof s === "string")
155
+ .map((s) => s.trim().toLowerCase())
156
+ .filter((s) => AUDIENCE_SEGMENT.test(s)),
157
+ ),
158
+ ].slice(0, MAX_SEGMENTS);
159
+ facts.segments = segments;
160
+ }
161
+ const country = typeof host.country === "string" ? host.country.trim().toUpperCase() : "";
162
+ if (COUNTRY.test(country)) facts.country = country;
163
+ if (host.device === "mobile" || host.device === "tablet" || host.device === "desktop")
164
+ facts.device = host.device;
165
+ if (typeof host.returning === "boolean") facts.returning = host.returning;
166
+ return facts;
167
+ }
168
+
111
169
  /**
112
170
  * What the server knows about this visitor, for visitor-aware elements (W-313): country from
113
171
  * the edge, device from the User-Agent, new or returning from a first-party cookie, and the time.
114
- * Only read when the layout has a visitor rule.
172
+ * Facts the host passes (W-329) win over detected ones. Only read when the layout has a rule.
115
173
  */
116
- export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorInfo | undefined {
174
+ export function visitorFor(
175
+ layout: Layout | null,
176
+ astro: VisitorAstro,
177
+ host?: HostVisitor,
178
+ ): VisitorInfo | undefined {
117
179
  if (!layout || !layoutUsesAudience(layout)) return undefined;
118
180
  const headers = astro.request?.headers;
119
181
  const visitor: VisitorInfo = { now: Date.now() };
@@ -121,8 +183,8 @@ export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorI
121
183
  if (country) visitor.country = country;
122
184
  const device = deviceFromUserAgent(headers?.get("user-agent"), headers?.get("sec-ch-ua-mobile"));
123
185
  if (device) visitor.device = device;
124
- if (astro.cookies) {
125
- visitor.returning = astro.cookies.get(SEEN_COOKIE)?.value === "1";
186
+ if (astro.cookies && layoutUsesVisitorRule(layout)) {
187
+ visitor.returning = requestCookie(astro, SEEN_COOKIE) === "1";
126
188
  if (!visitor.returning) {
127
189
  try {
128
190
  astro.cookies.set(SEEN_COOKIE, "1", {
@@ -138,5 +200,5 @@ export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorI
138
200
  }
139
201
  }
140
202
  markPersonalized(astro);
141
- return visitor;
203
+ return { ...visitor, ...hostVisitorFacts(host) };
142
204
  }
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const PLUGIN_ID = "emvb";
2
- export const PLUGIN_VERSION = "0.3.0";
2
+ export const PLUGIN_VERSION = "0.4.0";
3
3
  export const PACKAGE_NAME = "@perkyzz/emvb";
4
4
  export const ADMIN_ENTRY = `${PACKAGE_NAME}/admin`;
5
5
  export const PAGES_COLLECTION = "emvb_pages";
@@ -120,46 +120,37 @@ function underForm(layout: Layout, parentId: string): boolean {
120
120
 
121
121
  type Drop = { layout: Layout; node: LayoutNode; into: Located; isNew: boolean };
122
122
 
123
- /** 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`. */
124
152
  const DROP_RULES: [breaks: (drop: Drop) => boolean, reason: string][] = [
125
- [
126
- ({ node, into }) => node.type === "loop-empty" && into.node.type !== "loop",
127
- REASONS.emptyOutsideLoop,
128
- ],
129
- [
130
- ({ node, into }) => node.type === "tab-panel" && into.node.type !== "tabs",
131
- REASONS.tabOutsideTabs,
132
- ],
133
- [
134
- ({ node, into }) => into.node.type === "tabs" && node.type !== "tab-panel",
135
- REASONS.onlyTabPanels,
136
- ],
137
- [
138
- ({ node, into }) => node.type === "accordion-item" && into.node.type !== "accordion",
139
- REASONS.itemOutsideAccordion,
140
- ],
141
- [
142
- ({ node, into }) => into.node.type === "accordion" && node.type !== "accordion-item",
143
- REASONS.onlyAccordionItems,
144
- ],
145
- [
146
- ({ node, into }) =>
147
- node.type === "menu-item" && into.node.type !== "menu" && into.node.type !== "menu-item",
148
- REASONS.itemOutsideMenu,
149
- ],
150
- [
151
- ({ node, into }) => into.node.type === "menu" && node.type !== "menu-item",
152
- REASONS.onlyMenuItems,
153
- ],
154
- [
155
- ({ node, into, layout }) => isFormNode(node) && underForm(layout, into.node.id),
156
- REASONS.nestedForm,
157
- ],
158
153
  [({ node, into }) => isFormNode(node) && !isLayoutParentNode(into.node), REASONS.formIntoField],
159
- [
160
- ({ node, into, layout }) => isFormFieldType(node.type) && !underForm(layout, into.node.id),
161
- REASONS.fieldOutsideForm,
162
- ],
163
154
  // A 13th panel would be stored but never shown (W-188); moving within the same Tabs is fine.
164
155
  [
165
156
  ({ node, into }) =>
@@ -196,6 +187,8 @@ export function canDrop(layout: Layout, source: DragSource, parentId: string): A
196
187
  const moving = dragged(layout, source, parentId);
197
188
  if (!moving.ok) return moving;
198
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);
199
192
  const drop: Drop = { layout, node: moving.node, into, isNew: source.kind === "new" };
200
193
  const broken = DROP_RULES.find(([breaks]) => breaks(drop));
201
194
  return broken ? refuse(broken[1]) : { ok: true };
@@ -310,6 +303,38 @@ export function duplicateNode(
310
303
  };
311
304
  }
312
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
+
313
338
  /** Where click-to-add puts a new element: into a selected container, after a selected element, or at the end. */
314
339
  export function insertionPoint(layout: Layout, selectedId: string | null): Place {
315
340
  const found = selectedId ? locate(layout, selectedId) : undefined;
@@ -1,4 +1,5 @@
1
- import { isParentNode, type Audience, type Layout, type LayoutNode } from "../schema/layout.ts";
1
+ import { type Audience, type Layout, type LayoutNode } from "../schema/layout.ts";
2
+ import { knownChildren, someNode } from "../tree-ops.ts";
2
3
 
3
4
  /** What the host knows about this visitor (W-313). Anything unknown is left out. */
4
5
  export type VisitorInfo = {
@@ -8,6 +9,8 @@ export type VisitorInfo = {
8
9
  returning?: boolean;
9
10
  /** The request time, epoch ms. */
10
11
  now?: number;
12
+ /** Segments the host says this visitor is in (W-329), e.g. member, pro. */
13
+ segments?: readonly string[];
11
14
  };
12
15
 
13
16
  const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
@@ -49,6 +52,10 @@ function matches(audience: Audience, visitor: VisitorInfo): boolean {
49
52
  if (visitor.returning === undefined) return false;
50
53
  if ((audience.visitor === "returning") !== visitor.returning) return false;
51
54
  }
55
+ if (audience.segments) {
56
+ const has = new Set(visitor.segments ?? []);
57
+ if (!audience.segments.some((segment) => has.has(segment))) return false;
58
+ }
52
59
  if (audience.hours || audience.days) {
53
60
  if (visitor.now === undefined) return false;
54
61
  const { hour, day } = clockIn(visitor.now, audience.timeZone);
@@ -71,8 +78,19 @@ export function layoutUsesAudience(layout: Layout): boolean {
71
78
  return hasAudience(layout.root);
72
79
  }
73
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
+
74
89
  const hasAudience = (node: LayoutNode): boolean =>
75
- Boolean(node.audience) || (isParentNode(node) && node.children.some(hasAudience));
90
+ someNode(node, (current) => Boolean(current.audience), knownChildren);
91
+
92
+ const hasVisitorRule = (node: LayoutNode): boolean =>
93
+ someNode(node, (current) => current.audience?.visitor !== undefined, knownChildren);
76
94
 
77
95
  /** A device from a User-Agent and the Sec-CH-UA-Mobile hint (W-313). */
78
96
  export function deviceFromUserAgent(
@@ -97,6 +115,8 @@ export function audienceSummary(audience: Audience): string {
97
115
  );
98
116
  if (audience.devices) parts.push(audience.devices.map((d) => DEVICE_LABELS[d]).join("/"));
99
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 ? "…" : ""));
100
120
  if (audience.hours) parts.push(`${audience.hours.from}:00–${audience.hours.to}:00`);
101
121
  if (audience.days) parts.push(audience.days.map((d) => WEEKDAYS[d]).join(" "));
102
122
  const who = parts.join(" · ") || "everyone";
@@ -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";
@@ -32,6 +32,9 @@ export type CssInput = {
32
32
  tablet?: Declaration[];
33
33
  mobile?: Declaration[];
34
34
  hiddenOn?: readonly PopupDevice[];
35
+ /** Container-query overrides (W-346). */
36
+ query?: Declaration[];
37
+ queryMin?: number;
35
38
  }>;
36
39
  /** Editor canvas only: repeat each state rule for `[data-emvb-state="<state>"]` (W-089). */
37
40
  previewStates?: boolean;
@@ -239,6 +242,12 @@ export function generateCss({
239
242
  ...[...usedTypes].toSorted().map((type) => baseCss.get(type) ?? ""),
240
243
  ...classes,
241
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
+ ),
242
251
  at(DEVICE_MEDIA.tablet, "tablet"),
243
252
  at(DEVICE_MEDIA.mobile, "mobile"),
244
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[] {