@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,515 @@
1
+ import { getEmDashCollection, getEmDashEntry, getTerm } from "emdash";
2
+ import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
3
+ import {
4
+ collectLoopItemPartIds,
5
+ collectSectionPartIds,
6
+ contentPartTypeForContext,
7
+ defaultConditions,
8
+ defaultFloatSettings,
9
+ defaultTriggers,
10
+ FLOAT_CHROME_CSS,
11
+ floatHasOwnSurface,
12
+ listMatchingThemeParts,
13
+ parseThemePartType,
14
+ pickThemePartWinner,
15
+ POPUP_CHROME_CSS,
16
+ validateConditions,
17
+ validateFloatSettings,
18
+ validateTriggers,
19
+ wrapFloatMarkup,
20
+ wrapPopupMarkup,
21
+ type FloatSettings,
22
+ type Layout,
23
+ type ThemeDynamicData,
24
+ type ThemePartCandidate,
25
+ type ThemePartType,
26
+ type ThemePostFields,
27
+ type ThemeRequestContext,
28
+ type TriggersDoc,
29
+ archivePagePath,
30
+ loopPerPage,
31
+ type ArchivePagination,
32
+ } from "../core/index.ts";
33
+ import { THEME_PARTS_COLLECTION } from "../constants.ts";
34
+ import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
35
+ import { themeContextFrom } from "./theme-context.ts";
36
+ import { themePostFromEntry } from "./theme-posts.ts";
37
+
38
+ /** The landmark element for a part's wrapper (W-216); other parts get a plain div. */
39
+ const WRAPPER_TAGS: Partial<Record<string, "header" | "footer">> = {
40
+ header: "header",
41
+ footer: "footer",
42
+ };
43
+
44
+ export type RenderedThemePart = {
45
+ id: string;
46
+ title: string;
47
+ partType: ThemePartType;
48
+ html: string;
49
+ css: string;
50
+ };
51
+
52
+ export type RenderedPopup = {
53
+ id: string;
54
+ title: string;
55
+ html: string;
56
+ css: string;
57
+ triggers: TriggersDoc;
58
+ };
59
+
60
+ export type RenderedFloat = {
61
+ id: string;
62
+ title: string;
63
+ html: string;
64
+ css: string;
65
+ settings: FloatSettings;
66
+ };
67
+
68
+ export type ResolvedThemeParts = {
69
+ header: RenderedThemePart | null;
70
+ footer: RenderedThemePart | null;
71
+ /**
72
+ * Body/main replacement when a content theme part wins (404, search, page, post, archive).
73
+ * Null when none match — hosts keep their route slot content.
74
+ */
75
+ content: RenderedThemePart | null;
76
+ /** Matching published popups for this request (S7b). May be more than one. */
77
+ popups: RenderedPopup[];
78
+ /** Matching published floats. May be more than one. Not dialogs. */
79
+ floats: RenderedFloat[];
80
+ /** Concatenated CSS for all winners (empty when none match). */
81
+ css: string;
82
+ /** Hosts load `EmVBPopupsRuntime` only when this is true (R-031). */
83
+ needsPopupsRuntime: boolean;
84
+ /** Hosts load `EmVBFloatsRuntime` only when a float matches (R-031). */
85
+ needsFloatsRuntime: boolean;
86
+ /** Hosts load `EmVBTabsRuntime` only when Tabs appear in a winning part (R-031 / W-078). */
87
+ needsTabsRuntime: boolean;
88
+ /** Hosts load `EmVBMenuRuntime` only when a winning part has a Menu dropdown (W-197). */
89
+ needsMenuRuntime: boolean;
90
+ /**
91
+ * True for an archive page past the last one (`/posts/page/9` with no posts there). Hosts
92
+ * answer 404 (W-221). Page 1 with no posts is not a 404.
93
+ */
94
+ notFound: boolean;
95
+ /**
96
+ * The canonical path of an archive page: the bare archive path for page 1 (also for
97
+ * `/page/1`, which hosts should redirect there), else `<archive>/page/N` (W-221).
98
+ */
99
+ canonicalPath?: string;
100
+ /**
101
+ * The archive's title when an Archive part renders: "Posts", or the category/tag slug
102
+ * (W-229). Hosts build "Posts – page 2" with `archivePageTitle`.
103
+ */
104
+ archiveTitle?: string;
105
+ /** The archive page number when an Archive part renders (1 for the bare URL). */
106
+ archivePage?: number;
107
+ /** The site's text direction from Site styles when a part renders, for `<html dir>` (W-230). */
108
+ dir?: "ltr" | "rtl" | "auto";
109
+ };
110
+
111
+ type AstroLike = {
112
+ url: URL;
113
+ locals: unknown;
114
+ props?: Record<string, unknown>;
115
+ };
116
+
117
+ type StoredPart = {
118
+ id: string;
119
+ title: string;
120
+ partType: ThemePartType;
121
+ layout: unknown;
122
+ conditions: ReturnType<typeof defaultConditions>;
123
+ triggers: TriggersDoc;
124
+ float: FloatSettings;
125
+ updatedAt: string;
126
+ };
127
+
128
+ /** A stored JSON field, or `fallback` when the field was never set. */
129
+ const storedOr = <T>(raw: unknown, fallback: () => T): unknown =>
130
+ raw === undefined || raw === null || raw === "" ? fallback() : raw;
131
+
132
+ /** A published entry as a theme part, or undefined when its type or conditions are invalid. */
133
+ function storedPartFrom(entry: { id: string; data: unknown }): StoredPart | undefined {
134
+ const data = entry.data as Record<string, unknown>;
135
+ const partType = parseThemePartType(data["part_type"]);
136
+ if (!partType) return undefined;
137
+ const conditions = validateConditions(storedOr(data["conditions"], defaultConditions));
138
+ if (!conditions.ok) return undefined;
139
+ const triggers = validateTriggers(storedOr(data["triggers"], defaultTriggers));
140
+ // Invalid triggers fail closed for popups; other part types ignore triggers.
141
+ if (partType === "popup" && !triggers.ok) return undefined;
142
+ const float = validateFloatSettings(storedOr(data["float"], defaultFloatSettings));
143
+ // Invalid float settings fail closed for floats; other part types ignore them.
144
+ if (partType === "float" && !float.ok) return undefined;
145
+ return {
146
+ id: String(data["id"] ?? entry.id),
147
+ title: typeof data["title"] === "string" ? data["title"] : "",
148
+ partType,
149
+ layout: data["layout"],
150
+ conditions: conditions.conditions,
151
+ triggers: triggers.ok ? triggers.triggers : defaultTriggers(),
152
+ float: float.ok ? float.settings : defaultFloatSettings(),
153
+ updatedAt: String(data["updatedAt"] ?? data["updated_at"] ?? ""),
154
+ };
155
+ }
156
+
157
+ const THEME_PARTS_PAGE = 50;
158
+ /** Enough pages for any real site; stops a cursor that never ends. */
159
+ const THEME_PARTS_MAX_PAGES = 20;
160
+
161
+ /** Every published theme part, page by page; a failed page ends the read with what came before. */
162
+ async function loadPublishedThemeParts(): Promise<StoredPart[]> {
163
+ const entries: Awaited<ReturnType<typeof getEmDashCollection>>["entries"] = [];
164
+ let cursor: string | undefined;
165
+ for (let page = 0; page < THEME_PARTS_MAX_PAGES; page += 1) {
166
+ let result: Awaited<ReturnType<typeof getEmDashCollection>>;
167
+ try {
168
+ // No orderBy: D1/SQLite columns are snake_case and camelCase orderBy fails the query.
169
+ // Winners and popup order come from updatedAt in core/theme/conditions.ts.
170
+ // oxlint-disable-next-line no-await-in-loop -- each page needs the previous page's cursor
171
+ result = await getEmDashCollection(THEME_PARTS_COLLECTION, {
172
+ status: "published",
173
+ limit: THEME_PARTS_PAGE,
174
+ ...(cursor ? { cursor } : {}),
175
+ });
176
+ } catch {
177
+ break;
178
+ }
179
+ if (result.error) break;
180
+ entries.push(...(result.entries ?? []));
181
+ cursor = result.nextCursor;
182
+ if (!cursor) break;
183
+ }
184
+ return entries.map(storedPartFrom).filter((part): part is StoredPart => part !== undefined);
185
+ }
186
+
187
+ async function loadLoopTemplates(
188
+ layout: Layout,
189
+ parts: StoredPart[],
190
+ ): Promise<Record<string, Layout>> {
191
+ const ids = collectLoopItemPartIds(layout);
192
+ if (ids.length === 0) return {};
193
+ const byId = new Map(parts.map((p) => [p.id, p]));
194
+ const templates: Record<string, Layout> = {};
195
+ for (const id of ids) {
196
+ const part = byId.get(id);
197
+ if (!part || part.partType !== "loop_item") continue;
198
+ const itemLayout = readLayout(part.layout);
199
+ if (itemLayout) templates[id] = itemLayout;
200
+ }
201
+ return templates;
202
+ }
203
+
204
+ /** Section parts referenced by `layout`, including sections nested inside those parts. */
205
+ function loadSectionTemplates(layout: Layout, parts: StoredPart[]): Record<string, Layout> {
206
+ const byId = new Map(parts.map((p) => [p.id, p]));
207
+ const templates: Record<string, Layout> = {};
208
+ const queue = collectSectionPartIds(layout);
209
+ const seen = new Set<string>();
210
+ while (queue.length > 0 && seen.size < 32) {
211
+ const id = queue.shift();
212
+ if (!id || seen.has(id)) continue;
213
+ seen.add(id);
214
+ const part = byId.get(id);
215
+ if (!part || part.partType !== "section") continue;
216
+ const itemLayout = readLayout(part.layout);
217
+ if (!itemLayout) continue;
218
+ templates[id] = itemLayout;
219
+ queue.push(...collectSectionPartIds(itemLayout));
220
+ }
221
+ return templates;
222
+ }
223
+
224
+ /** Published Section layouts a page references. Empty when the page has no section parts. */
225
+ export async function sectionTemplatesFor(layout: Layout): Promise<Record<string, Layout>> {
226
+ if (collectSectionPartIds(layout).length === 0) return {};
227
+ return loadSectionTemplates(layout, await loadPublishedThemeParts());
228
+ }
229
+
230
+ async function loadSingularPost(ctx: ThemeRequestContext): Promise<ThemePostFields | undefined> {
231
+ if (ctx.kind !== "singular" || ctx.collection !== "posts") return undefined;
232
+ const key = ctx.entryId || undefined;
233
+ // Prefer slug from path `/posts/{slug}` when entry id is missing.
234
+ const pathSlug = /^\/posts\/([^/]+)$/.exec(ctx.path)?.[1];
235
+ const lookup = key || (pathSlug ? decodeURIComponent(pathSlug) : undefined);
236
+ if (!lookup) return undefined;
237
+ try {
238
+ const { entry } = await getEmDashEntry("posts", lookup);
239
+ if (!entry) return undefined;
240
+ return themePostFromEntry(entry) ?? undefined;
241
+ } catch {
242
+ return undefined;
243
+ }
244
+ }
245
+
246
+ /** A taxonomy term's label for archive titles; the slug when the term can't be read (W-263). */
247
+ async function termLabel(taxonomy: string, slug: string): Promise<string> {
248
+ try {
249
+ const term = await getTerm(taxonomy, slug);
250
+ return term?.label?.trim() || slug;
251
+ } catch {
252
+ return slug;
253
+ }
254
+ }
255
+
256
+ async function loadArchivePosts(
257
+ ctx: ThemeRequestContext,
258
+ perPage: number,
259
+ ): Promise<{
260
+ posts: ThemePostFields[];
261
+ archiveTitle?: string;
262
+ pagination?: ArchivePagination;
263
+ }> {
264
+ if (ctx.kind !== "archive" || ctx.isSearch) return { posts: [] };
265
+ const page = ctx.page ?? 1;
266
+ try {
267
+ // Offset paging for numbered `/page/N` routes (W-221); EmDash reports `hasMore`.
268
+ const filter: {
269
+ orderBy: { published_at: "desc" };
270
+ limit: number;
271
+ offset?: number;
272
+ where?: Record<string, string>;
273
+ } = {
274
+ orderBy: { published_at: "desc" },
275
+ limit: perPage,
276
+ ...(page > 1 ? { offset: (page - 1) * perPage } : {}),
277
+ };
278
+ if (ctx.taxonomy?.type === "category") {
279
+ filter.where = { category: ctx.taxonomy.slug };
280
+ } else if (ctx.taxonomy?.type === "tag") {
281
+ filter.where = { tag: ctx.taxonomy.slug };
282
+ }
283
+ const result = await getEmDashCollection("posts", filter);
284
+ if (result.error || !result.entries) return { posts: [] };
285
+ const hasMore = (result as { hasMore?: boolean }).hasMore === true;
286
+ const posts = result.entries
287
+ .map((entry) => themePostFromEntry(entry))
288
+ .filter((p): p is ThemePostFields => p !== null);
289
+ // W-263: a category or tag archive is titled by its term's label ("News"), not its slug.
290
+ const archiveTitle = ctx.taxonomy?.slug
291
+ ? await termLabel(ctx.taxonomy.type, ctx.taxonomy.slug)
292
+ : ctx.collection === "posts"
293
+ ? "Posts"
294
+ : undefined;
295
+ return { posts, archiveTitle, pagination: { page, hasMore, basePath: ctx.path } };
296
+ } catch {
297
+ return { posts: [] };
298
+ }
299
+ }
300
+
301
+ async function buildDynamicForContent(
302
+ partType: ThemePartType,
303
+ ctx: ThemeRequestContext,
304
+ layout: Layout,
305
+ parts: StoredPart[],
306
+ ): Promise<ThemeDynamicData | undefined> {
307
+ const loopTemplates = await loadLoopTemplates(layout, parts);
308
+ const sectionTemplates = loadSectionTemplates(layout, parts);
309
+ const referenced: ThemeDynamicData = {
310
+ ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
311
+ ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
312
+ };
313
+ if (partType === "single_post") {
314
+ const post = await loadSingularPost(ctx);
315
+ if (!post && Object.keys(referenced).length === 0) return undefined;
316
+ return { ...referenced, post };
317
+ }
318
+ if (partType === "archive") {
319
+ const { posts, archiveTitle, pagination } = await loadArchivePosts(ctx, loopPerPage(layout));
320
+ return { ...referenced, posts, archiveTitle, ...(pagination ? { pagination } : {}) };
321
+ }
322
+ if (Object.keys(referenced).length > 0) return referenced;
323
+ return undefined;
324
+ }
325
+
326
+ /**
327
+ * Resolve winning published theme parts for this request (R-062 / S7b–S7d).
328
+ * Returns plain HTML/CSS; popup JS is optional and only when `needsPopupsRuntime`.
329
+ * Single Post / Archive winners substitute post fields server-side.
330
+ */
331
+ export async function resolveThemeParts(
332
+ astro: AstroLike,
333
+ ctx?: ThemeRequestContext,
334
+ ): Promise<ResolvedThemeParts> {
335
+ const context =
336
+ ctx ??
337
+ themeContextFrom(astro.url, {
338
+ content:
339
+ (astro.props?.["content"] as
340
+ | { collection: string; id: string; slug?: string | null }
341
+ | undefined) ?? null,
342
+ });
343
+
344
+ const empty: ResolvedThemeParts = {
345
+ header: null,
346
+ footer: null,
347
+ content: null,
348
+ popups: [],
349
+ floats: [],
350
+ css: "",
351
+ needsPopupsRuntime: false,
352
+ needsFloatsRuntime: false,
353
+ needsTabsRuntime: false,
354
+ needsMenuRuntime: false,
355
+ notFound: false,
356
+ ...(context.kind === "archive" && !context.isSearch
357
+ ? { canonicalPath: archivePagePath(context.path, context.page ?? 1) }
358
+ : {}),
359
+ };
360
+
361
+ const parts = await loadPublishedThemeParts();
362
+ if (parts.length === 0) return empty;
363
+
364
+ const candidates: ThemePartCandidate[] = parts.map((part) => ({
365
+ id: part.id,
366
+ partType: part.partType,
367
+ conditions: part.conditions,
368
+ updatedAt: part.updatedAt,
369
+ }));
370
+
371
+ const headerWinner = pickThemePartWinner(candidates, "header", context);
372
+ const footerWinner = pickThemePartWinner(candidates, "footer", context);
373
+ const contentType = contentPartTypeForContext(context);
374
+ const contentWinner = contentType ? pickThemePartWinner(candidates, contentType, context) : null;
375
+ const popupMatches = listMatchingThemeParts(candidates, "popup", context);
376
+ const floatMatches = listMatchingThemeParts(candidates, "float", context);
377
+
378
+ if (
379
+ !headerWinner &&
380
+ !footerWinner &&
381
+ !contentWinner &&
382
+ popupMatches.length === 0 &&
383
+ floatMatches.length === 0
384
+ ) {
385
+ return empty;
386
+ }
387
+
388
+ const handler = getPublicPluginApiRouteHandler(astro.locals as never);
389
+ const design = await loadDesign(handler, astro.url);
390
+
391
+ const byId = new Map(parts.map((part) => [part.id, part]));
392
+ const rendered: RenderedPage[] = [];
393
+ const renderOne = (stored: StoredPart, dynamic?: ThemeDynamicData) => {
394
+ const page = renderStored(stored.layout, design, stored.id, undefined, dynamic);
395
+ rendered.push(page);
396
+ // W-216: a header or footer part is the page's banner or contentinfo landmark (hosts put it
397
+ // straight in <body> instead of their own <header>/<footer>).
398
+ const tag = WRAPPER_TAGS[stored.partType] ?? "div";
399
+ const html = page.html
400
+ ? `<${tag} class="emvb-theme-${stored.partType}" data-emvb-theme-part="${stored.id}">${page.html}</${tag}>`
401
+ : "";
402
+ return { html, css: page.css };
403
+ };
404
+
405
+ /** Synced sections and loop items a part uses, for every part type (W-200). */
406
+ const templatesFor = async (stored: StoredPart): Promise<ThemeDynamicData | undefined> => {
407
+ const layout = readLayout(stored.layout);
408
+ const sectionTemplates = layout ? loadSectionTemplates(layout, parts) : {};
409
+ const loopTemplates = layout ? await loadLoopTemplates(layout, parts) : {};
410
+ return Object.keys(sectionTemplates).length > 0 || Object.keys(loopTemplates).length > 0
411
+ ? {
412
+ ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
413
+ ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
414
+ }
415
+ : undefined;
416
+ };
417
+
418
+ let pastLastPage = false;
419
+ let archiveInfo: { title?: string; page: number } | undefined;
420
+ const renderPart = async (
421
+ winner: ThemePartCandidate | null,
422
+ ): Promise<RenderedThemePart | null> => {
423
+ const stored = winner ? byId.get(winner.id) : undefined;
424
+ if (!stored) return null;
425
+ const layout = readLayout(stored.layout);
426
+ const referenced = await templatesFor(stored);
427
+ const dynamic =
428
+ layout && winner === contentWinner
429
+ ? {
430
+ ...referenced,
431
+ ...(await buildDynamicForContent(stored.partType, context, layout, parts)),
432
+ }
433
+ : referenced;
434
+ // A page past the last one has no posts; the host answers 404 (W-221).
435
+ if (winner === contentWinner && dynamic?.pagination) {
436
+ archiveInfo = { title: dynamic.archiveTitle, page: dynamic.pagination.page };
437
+ }
438
+ if (winner === contentWinner && (dynamic?.pagination?.page ?? 1) > 1) {
439
+ pastLastPage = (dynamic?.posts ?? []).length === 0;
440
+ }
441
+ const { html, css } = renderOne(stored, dynamic);
442
+ return { id: stored.id, title: stored.title, partType: stored.partType, html, css };
443
+ };
444
+
445
+ const header = await renderPart(headerWinner);
446
+ const footer = await renderPart(footerWinner);
447
+ const content = await renderPart(contentWinner);
448
+
449
+ const extraParts = [...popupMatches, ...floatMatches]
450
+ .map((match) => byId.get(match.id))
451
+ .filter((stored): stored is StoredPart => stored !== undefined);
452
+ const extraTemplates = new Map(
453
+ await Promise.all(
454
+ extraParts.map(async (stored) => [stored.id, await templatesFor(stored)] as const),
455
+ ),
456
+ );
457
+
458
+ const popups: RenderedPopup[] = [];
459
+ for (const match of popupMatches) {
460
+ const stored = byId.get(match.id);
461
+ if (!stored) continue;
462
+ const { html, css } = renderOne(stored, extraTemplates.get(stored.id));
463
+ popups.push({
464
+ id: stored.id,
465
+ title: stored.title,
466
+ html: wrapPopupMarkup(stored.id, html, stored.triggers),
467
+ css,
468
+ triggers: stored.triggers,
469
+ });
470
+ }
471
+
472
+ const floats: RenderedFloat[] = [];
473
+ for (const match of floatMatches) {
474
+ const stored = byId.get(match.id);
475
+ if (!stored) continue;
476
+ const { html, css } = renderOne(stored, extraTemplates.get(stored.id));
477
+ const layout = readLayout(stored.layout);
478
+ const surface = !layout || !floatHasOwnSurface(layout, design);
479
+ floats.push({
480
+ id: stored.id,
481
+ title: stored.title,
482
+ html: wrapFloatMarkup(stored.id, stored.title, html, stored.float, surface),
483
+ css,
484
+ settings: stored.float,
485
+ });
486
+ }
487
+
488
+ const cssParts = [
489
+ header?.css,
490
+ content?.css,
491
+ footer?.css,
492
+ ...popups.map((p) => p.css),
493
+ ...floats.map((item) => item.css),
494
+ ];
495
+ if (popups.length > 0) cssParts.push(POPUP_CHROME_CSS);
496
+ if (floats.length > 0) cssParts.push(FLOAT_CHROME_CSS);
497
+ const css = cssParts.filter(Boolean).join("\n");
498
+ return {
499
+ header,
500
+ footer,
501
+ content,
502
+ popups,
503
+ floats,
504
+ css,
505
+ needsPopupsRuntime: popups.length > 0,
506
+ needsFloatsRuntime: floats.length > 0,
507
+ needsTabsRuntime: rendered.some((page) => page.needsTabsRuntime),
508
+ needsMenuRuntime: rendered.some((page) => page.needsMenuRuntime),
509
+ notFound: pastLastPage,
510
+ ...(design.direction ? { dir: design.direction } : {}),
511
+ ...(archiveInfo?.title ? { archiveTitle: archiveInfo.title } : {}),
512
+ ...(archiveInfo ? { archivePage: archiveInfo.page } : {}),
513
+ ...(empty.canonicalPath ? { canonicalPath: empty.canonicalPath } : {}),
514
+ };
515
+ }
@@ -0,0 +1,65 @@
1
+ import { decodeSlug, getEmDashEntry } from "emdash";
2
+ import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
3
+ import { PAGES_COLLECTION } from "../constants.ts";
4
+ import { formIdsInLayout, loadFormDefinitions } from "./forms-definitions.ts";
5
+ import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
6
+ import { sectionTemplatesFor } from "./resolve-theme.ts";
7
+
8
+ type EmDashEntry = NonNullable<Awaited<ReturnType<typeof getEmDashEntry>>["entry"]>;
9
+
10
+ export type ResolvedEmVBPage = RenderedPage & {
11
+ /** The EmDash entry, for `getSeoMeta` and the host's layout. */
12
+ entry: EmDashEntry;
13
+ title: string;
14
+ canvasMode: "site-layout" | "blank";
15
+ /** A valid `_preview` token is serving the draft: don't cache the response. */
16
+ isPreview: boolean;
17
+ };
18
+
19
+ type AstroLike = {
20
+ params: Record<string, string | undefined>;
21
+ url: URL;
22
+ locals: unknown;
23
+ };
24
+
25
+ /**
26
+ * Looks up the published EmVB page for this request's slug (or its draft under a preview token),
27
+ * so a host route can try EmVB first and fall through to its own content (R-030, R-052).
28
+ */
29
+ export async function resolveEmVBPage(
30
+ astro: AstroLike,
31
+ options: { param?: string } = {},
32
+ ): Promise<ResolvedEmVBPage | null> {
33
+ const slug = decodeSlug(astro.params[options.param ?? "slug"]);
34
+ if (!slug) return null;
35
+ let found: Awaited<ReturnType<typeof getEmDashEntry>>;
36
+ try {
37
+ found = await getEmDashEntry(PAGES_COLLECTION, slug);
38
+ } catch {
39
+ // No emvb_pages collection yet (EmVB not set up): not an EmVB page.
40
+ return null;
41
+ }
42
+ const entry = found.entry;
43
+ if (!entry) return null;
44
+ const data = entry.data as Record<string, unknown>;
45
+ const handler = getPublicPluginApiRouteHandler(astro.locals as never);
46
+ const design = await loadDesign(handler, astro.url);
47
+ const layout = readLayout(data["layout"]);
48
+ const formDefinitions = layout
49
+ ? await loadFormDefinitions(handler, astro.url, formIdsInLayout(layout))
50
+ : undefined;
51
+ const sectionTemplates = layout ? await sectionTemplatesFor(layout) : {};
52
+ return {
53
+ ...renderStored(
54
+ data["layout"],
55
+ design,
56
+ String(data["id"] ?? slug),
57
+ formDefinitions,
58
+ Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : undefined,
59
+ ),
60
+ entry,
61
+ title: typeof data["title"] === "string" ? data["title"] : "",
62
+ canvasMode: data["canvas_mode"] === "blank" ? "blank" : "site-layout",
63
+ isPreview: Boolean(found.isPreview),
64
+ };
65
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ // Optional Tabs keyboard / ARIA client (W-078). Hosts render this only when
3
+ // `needsTabsRuntime` so pages without Tabs stay zero EmVB JS (R-031).
4
+ // CSS radio + :has() remains the no-JS fallback.
5
+ ---
6
+
7
+ <script>
8
+ import { initTabs } from "./runtime.ts";
9
+ initTabs();
10
+ </script>
@@ -0,0 +1 @@
1
+ export { default as EmVBTabsRuntime } from "./EmVBTabsRuntime.astro";