@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,324 @@
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
+ /** Archive page from `/page/N` (W-221); `path` stays the archive's own path. Absent = 1. */
36
+ page?: number;
37
+ };
38
+
39
+ /** Entire Site include with a stable default id — used when creating a theme part. */
40
+ export const defaultConditions = (): ConditionsDoc => ({
41
+ schemaVersion: CONDITIONS_SCHEMA_VERSION,
42
+ rules: [
43
+ {
44
+ id: "default-entire-site",
45
+ op: "include",
46
+ group: "general",
47
+ name: "entire_site",
48
+ args: {},
49
+ },
50
+ ],
51
+ });
52
+
53
+ export type ConditionsValidation =
54
+ | { ok: true; conditions: ConditionsDoc }
55
+ | { ok: false; issues: { path: string; code: string; message: string }[] };
56
+
57
+ export function validateConditions(raw: unknown): ConditionsValidation {
58
+ const parsed = parseDoc(raw, ConditionsDocSchema, "conditions", "Conditions");
59
+ if (!parsed.ok) return parsed;
60
+ for (const [i, rule] of parsed.doc.rules.entries()) {
61
+ const vocab = vocabularyIssue(rule);
62
+ if (vocab) {
63
+ return {
64
+ ok: false,
65
+ issues: [{ path: `conditions.rules[${i}]`, code: "unknown_condition", message: vocab }],
66
+ };
67
+ }
68
+ }
69
+ return { ok: true, conditions: parsed.doc };
70
+ }
71
+
72
+ function vocabularyIssue(rule: ConditionRule): string | null {
73
+ const condition = known(rule);
74
+ if (!condition) return `Unknown condition ${rule.group}/${rule.name}.`;
75
+ for (const required of condition.requiredArgs) {
76
+ if (typeof rule.args[required] !== "string" || !rule.args[required]) {
77
+ return `Condition ${rule.group}/${rule.name} requires args.${required}.`;
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+
83
+ type Args = ConditionRule["args"];
84
+ type Known = {
85
+ requiredArgs: readonly string[];
86
+ specificity: number;
87
+ matches: (ctx: ThemeRequestContext, args: Args) => boolean;
88
+ };
89
+
90
+ /** True when `args[key]` is a string equal to `actual`. */
91
+ const argIs = (args: Args, key: string, actual: string | undefined) =>
92
+ typeof args[key] === "string" && actual === args[key];
93
+
94
+ function taxonomyMatches(ctx: ThemeRequestContext, args: Args): boolean {
95
+ if (ctx.kind !== "archive" || !ctx.taxonomy) return false;
96
+ if (args["taxonomy"] !== ctx.taxonomy.type) return false;
97
+ const slug = args["slug"];
98
+ if (typeof slug === "string" && slug) return ctx.taxonomy.slug === slug;
99
+ return true;
100
+ }
101
+
102
+ /**
103
+ * Each condition's required args, specificity and matcher. Specificity (higher wins):
104
+ * entry > taxonomy+slug > collection > front/404/search > singular/archive all > entire_site.
105
+ */
106
+ const KNOWN_CONDITIONS: Record<string, Known> = {
107
+ "general:entire_site": { requiredArgs: [], specificity: 1, matches: () => true },
108
+ "singular:all": { requiredArgs: [], specificity: 10, matches: (ctx) => ctx.kind === "singular" },
109
+ "singular:front": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.isFront },
110
+ "singular:not_found": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.is404 },
111
+ "singular:collection": {
112
+ requiredArgs: ["collection"],
113
+ specificity: 30,
114
+ matches: (ctx, args) => ctx.kind === "singular" && argIs(args, "collection", ctx.collection),
115
+ },
116
+ "singular:entry": {
117
+ requiredArgs: ["collection", "id"],
118
+ specificity: 50,
119
+ matches: (ctx, args) =>
120
+ ctx.kind === "singular" &&
121
+ argIs(args, "collection", ctx.collection) &&
122
+ argIs(args, "id", ctx.entryId),
123
+ },
124
+ "archive:all": { requiredArgs: [], specificity: 10, matches: (ctx) => ctx.kind === "archive" },
125
+ "archive:collection": {
126
+ requiredArgs: ["collection"],
127
+ specificity: 30,
128
+ matches: (ctx, args) => ctx.kind === "archive" && argIs(args, "collection", ctx.collection),
129
+ },
130
+ "archive:taxonomy": { requiredArgs: ["taxonomy"], specificity: 35, matches: taxonomyMatches },
131
+ "archive:search": { requiredArgs: [], specificity: 20, matches: (ctx) => ctx.isSearch },
132
+ };
133
+
134
+ const known = (rule: ConditionRule): Known | undefined =>
135
+ KNOWN_CONDITIONS[`${rule.group}:${rule.name}`];
136
+
137
+ export function conditionSpecificity(rule: ConditionRule): number {
138
+ const condition = known(rule);
139
+ if (!condition) return 0;
140
+ let score = condition.specificity;
141
+ // taxonomy with a concrete slug is more specific than taxonomy type alone
142
+ if (
143
+ rule.group === "archive" &&
144
+ rule.name === "taxonomy" &&
145
+ typeof rule.args["slug"] === "string"
146
+ ) {
147
+ score += 5;
148
+ }
149
+ return score;
150
+ }
151
+
152
+ /** Highest include-rule specificity among matching includes (0 if none). */
153
+ export function conditionsSpecificity(doc: ConditionsDoc, ctx: ThemeRequestContext): number {
154
+ if (!matchesConditions(doc, ctx)) return 0;
155
+ let best = 0;
156
+ for (const rule of doc.rules) {
157
+ if (rule.op !== "include") continue;
158
+ if (!ruleMatches(rule, ctx)) continue;
159
+ best = Math.max(best, conditionSpecificity(rule));
160
+ }
161
+ return best;
162
+ }
163
+
164
+ /**
165
+ * A part matches when any include rule matches AND no exclude rule matches.
166
+ * Unknown condition names fail closed (never match) on the public side.
167
+ */
168
+ export function matchesConditions(doc: ConditionsDoc, ctx: ThemeRequestContext): boolean {
169
+ let included = false;
170
+ for (const rule of doc.rules) {
171
+ if (!ruleMatches(rule, ctx)) continue;
172
+ if (rule.op === "exclude") return false;
173
+ included = true;
174
+ }
175
+ return included;
176
+ }
177
+
178
+ function ruleMatches(rule: ConditionRule, ctx: ThemeRequestContext): boolean {
179
+ return known(rule)?.matches(ctx, rule.args) ?? false;
180
+ }
181
+
182
+ /**
183
+ * Location gate for a part type (Elementor-like theme locations).
184
+ * Headers/footers always compete; content types only on their route class.
185
+ * Single Page targets EmDash `pages` singular only (not posts, not emvb_pages).
186
+ */
187
+ export function themePartLocationApplies(
188
+ partType: ThemePartType,
189
+ ctx: ThemeRequestContext,
190
+ ): boolean {
191
+ switch (partType) {
192
+ case "header":
193
+ case "footer":
194
+ case "popup":
195
+ case "float":
196
+ // Overlays and floats compete on every route; conditions decide.
197
+ return true;
198
+ case "error_404":
199
+ return ctx.is404;
200
+ case "search_results":
201
+ return ctx.isSearch;
202
+ case "single_page":
203
+ // Front page is a separate singular location (not Single Page).
204
+ return !ctx.isFront && ctx.kind === "singular" && ctx.collection === "pages";
205
+ case "single_post":
206
+ return !ctx.isFront && ctx.kind === "singular" && ctx.collection === "posts";
207
+ case "archive":
208
+ // Posts index + category/tag archives (not search — that is search_results).
209
+ return ctx.kind === "archive" && !ctx.isSearch;
210
+ case "loop_item":
211
+ // Reusable item template; never selected as a page location.
212
+ return false;
213
+ case "section":
214
+ case "page_template":
215
+ // Reusable fragments; never selected as a page location.
216
+ return false;
217
+ }
218
+ }
219
+
220
+ /** The single Include rule a new content part starts with; other types start on Entire Site. */
221
+ const DEFAULT_RULES: Partial<Record<ThemePartType, Omit<ConditionRule, "op">>> = {
222
+ error_404: { id: "default-404", group: "singular", name: "not_found", args: {} },
223
+ search_results: { id: "default-search", group: "archive", name: "search", args: {} },
224
+ single_page: {
225
+ id: "default-pages",
226
+ group: "singular",
227
+ name: "collection",
228
+ args: { collection: "pages" },
229
+ },
230
+ single_post: {
231
+ id: "default-posts",
232
+ group: "singular",
233
+ name: "collection",
234
+ args: { collection: "posts" },
235
+ },
236
+ // Posts index + category/tag (location gate already excludes search).
237
+ archive: { id: "default-archive-all", group: "archive", name: "all", args: {} },
238
+ };
239
+
240
+ /** Default Include rule(s) when creating a part of this type. */
241
+ export function defaultConditionsFor(partType: ThemePartType): ConditionsDoc {
242
+ const rule = DEFAULT_RULES[partType];
243
+ if (!rule) return defaultConditions();
244
+ const { id, ...rest } = rule;
245
+ return { schemaVersion: CONDITIONS_SCHEMA_VERSION, rules: [{ id, op: "include", ...rest }] };
246
+ }
247
+
248
+ /**
249
+ * Which content-template type (if any) should compete for this request's main body.
250
+ * Mutual exclusivity: 404 > search > single_post > single_page > archive.
251
+ */
252
+ export function contentPartTypeForContext(ctx: ThemeRequestContext): ContentThemePartType | null {
253
+ if (ctx.is404) return "error_404";
254
+ if (ctx.isSearch) return "search_results";
255
+ if (!ctx.isFront && ctx.kind === "singular" && ctx.collection === "posts") {
256
+ return "single_post";
257
+ }
258
+ if (!ctx.isFront && ctx.kind === "singular" && ctx.collection === "pages") {
259
+ return "single_page";
260
+ }
261
+ if (ctx.kind === "archive" && !ctx.isSearch) {
262
+ return "archive";
263
+ }
264
+ return null;
265
+ }
266
+
267
+ export type ThemePartCandidate = {
268
+ id: string;
269
+ partType: ThemePartType;
270
+ conditions: ConditionsDoc;
271
+ updatedAt: string;
272
+ };
273
+
274
+ /** Candidates of one type whose location applies and whose conditions match. */
275
+ const matching = (
276
+ candidates: readonly ThemePartCandidate[],
277
+ partType: ThemePartType,
278
+ ctx: ThemeRequestContext,
279
+ ) =>
280
+ candidates.filter(
281
+ (candidate) =>
282
+ candidate.partType === partType &&
283
+ themePartLocationApplies(candidate.partType, ctx) &&
284
+ matchesConditions(candidate.conditions, ctx),
285
+ );
286
+
287
+ /**
288
+ * Among matching candidates of one type, pick the highest specificity; ties break by
289
+ * `updatedAt` descending (ISO timestamps). Content types are also gated by location
290
+ * so a Single Page never wins on a post route, etc.
291
+ */
292
+ export function pickThemePartWinner(
293
+ candidates: readonly ThemePartCandidate[],
294
+ partType: ThemePartType,
295
+ ctx: ThemeRequestContext,
296
+ ): ThemePartCandidate | null {
297
+ let winner: ThemePartCandidate | null = null;
298
+ let bestScore = -1;
299
+ for (const candidate of matching(candidates, partType, ctx)) {
300
+ const score = conditionsSpecificity(candidate.conditions, ctx);
301
+ if (
302
+ score > bestScore ||
303
+ (score === bestScore && winner !== null && candidate.updatedAt > winner.updatedAt)
304
+ ) {
305
+ bestScore = score;
306
+ winner = candidate;
307
+ }
308
+ }
309
+ return winner;
310
+ }
311
+
312
+ /**
313
+ * All candidates of one type that match location + conditions (S7b popups).
314
+ * Sorted by updatedAt descending so newest configs win for equal conditions.
315
+ */
316
+ export function listMatchingThemeParts(
317
+ candidates: readonly ThemePartCandidate[],
318
+ partType: ThemePartType,
319
+ ctx: ThemeRequestContext,
320
+ ): ThemePartCandidate[] {
321
+ return matching(candidates, partType, ctx).toSorted((a, b) =>
322
+ a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0,
323
+ );
324
+ }
@@ -0,0 +1,143 @@
1
+ import type { ArchivePagination } from "./pagination.ts";
2
+ import type { Layout, LayoutNode } from "../schema/layout.ts";
3
+ import { isParentNode } from "../schema/layout.ts";
4
+ import type { VNode } from "../render/vnode.ts";
5
+
6
+ /** Normalized post fields for server-side theme binding (framework-free). */
7
+ export type ThemePostFields = {
8
+ id: string;
9
+ slug: string;
10
+ title: string;
11
+ excerpt: string;
12
+ /** Portable Text JSON, plain string, or already-normalized blocks. */
13
+ content: unknown;
14
+ featuredImageUrl?: string;
15
+ featuredImageAlt?: string;
16
+ /** Public path, e.g. `/posts/welcome`. */
17
+ permalink: string;
18
+ /** ISO date or a display string from the post. */
19
+ publishedAt?: string;
20
+ authorName?: string;
21
+ };
22
+
23
+ /** Data passed into `renderPage` when resolving Single Post / Archive / Loop Item. */
24
+ export type ThemeDynamicData = {
25
+ post?: ThemePostFields;
26
+ posts?: ThemePostFields[];
27
+ /** Published Loop Item layouts keyed by theme-part entry id. */
28
+ loopTemplates?: Record<string, Layout>;
29
+ /** Published Section layouts keyed by theme-part entry id. */
30
+ sectionTemplates?: Record<string, Layout>;
31
+ /** Section part ids already being expanded, so a section cannot include itself. */
32
+ sectionStack?: readonly string[];
33
+ /**
34
+ * Where the nodes being rendered come from (W-250): unset for the page itself, else the synced
35
+ * section and loop item parts they were expanded from. Another layout can reuse an id.
36
+ */
37
+ idOrigin?: string;
38
+ archiveTitle?: string;
39
+ /** Which archive page is showing, for the Pagination element (W-221). */
40
+ pagination?: ArchivePagination;
41
+ /** Set inside a Loop's item, where a Pagination would repeat once per post (W-228). */
42
+ inLoopItem?: boolean;
43
+ };
44
+
45
+ /** Editor canvas placeholders when no live post is bound. */
46
+ export const SAMPLE_POST: ThemePostFields = {
47
+ id: "sample",
48
+ slug: "sample",
49
+ title: "Post Title",
50
+ excerpt: "Post excerpt…",
51
+ content: "Post content…",
52
+ permalink: "#",
53
+ featuredImageAlt: "Featured image",
54
+ };
55
+
56
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
57
+ Boolean(value) && typeof value === "object";
58
+
59
+ const spanText = (children: unknown) =>
60
+ Array.isArray(children)
61
+ ? children
62
+ .filter(isRecord)
63
+ .map((span) => (typeof span["text"] === "string" ? span["text"] : ""))
64
+ .join("")
65
+ : "";
66
+
67
+ const HEADING_STYLES = new Set(["h1", "h2", "h3", "h4"]);
68
+
69
+ /**
70
+ * Convert Portable Text (or a plain string) into safe VNodes.
71
+ * Marks are flattened to escaped text; only block structure is preserved.
72
+ */
73
+ export function portableTextToVNodes(value: unknown): VNode[] {
74
+ if (typeof value === "string") {
75
+ const trimmed = value.trim();
76
+ return trimmed ? [{ tag: "p", attrs: {}, children: [trimmed] }] : [];
77
+ }
78
+ if (!Array.isArray(value)) return [];
79
+ return value.flatMap((block): VNode[] => {
80
+ if (!isRecord(block) || block["_type"] !== "block") return [];
81
+ const text = spanText(block["children"]).trim();
82
+ if (!text) return [];
83
+ const style = block["style"];
84
+ const tag = typeof style === "string" && HEADING_STYLES.has(style) ? style : "p";
85
+ return [{ tag, attrs: {}, children: [text] }];
86
+ });
87
+ }
88
+
89
+ /** Collect `loop.itemPartId` values so hosts can load Loop Item templates. */
90
+ export function collectLoopItemPartIds(layout: Layout): string[] {
91
+ const ids = new Set<string>();
92
+ const walk = (node: LayoutNode): void => {
93
+ if (node.type === "loop") {
94
+ const id =
95
+ typeof (node.props as { itemPartId?: unknown }).itemPartId === "string"
96
+ ? (node.props as { itemPartId: string }).itemPartId.trim()
97
+ : "";
98
+ if (id) ids.add(id);
99
+ }
100
+ if (isParentNode(node)) {
101
+ for (const child of node.children) walk(child);
102
+ }
103
+ };
104
+ walk(layout.root);
105
+ return [...ids];
106
+ }
107
+
108
+ /** Collect `section.partId` values so hosts can load Section templates. */
109
+ export function collectSectionPartIds(layout: Layout): string[] {
110
+ const ids = new Set<string>();
111
+ const walk = (node: LayoutNode): void => {
112
+ if (node.type === "section") {
113
+ const id =
114
+ typeof (node.props as { partId?: unknown }).partId === "string"
115
+ ? (node.props as { partId: string }).partId.trim()
116
+ : "";
117
+ if (id) ids.add(id);
118
+ }
119
+ if (isParentNode(node)) {
120
+ for (const child of node.children) walk(child);
121
+ }
122
+ };
123
+ walk(layout.root);
124
+ return [...ids];
125
+ }
126
+
127
+ export function resolvePostForRender(
128
+ dynamic: ThemeDynamicData | undefined,
129
+ mode: "public" | "editor",
130
+ ): ThemePostFields | undefined {
131
+ if (dynamic?.post) return dynamic.post;
132
+ if (mode === "editor") return SAMPLE_POST;
133
+ return undefined;
134
+ }
135
+
136
+ export function resolvePostsForLoop(
137
+ dynamic: ThemeDynamicData | undefined,
138
+ mode: "public" | "editor",
139
+ ): ThemePostFields[] {
140
+ if (dynamic?.posts && dynamic.posts.length > 0) return dynamic.posts;
141
+ if (mode === "editor") return [SAMPLE_POST];
142
+ return [];
143
+ }
@@ -0,0 +1,113 @@
1
+ import { z } from "zod";
2
+ import { escapeAttr } from "../sanitize/escape.ts";
3
+ import type { DesignSystem } from "../schema/design.ts";
4
+ import type { Layout } from "../schema/layout.ts";
5
+ import type { StyleProps } from "../schema/style.ts";
6
+ import { parseDoc, type DocIssue } from "./parse-doc.ts";
7
+
8
+ const FLOAT_SCHEMA_VERSION = 1;
9
+
10
+ /** Where a float sits. Start and end follow the page's writing direction. */
11
+ export const FLOAT_EDGES = [
12
+ "top",
13
+ "bottom",
14
+ "start-top",
15
+ "end-top",
16
+ "start-bottom",
17
+ "end-bottom",
18
+ ] as const;
19
+
20
+ export type FloatEdge = (typeof FLOAT_EDGES)[number];
21
+
22
+ const FloatSettingsSchema = z.strictObject({
23
+ schemaVersion: z.literal(FLOAT_SCHEMA_VERSION),
24
+ edge: z.enum(FLOAT_EDGES),
25
+ dismiss: z.boolean(),
26
+ });
27
+
28
+ export type FloatSettings = z.infer<typeof FloatSettingsSchema>;
29
+
30
+ export type FloatValidation =
31
+ | { ok: true; settings: FloatSettings }
32
+ | { ok: false; issues: DocIssue[] };
33
+
34
+ /** A top bar, kept until the author turns on a close button. */
35
+ export function defaultFloatSettings(): FloatSettings {
36
+ return { schemaVersion: FLOAT_SCHEMA_VERSION, edge: "top", dismiss: false };
37
+ }
38
+
39
+ export function validateFloatSettings(raw: unknown): FloatValidation {
40
+ const parsed = parseDoc(raw, FloatSettingsSchema, "float", "Float settings");
41
+ return parsed.ok ? { ok: true, settings: parsed.doc } : parsed;
42
+ }
43
+
44
+ /**
45
+ * Chrome for pinned bars and corner floats. Loaded only when a float matches.
46
+ * Bars reserve their height through the two custom properties the runtime sets.
47
+ */
48
+ export const FLOAT_CHROME_CSS = `
49
+ .emvb-float{position:fixed;z-index:9000;box-sizing:border-box;max-width:100%;display:flex;align-items:flex-start;gap:.35rem}.emvb-float:hover,.emvb-float:focus-within{z-index:9001}
50
+ .emvb-float[hidden]{display:none!important}
51
+ .emvb-float--top{top:0;inset-inline:0}
52
+ .emvb-float--bottom{bottom:0;inset-inline:0}
53
+ .emvb-float--start-top{top:1rem;inset-inline-start:1rem}
54
+ .emvb-float--end-top{top:1rem;inset-inline-end:1rem}
55
+ .emvb-float--start-bottom{bottom:1rem;inset-inline-start:1rem}
56
+ .emvb-float--end-bottom{bottom:1rem;inset-inline-end:1rem}
57
+ :where(.emvb-float--surface){background:#fff;color:#0f172a;box-shadow:0 4px 16px -4px rgba(15,23,42,.25);padding:.5rem 1rem}
58
+ :where(.emvb-float--surface:is(.emvb-float--start-top,.emvb-float--end-top,.emvb-float--start-bottom,.emvb-float--end-bottom)){border-radius:.75rem;padding:.75rem 1rem}
59
+ .emvb-float__body{min-width:0;flex:1}
60
+ .emvb-float__close{flex:none;width:2rem;height:2rem;border:0;border-radius:999px;background:transparent;color:inherit;font-size:1.5rem;line-height:1;cursor:pointer}
61
+ .emvb-float__close:focus-visible{outline:2px solid #2563eb;outline-offset:2px}
62
+ html{--emvb-float-top:0px;--emvb-float-bottom:0px}
63
+ body{padding-top:var(--emvb-float-top);padding-bottom:var(--emvb-float-bottom)}
64
+ `
65
+ .replace(/\n+/g, "")
66
+ .trim();
67
+
68
+ const paintsBackground = (style: StyleProps | undefined): boolean =>
69
+ style?.backgroundColor !== undefined ||
70
+ style?.backgroundImage !== undefined ||
71
+ style?.backgroundVideo !== undefined ||
72
+ style?.gradient !== undefined;
73
+
74
+ /**
75
+ * Whether the float's outer box paints its own background (on the box, a device or one of its
76
+ * classes). Otherwise the float gets the default card surface, so its text isn't drawn over the
77
+ * page (W-171).
78
+ */
79
+ export function floatHasOwnSurface(layout: Layout, design: DesignSystem): boolean {
80
+ const root = layout.root;
81
+ const classes = (design.classes ?? []).filter((item) => root.classes?.includes(item.id));
82
+ return [root, ...classes].some(
83
+ (item) =>
84
+ paintsBackground(item.style) ||
85
+ paintsBackground(item.devices?.tablet) ||
86
+ paintsBackground(item.devices?.mobile),
87
+ );
88
+ }
89
+
90
+ /**
91
+ * Pin rendered float HTML. Not a dialog: no backdrop and no focus trap.
92
+ * A close button is present only when dismiss is on. `surface` adds the default card surface.
93
+ */
94
+ export function wrapFloatMarkup(
95
+ id: string,
96
+ title: string,
97
+ bodyHtml: string,
98
+ settings: FloatSettings,
99
+ surface = true,
100
+ ): string {
101
+ const safeId = escapeAttr(id);
102
+ const label = escapeAttr(title.trim() || "Notice");
103
+ const edge = settings.edge;
104
+ const close = settings.dismiss
105
+ ? `<button type="button" class="emvb-float__close" data-emvb-float-dismiss aria-label="Close"><span aria-hidden="true">×</span></button>`
106
+ : "";
107
+ return [
108
+ `<aside class="emvb-float emvb-float--${edge}${surface ? " emvb-float--surface" : ""}" id="emvb-float-${safeId}" data-emvb-float="${safeId}" data-emvb-float-edge="${edge}" role="region" aria-label="${label}">`,
109
+ `<div class="emvb-float__body">${bodyHtml}</div>`,
110
+ close,
111
+ `</aside>`,
112
+ ].join("");
113
+ }
@@ -0,0 +1,97 @@
1
+ import { isParentNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
+
3
+ /** Posts per archive page when the Loop has no "Posts per page" (the pre-pagination count). */
4
+ export const DEFAULT_PER_PAGE = 20;
5
+ /** Highest page number EmVB reads from `/page/N`; larger numbers are not archive pages. */
6
+ export const MAX_ARCHIVE_PAGE = 100_000;
7
+
8
+ /** Where an archive request sits: its page and whether a later page exists (W-221). */
9
+ export type ArchivePagination = {
10
+ /** 1-based page number. */
11
+ page: number;
12
+ /** True when at least one more post exists after this page. */
13
+ hasMore: boolean;
14
+ /** The archive's own path without `/page/N`, e.g. `/posts` or `/category/news`. */
15
+ basePath: string;
16
+ };
17
+
18
+ /** The URL path of page `n` of an archive; page 1 is the bare archive path (W-221). */
19
+ export function archivePagePath(basePath: string, n: number): string {
20
+ const base = basePath.replace(/\/+$/, "") || "/";
21
+ if (n <= 1) return base;
22
+ return `${base === "/" ? "" : base}/page/${n}`;
23
+ }
24
+
25
+ /**
26
+ * Splits `/posts/page/3` into the archive path and page. Null for anything that is not a
27
+ * valid page suffix (`/page/0`, `/page/01`, `/page/abc`, a page past MAX_ARCHIVE_PAGE).
28
+ * A path without `/page/N` is page 1.
29
+ */
30
+ export function splitArchivePage(path: string): { basePath: string; page: number } | null {
31
+ const match = /^(.*?)\/page\/([^/]+)$/.exec(path);
32
+ if (!match) return { basePath: path, page: 1 };
33
+ const raw = match[2] ?? "";
34
+ if (!/^[1-9]\d{0,5}$/.test(raw)) return null;
35
+ const page = Number(raw);
36
+ if (page > MAX_ARCHIVE_PAGE) return null;
37
+ return { basePath: match[1] || "/", page };
38
+ }
39
+
40
+ /** Posts per page from the first Loop in an archive layout, else DEFAULT_PER_PAGE (W-221). */
41
+ export function loopPerPage(layout: Layout): number {
42
+ let found: number | undefined;
43
+ const walk = (node: LayoutNode): void => {
44
+ if (found !== undefined) return;
45
+ if (node.type === "loop") {
46
+ const perPage = (node.props as { perPage?: unknown }).perPage;
47
+ found =
48
+ typeof perPage === "number" && Number.isInteger(perPage) && perPage >= 1 && perPage <= 50
49
+ ? perPage
50
+ : DEFAULT_PER_PAGE;
51
+ return;
52
+ }
53
+ if (isParentNode(node)) for (const child of node.children) walk(child);
54
+ };
55
+ walk(layout.root);
56
+ return found ?? DEFAULT_PER_PAGE;
57
+ }
58
+
59
+ /**
60
+ * A paged archive's title for `<title>` and headings: "Posts – page 2"; page 1 is the bare
61
+ * title (W-229).
62
+ */
63
+ export function archivePageTitle(title: string, page: number | undefined): string {
64
+ return page !== undefined && page > 1 ? `${title} – page ${page}` : title;
65
+ }
66
+
67
+ /** One entry of a Pagination bar: a page link, the current page, or a gap (W-222). */
68
+ export type PaginationItem =
69
+ | { kind: "prev" | "next"; href: string }
70
+ | { kind: "page"; n: number; href: string; current: boolean }
71
+ | { kind: "gap" };
72
+
73
+ /**
74
+ * The links a Pagination element shows. Empty when there is only one page. EmDash gives no
75
+ * total count, so the numbers run from 1 to one past the current page (when there is one),
76
+ * with a gap after 1 when the current page is far in (W-222).
77
+ */
78
+ export function paginationItems(p: ArchivePagination): PaginationItem[] {
79
+ if (p.page <= 1 && !p.hasMore) return [];
80
+ const items: PaginationItem[] = [];
81
+ const page = (n: number): PaginationItem => ({
82
+ kind: "page",
83
+ n,
84
+ href: archivePagePath(p.basePath, n),
85
+ current: n === p.page,
86
+ });
87
+ if (p.page > 1) items.push({ kind: "prev", href: archivePagePath(p.basePath, p.page - 1) });
88
+ const from = Math.max(1, p.page - 2);
89
+ if (from > 1) items.push(page(1));
90
+ if (from > 2) items.push({ kind: "gap" });
91
+ for (let n = from; n <= p.page; n++) items.push(page(n));
92
+ if (p.hasMore) {
93
+ items.push(page(p.page + 1));
94
+ items.push({ kind: "next", href: archivePagePath(p.basePath, p.page + 1) });
95
+ }
96
+ return items;
97
+ }