@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,371 @@
1
+ import { getEmDashCollection, getEmDashEntry } from "emdash";
2
+ import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
3
+ import {
4
+ collectLoopItemPartIds,
5
+ collectSectionPartIds,
6
+ contentPartTypeForContext,
7
+ defaultConditions,
8
+ defaultTriggers,
9
+ listMatchingThemeParts,
10
+ parseThemePartType,
11
+ pickThemePartWinner,
12
+ POPUP_CHROME_CSS,
13
+ validateConditions,
14
+ validateTriggers,
15
+ wrapPopupMarkup,
16
+ type Layout,
17
+ type ThemeDynamicData,
18
+ type ThemePartCandidate,
19
+ type ThemePartType,
20
+ type ThemePostFields,
21
+ type ThemeRequestContext,
22
+ type TriggersDoc,
23
+ } from "../core/index.ts";
24
+ import { THEME_PARTS_COLLECTION } from "../constants.ts";
25
+ import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
26
+ import { themeContextFrom } from "./theme-context.ts";
27
+ import { themePostFromEntry } from "./theme-posts.ts";
28
+
29
+ export type RenderedThemePart = {
30
+ id: string;
31
+ title: string;
32
+ partType: ThemePartType;
33
+ html: string;
34
+ css: string;
35
+ };
36
+
37
+ export type RenderedPopup = {
38
+ id: string;
39
+ title: string;
40
+ html: string;
41
+ css: string;
42
+ triggers: TriggersDoc;
43
+ };
44
+
45
+ export type ResolvedThemeParts = {
46
+ header: RenderedThemePart | null;
47
+ footer: RenderedThemePart | null;
48
+ /**
49
+ * Body/main replacement when a content theme part wins (404, search, page, post, archive).
50
+ * Null when none match — hosts keep their route slot content.
51
+ */
52
+ content: RenderedThemePart | null;
53
+ /** Matching published popups for this request (S7b). May be more than one. */
54
+ popups: RenderedPopup[];
55
+ /** Concatenated CSS for all winners (empty when none match). */
56
+ css: string;
57
+ /** Hosts load `EmVBPopupsRuntime` only when this is true (R-031). */
58
+ needsPopupsRuntime: boolean;
59
+ /** Hosts load `EmVBTabsRuntime` only when Tabs appear in a winning part (R-031 / W-078). */
60
+ needsTabsRuntime: boolean;
61
+ };
62
+
63
+ type AstroLike = {
64
+ url: URL;
65
+ locals: unknown;
66
+ props?: Record<string, unknown>;
67
+ };
68
+
69
+ type StoredPart = {
70
+ id: string;
71
+ title: string;
72
+ partType: ThemePartType;
73
+ layout: unknown;
74
+ conditions: ReturnType<typeof defaultConditions>;
75
+ triggers: TriggersDoc;
76
+ updatedAt: string;
77
+ };
78
+
79
+ /** A stored JSON field, or `fallback` when the field was never set. */
80
+ const storedOr = <T>(raw: unknown, fallback: () => T): unknown =>
81
+ raw === undefined || raw === null || raw === "" ? fallback() : raw;
82
+
83
+ /** A published entry as a theme part, or undefined when its type or conditions are invalid. */
84
+ function storedPartFrom(entry: { id: string; data: unknown }): StoredPart | undefined {
85
+ const data = entry.data as Record<string, unknown>;
86
+ const partType = parseThemePartType(data["part_type"]);
87
+ if (!partType) return undefined;
88
+ const conditions = validateConditions(storedOr(data["conditions"], defaultConditions));
89
+ if (!conditions.ok) return undefined;
90
+ const triggers = validateTriggers(storedOr(data["triggers"], defaultTriggers));
91
+ // Invalid triggers fail closed for popups; other part types ignore triggers.
92
+ if (partType === "popup" && !triggers.ok) return undefined;
93
+ return {
94
+ id: String(data["id"] ?? entry.id),
95
+ title: typeof data["title"] === "string" ? data["title"] : "",
96
+ partType,
97
+ layout: data["layout"],
98
+ conditions: conditions.conditions,
99
+ triggers: triggers.ok ? triggers.triggers : defaultTriggers(),
100
+ updatedAt: String(data["updatedAt"] ?? data["updated_at"] ?? ""),
101
+ };
102
+ }
103
+
104
+ const THEME_PARTS_PAGE = 50;
105
+ /** Enough pages for any real site; stops a cursor that never ends. */
106
+ const THEME_PARTS_MAX_PAGES = 20;
107
+
108
+ /** Every published theme part, page by page; a failed page ends the read with what came before. */
109
+ async function loadPublishedThemeParts(): Promise<StoredPart[]> {
110
+ const entries: Awaited<ReturnType<typeof getEmDashCollection>>["entries"] = [];
111
+ let cursor: string | undefined;
112
+ for (let page = 0; page < THEME_PARTS_MAX_PAGES; page += 1) {
113
+ let result: Awaited<ReturnType<typeof getEmDashCollection>>;
114
+ try {
115
+ // No orderBy: D1/SQLite columns are snake_case and camelCase orderBy fails the query.
116
+ // Winners and popup order come from updatedAt in core/theme/conditions.ts.
117
+ // oxlint-disable-next-line no-await-in-loop -- each page needs the previous page's cursor
118
+ result = await getEmDashCollection(THEME_PARTS_COLLECTION, {
119
+ status: "published",
120
+ limit: THEME_PARTS_PAGE,
121
+ ...(cursor ? { cursor } : {}),
122
+ });
123
+ } catch {
124
+ break;
125
+ }
126
+ if (result.error) break;
127
+ entries.push(...(result.entries ?? []));
128
+ cursor = result.nextCursor;
129
+ if (!cursor) break;
130
+ }
131
+ return entries.map(storedPartFrom).filter((part): part is StoredPart => part !== undefined);
132
+ }
133
+
134
+ async function loadLoopTemplates(
135
+ layout: Layout,
136
+ parts: StoredPart[],
137
+ ): Promise<Record<string, Layout>> {
138
+ const ids = collectLoopItemPartIds(layout);
139
+ if (ids.length === 0) return {};
140
+ const byId = new Map(parts.map((p) => [p.id, p]));
141
+ const templates: Record<string, Layout> = {};
142
+ for (const id of ids) {
143
+ const part = byId.get(id);
144
+ if (!part || part.partType !== "loop_item") continue;
145
+ const itemLayout = readLayout(part.layout);
146
+ if (itemLayout) templates[id] = itemLayout;
147
+ }
148
+ return templates;
149
+ }
150
+
151
+ /** Section parts referenced by `layout`, including sections nested inside those parts. */
152
+ function loadSectionTemplates(layout: Layout, parts: StoredPart[]): Record<string, Layout> {
153
+ const byId = new Map(parts.map((p) => [p.id, p]));
154
+ const templates: Record<string, Layout> = {};
155
+ const queue = collectSectionPartIds(layout);
156
+ const seen = new Set<string>();
157
+ while (queue.length > 0 && seen.size < 32) {
158
+ const id = queue.shift();
159
+ if (!id || seen.has(id)) continue;
160
+ seen.add(id);
161
+ const part = byId.get(id);
162
+ if (!part || part.partType !== "section") continue;
163
+ const itemLayout = readLayout(part.layout);
164
+ if (!itemLayout) continue;
165
+ templates[id] = itemLayout;
166
+ queue.push(...collectSectionPartIds(itemLayout));
167
+ }
168
+ return templates;
169
+ }
170
+
171
+ /** Published Section layouts a page references. Empty when the page has no section parts. */
172
+ export async function sectionTemplatesFor(layout: Layout): Promise<Record<string, Layout>> {
173
+ if (collectSectionPartIds(layout).length === 0) return {};
174
+ return loadSectionTemplates(layout, await loadPublishedThemeParts());
175
+ }
176
+
177
+ async function loadSingularPost(ctx: ThemeRequestContext): Promise<ThemePostFields | undefined> {
178
+ if (ctx.kind !== "singular" || ctx.collection !== "posts") return undefined;
179
+ const key = ctx.entryId || undefined;
180
+ // Prefer slug from path `/posts/{slug}` when entry id is missing.
181
+ const pathSlug = /^\/posts\/([^/]+)$/.exec(ctx.path)?.[1];
182
+ const lookup = key || (pathSlug ? decodeURIComponent(pathSlug) : undefined);
183
+ if (!lookup) return undefined;
184
+ try {
185
+ const { entry } = await getEmDashEntry("posts", lookup);
186
+ if (!entry) return undefined;
187
+ return themePostFromEntry(entry) ?? undefined;
188
+ } catch {
189
+ return undefined;
190
+ }
191
+ }
192
+
193
+ async function loadArchivePosts(ctx: ThemeRequestContext): Promise<{
194
+ posts: ThemePostFields[];
195
+ archiveTitle?: string;
196
+ }> {
197
+ if (ctx.kind !== "archive" || ctx.isSearch) return { posts: [] };
198
+ try {
199
+ const filter: {
200
+ orderBy: { published_at: "desc" };
201
+ limit: number;
202
+ where?: Record<string, string>;
203
+ } = {
204
+ orderBy: { published_at: "desc" },
205
+ limit: 20,
206
+ };
207
+ if (ctx.taxonomy?.type === "category") {
208
+ filter.where = { category: ctx.taxonomy.slug };
209
+ } else if (ctx.taxonomy?.type === "tag") {
210
+ filter.where = { tag: ctx.taxonomy.slug };
211
+ }
212
+ const result = await getEmDashCollection("posts", filter);
213
+ if (result.error || !result.entries) return { posts: [] };
214
+ const posts = result.entries
215
+ .map((entry) => themePostFromEntry(entry))
216
+ .filter((p): p is ThemePostFields => p !== null);
217
+ const archiveTitle = ctx.taxonomy?.slug
218
+ ? ctx.taxonomy.slug
219
+ : ctx.collection === "posts"
220
+ ? "Posts"
221
+ : undefined;
222
+ return { posts, archiveTitle };
223
+ } catch {
224
+ return { posts: [] };
225
+ }
226
+ }
227
+
228
+ async function buildDynamicForContent(
229
+ partType: ThemePartType,
230
+ ctx: ThemeRequestContext,
231
+ layout: Layout,
232
+ parts: StoredPart[],
233
+ ): Promise<ThemeDynamicData | undefined> {
234
+ const loopTemplates = await loadLoopTemplates(layout, parts);
235
+ const sectionTemplates = loadSectionTemplates(layout, parts);
236
+ const referenced: ThemeDynamicData = {
237
+ ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
238
+ ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
239
+ };
240
+ if (partType === "single_post") {
241
+ const post = await loadSingularPost(ctx);
242
+ if (!post && Object.keys(referenced).length === 0) return undefined;
243
+ return { ...referenced, post };
244
+ }
245
+ if (partType === "archive") {
246
+ const { posts, archiveTitle } = await loadArchivePosts(ctx);
247
+ return { ...referenced, posts, archiveTitle };
248
+ }
249
+ if (Object.keys(referenced).length > 0) return referenced;
250
+ return undefined;
251
+ }
252
+
253
+ /**
254
+ * Resolve winning published theme parts for this request (R-062 / S7b–S7d).
255
+ * Returns plain HTML/CSS; popup JS is optional and only when `needsPopupsRuntime`.
256
+ * Single Post / Archive winners substitute post fields server-side.
257
+ */
258
+ export async function resolveThemeParts(
259
+ astro: AstroLike,
260
+ ctx?: ThemeRequestContext,
261
+ ): Promise<ResolvedThemeParts> {
262
+ const context =
263
+ ctx ??
264
+ themeContextFrom(astro.url, {
265
+ content:
266
+ (astro.props?.["content"] as
267
+ | { collection: string; id: string; slug?: string | null }
268
+ | undefined) ?? null,
269
+ });
270
+
271
+ const empty: ResolvedThemeParts = {
272
+ header: null,
273
+ footer: null,
274
+ content: null,
275
+ popups: [],
276
+ css: "",
277
+ needsPopupsRuntime: false,
278
+ needsTabsRuntime: false,
279
+ };
280
+
281
+ const parts = await loadPublishedThemeParts();
282
+ if (parts.length === 0) return empty;
283
+
284
+ const candidates: ThemePartCandidate[] = parts.map((part) => ({
285
+ id: part.id,
286
+ partType: part.partType,
287
+ conditions: part.conditions,
288
+ updatedAt: part.updatedAt,
289
+ }));
290
+
291
+ const headerWinner = pickThemePartWinner(candidates, "header", context);
292
+ const footerWinner = pickThemePartWinner(candidates, "footer", context);
293
+ const contentType = contentPartTypeForContext(context);
294
+ const contentWinner = contentType ? pickThemePartWinner(candidates, contentType, context) : null;
295
+ const popupMatches = listMatchingThemeParts(candidates, "popup", context);
296
+
297
+ if (!headerWinner && !footerWinner && !contentWinner && popupMatches.length === 0) {
298
+ return empty;
299
+ }
300
+
301
+ const handler = getPublicPluginApiRouteHandler(astro.locals as never);
302
+ const design = await loadDesign(handler, astro.url);
303
+
304
+ const byId = new Map(parts.map((part) => [part.id, part]));
305
+ const rendered: RenderedPage[] = [];
306
+ const renderOne = (stored: StoredPart, dynamic?: ThemeDynamicData) => {
307
+ const page = renderStored(stored.layout, design, stored.id, undefined, dynamic);
308
+ rendered.push(page);
309
+ const html = page.html
310
+ ? `<div class="emvb-theme-${stored.partType}" data-emvb-theme-part="${stored.id}">${page.html}</div>`
311
+ : "";
312
+ return { html, css: page.css };
313
+ };
314
+
315
+ const renderPart = async (
316
+ winner: ThemePartCandidate | null,
317
+ ): Promise<RenderedThemePart | null> => {
318
+ const stored = winner ? byId.get(winner.id) : undefined;
319
+ if (!stored) return null;
320
+ const layout = readLayout(stored.layout);
321
+ const sectionTemplates = layout ? loadSectionTemplates(layout, parts) : {};
322
+ const loopTemplates = layout ? await loadLoopTemplates(layout, parts) : {};
323
+ const referenced: ThemeDynamicData | undefined =
324
+ Object.keys(sectionTemplates).length > 0 || Object.keys(loopTemplates).length > 0
325
+ ? {
326
+ ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
327
+ ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
328
+ }
329
+ : undefined;
330
+ const dynamic =
331
+ layout && winner === contentWinner
332
+ ? {
333
+ ...referenced,
334
+ ...(await buildDynamicForContent(stored.partType, context, layout, parts)),
335
+ }
336
+ : referenced;
337
+ const { html, css } = renderOne(stored, dynamic);
338
+ return { id: stored.id, title: stored.title, partType: stored.partType, html, css };
339
+ };
340
+
341
+ const header = await renderPart(headerWinner);
342
+ const footer = await renderPart(footerWinner);
343
+ const content = await renderPart(contentWinner);
344
+
345
+ const popups: RenderedPopup[] = [];
346
+ for (const match of popupMatches) {
347
+ const stored = byId.get(match.id);
348
+ if (!stored) continue;
349
+ const { html, css } = renderOne(stored);
350
+ popups.push({
351
+ id: stored.id,
352
+ title: stored.title,
353
+ html: wrapPopupMarkup(stored.id, html, stored.triggers),
354
+ css,
355
+ triggers: stored.triggers,
356
+ });
357
+ }
358
+
359
+ const cssParts = [header?.css, content?.css, footer?.css, ...popups.map((p) => p.css)];
360
+ if (popups.length > 0) cssParts.push(POPUP_CHROME_CSS);
361
+ const css = cssParts.filter(Boolean).join("\n");
362
+ return {
363
+ header,
364
+ footer,
365
+ content,
366
+ popups,
367
+ css,
368
+ needsPopupsRuntime: popups.length > 0,
369
+ needsTabsRuntime: rendered.some((page) => page.needsTabsRuntime),
370
+ };
371
+ }
@@ -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";
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Optional public Tabs keyboard / ARIA runtime (W-078).
3
+ * Hosts load this only when `needsTabsRuntime` is true (R-031).
4
+ * CSS radio + :has() remains the no-JS fallback.
5
+ */
6
+
7
+ /** The group's own radios, tab labels and panels; nested groups are left out. */
8
+ function parts(root: HTMLElement) {
9
+ const all = <T extends HTMLElement>(selector: string) => [
10
+ ...root.querySelectorAll<T>(`:scope > ${selector}`),
11
+ ];
12
+ return {
13
+ inputs: all<HTMLInputElement>(".emvb-tab-input"),
14
+ labels: all(".emvb-tab-list > .emvb-tab-label"),
15
+ panels: all(".emvb-tab-panels > .emvb-tab-panel"),
16
+ };
17
+ }
18
+
19
+ /** Where each navigation key moves from tab `current` of `count`. */
20
+ const KEY_TARGETS: Record<string, (current: number, count: number) => number> = {
21
+ ArrowRight: (current) => current + 1,
22
+ ArrowLeft: (current) => current - 1,
23
+ Home: () => 0,
24
+ End: (_current, count) => count - 1,
25
+ };
26
+
27
+ /** Selects tab `index`; only keyboard navigation moves focus, never load or a radio change. */
28
+ function activate(root: HTMLElement, index: number, focus = false): void {
29
+ if (root.dataset["emvbTabsActivating"] === "1") return;
30
+ root.dataset["emvbTabsActivating"] = "1";
31
+ try {
32
+ const { inputs, labels, panels } = parts(root);
33
+ if (inputs.length === 0 || labels.length === 0) return;
34
+ const next = ((index % inputs.length) + inputs.length) % inputs.length;
35
+ const input = inputs[next];
36
+ if (!input) return;
37
+ if (!input.checked) input.checked = true;
38
+ for (const [i, label] of labels.entries()) {
39
+ const selected = i === next;
40
+ label.setAttribute("aria-selected", String(selected));
41
+ label.tabIndex = selected ? 0 : -1;
42
+ panels[i]?.setAttribute("aria-hidden", String(!selected));
43
+ }
44
+ const focusTarget = focus ? labels[next] : undefined;
45
+ if (focusTarget && document.activeElement !== focusTarget) {
46
+ try {
47
+ focusTarget.focus({ preventScroll: true });
48
+ } catch {
49
+ // focus may fail in non-interactive test hosts
50
+ }
51
+ }
52
+ } finally {
53
+ delete root.dataset["emvbTabsActivating"];
54
+ }
55
+ }
56
+
57
+ function selectedIndex(root: HTMLElement): number {
58
+ const checked = parts(root).inputs.findIndex((el) => el.checked);
59
+ return checked >= 0 ? checked : 0;
60
+ }
61
+
62
+ /** Points each tab at its panel and back, giving either an id when it has none. */
63
+ function linkTabs(root: HTMLElement, labels: HTMLElement[], panels: HTMLElement[]): void {
64
+ const prefix = root.id || "emvb-tabs";
65
+ for (const [i, label] of labels.entries()) {
66
+ const panel = panels[i];
67
+ const panelId = panel?.id || `${prefix}-panel-${i}`;
68
+ if (panel && !panel.id) panel.id = panelId;
69
+ label.setAttribute("aria-controls", panelId);
70
+ if (panel) {
71
+ if (!label.id) label.id = `${prefix}-tab-${i}`;
72
+ panel.setAttribute("aria-labelledby", label.id);
73
+ }
74
+ }
75
+ }
76
+
77
+ function enhance(root: HTMLElement): void {
78
+ if (root.dataset["emvbTabsReady"] === "1") return;
79
+ root.dataset["emvbTabsReady"] = "1";
80
+ const list = root.querySelector<HTMLElement>(":scope > .emvb-tab-list");
81
+ if (!list) return;
82
+ list.setAttribute("aria-orientation", "horizontal");
83
+ const { labels, panels } = parts(root);
84
+ linkTabs(root, labels, panels);
85
+ activate(root, selectedIndex(root));
86
+
87
+ list.addEventListener("keydown", (event) => {
88
+ const target = KEY_TARGETS[event.key];
89
+ if (!target) return;
90
+ event.preventDefault();
91
+ if (labels.length === 0) return;
92
+ activate(root, target(selectedIndex(root), labels.length), true);
93
+ });
94
+
95
+ // Keep ARIA in sync when the CSS-only radio path is used (click / label).
96
+ root.addEventListener("change", (event) => {
97
+ const target = event.target as HTMLInputElement | null;
98
+ if (!target || !target.classList.contains("emvb-tab-input")) return;
99
+ activate(root, selectedIndex(root));
100
+ });
101
+ }
102
+
103
+ export function initTabs(root: ParentNode = document): void {
104
+ const nodes = root.querySelectorAll<HTMLElement>(".emvb-tabs");
105
+ for (const node of nodes) enhance(node);
106
+ }
107
+
108
+ /** Test helper: select tab by index after enhance. */
109
+ export function selectTabForTest(root: HTMLElement, index: number): void {
110
+ activate(root, index);
111
+ }
@@ -0,0 +1,81 @@
1
+ import type { ThemeRequestContext } from "../core/index.ts";
2
+
3
+ type ContentRef = { collection: string; id: string; slug?: string | null };
4
+ type Kind = Pick<ThemeRequestContext, "kind">;
5
+
6
+ /** A context for `path` that is not the front page, a 404 or a search, plus `rest`. */
7
+ const context = (path: string, rest: Kind & Partial<ThemeRequestContext>): ThemeRequestContext => ({
8
+ path,
9
+ isFront: false,
10
+ is404: false,
11
+ isSearch: false,
12
+ ...rest,
13
+ });
14
+
15
+ /** Archive URLs by pattern, and what each adds to the context. */
16
+ const ARCHIVES: [RegExp, (match: RegExpExecArray) => Partial<ThemeRequestContext>][] = [
17
+ [
18
+ /^\/category\/([^/]+)$/,
19
+ ([, slug]) => ({ taxonomy: { type: "category", slug: decodeURIComponent(slug ?? "") } }),
20
+ ],
21
+ [
22
+ /^\/tag\/([^/]+)$/,
23
+ ([, slug]) => ({ taxonomy: { type: "tag", slug: decodeURIComponent(slug ?? "") } }),
24
+ ],
25
+ [/^\/posts$/, () => ({ collection: "posts" })],
26
+ ];
27
+
28
+ /**
29
+ * Build a ThemeRequestContext from the request URL and optional host content hint.
30
+ * Hosts can override by passing a fully built context to `resolveThemeParts`.
31
+ */
32
+ export function themeContextFrom(
33
+ url: URL,
34
+ options: {
35
+ content?: ContentRef | null;
36
+ is404?: boolean;
37
+ isFront?: boolean;
38
+ isSearch?: boolean;
39
+ } = {},
40
+ ): ThemeRequestContext {
41
+ const path = url.pathname.replace(/\/+$/, "") || "/";
42
+ const { content } = options;
43
+ if (options.is404 === true) return themeContext404(path);
44
+ if (options.isFront === true || (!content && path === "/")) {
45
+ return context("/", {
46
+ isFront: true,
47
+ kind: "singular",
48
+ collection: content?.collection,
49
+ entryId: content?.id,
50
+ });
51
+ }
52
+ if (options.isSearch === true || path === "/search") return themeContextSearch(path);
53
+ for (const [pattern, extra] of ARCHIVES) {
54
+ const match = pattern.exec(path);
55
+ if (match) return context(path, { kind: "archive", ...extra(match) });
56
+ }
57
+ if (content) {
58
+ return context(path, { kind: "singular", collection: content.collection, entryId: content.id });
59
+ }
60
+ // EmVB / pages singular under /{slug} without an explicit content hint
61
+ if (path !== "/" && !path.includes("/", 1)) {
62
+ return context(path, { kind: "singular", collection: "pages" });
63
+ }
64
+ return context(path, { kind: "other" });
65
+ }
66
+
67
+ export function themeContextFront(): ThemeRequestContext {
68
+ return context("/", { isFront: true, kind: "singular" });
69
+ }
70
+
71
+ export function themeContext404(path = "/404"): ThemeRequestContext {
72
+ return context(path, { is404: true, kind: "other" });
73
+ }
74
+
75
+ export function themeContextFromContent(content: ContentRef, path: string): ThemeRequestContext {
76
+ return themeContextFrom(new URL(path, "http://local.invalid"), { content });
77
+ }
78
+
79
+ export function themeContextSearch(path = "/search"): ThemeRequestContext {
80
+ return context(path, { isSearch: true, kind: "archive" });
81
+ }