@perkyzz/emvb 0.0.0-stage → 0.2.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/THIRD_PARTY_NOTICES.md +32 -0
  4. package/licenses/fontawesome-free.LICENSE +165 -0
  5. package/licenses/lucide-static.LICENSE +43 -0
  6. package/licenses/remixicon.LICENSE +201 -0
  7. package/licenses/tabler-icons.LICENSE +21 -0
  8. package/package.json +76 -4
  9. package/src/admin/access/RequireEditor.tsx +39 -0
  10. package/src/admin/access/role.ts +36 -0
  11. package/src/admin/access/sidebar-shim.ts +108 -0
  12. package/src/admin/api.ts +75 -0
  13. package/src/admin/content-api.ts +210 -0
  14. package/src/admin/editor/Editor.tsx +532 -0
  15. package/src/admin/editor/EditorOverlay.tsx +66 -0
  16. package/src/admin/editor/ShortcutsDialog.tsx +30 -0
  17. package/src/admin/editor/SmallScreenNotice.tsx +21 -0
  18. package/src/admin/editor/TopBar.tsx +243 -0
  19. package/src/admin/editor/canvas/CanvasFrame.tsx +536 -0
  20. package/src/admin/editor/canvas/CanvasTextEdit.tsx +87 -0
  21. package/src/admin/editor/canvas/DeviceBar.tsx +91 -0
  22. package/src/admin/editor/canvas/EmptyCanvas.tsx +49 -0
  23. package/src/admin/editor/canvas/SelectionOverlay.tsx +239 -0
  24. package/src/admin/editor/canvas/canvas-events.ts +245 -0
  25. package/src/admin/editor/canvas/state-preview.ts +19 -0
  26. package/src/admin/editor/canvas/tab-reveal.ts +101 -0
  27. package/src/admin/editor/canvas/vnode-react.tsx +69 -0
  28. package/src/admin/editor/clipboard-store.ts +44 -0
  29. package/src/admin/editor/dialogs.tsx +164 -0
  30. package/src/admin/editor/dnd/drag-stash.ts +27 -0
  31. package/src/admin/editor/dnd/drop-target.ts +148 -0
  32. package/src/admin/editor/dnd/new-element.ts +107 -0
  33. package/src/admin/editor/editor-css.ts +625 -0
  34. package/src/admin/editor/exit.ts +27 -0
  35. package/src/admin/editor/host.ts +30 -0
  36. package/src/admin/editor/icons/IconLibraryDialog.tsx +850 -0
  37. package/src/admin/editor/icons/library.ts +243 -0
  38. package/src/admin/editor/icons/set-format.ts +29 -0
  39. package/src/admin/editor/icons/sets/fontawesome.json +1 -0
  40. package/src/admin/editor/icons/sets/lucide.json +1 -0
  41. package/src/admin/editor/icons/sets/remix.json +1 -0
  42. package/src/admin/editor/icons/sets/tabler.json +1 -0
  43. package/src/admin/editor/panels/AddPanel.tsx +146 -0
  44. package/src/admin/editor/panels/ClassesSection.tsx +372 -0
  45. package/src/admin/editor/panels/ColorControl.tsx +477 -0
  46. package/src/admin/editor/panels/ConditionsEditor.tsx +201 -0
  47. package/src/admin/editor/panels/ElementPanel.tsx +773 -0
  48. package/src/admin/editor/panels/LayersPanel.tsx +573 -0
  49. package/src/admin/editor/panels/LeftPanel.tsx +81 -0
  50. package/src/admin/editor/panels/PageSettings.tsx +255 -0
  51. package/src/admin/editor/panels/SettingsPanel.tsx +113 -0
  52. package/src/admin/editor/panels/SiteStylesDrawer.tsx +548 -0
  53. package/src/admin/editor/panels/TriggerSettings.tsx +132 -0
  54. package/src/admin/editor/panels/TriggersEditor.tsx +214 -0
  55. package/src/admin/editor/panels/VariableSection.tsx +530 -0
  56. package/src/admin/editor/panels/color-space.ts +195 -0
  57. package/src/admin/editor/panels/settings/AdvancedFields.tsx +119 -0
  58. package/src/admin/editor/panels/settings/BackgroundControls.tsx +418 -0
  59. package/src/admin/editor/panels/settings/BackgroundFill.tsx +221 -0
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +271 -0
  61. package/src/admin/editor/panels/settings/ChoiceGroup.tsx +138 -0
  62. package/src/admin/editor/panels/settings/ClassChip.tsx +167 -0
  63. package/src/admin/editor/panels/settings/ClassChipInput.tsx +451 -0
  64. package/src/admin/editor/panels/settings/DraftTextField.tsx +242 -0
  65. package/src/admin/editor/panels/settings/EffectsControls.tsx +354 -0
  66. package/src/admin/editor/panels/settings/FieldBindControl.tsx +119 -0
  67. package/src/admin/editor/panels/settings/FieldControl.tsx +270 -0
  68. package/src/admin/editor/panels/settings/FormBindControl.tsx +106 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +438 -0
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +170 -0
  71. package/src/admin/editor/panels/settings/ItemList.tsx +199 -0
  72. package/src/admin/editor/panels/settings/LengthRow.tsx +217 -0
  73. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +130 -0
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +220 -0
  75. package/src/admin/editor/panels/settings/NumberRow.tsx +154 -0
  76. package/src/admin/editor/panels/settings/StateSwitcher.tsx +87 -0
  77. package/src/admin/editor/panels/settings/StyleRow.tsx +563 -0
  78. package/src/admin/editor/panels/settings/VariableBinding.tsx +171 -0
  79. package/src/admin/editor/panels/settings/advanced-rules.ts +63 -0
  80. package/src/admin/editor/panels/settings/background-mode.ts +112 -0
  81. package/src/admin/editor/panels/settings/box-link-name.ts +38 -0
  82. package/src/admin/editor/panels/settings/box-sides.ts +153 -0
  83. package/src/admin/editor/panels/settings/button-url.ts +27 -0
  84. package/src/admin/editor/panels/settings/class-suggest.ts +53 -0
  85. package/src/admin/editor/panels/settings/form-names.ts +38 -0
  86. package/src/admin/editor/panels/settings/heading-warning.ts +25 -0
  87. package/src/admin/editor/panels/settings/image-alt.ts +25 -0
  88. package/src/admin/editor/panels/settings/length-units.ts +116 -0
  89. package/src/admin/editor/panels/settings/loop-context.ts +26 -0
  90. package/src/admin/editor/panels/settings/node-props.ts +11 -0
  91. package/src/admin/editor/panels/settings/style-sections.ts +394 -0
  92. package/src/admin/editor/panels/settings/svg-images.ts +14 -0
  93. package/src/admin/editor/panels/site-list.tsx +209 -0
  94. package/src/admin/editor/panels/variable-values.ts +73 -0
  95. package/src/admin/editor/restore-deleted.ts +80 -0
  96. package/src/admin/editor/section-templates.ts +50 -0
  97. package/src/admin/editor/shortcuts.ts +20 -0
  98. package/src/admin/editor/store.ts +240 -0
  99. package/src/admin/editor/useClipboardActions.ts +136 -0
  100. package/src/admin/editor/useEditorCommands.ts +203 -0
  101. package/src/admin/editor/useEditorData.ts +193 -0
  102. package/src/admin/editor/useEditorShortcuts.ts +180 -0
  103. package/src/admin/editor/useMediaQuery.ts +20 -0
  104. package/src/admin/editor/useNodeActions.ts +184 -0
  105. package/src/admin/editor/useSave.ts +242 -0
  106. package/src/admin/entry-status.ts +19 -0
  107. package/src/admin/forms-api.ts +73 -0
  108. package/src/admin/icon-uploads-api.ts +44 -0
  109. package/src/admin/index.tsx +20 -0
  110. package/src/admin/media-api.ts +68 -0
  111. package/src/admin/pages/CreateDialog.tsx +150 -0
  112. package/src/admin/pages/EditorPage.tsx +57 -0
  113. package/src/admin/pages/NewPageDialog.tsx +83 -0
  114. package/src/admin/pages/NewThemePartDialog.tsx +61 -0
  115. package/src/admin/pages/PageList.tsx +91 -0
  116. package/src/admin/pages/PagesPage.tsx +25 -0
  117. package/src/admin/pages/SetupShell.tsx +90 -0
  118. package/src/admin/pages/ThemeBuilderPage.tsx +25 -0
  119. package/src/admin/pages/ThemePartList.tsx +221 -0
  120. package/src/admin/pages/list-kit.tsx +125 -0
  121. package/src/admin/setup/plan.ts +150 -0
  122. package/src/admin/setup/run.ts +61 -0
  123. package/src/admin/setup/spec.ts +107 -0
  124. package/src/admin/setup/useSetupStatus.ts +62 -0
  125. package/src/admin/theme-api.ts +233 -0
  126. package/src/admin/ui.ts +244 -0
  127. package/src/admin/widgets/LayoutField.tsx +67 -0
  128. package/src/astro/EmVBPage.astro +63 -0
  129. package/src/astro/env.d.ts +5 -0
  130. package/src/astro/floats/EmVBFloatsRuntime.astro +9 -0
  131. package/src/astro/floats/index.ts +1 -0
  132. package/src/astro/floats/runtime.ts +78 -0
  133. package/src/astro/forms/EmVBFormsRuntime.astro +9 -0
  134. package/src/astro/forms/index.ts +1 -0
  135. package/src/astro/forms-definitions.ts +126 -0
  136. package/src/astro/index.ts +16 -0
  137. package/src/astro/menu/EmVBMenuRuntime.astro +9 -0
  138. package/src/astro/menu/index.ts +1 -0
  139. package/src/astro/menu/runtime.ts +37 -0
  140. package/src/astro/popups/EmVBPopupsRuntime.astro +9 -0
  141. package/src/astro/popups/index.ts +1 -0
  142. package/src/astro/popups/runtime.ts +296 -0
  143. package/src/astro/render.ts +108 -0
  144. package/src/astro/resolve-theme.ts +515 -0
  145. package/src/astro/resolve.ts +65 -0
  146. package/src/astro/tabs/EmVBTabsRuntime.astro +10 -0
  147. package/src/astro/tabs/index.ts +1 -0
  148. package/src/astro/tabs/runtime.ts +116 -0
  149. package/src/astro/theme-context.ts +89 -0
  150. package/src/astro/theme-posts.ts +84 -0
  151. package/src/constants.ts +12 -0
  152. package/src/core/arrange.ts +448 -0
  153. package/src/core/clipboard.ts +504 -0
  154. package/src/core/css/generate.ts +236 -0
  155. package/src/core/css/scope.ts +88 -0
  156. package/src/core/design/cascade.ts +28 -0
  157. package/src/core/design/classes.ts +224 -0
  158. package/src/core/design/devices.ts +56 -0
  159. package/src/core/design/states.ts +49 -0
  160. package/src/core/design/transfer.ts +132 -0
  161. package/src/core/design/variables.ts +359 -0
  162. package/src/core/elements/definition.ts +12 -0
  163. package/src/core/elements/dynamic-elements.ts +225 -0
  164. package/src/core/elements/field-id.ts +6 -0
  165. package/src/core/elements/form-elements.ts +219 -0
  166. package/src/core/elements/index.ts +960 -0
  167. package/src/core/elements/menu.ts +190 -0
  168. package/src/core/elements/plain-text.ts +32 -0
  169. package/src/core/forms/binding.ts +61 -0
  170. package/src/core/forms/definition.ts +45 -0
  171. package/src/core/forms/success-layout.ts +63 -0
  172. package/src/core/icons/catalog.ts +273 -0
  173. package/src/core/index.ts +380 -0
  174. package/src/core/limits.ts +9 -0
  175. package/src/core/migrate/index.ts +126 -0
  176. package/src/core/nesting.ts +51 -0
  177. package/src/core/render/context.ts +21 -0
  178. package/src/core/render/dynamic-post.ts +175 -0
  179. package/src/core/render/extras.ts +98 -0
  180. package/src/core/render/form.ts +235 -0
  181. package/src/core/render/index.ts +372 -0
  182. package/src/core/render/loop.ts +43 -0
  183. package/src/core/render/pagination.ts +76 -0
  184. package/src/core/render/section.ts +37 -0
  185. package/src/core/render/tabs.ts +76 -0
  186. package/src/core/render/vnode.ts +87 -0
  187. package/src/core/sanitize/css.ts +771 -0
  188. package/src/core/sanitize/embed-url.ts +160 -0
  189. package/src/core/sanitize/escape.ts +10 -0
  190. package/src/core/sanitize/href.ts +6 -0
  191. package/src/core/sanitize/media-url.ts +7 -0
  192. package/src/core/sanitize/svg-upload.ts +203 -0
  193. package/src/core/sanitize/svg.ts +374 -0
  194. package/src/core/sanitize/url.ts +31 -0
  195. package/src/core/schema/descriptors.ts +37 -0
  196. package/src/core/schema/design.ts +93 -0
  197. package/src/core/schema/layout.ts +1008 -0
  198. package/src/core/schema/state-names.ts +4 -0
  199. package/src/core/schema/style.ts +336 -0
  200. package/src/core/stats.ts +18 -0
  201. package/src/core/tabs/presence.ts +25 -0
  202. package/src/core/theme/conditions.ts +324 -0
  203. package/src/core/theme/dynamic.ts +143 -0
  204. package/src/core/theme/float.ts +113 -0
  205. package/src/core/theme/pagination.ts +97 -0
  206. package/src/core/theme/parse-doc.ts +36 -0
  207. package/src/core/theme/part-types.ts +81 -0
  208. package/src/core/theme/popup-markup.ts +41 -0
  209. package/src/core/theme/popup-rules.ts +62 -0
  210. package/src/core/theme/triggers.ts +104 -0
  211. package/src/core/tree-ops.ts +139 -0
  212. package/src/core/validate.ts +185 -0
  213. package/src/index.ts +18 -0
  214. package/src/server/design-routes.ts +125 -0
  215. package/src/server/hooks.ts +118 -0
  216. package/src/server/icon-routes.ts +79 -0
  217. package/src/server/plugin.ts +43 -0
@@ -0,0 +1,175 @@
1
+ import type { LayoutNode, POST_DATE_FORMATS } from "../schema/layout.ts";
2
+ import { sanitizeHref } from "../sanitize/href.ts";
3
+ import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
4
+ import { portableTextToVNodes, type ThemePostFields } from "../theme/dynamic.ts";
5
+ import type { RenderMode } from "./context.ts";
6
+ import type { VNode } from "./vnode.ts";
7
+
8
+ /**
9
+ * W-196: only an ISO date (`2026-10-06`, optionally with a time) is read as a date. `Date.parse`
10
+ * also takes text like "Spring 2026" (as Jan 1) or "2026-02-30", which would show a wrong date.
11
+ */
12
+ const parseIsoDate = (raw: string): number => {
13
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[T ][\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/.exec(raw);
14
+ if (!match) return Number.NaN;
15
+ const parsed = Date.parse(raw.replace(" ", "T"));
16
+ if (Number.isNaN(parsed)) return Number.NaN;
17
+ const day = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
18
+ return day.getUTCDate() === Number(match[3]) && day.getUTCMonth() === Number(match[2]) - 1
19
+ ? parsed
20
+ : Number.NaN;
21
+ };
22
+
23
+ type Attrs = Record<string, string>;
24
+
25
+ type PostField = {
26
+ /** Shown in the editor when there is no post, or the post lacks this field; public pages show nothing. */
27
+ placeholder: (attrs: Attrs) => VNode;
28
+ /** Whether the post has this field; the placeholder stands in when it doesn't. */
29
+ has?: (post: ThemePostFields) => boolean;
30
+ /** The field's markup, or nothing when the post's value is empty or unsafe. */
31
+ render: (node: LayoutNode, attrs: Attrs, post: ThemePostFields) => VNode | undefined;
32
+ };
33
+
34
+ const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const;
35
+
36
+ type PostDateFormat = (typeof POST_DATE_FORMATS)[number];
37
+
38
+ /** In UTC, so the date doesn't move with the server's time zone. */
39
+ function formatPostDate(time: number, format: PostDateFormat): string {
40
+ const date = new Date(time);
41
+ if (format === "numeric") return date.toISOString().slice(0, 10);
42
+ return new Intl.DateTimeFormat("en", { dateStyle: format, timeZone: "UTC" }).format(date);
43
+ }
44
+
45
+ const props = <T>(node: LayoutNode) => node.props as T;
46
+
47
+ const POST_FIELDS = new Map<string, PostField>([
48
+ [
49
+ "post-title",
50
+ {
51
+ placeholder: (attrs) => ({ tag: "h1", attrs, children: ["Post Title"] }),
52
+ render: (node, attrs, post) => {
53
+ const level = props<{ level?: number }>(node).level ?? 1;
54
+ const tag = HEADING_TAGS[Math.min(6, Math.max(1, level)) - 1] ?? "h1";
55
+ return { tag, attrs, children: [post.title] };
56
+ },
57
+ },
58
+ ],
59
+ [
60
+ "post-excerpt",
61
+ {
62
+ placeholder: (attrs) => ({ tag: "p", attrs, children: ["Post excerpt…"] }),
63
+ render: (node, attrs, post) => {
64
+ if (!post.excerpt) return undefined;
65
+ const max = props<{ maxWords?: number }>(node).maxWords;
66
+ const words = post.excerpt.trim().split(/\s+/);
67
+ const text = max && words.length > max ? `${words.slice(0, max).join(" ")}…` : post.excerpt;
68
+ return { tag: "p", attrs, children: [text] };
69
+ },
70
+ },
71
+ ],
72
+ [
73
+ "post-content",
74
+ {
75
+ placeholder: (attrs) => ({
76
+ tag: "div",
77
+ attrs,
78
+ children: [{ tag: "p", attrs: {}, children: ["Post content…"] }],
79
+ }),
80
+ render: (_node, attrs, post) => {
81
+ const blocks = portableTextToVNodes(post.content);
82
+ return blocks.length > 0 ? { tag: "div", attrs, children: blocks } : undefined;
83
+ },
84
+ },
85
+ ],
86
+ [
87
+ "post-image",
88
+ {
89
+ placeholder: (attrs) => ({
90
+ tag: "div",
91
+ attrs: { ...attrs, class: `${attrs.class ?? ""} emvb-post-image-missing`.trim() },
92
+ children: ["Featured image"],
93
+ }),
94
+ has: (post) => !!post.featuredImageUrl,
95
+ render: (node, attrs, post) => {
96
+ const src = sanitizeMediaUrl(post.featuredImageUrl ?? "");
97
+ if (!src) return undefined;
98
+ const alt = props<{ decorative?: boolean }>(node).decorative
99
+ ? ""
100
+ : post.featuredImageAlt?.trim() || post.title || "Featured image";
101
+ return { tag: "img", attrs: { ...attrs, src, alt }, children: [] };
102
+ },
103
+ },
104
+ ],
105
+ [
106
+ "post-link",
107
+ {
108
+ placeholder: (attrs) => ({
109
+ tag: "a",
110
+ attrs: { ...attrs, href: "#" },
111
+ children: ["Post link"],
112
+ }),
113
+ render: (node, attrs, post) => {
114
+ const href = sanitizeHref(post.permalink);
115
+ if (!href) return undefined;
116
+ const { text, newTab } = props<{ text?: string; newTab?: boolean }>(node);
117
+ const linkAttrs: Attrs = { ...attrs, href };
118
+ if (newTab) {
119
+ linkAttrs.target = "_blank";
120
+ linkAttrs.rel = "noopener noreferrer";
121
+ }
122
+ return {
123
+ tag: "a",
124
+ attrs: linkAttrs,
125
+ children: [text?.trim() || post.title || post.permalink],
126
+ };
127
+ },
128
+ },
129
+ ],
130
+ [
131
+ "post-date",
132
+ {
133
+ placeholder: (attrs) => ({ tag: "time", attrs, children: ["Post date"] }),
134
+ has: (post) => !!post.publishedAt?.trim(),
135
+ render: (node, attrs, post) => {
136
+ const raw = post.publishedAt?.trim();
137
+ if (!raw) return undefined;
138
+ const parsed = parseIsoDate(raw);
139
+ const format = props<{ format?: PostDateFormat }>(node).format ?? "medium";
140
+ const text = Number.isNaN(parsed) ? raw.slice(0, 80) : formatPostDate(parsed, format);
141
+ // W-196: `datetime` must be machine-readable, so a date we can't read only shows as text.
142
+ const timeAttrs = Number.isNaN(parsed) ? attrs : { ...attrs, datetime: raw.slice(0, 80) };
143
+ return { tag: "time", attrs: timeAttrs, children: [text] };
144
+ },
145
+ },
146
+ ],
147
+ [
148
+ "post-author",
149
+ {
150
+ placeholder: (attrs) => ({ tag: "span", attrs, children: ["Author"] }),
151
+ has: (post) => !!post.authorName?.trim(),
152
+ render: (_node, attrs, post) => {
153
+ const name = post.authorName?.trim();
154
+ return name ? { tag: "span", attrs, children: [name.slice(0, 200)] } : undefined;
155
+ },
156
+ },
157
+ ],
158
+ ]);
159
+
160
+ export const isDynamicPostNode = (node: LayoutNode) => POST_FIELDS.has(node.type);
161
+
162
+ /** A post field element: the post's value publicly, a placeholder in the editor when there is no post. */
163
+ export function renderDynamicPost(
164
+ node: LayoutNode,
165
+ attrs: Attrs,
166
+ post: ThemePostFields | undefined,
167
+ mode: RenderMode,
168
+ ): VNode | undefined {
169
+ const field = POST_FIELDS.get(node.type);
170
+ if (!field) return undefined;
171
+ if (!post || field.has?.(post) === false) {
172
+ return mode === "editor" ? field.placeholder(attrs) : undefined;
173
+ }
174
+ return field.render(node, attrs, post);
175
+ }
@@ -0,0 +1,98 @@
1
+ import type { LayoutNode } from "../schema/layout.ts";
2
+ import { sanitizeHref } from "../sanitize/href.ts";
3
+ import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
4
+ import type { VNode } from "./vnode.ts";
5
+
6
+ const ATTR_NAME = /^(?:data|aria)-[a-z][a-z0-9-]{0,40}$/;
7
+ const BOX = new Set(["container", "div-block", "flexbox", "grid"]);
8
+
9
+ /**
10
+ * Names the EmDash forms client reads (`[data-ec-form]`, `[data-page]`, `[data-error-for]`…). One of
11
+ * them on an element would make the client treat it as a form, a form page or an error slot (W-191).
12
+ */
13
+ const FORMS_RUNTIME_ATTRS = new Set([
14
+ "data-condition",
15
+ "data-error-for",
16
+ "data-form-id",
17
+ "data-form-status",
18
+ "data-page",
19
+ "data-sitekey",
20
+ "data-submit-label",
21
+ "data-was-required",
22
+ ]);
23
+
24
+ /** Custom attribute names EmVB keeps for itself: the editor's and the forms client's. */
25
+ export const isReservedAttribute = (name: string): boolean =>
26
+ name.startsWith("data-emvb") || name.startsWith("data-ec-") || FORMS_RUNTIME_ATTRS.has(name);
27
+
28
+ /** `data-*` and `aria-*` from Advanced, minus the reserved names (`isReservedAttribute`). */
29
+ export function customAttributes(node: LayoutNode): Record<string, string> {
30
+ const list = node.attributes;
31
+ if (!list) return {};
32
+ const attrs: Record<string, string> = {};
33
+ const seen = new Set<string>();
34
+ for (const item of list) {
35
+ if (!ATTR_NAME.test(item.name) || isReservedAttribute(item.name)) continue;
36
+ if (seen.has(item.name) || item.value.length > 200) continue;
37
+ if ([...item.value].some((char) => char.charCodeAt(0) < 32)) continue;
38
+ seen.add(item.name);
39
+ attrs[item.name] = item.value;
40
+ }
41
+ return attrs;
42
+ }
43
+
44
+ function childrenOf(node: LayoutNode): LayoutNode[] {
45
+ return "children" in node && Array.isArray(node.children) ? node.children : [];
46
+ }
47
+
48
+ /** A link, a button, or a box that is already a link. */
49
+ function containsInteractive(node: LayoutNode): boolean {
50
+ if (node.type === "link" || node.type === "post-link" || node.type === "button") return true;
51
+ if (BOX.has(node.type) || node.type === "heading" || node.type === "icon") {
52
+ const href = (node.props as { href?: unknown }).href;
53
+ if (typeof href === "string" && href.trim()) return true;
54
+ }
55
+ return childrenOf(node).some(containsInteractive);
56
+ }
57
+
58
+ /**
59
+ * A div box becomes the link. A landmark tag stays a landmark. A link already inside the box
60
+ * keeps the box from becoming a link, so the page never nests anchors.
61
+ */
62
+ export function applyBoxLink(node: LayoutNode, vnode: VNode): VNode {
63
+ if (!BOX.has(node.type) || vnode.tag !== "div") return vnode;
64
+ const { href, newTab } = node.props as { href?: string; newTab?: boolean };
65
+ if (!href?.trim()) return vnode;
66
+ if (childrenOf(node).some(containsInteractive)) return vnode;
67
+ const safe = sanitizeHref(href);
68
+ if (!safe) return vnode;
69
+ const attrs: Record<string, string> = { ...vnode.attrs, href: safe };
70
+ if (newTab) {
71
+ attrs.target = "_blank";
72
+ attrs.rel = "noopener noreferrer";
73
+ }
74
+ return { ...vnode, tag: "a", attrs };
75
+ }
76
+
77
+ export function safeBackgroundVideo(url: string | undefined): string | undefined {
78
+ if (!url || /[()\\\s"'`]/.test(url)) return undefined;
79
+ return sanitizeMediaUrl(url) === url ? url : undefined;
80
+ }
81
+
82
+ /** A muted, looping video behind the element's children. */
83
+ export function applyBackgroundVideo(vnode: VNode, src: string | undefined): VNode {
84
+ if (!src) return vnode;
85
+ const className = `${vnode.attrs.class ?? ""} emvb-has-bg-video`.trim();
86
+ return {
87
+ ...vnode,
88
+ attrs: { ...vnode.attrs, class: className },
89
+ children: [
90
+ {
91
+ tag: "video",
92
+ attrs: { class: "emvb-bg-video", src, muted: "", loop: "", playsinline: "", autoplay: "" },
93
+ children: [],
94
+ },
95
+ ...vnode.children,
96
+ ],
97
+ };
98
+ }
@@ -0,0 +1,235 @@
1
+ import { fieldByName, type FormDefinitions, type PublicFormField } from "../forms/definition.ts";
2
+ import type { FormNode, LayoutNode } from "../schema/layout.ts";
3
+ import type { ThemeDynamicData } from "../theme/dynamic.ts";
4
+ import { nodeChildren } from "../tree-ops.ts";
5
+ import type { RenderContext } from "./context.ts";
6
+ import type { VNode } from "./vnode.ts";
7
+
8
+ export const FORMS_SUBMIT_PATH = "/_emdash/api/plugins/emdash-forms/submit";
9
+
10
+ const honeypot = (inputId: string): VNode => ({
11
+ tag: "div",
12
+ attrs: {
13
+ class: "ec-form-hp",
14
+ "aria-hidden": "true",
15
+ },
16
+ children: [
17
+ {
18
+ tag: "label",
19
+ attrs: { for: inputId },
20
+ children: ["Leave blank"],
21
+ },
22
+ {
23
+ tag: "input",
24
+ attrs: {
25
+ type: "text",
26
+ id: inputId,
27
+ name: "_hp",
28
+ tabindex: "-1",
29
+ autocomplete: "off",
30
+ },
31
+ children: [],
32
+ },
33
+ ],
34
+ });
35
+
36
+ /** An EmDash Forms markup shell (D-006) around the form's fields; unbound forms only preview in the editor. */
37
+ /** The text of the form's first Submit button, as the page renders it. */
38
+ function firstSubmitLabel(nodes: readonly LayoutNode[]): string | undefined {
39
+ for (const child of nodes) {
40
+ if (child.type === "submit") return (child.props as { label?: string }).label ?? "Submit";
41
+ const found = firstSubmitLabel(nodeChildren(child));
42
+ if (found !== undefined) return found;
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ export function renderForm(
48
+ node: FormNode,
49
+ attrs: Record<string, string>,
50
+ ctx: RenderContext,
51
+ dynamic: ThemeDynamicData | undefined,
52
+ ): VNode | undefined {
53
+ const formId = node.props.formId.trim();
54
+ // Unbound forms: no live <form>/ec-form shell (avoids broken preview; public stays zero-JS).
55
+ if (!formId) {
56
+ if (ctx.mode === "public") return undefined;
57
+ return {
58
+ tag: "div",
59
+ attrs: {
60
+ ...attrs,
61
+ class: `${attrs.class} emvb-form-unbound`.trim(),
62
+ "data-emvb-form-unbound": "",
63
+ },
64
+ children: ["Bind a form in settings to preview it here."],
65
+ };
66
+ }
67
+ // W-203: the forms client puts this label back on the button after each submit, so it must be
68
+ // the label the page shows, not the form definition's.
69
+ const submitLabel =
70
+ firstSubmitLabel(node.children) ??
71
+ ctx.definitions.get(formId)?.settings.submitLabel ??
72
+ "Submit";
73
+ const page: VNode = {
74
+ tag: "div",
75
+ attrs: { "data-page": "0" },
76
+ children: ctx.children(node.children, dynamic),
77
+ };
78
+ return {
79
+ tag: "form",
80
+ attrs: {
81
+ ...attrs,
82
+ class: `${attrs.class} ec-form`.trim(),
83
+ method: "POST",
84
+ action: FORMS_SUBMIT_PATH,
85
+ "data-ec-form": "",
86
+ "data-form-id": formId,
87
+ // W-297: the forms client checks each control itself and writes the message next to the
88
+ // field, as the server's errors are; without this the browser's bubble would come first.
89
+ novalidate: "",
90
+ "data-submit-label": submitLabel,
91
+ },
92
+ children: [
93
+ page,
94
+ { tag: "input", attrs: { type: "hidden", name: "formId", value: formId }, children: [] },
95
+ // One id per form element, so the same form placed twice keeps unique ids (W-187), also
96
+ // when one form element renders twice, from a synced section or a loop item (W-249).
97
+ honeypot(ctx.uniqueId(`emvb-hp-${node.id}`)),
98
+ {
99
+ tag: "div",
100
+ attrs: { class: "ec-form-status", "data-form-status": "", "aria-live": "polite" },
101
+ children: [],
102
+ },
103
+ ],
104
+ };
105
+ }
106
+
107
+ /** Replaces the children of every node matching `match`, anywhere in the tree. */
108
+ function replaceChildren(vnode: VNode, match: (node: VNode) => boolean, children: VNode[]): VNode {
109
+ if (match(vnode)) return { ...vnode, children };
110
+ return {
111
+ ...vnode,
112
+ children: vnode.children.map((child) =>
113
+ typeof child === "string" ? child : replaceChildren(child, match, children),
114
+ ),
115
+ };
116
+ }
117
+
118
+ /** Applies `edit` to every element node in the tree, children first. */
119
+ function mapNodes(vnode: VNode, edit: (node: VNode) => VNode): VNode {
120
+ return edit({
121
+ ...vnode,
122
+ children: vnode.children.map((child) =>
123
+ typeof child === "string" ? child : mapNodes(child, edit),
124
+ ),
125
+ });
126
+ }
127
+
128
+ /** Definition types a Text input can take on; the rest stay `text`. */
129
+ const INPUT_TYPES = new Set(["email", "tel", "url", "number", "date"]);
130
+ const LENGTH_TYPES = new Set(["text", "email", "tel", "url", "textarea"]);
131
+ const isControl = (node: VNode) =>
132
+ ["input", "select", "textarea"].includes(node.tag) && node.attrs.type !== "hidden";
133
+
134
+ /**
135
+ * W-297: what the forms plugin's own embed puts on a control: the input type (so phones show the
136
+ * right keyboard), `required`, and the length, range and pattern limits, plus a visible mark on
137
+ * the label. Without them the forms client found nothing to check before sending.
138
+ */
139
+ function withFieldMeta(vnode: VNode, node: LayoutNode, meta: PublicFormField): VNode {
140
+ const type = node.type === "text-input" && INPUT_TYPES.has(meta.type) ? meta.type : undefined;
141
+ const rules = meta.validation ?? {};
142
+ const kind = type ?? (node.type === "textarea" ? "textarea" : meta.type);
143
+ const limits: Record<string, string> = {};
144
+ if (node.type === "text-input" || node.type === "textarea") {
145
+ if (LENGTH_TYPES.has(kind)) {
146
+ if (rules.minLength !== undefined) limits.minlength = String(rules.minLength);
147
+ if (rules.maxLength !== undefined) limits.maxlength = String(rules.maxLength);
148
+ }
149
+ if (kind === "number") {
150
+ if (rules.min !== undefined) limits.min = String(rules.min);
151
+ if (rules.max !== undefined) limits.max = String(rules.max);
152
+ }
153
+ if (node.type === "text-input" && kind !== "number" && kind !== "date" && rules.pattern) {
154
+ limits.pattern = rules.pattern;
155
+ }
156
+ }
157
+ const mark: VNode = {
158
+ tag: "span",
159
+ attrs: { class: "emvb-form-required", "aria-hidden": "true" },
160
+ children: [" *"],
161
+ };
162
+ return mapNodes(vnode, (child) => {
163
+ if (isControl(child)) {
164
+ return {
165
+ ...child,
166
+ attrs: {
167
+ ...child.attrs,
168
+ ...(type ? { type } : {}),
169
+ ...(meta.required ? { required: "" } : {}),
170
+ ...limits,
171
+ },
172
+ };
173
+ }
174
+ if (!meta.required || child.tag !== "label") return child;
175
+ if (child.attrs.class === "emvb-form-label") {
176
+ return { ...child, children: [...child.children, mark] };
177
+ }
178
+ // The checkbox label wraps the input and the label text; the mark follows the text.
179
+ if (child.attrs.class === "emvb-form-checkbox-label") {
180
+ return {
181
+ ...child,
182
+ children: child.children.map((part) => (typeof part === "string" ? `${part} *` : part)),
183
+ };
184
+ }
185
+ return child;
186
+ });
187
+ }
188
+
189
+ /** Fills a field from the first bound form definition that has it: options, type, limits. */
190
+ export function withFieldOptions(
191
+ vnode: VNode,
192
+ node: LayoutNode,
193
+ definitions: FormDefinitions,
194
+ ): VNode {
195
+ const field = (node.props as { field?: unknown }).field;
196
+ if (typeof field !== "string") return vnode;
197
+ for (const definition of definitions.values()) {
198
+ const meta = fieldByName(definition, field);
199
+ if (!meta) continue;
200
+ return withFieldMeta(withOptions(vnode, node, meta), node, meta);
201
+ }
202
+ return vnode;
203
+ }
204
+
205
+ /** A select or radio field filled with the definition's options. */
206
+ function withOptions(vnode: VNode, node: LayoutNode, meta: PublicFormField): VNode {
207
+ const field = meta.name;
208
+ if ((node.type !== "select" && node.type !== "radio") || !meta.options?.length) return vnode;
209
+ if (node.type === "select") {
210
+ return replaceChildren(vnode, (child) => child.tag === "select", [
211
+ { tag: "option", attrs: { value: "" }, children: ["Choose…"] },
212
+ ...meta.options.map((option): VNode => ({
213
+ tag: "option",
214
+ attrs: { value: option.value },
215
+ children: [option.label],
216
+ })),
217
+ ]);
218
+ }
219
+ return replaceChildren(
220
+ vnode,
221
+ (child) => child.tag === "fieldset" && (child.attrs.class ?? "").includes("emvb-radio-group"),
222
+ meta.options.map((option) => ({
223
+ tag: "label",
224
+ attrs: { class: "emvb-form-radio-label" },
225
+ children: [
226
+ {
227
+ tag: "input",
228
+ attrs: { type: "radio", name: field, value: option.value },
229
+ children: [],
230
+ },
231
+ ` ${option.label}`,
232
+ ],
233
+ })),
234
+ );
235
+ }