@perkyzz/emvb 0.0.0-stage → 0.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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/package.json +72 -4
  4. package/src/admin/access/RequireEditor.tsx +39 -0
  5. package/src/admin/access/role.ts +36 -0
  6. package/src/admin/access/sidebar-shim.ts +108 -0
  7. package/src/admin/api.ts +48 -0
  8. package/src/admin/content-api.ts +147 -0
  9. package/src/admin/editor/Editor.tsx +457 -0
  10. package/src/admin/editor/EditorOverlay.tsx +54 -0
  11. package/src/admin/editor/ShortcutsDialog.tsx +30 -0
  12. package/src/admin/editor/SmallScreenNotice.tsx +20 -0
  13. package/src/admin/editor/TopBar.tsx +179 -0
  14. package/src/admin/editor/canvas/CanvasFrame.tsx +355 -0
  15. package/src/admin/editor/canvas/CanvasTextEdit.tsx +87 -0
  16. package/src/admin/editor/canvas/DeviceBar.tsx +50 -0
  17. package/src/admin/editor/canvas/EmptyCanvas.tsx +49 -0
  18. package/src/admin/editor/canvas/SelectionOverlay.tsx +185 -0
  19. package/src/admin/editor/canvas/canvas-events.ts +232 -0
  20. package/src/admin/editor/canvas/state-preview.ts +19 -0
  21. package/src/admin/editor/canvas/tab-reveal.ts +35 -0
  22. package/src/admin/editor/canvas/vnode-react.tsx +49 -0
  23. package/src/admin/editor/clipboard-store.ts +44 -0
  24. package/src/admin/editor/dialogs.tsx +125 -0
  25. package/src/admin/editor/dnd/drag-stash.ts +27 -0
  26. package/src/admin/editor/dnd/drop-target.ts +101 -0
  27. package/src/admin/editor/dnd/new-element.ts +32 -0
  28. package/src/admin/editor/editor-css.ts +539 -0
  29. package/src/admin/editor/exit.ts +27 -0
  30. package/src/admin/editor/panels/AddPanel.tsx +142 -0
  31. package/src/admin/editor/panels/ClassesSection.tsx +334 -0
  32. package/src/admin/editor/panels/ColorControl.tsx +230 -0
  33. package/src/admin/editor/panels/ConditionsEditor.tsx +201 -0
  34. package/src/admin/editor/panels/ElementPanel.tsx +629 -0
  35. package/src/admin/editor/panels/LayersPanel.tsx +336 -0
  36. package/src/admin/editor/panels/LeftPanel.tsx +77 -0
  37. package/src/admin/editor/panels/PageSettings.tsx +126 -0
  38. package/src/admin/editor/panels/SettingsPanel.tsx +101 -0
  39. package/src/admin/editor/panels/SiteStylesDrawer.tsx +392 -0
  40. package/src/admin/editor/panels/TriggerSettings.tsx +132 -0
  41. package/src/admin/editor/panels/TriggersEditor.tsx +197 -0
  42. package/src/admin/editor/panels/VariableSection.tsx +492 -0
  43. package/src/admin/editor/panels/settings/BackgroundControls.tsx +320 -0
  44. package/src/admin/editor/panels/settings/ClassChip.tsx +167 -0
  45. package/src/admin/editor/panels/settings/ClassChipInput.tsx +349 -0
  46. package/src/admin/editor/panels/settings/DraftTextField.tsx +201 -0
  47. package/src/admin/editor/panels/settings/EffectsControls.tsx +347 -0
  48. package/src/admin/editor/panels/settings/FieldBindControl.tsx +83 -0
  49. package/src/admin/editor/panels/settings/FieldControl.tsx +150 -0
  50. package/src/admin/editor/panels/settings/FormBindControl.tsx +97 -0
  51. package/src/admin/editor/panels/settings/IconPicker.tsx +109 -0
  52. package/src/admin/editor/panels/settings/LengthRow.tsx +181 -0
  53. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +124 -0
  54. package/src/admin/editor/panels/settings/MediaPicker.tsx +218 -0
  55. package/src/admin/editor/panels/settings/NumberRow.tsx +154 -0
  56. package/src/admin/editor/panels/settings/StateSwitcher.tsx +87 -0
  57. package/src/admin/editor/panels/settings/StyleRow.tsx +480 -0
  58. package/src/admin/editor/panels/settings/VariableBinding.tsx +167 -0
  59. package/src/admin/editor/panels/settings/class-suggest.ts +51 -0
  60. package/src/admin/editor/panels/settings/length-units.ts +83 -0
  61. package/src/admin/editor/panels/settings/node-props.ts +11 -0
  62. package/src/admin/editor/panels/settings/style-sections.ts +291 -0
  63. package/src/admin/editor/panels/site-list.tsx +206 -0
  64. package/src/admin/editor/panels/variable-values.ts +73 -0
  65. package/src/admin/editor/section-templates.ts +50 -0
  66. package/src/admin/editor/shortcuts.ts +20 -0
  67. package/src/admin/editor/store.ts +212 -0
  68. package/src/admin/editor/useClipboardActions.ts +136 -0
  69. package/src/admin/editor/useEditorCommands.ts +142 -0
  70. package/src/admin/editor/useEditorData.ts +167 -0
  71. package/src/admin/editor/useEditorShortcuts.ts +148 -0
  72. package/src/admin/editor/useMediaQuery.ts +20 -0
  73. package/src/admin/editor/useNodeActions.ts +122 -0
  74. package/src/admin/editor/useSave.ts +185 -0
  75. package/src/admin/forms-api.ts +73 -0
  76. package/src/admin/index.tsx +20 -0
  77. package/src/admin/media-api.ts +68 -0
  78. package/src/admin/pages/CreateDialog.tsx +150 -0
  79. package/src/admin/pages/EditorPage.tsx +57 -0
  80. package/src/admin/pages/NewPageDialog.tsx +83 -0
  81. package/src/admin/pages/NewThemePartDialog.tsx +61 -0
  82. package/src/admin/pages/PageList.tsx +71 -0
  83. package/src/admin/pages/PagesPage.tsx +25 -0
  84. package/src/admin/pages/SetupShell.tsx +90 -0
  85. package/src/admin/pages/ThemeBuilderPage.tsx +25 -0
  86. package/src/admin/pages/ThemePartList.tsx +202 -0
  87. package/src/admin/pages/list-kit.tsx +75 -0
  88. package/src/admin/setup/plan.ts +150 -0
  89. package/src/admin/setup/run.ts +61 -0
  90. package/src/admin/setup/spec.ts +100 -0
  91. package/src/admin/setup/useSetupStatus.ts +62 -0
  92. package/src/admin/theme-api.ts +186 -0
  93. package/src/admin/ui.ts +231 -0
  94. package/src/admin/widgets/LayoutField.tsx +67 -0
  95. package/src/astro/EmVBPage.astro +37 -0
  96. package/src/astro/env.d.ts +5 -0
  97. package/src/astro/forms/EmVBFormsRuntime.astro +9 -0
  98. package/src/astro/forms/index.ts +1 -0
  99. package/src/astro/forms-definitions.ts +104 -0
  100. package/src/astro/index.ts +15 -0
  101. package/src/astro/popups/EmVBPopupsRuntime.astro +9 -0
  102. package/src/astro/popups/index.ts +1 -0
  103. package/src/astro/popups/runtime.ts +246 -0
  104. package/src/astro/render.ts +74 -0
  105. package/src/astro/resolve-theme.ts +371 -0
  106. package/src/astro/resolve.ts +65 -0
  107. package/src/astro/tabs/EmVBTabsRuntime.astro +10 -0
  108. package/src/astro/tabs/index.ts +1 -0
  109. package/src/astro/tabs/runtime.ts +111 -0
  110. package/src/astro/theme-context.ts +81 -0
  111. package/src/astro/theme-posts.ts +84 -0
  112. package/src/constants.ts +12 -0
  113. package/src/core/arrange.ts +360 -0
  114. package/src/core/clipboard.ts +422 -0
  115. package/src/core/css/generate.ts +219 -0
  116. package/src/core/css/scope.ts +88 -0
  117. package/src/core/design/cascade.ts +28 -0
  118. package/src/core/design/classes.ts +138 -0
  119. package/src/core/design/devices.ts +56 -0
  120. package/src/core/design/states.ts +49 -0
  121. package/src/core/design/transfer.ts +33 -0
  122. package/src/core/design/variables.ts +319 -0
  123. package/src/core/elements/definition.ts +12 -0
  124. package/src/core/elements/dynamic-elements.ts +173 -0
  125. package/src/core/elements/form-elements.ts +204 -0
  126. package/src/core/elements/index.ts +742 -0
  127. package/src/core/elements/plain-text.ts +32 -0
  128. package/src/core/forms/binding.ts +61 -0
  129. package/src/core/forms/definition.ts +34 -0
  130. package/src/core/forms/success-layout.ts +63 -0
  131. package/src/core/icons/catalog.ts +273 -0
  132. package/src/core/index.ts +316 -0
  133. package/src/core/limits.ts +7 -0
  134. package/src/core/migrate/index.ts +76 -0
  135. package/src/core/render/context.ts +14 -0
  136. package/src/core/render/dynamic-post.ts +147 -0
  137. package/src/core/render/extras.ts +79 -0
  138. package/src/core/render/form.ts +137 -0
  139. package/src/core/render/index.ts +274 -0
  140. package/src/core/render/loop.ts +36 -0
  141. package/src/core/render/section.ts +33 -0
  142. package/src/core/render/tabs.ts +72 -0
  143. package/src/core/render/vnode.ts +87 -0
  144. package/src/core/sanitize/css.ts +591 -0
  145. package/src/core/sanitize/embed-url.ts +103 -0
  146. package/src/core/sanitize/escape.ts +10 -0
  147. package/src/core/sanitize/href.ts +6 -0
  148. package/src/core/sanitize/media-url.ts +7 -0
  149. package/src/core/sanitize/svg.ts +293 -0
  150. package/src/core/sanitize/url.ts +31 -0
  151. package/src/core/schema/descriptors.ts +33 -0
  152. package/src/core/schema/design.ts +88 -0
  153. package/src/core/schema/layout.ts +817 -0
  154. package/src/core/schema/state-names.ts +4 -0
  155. package/src/core/schema/style.ts +257 -0
  156. package/src/core/stats.ts +18 -0
  157. package/src/core/tabs/presence.ts +16 -0
  158. package/src/core/theme/conditions.ts +321 -0
  159. package/src/core/theme/dynamic.ts +133 -0
  160. package/src/core/theme/parse-doc.ts +36 -0
  161. package/src/core/theme/part-types.ts +79 -0
  162. package/src/core/theme/popup-markup.ts +39 -0
  163. package/src/core/theme/popup-rules.ts +61 -0
  164. package/src/core/theme/triggers.ts +104 -0
  165. package/src/core/tree-ops.ts +139 -0
  166. package/src/core/validate.ts +185 -0
  167. package/src/index.ts +18 -0
  168. package/src/server/design-routes.ts +125 -0
  169. package/src/server/hooks.ts +98 -0
  170. package/src/server/plugin.ts +39 -0
@@ -0,0 +1,133 @@
1
+ import type { Layout, LayoutNode } from "../schema/layout.ts";
2
+ import { isParentNode } from "../schema/layout.ts";
3
+ import type { VNode } from "../render/vnode.ts";
4
+
5
+ /** Normalized post fields for server-side theme binding (framework-free). */
6
+ export type ThemePostFields = {
7
+ id: string;
8
+ slug: string;
9
+ title: string;
10
+ excerpt: string;
11
+ /** Portable Text JSON, plain string, or already-normalized blocks. */
12
+ content: unknown;
13
+ featuredImageUrl?: string;
14
+ featuredImageAlt?: string;
15
+ /** Public path, e.g. `/posts/welcome`. */
16
+ permalink: string;
17
+ /** ISO date or a display string from the post. */
18
+ publishedAt?: string;
19
+ authorName?: string;
20
+ };
21
+
22
+ /** Data passed into `renderPage` when resolving Single Post / Archive / Loop Item. */
23
+ export type ThemeDynamicData = {
24
+ post?: ThemePostFields;
25
+ posts?: ThemePostFields[];
26
+ /** Published Loop Item layouts keyed by theme-part entry id. */
27
+ loopTemplates?: Record<string, Layout>;
28
+ /** Published Section layouts keyed by theme-part entry id. */
29
+ sectionTemplates?: Record<string, Layout>;
30
+ /** Section part ids already being expanded, so a section cannot include itself. */
31
+ sectionStack?: readonly string[];
32
+ archiveTitle?: string;
33
+ };
34
+
35
+ /** Editor canvas placeholders when no live post is bound. */
36
+ export const SAMPLE_POST: ThemePostFields = {
37
+ id: "sample",
38
+ slug: "sample",
39
+ title: "Post Title",
40
+ excerpt: "Post excerpt…",
41
+ content: "Post content…",
42
+ permalink: "#",
43
+ featuredImageAlt: "Featured image",
44
+ };
45
+
46
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
47
+ Boolean(value) && typeof value === "object";
48
+
49
+ const spanText = (children: unknown) =>
50
+ Array.isArray(children)
51
+ ? children
52
+ .filter(isRecord)
53
+ .map((span) => (typeof span["text"] === "string" ? span["text"] : ""))
54
+ .join("")
55
+ : "";
56
+
57
+ const HEADING_STYLES = new Set(["h1", "h2", "h3", "h4"]);
58
+
59
+ /**
60
+ * Convert Portable Text (or a plain string) into safe VNodes.
61
+ * Marks are flattened to escaped text; only block structure is preserved.
62
+ */
63
+ export function portableTextToVNodes(value: unknown): VNode[] {
64
+ if (typeof value === "string") {
65
+ const trimmed = value.trim();
66
+ return trimmed ? [{ tag: "p", attrs: {}, children: [trimmed] }] : [];
67
+ }
68
+ if (!Array.isArray(value)) return [];
69
+ return value.flatMap((block): VNode[] => {
70
+ if (!isRecord(block) || block["_type"] !== "block") return [];
71
+ const text = spanText(block["children"]).trim();
72
+ if (!text) return [];
73
+ const style = block["style"];
74
+ const tag = typeof style === "string" && HEADING_STYLES.has(style) ? style : "p";
75
+ return [{ tag, attrs: {}, children: [text] }];
76
+ });
77
+ }
78
+
79
+ /** Collect `loop.itemPartId` values so hosts can load Loop Item templates. */
80
+ export function collectLoopItemPartIds(layout: Layout): string[] {
81
+ const ids = new Set<string>();
82
+ const walk = (node: LayoutNode): void => {
83
+ if (node.type === "loop") {
84
+ const id =
85
+ typeof (node.props as { itemPartId?: unknown }).itemPartId === "string"
86
+ ? (node.props as { itemPartId: string }).itemPartId.trim()
87
+ : "";
88
+ if (id) ids.add(id);
89
+ }
90
+ if (isParentNode(node)) {
91
+ for (const child of node.children) walk(child);
92
+ }
93
+ };
94
+ walk(layout.root);
95
+ return [...ids];
96
+ }
97
+
98
+ /** Collect `section.partId` values so hosts can load Section templates. */
99
+ export function collectSectionPartIds(layout: Layout): string[] {
100
+ const ids = new Set<string>();
101
+ const walk = (node: LayoutNode): void => {
102
+ if (node.type === "section") {
103
+ const id =
104
+ typeof (node.props as { partId?: unknown }).partId === "string"
105
+ ? (node.props as { partId: string }).partId.trim()
106
+ : "";
107
+ if (id) ids.add(id);
108
+ }
109
+ if (isParentNode(node)) {
110
+ for (const child of node.children) walk(child);
111
+ }
112
+ };
113
+ walk(layout.root);
114
+ return [...ids];
115
+ }
116
+
117
+ export function resolvePostForRender(
118
+ dynamic: ThemeDynamicData | undefined,
119
+ mode: "public" | "editor",
120
+ ): ThemePostFields | undefined {
121
+ if (dynamic?.post) return dynamic.post;
122
+ if (mode === "editor") return SAMPLE_POST;
123
+ return undefined;
124
+ }
125
+
126
+ export function resolvePostsForLoop(
127
+ dynamic: ThemeDynamicData | undefined,
128
+ mode: "public" | "editor",
129
+ ): ThemePostFields[] {
130
+ if (dynamic?.posts && dynamic.posts.length > 0) return dynamic.posts;
131
+ if (mode === "editor") return [SAMPLE_POST];
132
+ return [];
133
+ }
@@ -0,0 +1,36 @@
1
+ import type { z } from "zod";
2
+
3
+ export type DocIssue = { path: string; code: string; message: string };
4
+
5
+ /**
6
+ * Parses a stored JSON document (a string or an already-parsed value) with `schema`. Issue paths
7
+ * start at `root`; unparseable JSON is one `invalid_json` issue saying "`label` must be JSON."
8
+ */
9
+ export function parseDoc<T>(
10
+ raw: unknown,
11
+ schema: z.ZodType<T>,
12
+ root: string,
13
+ label: string,
14
+ ): { ok: true; doc: T } | { ok: false; issues: DocIssue[] } {
15
+ let value = raw;
16
+ if (typeof raw === "string") {
17
+ try {
18
+ value = JSON.parse(raw) as unknown;
19
+ } catch {
20
+ return {
21
+ ok: false,
22
+ issues: [{ path: root, code: "invalid_json", message: `${label} must be JSON.` }],
23
+ };
24
+ }
25
+ }
26
+ const parsed = schema.safeParse(value);
27
+ if (parsed.success) return { ok: true, doc: parsed.data };
28
+ return {
29
+ ok: false,
30
+ issues: parsed.error.issues.map((issue) => ({
31
+ path: issue.path.length ? `${root}.${issue.path.join(".")}` : root,
32
+ code: issue.code,
33
+ message: issue.message,
34
+ })),
35
+ };
36
+ }
@@ -0,0 +1,79 @@
1
+ /** Site-part types stored on `emvb_theme_parts.part_type` (S7a–S7d + S7b popups). */
2
+ export const THEME_PART_TYPES = [
3
+ "header",
4
+ "footer",
5
+ "error_404",
6
+ "search_results",
7
+ "single_page",
8
+ "single_post",
9
+ "archive",
10
+ "loop_item",
11
+ "section",
12
+ "page_template",
13
+ "popup",
14
+ ] as const;
15
+
16
+ export type ThemePartType = (typeof THEME_PART_TYPES)[number];
17
+
18
+ /**
19
+ * Body/main templates that compete for `<main>` (S7c + S7d).
20
+ * `loop_item`, `section`, and `page_template` are reusable fragments — not page locations.
21
+ * `popup` injects overlays (not a main replacement).
22
+ */
23
+ export const CONTENT_THEME_PART_TYPES = [
24
+ "error_404",
25
+ "search_results",
26
+ "single_page",
27
+ "single_post",
28
+ "archive",
29
+ ] as const;
30
+
31
+ export type ContentThemePartType = (typeof CONTENT_THEME_PART_TYPES)[number];
32
+
33
+ /** Reusable item templates (not selected by route). */
34
+ export const ITEM_THEME_PART_TYPES = ["loop_item", "section", "page_template"] as const;
35
+
36
+ export type ItemThemePartType = (typeof ITEM_THEME_PART_TYPES)[number];
37
+
38
+ /** Overlay parts that inject into the page end (S7b). */
39
+ export const OVERLAY_THEME_PART_TYPES = ["popup"] as const;
40
+
41
+ export type OverlayThemePartType = (typeof OVERLAY_THEME_PART_TYPES)[number];
42
+
43
+ export const THEME_PART_TYPE_LABELS: Record<ThemePartType, string> = {
44
+ header: "Header",
45
+ footer: "Footer",
46
+ error_404: "Error 404",
47
+ search_results: "Search Results",
48
+ single_page: "Single Page",
49
+ single_post: "Single Post",
50
+ archive: "Archive",
51
+ loop_item: "Loop Item",
52
+ section: "Section",
53
+ page_template: "Page template",
54
+ popup: "Popup",
55
+ };
56
+
57
+ export function isThemePartType(value: unknown): value is ThemePartType {
58
+ return typeof value === "string" && (THEME_PART_TYPES as readonly string[]).includes(value);
59
+ }
60
+
61
+ export function parseThemePartType(value: unknown): ThemePartType | null {
62
+ return isThemePartType(value) ? value : null;
63
+ }
64
+
65
+ export function isContentThemePartType(value: unknown): value is ContentThemePartType {
66
+ return (
67
+ typeof value === "string" && (CONTENT_THEME_PART_TYPES as readonly string[]).includes(value)
68
+ );
69
+ }
70
+
71
+ export function isItemThemePartType(value: unknown): value is ItemThemePartType {
72
+ return typeof value === "string" && (ITEM_THEME_PART_TYPES as readonly string[]).includes(value);
73
+ }
74
+
75
+ export function isOverlayThemePartType(value: unknown): value is OverlayThemePartType {
76
+ return (
77
+ typeof value === "string" && (OVERLAY_THEME_PART_TYPES as readonly string[]).includes(value)
78
+ );
79
+ }
@@ -0,0 +1,39 @@
1
+ import { escapeAttr } from "../sanitize/escape.ts";
2
+ import type { TriggersDoc } from "./triggers.ts";
3
+
4
+ /** Minimal chrome styles for public popups (loaded only when popups match). */
5
+ export const POPUP_CHROME_CSS = `
6
+ .emvb-popup{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;padding:1.5rem;box-sizing:border-box}
7
+ .emvb-popup[hidden]{display:none!important}
8
+ .emvb-popup__backdrop{position:absolute;inset:0;background:rgba(15,23,42,.55)}
9
+ .emvb-popup__dialog{position:relative;z-index:1;max-width:min(36rem,100%);max-height:min(90vh,100%);overflow:auto;background:#fff;color:#0f172a;border-radius:.75rem;box-shadow:0 25px 50px -12px rgba(0,0,0,.35);padding:1.5rem 1.5rem 1.25rem}
10
+ .emvb-popup__close{position:absolute;top:.5rem;right:.5rem;width:2rem;height:2rem;border:0;border-radius:999px;background:transparent;color:inherit;font-size:1.5rem;line-height:1;cursor:pointer}
11
+ .emvb-popup__close:focus-visible{outline:2px solid #2563eb;outline-offset:2px}
12
+ .emvb-popup__content{min-width:12rem}
13
+ `
14
+ .replace(/\n+/g, "")
15
+ .trim();
16
+
17
+ export type PopupPublicConfig = {
18
+ id: string;
19
+ triggers: TriggersDoc;
20
+ };
21
+
22
+ /**
23
+ * Wrap rendered popup body HTML with dialog chrome and a JSON config attribute
24
+ * for the optional public runtime (R-031: only loaded when popups are present).
25
+ */
26
+ export function wrapPopupMarkup(id: string, bodyHtml: string, triggers: TriggersDoc): string {
27
+ const config: PopupPublicConfig = { id, triggers };
28
+ const configJson = escapeAttr(JSON.stringify(config));
29
+ const safeId = escapeAttr(id);
30
+ const titleId = `emvb-popup-title-${safeId}`;
31
+ return [
32
+ `<div class="emvb-popup" id="emvb-popup-${safeId}" data-emvb-popup="${safeId}" data-emvb-popup-config="${configJson}" hidden>`,
33
+ `<div class="emvb-popup__backdrop" data-emvb-popup-dismiss tabindex="-1"></div>`,
34
+ `<div class="emvb-popup__dialog" role="dialog" aria-modal="true" aria-labelledby="${titleId}" tabindex="-1">`,
35
+ `<button type="button" class="emvb-popup__close" data-emvb-popup-dismiss aria-label="Close"><span aria-hidden="true">×</span></button>`,
36
+ `<div class="emvb-popup__content" id="${titleId}">${bodyHtml}</div>`,
37
+ `</div></div>`,
38
+ ].join("");
39
+ }
@@ -0,0 +1,61 @@
1
+ // No zod here: the public popup runtime imports this file, and pages with popups should only
2
+ // ship the runtime.
3
+
4
+ /** Trigger limits shared by the triggers schema, the editor fields and the public runtime. */
5
+ export const TRIGGER_LIMITS = {
6
+ maxDelayMs: 120_000,
7
+ maxScrollPercent: 100,
8
+ minIdleMs: 1_000,
9
+ } as const;
10
+
11
+ export const POPUP_DEVICES = ["desktop", "tablet", "mobile"] as const;
12
+ export type PopupDevice = (typeof POPUP_DEVICES)[number];
13
+
14
+ /**
15
+ * Widths that agree with `deviceForWidth` (W-096). The canvas previews tablet at 768 and mobile
16
+ * at 390, with no zoom. Public CSS uses the matching max-width queries.
17
+ */
18
+ export const DEVICE_PREVIEW_PX = { tablet: 768, mobile: 390 } as const;
19
+
20
+ /** Public CSS queries. Bounds match `deviceForWidth`: 767 mobile, 1024 tablet, 1025 desktop. */
21
+ export const DEVICE_MEDIA = {
22
+ tablet: "(max-width: 1024px)",
23
+ mobile: "(max-width: 767px)",
24
+ hideDesktop: "(min-width: 1025px)",
25
+ hideTablet: "(min-width: 768px) and (max-width: 1024px)",
26
+ hideMobile: "(max-width: 767px)",
27
+ } as const;
28
+
29
+ /** A scroll percent as a number from 0 to 100; anything unreadable is 0. */
30
+ export const clampScrollPercent = (value: unknown): number =>
31
+ Math.min(TRIGGER_LIMITS.maxScrollPercent, Math.max(0, Number(value) || 0));
32
+
33
+ /** Breakpoints aligned with common Elementor/EmVB device tiers. */
34
+ export function deviceForWidth(width: number): PopupDevice {
35
+ if (width < 768) return "mobile";
36
+ if (width < 1025) return "tablet";
37
+ return "desktop";
38
+ }
39
+
40
+ /** True when advanced.devices is unset/empty or includes the current device. */
41
+ export function matchesPopupDevices(
42
+ advanced: { devices?: readonly PopupDevice[] | null | undefined } | undefined,
43
+ width: number,
44
+ ): boolean {
45
+ const devices = advanced?.devices;
46
+ if (!devices || devices.length === 0) return true;
47
+ return devices.includes(deviceForWidth(width));
48
+ }
49
+
50
+ /**
51
+ * Pure check for show-times (localStorage count is supplied by the runtime).
52
+ * `null`/`undefined` showTimes = unlimited.
53
+ */
54
+ export function withinShowTimes(
55
+ advanced: { showTimes?: number | null | undefined } | undefined,
56
+ timesShown: number,
57
+ ): boolean {
58
+ const limit = advanced?.showTimes;
59
+ if (limit === null || limit === undefined) return true;
60
+ return timesShown < limit;
61
+ }
@@ -0,0 +1,104 @@
1
+ import { z } from "zod";
2
+ import { parseDoc } from "./parse-doc.ts";
3
+ import { POPUP_DEVICES, TRIGGER_LIMITS } from "./popup-rules.ts";
4
+
5
+ export const TRIGGERS_SCHEMA_VERSION = 1;
6
+ export const MAX_POPUP_TRIGGERS = 8;
7
+ const MAX_CLICK_SELECTOR_LENGTH = 200;
8
+ const MAX_SHOW_TIMES = 100;
9
+
10
+ /** Open triggers (Elementor-inspired). URL rules / scheduling / A/B deferred (W-081). */
11
+ const PageLoadTrigger = z.strictObject({ type: z.literal("page_load") });
12
+ const DelayTrigger = z.strictObject({
13
+ type: z.literal("delay"),
14
+ ms: z.number().int().min(0).max(TRIGGER_LIMITS.maxDelayMs),
15
+ });
16
+ const ScrollTrigger = z.strictObject({
17
+ type: z.literal("scroll"),
18
+ percent: z.number().int().min(0).max(TRIGGER_LIMITS.maxScrollPercent),
19
+ });
20
+ const ClickTrigger = z.strictObject({
21
+ type: z.literal("click"),
22
+ selector: z.string().min(1).max(MAX_CLICK_SELECTOR_LENGTH),
23
+ });
24
+ const ExitIntentTrigger = z.strictObject({ type: z.literal("exit_intent") });
25
+ const InactivityTrigger = z.strictObject({
26
+ type: z.literal("inactivity"),
27
+ ms: z.number().int().min(TRIGGER_LIMITS.minIdleMs).max(TRIGGER_LIMITS.maxDelayMs),
28
+ });
29
+
30
+ const PopupOpenTriggerSchema = z.discriminatedUnion("type", [
31
+ PageLoadTrigger,
32
+ DelayTrigger,
33
+ ScrollTrigger,
34
+ ClickTrigger,
35
+ ExitIntentTrigger,
36
+ InactivityTrigger,
37
+ ]);
38
+
39
+ export type PopupOpenTrigger = z.infer<typeof PopupOpenTriggerSchema>;
40
+
41
+ const DeviceSchema = z.enum(POPUP_DEVICES);
42
+
43
+ /**
44
+ * Advanced rules — MVP-thin (D-TB-11).
45
+ * `showTimes` null = unlimited; `devices` null/empty = all devices.
46
+ */
47
+ const AdvancedRulesSchema = z.strictObject({
48
+ showTimes: z.number().int().min(1).max(MAX_SHOW_TIMES).nullable().optional(),
49
+ devices: z.array(DeviceSchema).max(3).nullable().optional(),
50
+ });
51
+
52
+ export type PopupAdvancedRules = z.infer<typeof AdvancedRulesSchema>;
53
+
54
+ const TriggersDocSchema = z.strictObject({
55
+ schemaVersion: z.literal(TRIGGERS_SCHEMA_VERSION),
56
+ open: z.array(PopupOpenTriggerSchema).min(1).max(MAX_POPUP_TRIGGERS),
57
+ advanced: AdvancedRulesSchema.default({}),
58
+ });
59
+
60
+ export type TriggersDoc = z.infer<typeof TriggersDocSchema>;
61
+
62
+ /** Default: open on page load (Elementor default). */
63
+ export const defaultTriggers = (): TriggersDoc => ({
64
+ schemaVersion: TRIGGERS_SCHEMA_VERSION,
65
+ open: [{ type: "page_load" }],
66
+ advanced: {},
67
+ });
68
+
69
+ export type TriggersValidation =
70
+ | { ok: true; triggers: TriggersDoc }
71
+ | { ok: false; issues: { path: string; code: string; message: string }[] };
72
+
73
+ export function validateTriggers(raw: unknown): TriggersValidation {
74
+ const parsed = parseDoc(raw, TriggersDocSchema, "triggers", "Triggers");
75
+ if (!parsed.ok) return parsed;
76
+ for (const [i, trigger] of parsed.doc.open.entries()) {
77
+ if (trigger.type === "click" && !isSafeClickSelector(trigger.selector)) {
78
+ return {
79
+ ok: false,
80
+ issues: [
81
+ {
82
+ path: `triggers.open[${i}].selector`,
83
+ code: "unsafe_selector",
84
+ message: "Click selector may only use simple CSS selectors (no scripts).",
85
+ },
86
+ ],
87
+ };
88
+ }
89
+ }
90
+ return { ok: true, triggers: parsed.doc };
91
+ }
92
+
93
+ /**
94
+ * Reject selectors that look like they could smuggle JS or break out of attributes.
95
+ * Public runtime uses querySelector; keep the surface small.
96
+ */
97
+ export function isSafeClickSelector(selector: string): boolean {
98
+ const trimmed = selector.trim();
99
+ if (!trimmed || trimmed.length > MAX_CLICK_SELECTOR_LENGTH) return false;
100
+ if (/[<>`]/.test(trimmed)) return false;
101
+ if (/javascript:/i.test(trimmed)) return false;
102
+ // Allow common CSS selector chars only.
103
+ return /^[a-zA-Z0-9\s\-_.#[\]=,:()>+~*"'|/]+$/.test(trimmed);
104
+ }
@@ -0,0 +1,139 @@
1
+ import {
2
+ isContainerNode,
3
+ isParentNode,
4
+ type ContainerNode,
5
+ type Layout,
6
+ type LayoutNode,
7
+ LAYOUT_SCHEMA_VERSION,
8
+ } from "./schema/layout.ts";
9
+
10
+ /** Children of a parent node (container/form), or of an unknown node that carried children (W-022). */
11
+ export const nodeChildren = (node: LayoutNode): LayoutNode[] => {
12
+ if (isParentNode(node)) return node.children;
13
+ if ("children" in node && Array.isArray(node.children)) return node.children as LayoutNode[];
14
+ return [];
15
+ };
16
+
17
+ /** Where a removed node was, so it can be put back exactly (the Restore toast, D-025). */
18
+ export type Removed = { node: LayoutNode; parentId: string; index: number };
19
+
20
+ export function findNode(layout: Layout, id: string): LayoutNode | undefined {
21
+ const walk = (node: LayoutNode): LayoutNode | undefined => {
22
+ if (node.id === id) return node;
23
+ for (const child of nodeChildren(node)) {
24
+ const found = walk(child);
25
+ if (found) return found;
26
+ }
27
+ return undefined;
28
+ };
29
+ return walk(layout.root);
30
+ }
31
+
32
+ function mapTree(node: LayoutNode, fn: (node: LayoutNode) => LayoutNode): LayoutNode {
33
+ const mapped = fn(node);
34
+ const kids = nodeChildren(mapped);
35
+ if (kids.length === 0 && !isParentNode(mapped)) return mapped;
36
+ if (isParentNode(mapped)) {
37
+ return { ...mapped, children: mapped.children.map((child) => mapTree(child, fn)) };
38
+ }
39
+ if ("children" in mapped && Array.isArray(mapped.children)) {
40
+ return {
41
+ ...mapped,
42
+ children: (mapped.children as LayoutNode[]).map((child) => mapTree(child, fn)),
43
+ };
44
+ }
45
+ return mapped;
46
+ }
47
+
48
+ /** Replaces the node with `id` by `update(node)`. Pure: the input layout is not changed. */
49
+ export function updateNode(
50
+ layout: Layout,
51
+ id: string,
52
+ update: (node: LayoutNode) => LayoutNode,
53
+ ): Layout {
54
+ const root = mapTree(layout.root, (node) => (node.id === id ? update(node) : node));
55
+ return { ...layout, root: root as ContainerNode };
56
+ }
57
+
58
+ /** Removes a node (never the root) and reports where it was. */
59
+ export function removeNode(layout: Layout, id: string): { layout: Layout; removed?: Removed } {
60
+ if (layout.root.id === id) return { layout };
61
+ let removed: Removed | undefined;
62
+ const root = mapTree(layout.root, (node) => {
63
+ if (!isParentNode(node)) return node;
64
+ const index = node.children.findIndex((child) => child.id === id);
65
+ if (index === -1) return node;
66
+ removed = { node: node.children[index] as LayoutNode, parentId: node.id, index };
67
+ return { ...node, children: node.children.filter((child) => child.id !== id) };
68
+ });
69
+ return removed ? { layout: { ...layout, root: root as ContainerNode }, removed } : { layout };
70
+ }
71
+
72
+ /** Inserts `node` into container `parentId` at `index` (clamped). Unknown parents leave it unchanged. */
73
+ export function insertNode(
74
+ layout: Layout,
75
+ parentId: string,
76
+ index: number,
77
+ node: LayoutNode,
78
+ ): Layout {
79
+ return updateNode(layout, parentId, (parent) => {
80
+ if (!isParentNode(parent)) return parent;
81
+ const at = Math.max(0, Math.min(index, parent.children.length));
82
+ return {
83
+ ...parent,
84
+ children: [...parent.children.slice(0, at), node, ...parent.children.slice(at)],
85
+ };
86
+ });
87
+ }
88
+
89
+ /**
90
+ * The id of the node a validation path points at, for example `root.children[0].props.level`.
91
+ * Used to select the element at fault when the server rejects a save (IA, 422 handling).
92
+ */
93
+ export function nodeIdAtPath(layout: Layout, path: string): string | undefined {
94
+ if (!path.startsWith("root")) return undefined;
95
+ let node: LayoutNode = layout.root;
96
+ for (const match of path.slice(4).matchAll(/\.children\[(\d+)\]/g)) {
97
+ const kids = nodeChildren(node);
98
+ if (kids.length === 0 && !isContainerNode(node)) break;
99
+ const next: LayoutNode | undefined = kids[Number(match[1])];
100
+ if (!next) break;
101
+ node = next;
102
+ }
103
+ return node.id;
104
+ }
105
+
106
+ const ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
107
+
108
+ /** A short random node id (A-06). */
109
+ export function newNodeId(random: () => number = Math.random): string {
110
+ let id = "";
111
+ for (let i = 0; i < 8; i++) id += ID_ALPHABET[Math.floor(random() * ID_ALPHABET.length)];
112
+ return id;
113
+ }
114
+
115
+ /** The S1 page every new page starts from: a column container with the title as its heading. */
116
+ export function starterLayout(title: string, random?: () => number): Layout {
117
+ return {
118
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
119
+ root: {
120
+ id: newNodeId(random),
121
+ type: "container",
122
+ props: {},
123
+ style: { flexDirection: "column", gap: { value: 16, unit: "px" } },
124
+ children: [{ id: newNodeId(random), type: "heading", props: { text: title, level: 1 } }],
125
+ },
126
+ };
127
+ }
128
+
129
+ /** A URL slug from a title: lowercase ASCII letters, digits and single hyphens. */
130
+ export function slugify(text: string): string {
131
+ return text
132
+ .normalize("NFKD")
133
+ .replace(/[\u0300-\u036f]/g, "")
134
+ .toLowerCase()
135
+ .replace(/[^a-z0-9]+/g, "-")
136
+ .replace(/^-+|-+$/g, "")
137
+ .slice(0, 80)
138
+ .replace(/-+$/g, "");
139
+ }