@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,4 @@
1
+ /** The style states (W-089, D-032), in cascade order. Focus means `:focus-visible`. */
2
+ export const STYLE_STATES = ["hover", "focus", "active"] as const;
3
+
4
+ export type StyleStateName = (typeof STYLE_STATES)[number];
@@ -0,0 +1,257 @@
1
+ import { z } from "zod";
2
+ import { isSafeFontStack } from "../sanitize/css.ts";
3
+ import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
4
+ import { POPUP_DEVICES } from "../theme/popup-rules.ts";
5
+
6
+ /** Colour refs omit `from` (legacy). Length/font refs set `from` (W-028). */
7
+ export const VariableRef = z.strictObject({
8
+ var: z.string().regex(/^[a-z0-9-]{1,40}$/),
9
+ from: z.enum(["color", "font", "fontSize", "spacing"]).optional(),
10
+ });
11
+
12
+ const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
13
+ export const ColorValue = z.union([
14
+ z.string().regex(HEX_COLOR, "Use a hex color such as #1a2b3c"),
15
+ VariableRef,
16
+ ]);
17
+
18
+ const LengthUnit = z.enum(["px", "rem", "em", "%", "vw", "vh"]);
19
+
20
+ export const Length = z.strictObject({
21
+ value: z.number().finite().min(0).max(10_000),
22
+ unit: LengthUnit,
23
+ });
24
+
25
+ /** Literal length or a fontSize/spacing variable reference. */
26
+ export const LengthValue = z.union([Length, VariableRef]);
27
+
28
+ /** Width, height and margins may also be `auto` (W-088). */
29
+ const SizeValue = z.union([Length, VariableRef, z.literal("auto")]);
30
+
31
+ /** Top, right, bottom and left may be negative, `auto` or a spacing variable (W-088). */
32
+ const OffsetValue = z.union([
33
+ z.strictObject({ value: z.number().finite().min(-10_000).max(10_000), unit: LengthUnit }),
34
+ VariableRef,
35
+ z.literal("auto"),
36
+ ]);
37
+
38
+ /** `w/h` with whole numbers 1–9999, emitted as `w / h` (W-088). */
39
+ const ASPECT_RATIO = /^[1-9]\d{0,3}\/[1-9]\d{0,3}$/;
40
+
41
+ const num = (min: number, max: number) => z.number().finite().min(min).max(max);
42
+
43
+ /** One box shadow in px (W-088). No colour means the text colour, as in CSS. */
44
+ const BoxShadow = z.strictObject({
45
+ x: num(-1000, 1000),
46
+ y: num(-1000, 1000),
47
+ blur: num(0, 1000),
48
+ spread: num(-1000, 1000),
49
+ color: ColorValue.optional(),
50
+ inset: z.boolean().optional(),
51
+ });
52
+
53
+ /** Filter functions, emitted in a fixed order; at least one is set (W-088). */
54
+ const Filter = z
55
+ .strictObject({
56
+ blur: num(0, 100).optional(),
57
+ brightness: num(0, 300).optional(),
58
+ contrast: num(0, 300).optional(),
59
+ saturate: num(0, 300).optional(),
60
+ grayscale: num(0, 100).optional(),
61
+ hueRotate: num(0, 360).optional(),
62
+ })
63
+ .refine(
64
+ (filter) => Object.values(filter).some((v) => v !== undefined),
65
+ "Set at least one filter",
66
+ );
67
+
68
+ /**
69
+ * A simple transition (W-089, Normal only): one duration, delay and easing for a fixed property
70
+ * group. `colors` means color, background-color and border-color. No free-form lists or curves.
71
+ */
72
+ const Transition = z.strictObject({
73
+ duration: z.number().int().min(0).max(2000),
74
+ delay: z.number().int().min(0).max(2000).optional(),
75
+ easing: z.enum(["ease", "ease-in", "ease-out", "ease-in-out", "linear"]),
76
+ property: z.enum(["all", "colors", "opacity", "shadow", "filter"]),
77
+ });
78
+
79
+ /** Style properties for layout and text elements (W-017 / R-012). Unknown keys are rejected. */
80
+ export const StyleProps = z.strictObject({
81
+ flexDirection: z.enum(["row", "column", "row-reverse", "column-reverse"]).optional(),
82
+ flexWrap: z.enum(["nowrap", "wrap", "wrap-reverse"]).optional(),
83
+ justifyContent: z
84
+ .enum(["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly"])
85
+ .optional(),
86
+ alignItems: z.enum(["stretch", "flex-start", "flex-end", "center", "baseline"]).optional(),
87
+ gap: LengthValue.optional(),
88
+ /** How many grid columns this element spans (1–12). */
89
+ gridColumnSpan: z.number().int().min(1).max(12).optional(),
90
+ /** How many grid rows this element spans (1–12). */
91
+ gridRowSpan: z.number().int().min(1).max(12).optional(),
92
+ width: SizeValue.optional(),
93
+ minWidth: LengthValue.optional(),
94
+ maxWidth: LengthValue.optional(),
95
+ height: SizeValue.optional(),
96
+ minHeight: LengthValue.optional(),
97
+ maxHeight: LengthValue.optional(),
98
+ overflow: z.enum(["visible", "hidden", "clip", "scroll", "auto"]).optional(),
99
+ aspectRatio: z
100
+ .union([z.literal("auto"), z.string().regex(ASPECT_RATIO, "Use a ratio such as 16/9")])
101
+ .optional(),
102
+ objectFit: z.enum(["fill", "contain", "cover", "none", "scale-down"]).optional(),
103
+ paddingTop: LengthValue.optional(),
104
+ paddingRight: LengthValue.optional(),
105
+ paddingBottom: LengthValue.optional(),
106
+ paddingLeft: LengthValue.optional(),
107
+ marginTop: SizeValue.optional(),
108
+ marginRight: SizeValue.optional(),
109
+ marginBottom: SizeValue.optional(),
110
+ marginLeft: SizeValue.optional(),
111
+ position: z.enum(["static", "relative", "absolute", "fixed", "sticky"]).optional(),
112
+ top: OffsetValue.optional(),
113
+ right: OffsetValue.optional(),
114
+ bottom: OffsetValue.optional(),
115
+ left: OffsetValue.optional(),
116
+ zIndex: z.number().int().min(-9999).max(9999).optional(),
117
+ fontFamily: z
118
+ .union([
119
+ z.string().min(1).max(200).refine(isSafeFontStack, "Font stack looks unsafe."),
120
+ VariableRef,
121
+ ])
122
+ .optional(),
123
+ fontSize: LengthValue.optional(),
124
+ fontWeight: z
125
+ .union([
126
+ z.literal(400),
127
+ z.literal(500),
128
+ z.literal(600),
129
+ z.literal(700),
130
+ z.enum(["normal", "bold"]),
131
+ ])
132
+ .optional(),
133
+ lineHeight: LengthValue.optional(),
134
+ letterSpacing: LengthValue.optional(),
135
+ textAlign: z.enum(["left", "center", "right", "justify"]).optional(),
136
+ textTransform: z.enum(["none", "uppercase", "lowercase", "capitalize"]).optional(),
137
+ /** W-113. A button sets `none` in its base CSS, so it is not underlined unless a style says so. */
138
+ textDecoration: z.enum(["none", "underline", "overline", "line-through"]).optional(),
139
+ color: ColorValue.optional(),
140
+ backgroundColor: ColorValue.optional(),
141
+ /** http(s) or a site path. Spaces, quotes and parentheses are refused so the URL can sit inside `url("")`. */
142
+ backgroundImage: z
143
+ .string()
144
+ .min(1)
145
+ .max(2000)
146
+ .refine(
147
+ (value) => sanitizeMediaUrl(value) === value && !/[()\\\s"'`]/.test(value),
148
+ "Use an http(s) URL or a site path, with no spaces or parentheses",
149
+ )
150
+ .optional(),
151
+ backgroundSize: z.enum(["auto", "cover", "contain"]).optional(),
152
+ backgroundPosition: z
153
+ .enum([
154
+ "center",
155
+ "top",
156
+ "bottom",
157
+ "left",
158
+ "right",
159
+ "top left",
160
+ "top right",
161
+ "bottom left",
162
+ "bottom right",
163
+ ])
164
+ .optional(),
165
+ backgroundRepeat: z.enum(["no-repeat", "repeat", "repeat-x", "repeat-y"]).optional(),
166
+ /** Video behind the element. Same URL rules as a background image (W-110). */
167
+ backgroundVideo: z
168
+ .string()
169
+ .min(1)
170
+ .max(2000)
171
+ .refine(
172
+ (value) => sanitizeMediaUrl(value) === value && !/[()\\\s"'`]/.test(value),
173
+ "Use an http(s) URL or a site path, with no spaces or parentheses",
174
+ )
175
+ .optional(),
176
+ /** Two-stop linear gradient. Stops are colours, so a variable binding is a colour use (W-094). */
177
+ gradient: z
178
+ .strictObject({
179
+ angle: z.number().int().min(0).max(360),
180
+ from: ColorValue,
181
+ to: ColorValue,
182
+ })
183
+ .optional(),
184
+ /** A colour laid over the image and gradient. `opacity` is 0–1 (W-094). */
185
+ overlay: z
186
+ .strictObject({
187
+ color: ColorValue,
188
+ opacity: z.number().finite().min(0).max(1),
189
+ })
190
+ .optional(),
191
+ borderWidth: LengthValue.optional(),
192
+ borderStyle: z.enum(["none", "solid", "dashed", "dotted"]).optional(),
193
+ borderColor: ColorValue.optional(),
194
+ borderRadius: LengthValue.optional(),
195
+ opacity: z.number().finite().min(0).max(1).optional(),
196
+ boxShadow: BoxShadow.optional(),
197
+ filter: Filter.optional(),
198
+ cursor: z
199
+ .enum([
200
+ "default",
201
+ "pointer",
202
+ "text",
203
+ "move",
204
+ "grab",
205
+ "not-allowed",
206
+ "help",
207
+ "crosshair",
208
+ "zoom-in",
209
+ ])
210
+ .optional(),
211
+ transition: Transition.optional(),
212
+ /**
213
+ * Plays once (W-101, W-107). `delay` waits before it starts. `view` starts as the element
214
+ * scrolls into view, using CSS scroll-driven animations, and falls back to playing on load.
215
+ * Not a state style.
216
+ */
217
+ entrance: z
218
+ .strictObject({
219
+ type: z.enum(["fade", "fade-up", "fade-down", "slide-up", "slide-down", "scale"]),
220
+ duration: z.number().int().min(0).max(2000),
221
+ delay: z.number().int().min(0).max(2000).optional(),
222
+ trigger: z.enum(["load", "view"]).optional(),
223
+ })
224
+ .optional(),
225
+ });
226
+
227
+ export type StyleProps = z.infer<typeof StyleProps>;
228
+
229
+ /**
230
+ * `states` on a node or class (D-032, W-089): hover, focus (`:focus-visible`) and active, each with
231
+ * the same keys and limits as `style` except `transition` and `entrance`. Unknown states are refused.
232
+ */
233
+ const StateStyle = StyleProps.omit({ transition: true, entrance: true });
234
+
235
+ export const StyleStates = z.strictObject({
236
+ hover: StateStyle.optional(),
237
+ focus: StateStyle.optional(),
238
+ active: StateStyle.optional(),
239
+ });
240
+
241
+ export type StyleStates = z.infer<typeof StyleStates>;
242
+
243
+ /**
244
+ * Tablet and mobile overrides (W-096). Desktop is the element's `style`. Only keys that differ
245
+ * are stored. A phone matches both media queries, so mobile wins over tablet for the same key.
246
+ */
247
+ export const DeviceStyles = z.strictObject({
248
+ tablet: StyleProps.optional(),
249
+ mobile: StyleProps.optional(),
250
+ });
251
+
252
+ export type DeviceStyles = z.infer<typeof DeviceStyles>;
253
+
254
+ /** Devices on which the element is `display: none`. Empty means shown everywhere. */
255
+ export const HiddenOn = z.array(z.enum(POPUP_DEVICES)).max(3);
256
+
257
+ export type HiddenOn = z.infer<typeof HiddenOn>;
@@ -0,0 +1,18 @@
1
+ export type LayoutSummary = { nodes: number; schemaVersion: number | undefined };
2
+
3
+ /** Counts nodes without trusting the input shape (used for read-only summaries). */
4
+ export function summarizeLayout(input: unknown): LayoutSummary | undefined {
5
+ if (typeof input !== "object" || input === null) return undefined;
6
+ const doc = input as { schemaVersion?: unknown; root?: unknown };
7
+ const schemaVersion = typeof doc.schemaVersion === "number" ? doc.schemaVersion : undefined;
8
+ let nodes = 0;
9
+ const stack: unknown[] = doc.root === undefined ? [] : [doc.root];
10
+ while (stack.length > 0 && nodes <= 100_000) {
11
+ const node = stack.pop();
12
+ if (typeof node !== "object" || node === null) continue;
13
+ nodes++;
14
+ const children = (node as { children?: unknown }).children;
15
+ if (Array.isArray(children)) stack.push(...children);
16
+ }
17
+ return { nodes, schemaVersion };
18
+ }
@@ -0,0 +1,16 @@
1
+ import { isTabsNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
+ import { nodeChildren } from "../tree-ops.ts";
3
+
4
+ function walk(node: LayoutNode, visit: (node: LayoutNode) => void): void {
5
+ visit(node);
6
+ for (const child of nodeChildren(node)) walk(child, visit);
7
+ }
8
+
9
+ /** True when the layout includes at least one Tabs element (optional public runtime). */
10
+ export function layoutHasTabs(layout: Layout): boolean {
11
+ let found = false;
12
+ walk(layout.root, (node) => {
13
+ if (isTabsNode(node)) found = true;
14
+ });
15
+ return found;
16
+ }
@@ -0,0 +1,321 @@
1
+ import { z } from "zod";
2
+ import { parseDoc } from "./parse-doc.ts";
3
+ import { type ContentThemePartType, type ThemePartType } from "./part-types.ts";
4
+
5
+ export const CONDITIONS_SCHEMA_VERSION = 1;
6
+ export const MAX_CONDITION_RULES = 20;
7
+
8
+ const ConditionArgs = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]));
9
+
10
+ const ConditionRuleSchema = z.strictObject({
11
+ id: z.string().min(1).max(64),
12
+ op: z.enum(["include", "exclude"]),
13
+ group: z.enum(["general", "singular", "archive"]),
14
+ name: z.string().min(1).max(40),
15
+ args: ConditionArgs.default({}),
16
+ });
17
+
18
+ const ConditionsDocSchema = z.strictObject({
19
+ schemaVersion: z.literal(CONDITIONS_SCHEMA_VERSION),
20
+ rules: z.array(ConditionRuleSchema).max(MAX_CONDITION_RULES),
21
+ });
22
+
23
+ export type ConditionRule = z.infer<typeof ConditionRuleSchema>;
24
+ export type ConditionsDoc = z.infer<typeof ConditionsDocSchema>;
25
+
26
+ export type ThemeRequestContext = {
27
+ path: string;
28
+ isFront: boolean;
29
+ is404: boolean;
30
+ isSearch: boolean;
31
+ kind: "singular" | "archive" | "other";
32
+ collection?: string;
33
+ entryId?: string;
34
+ taxonomy?: { type: "category" | "tag"; slug: string };
35
+ };
36
+
37
+ /** Entire Site include with a stable default id — used when creating a theme part. */
38
+ export const defaultConditions = (): ConditionsDoc => ({
39
+ schemaVersion: CONDITIONS_SCHEMA_VERSION,
40
+ rules: [
41
+ {
42
+ id: "default-entire-site",
43
+ op: "include",
44
+ group: "general",
45
+ name: "entire_site",
46
+ args: {},
47
+ },
48
+ ],
49
+ });
50
+
51
+ export type ConditionsValidation =
52
+ | { ok: true; conditions: ConditionsDoc }
53
+ | { ok: false; issues: { path: string; code: string; message: string }[] };
54
+
55
+ export function validateConditions(raw: unknown): ConditionsValidation {
56
+ const parsed = parseDoc(raw, ConditionsDocSchema, "conditions", "Conditions");
57
+ if (!parsed.ok) return parsed;
58
+ for (const [i, rule] of parsed.doc.rules.entries()) {
59
+ const vocab = vocabularyIssue(rule);
60
+ if (vocab) {
61
+ return {
62
+ ok: false,
63
+ issues: [{ path: `conditions.rules[${i}]`, code: "unknown_condition", message: vocab }],
64
+ };
65
+ }
66
+ }
67
+ return { ok: true, conditions: parsed.doc };
68
+ }
69
+
70
+ function vocabularyIssue(rule: ConditionRule): string | null {
71
+ const condition = known(rule);
72
+ if (!condition) return `Unknown condition ${rule.group}/${rule.name}.`;
73
+ for (const required of condition.requiredArgs) {
74
+ if (typeof rule.args[required] !== "string" || !rule.args[required]) {
75
+ return `Condition ${rule.group}/${rule.name} requires args.${required}.`;
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+
81
+ type Args = ConditionRule["args"];
82
+ type Known = {
83
+ requiredArgs: readonly string[];
84
+ specificity: number;
85
+ matches: (ctx: ThemeRequestContext, args: Args) => boolean;
86
+ };
87
+
88
+ /** True when `args[key]` is a string equal to `actual`. */
89
+ const argIs = (args: Args, key: string, actual: string | undefined) =>
90
+ typeof args[key] === "string" && actual === args[key];
91
+
92
+ function taxonomyMatches(ctx: ThemeRequestContext, args: Args): boolean {
93
+ if (ctx.kind !== "archive" || !ctx.taxonomy) return false;
94
+ if (args["taxonomy"] !== ctx.taxonomy.type) return false;
95
+ const slug = args["slug"];
96
+ if (typeof slug === "string" && slug) return ctx.taxonomy.slug === slug;
97
+ return true;
98
+ }
99
+
100
+ /**
101
+ * Each condition's required args, specificity and matcher. Specificity (higher wins):
102
+ * entry > taxonomy+slug > collection > front/404/search > singular/archive all > entire_site.
103
+ */
104
+ const KNOWN_CONDITIONS: Record<string, Known> = {
105
+ "general:entire_site": { requiredArgs: [], specificity: 1, matches: () => true },
106
+ "singular:all": { requiredArgs: [], specificity: 10, matches: (ctx) => ctx.kind === "singular" },
107
+ "singular:front": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.isFront },
108
+ "singular:not_found": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.is404 },
109
+ "singular:collection": {
110
+ requiredArgs: ["collection"],
111
+ specificity: 30,
112
+ matches: (ctx, args) => ctx.kind === "singular" && argIs(args, "collection", ctx.collection),
113
+ },
114
+ "singular:entry": {
115
+ requiredArgs: ["collection", "id"],
116
+ specificity: 50,
117
+ matches: (ctx, args) =>
118
+ ctx.kind === "singular" &&
119
+ argIs(args, "collection", ctx.collection) &&
120
+ argIs(args, "id", ctx.entryId),
121
+ },
122
+ "archive:all": { requiredArgs: [], specificity: 10, matches: (ctx) => ctx.kind === "archive" },
123
+ "archive:collection": {
124
+ requiredArgs: ["collection"],
125
+ specificity: 30,
126
+ matches: (ctx, args) => ctx.kind === "archive" && argIs(args, "collection", ctx.collection),
127
+ },
128
+ "archive:taxonomy": { requiredArgs: ["taxonomy"], specificity: 35, matches: taxonomyMatches },
129
+ "archive:search": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.isSearch },
130
+ };
131
+
132
+ const known = (rule: ConditionRule): Known | undefined =>
133
+ KNOWN_CONDITIONS[`${rule.group}:${rule.name}`];
134
+
135
+ export function conditionSpecificity(rule: ConditionRule): number {
136
+ const condition = known(rule);
137
+ if (!condition) return 0;
138
+ let score = condition.specificity;
139
+ // taxonomy with a concrete slug is more specific than taxonomy type alone
140
+ if (
141
+ rule.group === "archive" &&
142
+ rule.name === "taxonomy" &&
143
+ typeof rule.args["slug"] === "string"
144
+ ) {
145
+ score += 5;
146
+ }
147
+ return score;
148
+ }
149
+
150
+ /** Highest include-rule specificity among matching includes (0 if none). */
151
+ export function conditionsSpecificity(doc: ConditionsDoc, ctx: ThemeRequestContext): number {
152
+ if (!matchesConditions(doc, ctx)) return 0;
153
+ let best = 0;
154
+ for (const rule of doc.rules) {
155
+ if (rule.op !== "include") continue;
156
+ if (!ruleMatches(rule, ctx)) continue;
157
+ best = Math.max(best, conditionSpecificity(rule));
158
+ }
159
+ return best;
160
+ }
161
+
162
+ /**
163
+ * A part matches when any include rule matches AND no exclude rule matches.
164
+ * Unknown condition names fail closed (never match) on the public side.
165
+ */
166
+ export function matchesConditions(doc: ConditionsDoc, ctx: ThemeRequestContext): boolean {
167
+ let included = false;
168
+ for (const rule of doc.rules) {
169
+ if (!ruleMatches(rule, ctx)) continue;
170
+ if (rule.op === "exclude") return false;
171
+ included = true;
172
+ }
173
+ return included;
174
+ }
175
+
176
+ function ruleMatches(rule: ConditionRule, ctx: ThemeRequestContext): boolean {
177
+ return known(rule)?.matches(ctx, rule.args) ?? false;
178
+ }
179
+
180
+ /**
181
+ * Location gate for a part type (Elementor-like theme locations).
182
+ * Headers/footers always compete; content types only on their route class.
183
+ * Single Page targets EmDash `pages` singular only (not posts, not emvb_pages).
184
+ */
185
+ export function themePartLocationApplies(
186
+ partType: ThemePartType,
187
+ ctx: ThemeRequestContext,
188
+ ): boolean {
189
+ switch (partType) {
190
+ case "header":
191
+ case "footer":
192
+ case "popup":
193
+ // Overlays compete on every route; conditions decide (S7b).
194
+ return true;
195
+ case "error_404":
196
+ return ctx.is404;
197
+ case "search_results":
198
+ return ctx.isSearch;
199
+ case "single_page":
200
+ // Front page is a separate singular location (not Single Page).
201
+ return !ctx.isFront && ctx.kind === "singular" && ctx.collection === "pages";
202
+ case "single_post":
203
+ return !ctx.isFront && ctx.kind === "singular" && ctx.collection === "posts";
204
+ case "archive":
205
+ // Posts index + category/tag archives (not search — that is search_results).
206
+ return ctx.kind === "archive" && !ctx.isSearch;
207
+ case "loop_item":
208
+ // Reusable item template; never selected as a page location.
209
+ return false;
210
+ case "section":
211
+ case "page_template":
212
+ // Reusable fragments; never selected as a page location.
213
+ return false;
214
+ }
215
+ }
216
+
217
+ /** The single Include rule a new content part starts with; other types start on Entire Site. */
218
+ const DEFAULT_RULES: Partial<Record<ThemePartType, Omit<ConditionRule, "op">>> = {
219
+ error_404: { id: "default-404", group: "singular", name: "not_found", args: {} },
220
+ search_results: { id: "default-search", group: "archive", name: "search", args: {} },
221
+ single_page: {
222
+ id: "default-pages",
223
+ group: "singular",
224
+ name: "collection",
225
+ args: { collection: "pages" },
226
+ },
227
+ single_post: {
228
+ id: "default-posts",
229
+ group: "singular",
230
+ name: "collection",
231
+ args: { collection: "posts" },
232
+ },
233
+ // Posts index + category/tag (location gate already excludes search).
234
+ archive: { id: "default-archive-all", group: "archive", name: "all", args: {} },
235
+ };
236
+
237
+ /** Default Include rule(s) when creating a part of this type. */
238
+ export function defaultConditionsFor(partType: ThemePartType): ConditionsDoc {
239
+ const rule = DEFAULT_RULES[partType];
240
+ if (!rule) return defaultConditions();
241
+ const { id, ...rest } = rule;
242
+ return { schemaVersion: CONDITIONS_SCHEMA_VERSION, rules: [{ id, op: "include", ...rest }] };
243
+ }
244
+
245
+ /**
246
+ * Which content-template type (if any) should compete for this request's main body.
247
+ * Mutual exclusivity: 404 > search > single_post > single_page > archive.
248
+ */
249
+ export function contentPartTypeForContext(ctx: ThemeRequestContext): ContentThemePartType | null {
250
+ if (ctx.is404) return "error_404";
251
+ if (ctx.isSearch) return "search_results";
252
+ if (!ctx.isFront && ctx.kind === "singular" && ctx.collection === "posts") {
253
+ return "single_post";
254
+ }
255
+ if (!ctx.isFront && ctx.kind === "singular" && ctx.collection === "pages") {
256
+ return "single_page";
257
+ }
258
+ if (ctx.kind === "archive" && !ctx.isSearch) {
259
+ return "archive";
260
+ }
261
+ return null;
262
+ }
263
+
264
+ export type ThemePartCandidate = {
265
+ id: string;
266
+ partType: ThemePartType;
267
+ conditions: ConditionsDoc;
268
+ updatedAt: string;
269
+ };
270
+
271
+ /** Candidates of one type whose location applies and whose conditions match. */
272
+ const matching = (
273
+ candidates: readonly ThemePartCandidate[],
274
+ partType: ThemePartType,
275
+ ctx: ThemeRequestContext,
276
+ ) =>
277
+ candidates.filter(
278
+ (candidate) =>
279
+ candidate.partType === partType &&
280
+ themePartLocationApplies(candidate.partType, ctx) &&
281
+ matchesConditions(candidate.conditions, ctx),
282
+ );
283
+
284
+ /**
285
+ * Among matching candidates of one type, pick the highest specificity; ties break by
286
+ * `updatedAt` descending (ISO timestamps). Content types are also gated by location
287
+ * so a Single Page never wins on a post route, etc.
288
+ */
289
+ export function pickThemePartWinner(
290
+ candidates: readonly ThemePartCandidate[],
291
+ partType: ThemePartType,
292
+ ctx: ThemeRequestContext,
293
+ ): ThemePartCandidate | null {
294
+ let winner: ThemePartCandidate | null = null;
295
+ let bestScore = -1;
296
+ for (const candidate of matching(candidates, partType, ctx)) {
297
+ const score = conditionsSpecificity(candidate.conditions, ctx);
298
+ if (
299
+ score > bestScore ||
300
+ (score === bestScore && winner !== null && candidate.updatedAt > winner.updatedAt)
301
+ ) {
302
+ bestScore = score;
303
+ winner = candidate;
304
+ }
305
+ }
306
+ return winner;
307
+ }
308
+
309
+ /**
310
+ * All candidates of one type that match location + conditions (S7b popups).
311
+ * Sorted by updatedAt descending so newest configs win for equal conditions.
312
+ */
313
+ export function listMatchingThemeParts(
314
+ candidates: readonly ThemePartCandidate[],
315
+ partType: ThemePartType,
316
+ ctx: ThemeRequestContext,
317
+ ): ThemePartCandidate[] {
318
+ return matching(candidates, partType, ctx).toSorted((a, b) =>
319
+ a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0,
320
+ );
321
+ }