@perkyzz/emvb 0.8.0 → 1.0.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 (179) hide show
  1. package/README.md +3 -3
  2. package/package.json +4 -4
  3. package/src/admin/agents-api.ts +45 -0
  4. package/src/admin/editor/A11yCopilot.tsx +1 -1
  5. package/src/admin/editor/Editor.tsx +325 -239
  6. package/src/admin/editor/FieldPreview.tsx +164 -0
  7. package/src/admin/editor/Timeline.tsx +2 -1
  8. package/src/admin/editor/TopBar.tsx +36 -3
  9. package/src/admin/editor/canvas/CanvasFrame.tsx +2 -2
  10. package/src/admin/editor/canvas/DeviceBar.tsx +17 -9
  11. package/src/admin/editor/canvas/canvas-scale.ts +2 -2
  12. package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
  13. package/src/admin/editor/co-design.ts +190 -0
  14. package/src/admin/editor/dnd/new-element.ts +26 -4
  15. package/src/admin/editor/editor-chrome.tsx +3 -3
  16. package/src/admin/editor/editor-commands.ts +8 -3
  17. package/src/admin/editor/editor-css.ts +3 -0
  18. package/src/admin/editor/element-chrome.ts +3 -1
  19. package/src/admin/editor/extension-manifests.ts +20 -0
  20. package/src/admin/editor/extensions/ExtensionPanels.tsx +26 -0
  21. package/src/admin/editor/extensions-context.tsx +27 -0
  22. package/src/admin/editor/feature-css.ts +17 -0
  23. package/src/admin/editor/host.ts +6 -0
  24. package/src/admin/editor/palette-items.ts +2 -2
  25. package/src/admin/editor/panels/AddPanel.tsx +31 -1
  26. package/src/admin/editor/panels/AgentRequestBox.tsx +116 -0
  27. package/src/admin/editor/panels/ClassesSection.tsx +9 -6
  28. package/src/admin/editor/panels/CoDesignPanel.tsx +170 -0
  29. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  30. package/src/admin/editor/panels/ElementPanel.tsx +53 -15
  31. package/src/admin/editor/panels/LanguagesSection.tsx +152 -0
  32. package/src/admin/editor/panels/LayersPanel.tsx +10 -6
  33. package/src/admin/editor/panels/LeftPanel.tsx +33 -5
  34. package/src/admin/editor/panels/PageSettings.tsx +4 -0
  35. package/src/admin/editor/panels/SettingsPanel.tsx +21 -2
  36. package/src/admin/editor/panels/SiteStylesDrawer.tsx +7 -7
  37. package/src/admin/editor/panels/settings/BackgroundControls.tsx +76 -20
  38. package/src/admin/editor/panels/settings/BackgroundFill.tsx +8 -6
  39. package/src/admin/editor/panels/settings/BoxControl.tsx +5 -5
  40. package/src/admin/editor/panels/settings/EffectsControls.tsx +104 -9
  41. package/src/admin/editor/panels/settings/FieldControl.tsx +9 -3
  42. package/src/admin/editor/panels/settings/IconControls.tsx +14 -11
  43. package/src/admin/editor/panels/settings/LengthRow.tsx +27 -16
  44. package/src/admin/editor/panels/settings/LoopControl.tsx +269 -0
  45. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
  46. package/src/admin/editor/panels/settings/MediaPicker.tsx +5 -5
  47. package/src/admin/editor/panels/settings/MotionControl.tsx +12 -11
  48. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +7 -4
  49. package/src/admin/editor/panels/settings/StyleRow.tsx +113 -13
  50. package/src/admin/editor/panels/settings/TextMarksControl.tsx +247 -0
  51. package/src/admin/editor/panels/settings/VariableBinding.tsx +2 -2
  52. package/src/admin/editor/panels/settings/background-mode.ts +14 -11
  53. package/src/admin/editor/panels/settings/box-link-name.ts +1 -1
  54. package/src/admin/editor/panels/settings/box-sides.ts +22 -14
  55. package/src/admin/editor/panels/settings/heading-warning.ts +5 -1
  56. package/src/admin/editor/panels/settings/length-units.ts +55 -2
  57. package/src/admin/editor/panels/settings/query-style.ts +3 -3
  58. package/src/admin/editor/panels/settings/style-sections.ts +51 -10
  59. package/src/admin/editor/panels/style-target.ts +9 -7
  60. package/src/admin/editor/presence.ts +60 -0
  61. package/src/admin/editor/store.ts +6 -2
  62. package/src/admin/editor/useCoDesign.ts +177 -0
  63. package/src/admin/editor/useEditorCommands.ts +4 -4
  64. package/src/admin/editor/useExtensions.ts +45 -0
  65. package/src/admin/editor/useNodeActions.ts +15 -6
  66. package/src/admin/editor/useProposals.ts +81 -0
  67. package/src/admin/index.tsx +5 -1
  68. package/src/admin/languages-api.ts +61 -0
  69. package/src/admin/media-api.ts +27 -0
  70. package/src/admin/pages/AgentSetup.tsx +148 -0
  71. package/src/admin/pages/AgentsPage.tsx +11 -28
  72. package/src/admin/pages/CollectionsPage.tsx +215 -0
  73. package/src/admin/pages/CreateDialog.tsx +15 -0
  74. package/src/admin/pages/ImportButton.tsx +18 -0
  75. package/src/admin/pages/ImportElementorDialog.tsx +669 -0
  76. package/src/admin/pages/ImportPageLinks.tsx +86 -0
  77. package/src/admin/pages/PageList.tsx +15 -1
  78. package/src/admin/pages/ThemePartList.tsx +15 -1
  79. package/src/admin/pages/section-head.tsx +27 -0
  80. package/src/admin/proposals-api.ts +91 -0
  81. package/src/admin/setup/host-collections.ts +100 -0
  82. package/src/admin/ui.ts +39 -2
  83. package/src/admin/widgets/CanvasField.tsx +202 -0
  84. package/src/admin/widgets/convert-body.ts +54 -0
  85. package/src/admin/widgets/field-fetcher.ts +79 -0
  86. package/src/astro/content-port.ts +14 -1
  87. package/src/astro/index.ts +2 -0
  88. package/src/astro/page-count.ts +77 -0
  89. package/src/astro/resolve-theme.ts +58 -3
  90. package/src/astro/resolve.ts +128 -5
  91. package/src/astro/responsive-images.ts +99 -0
  92. package/src/constants.ts +1 -1
  93. package/src/core/a11y/audit.ts +44 -14
  94. package/src/core/arrange.ts +5 -1
  95. package/src/core/bounded-array.ts +31 -0
  96. package/src/core/canvas-collections.ts +20 -0
  97. package/src/core/clipboard.ts +9 -0
  98. package/src/core/contract.ts +285 -0
  99. package/src/core/css/generate.ts +89 -20
  100. package/src/core/css/trace.ts +18 -9
  101. package/src/core/css-keywords.ts +51 -1
  102. package/src/core/design/cascade.ts +12 -9
  103. package/src/core/design/classes.ts +4 -5
  104. package/src/core/design/devices.ts +13 -13
  105. package/src/core/design/states.ts +5 -3
  106. package/src/core/design/transfer.ts +5 -0
  107. package/src/core/design/variables.ts +17 -4
  108. package/src/core/elements/dynamic-elements.ts +19 -4
  109. package/src/core/elements/index.ts +73 -9
  110. package/src/core/extensions/define.ts +13 -0
  111. package/src/core/extensions/index.ts +41 -0
  112. package/src/core/extensions/namespace.ts +82 -0
  113. package/src/core/extensions/normalize.ts +141 -0
  114. package/src/core/extensions/placeholder.ts +41 -0
  115. package/src/core/extensions/registry.ts +94 -0
  116. package/src/core/extensions/render-ext.ts +118 -0
  117. package/src/core/extensions/safe-nodes.ts +93 -0
  118. package/src/core/extensions/schema.ts +112 -0
  119. package/src/core/extensions/types.ts +159 -0
  120. package/src/core/forms/binding.ts +1 -1
  121. package/src/core/history/diff.ts +1 -1
  122. package/src/core/import/elementor/atomic.ts +1595 -0
  123. package/src/core/import/elementor/classes.ts +127 -0
  124. package/src/core/import/elementor/context.ts +429 -0
  125. package/src/core/import/elementor/counter-steps.ts +72 -0
  126. package/src/core/import/elementor/css.ts +445 -0
  127. package/src/core/import/elementor/html.ts +500 -0
  128. package/src/core/import/elementor/index.ts +949 -0
  129. package/src/core/import/elementor/inline-marks.ts +81 -0
  130. package/src/core/import/elementor/snapshots.ts +48 -0
  131. package/src/core/import/elementor/style.ts +409 -0
  132. package/src/core/import/elementor/values.ts +241 -0
  133. package/src/core/import/elementor/widgets.ts +1897 -0
  134. package/src/core/index.ts +84 -0
  135. package/src/core/json-schema.ts +107 -0
  136. package/src/core/limits.ts +19 -0
  137. package/src/core/migrate/index.ts +6 -1
  138. package/src/core/migrate/v18.ts +222 -0
  139. package/src/core/perf/meter.ts +5 -5
  140. package/src/core/portable-text.ts +127 -0
  141. package/src/core/proposals-safety.ts +102 -0
  142. package/src/core/proposals.ts +357 -0
  143. package/src/core/recipes/index.ts +2 -2
  144. package/src/core/render/extras.ts +3 -3
  145. package/src/core/render/index.ts +140 -20
  146. package/src/core/render/loop.ts +1 -1
  147. package/src/core/render/pagination.ts +20 -1
  148. package/src/core/render/section.ts +4 -4
  149. package/src/core/render/vnode.ts +1 -1
  150. package/src/core/sanitize/css.ts +125 -10
  151. package/src/core/sanitize/motion.ts +116 -0
  152. package/src/core/saved-sections.ts +6 -0
  153. package/src/core/schema/descriptors.ts +3 -1
  154. package/src/core/schema/design.ts +2 -1
  155. package/src/core/schema/layout.ts +87 -14
  156. package/src/core/schema/style.ts +251 -114
  157. package/src/core/text-marks.ts +227 -0
  158. package/src/core/theme/dynamic.ts +9 -4
  159. package/src/core/theme/float.ts +1 -0
  160. package/src/core/theme/pagination.ts +9 -0
  161. package/src/core/theme/popup-rules.ts +17 -1
  162. package/src/core/translatable.ts +34 -0
  163. package/src/core/validate.ts +13 -1
  164. package/src/index.ts +35 -1
  165. package/src/mcp/errors.ts +3 -1
  166. package/src/mcp/ports.ts +67 -0
  167. package/src/mcp/prompts.ts +1 -11
  168. package/src/mcp/proposals.ts +281 -0
  169. package/src/mcp/read.ts +10 -9
  170. package/src/mcp/tools.ts +71 -3
  171. package/src/mcp/write.ts +66 -11
  172. package/src/server/agent-settings.ts +21 -2
  173. package/src/server/hooks.ts +81 -0
  174. package/src/server/mcp-routes.ts +15 -0
  175. package/src/server/plugin.ts +53 -5
  176. package/src/server/presence.ts +78 -0
  177. package/src/server/proposals.ts +261 -0
  178. package/src/server/requests.ts +196 -0
  179. package/src/server/tools-served.ts +45 -0
@@ -0,0 +1,54 @@
1
+ import { portableTextToLayout, type Layout } from "../../core/index.ts";
2
+ import { requestJson, type Fetcher } from "../api.ts";
3
+ import { readCollection } from "../setup/run.ts";
4
+
5
+ const SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
6
+
7
+ /** The host entry the field sits on, from the admin URL `/content/<collection>/<id>`. */
8
+ export function hostEntryFromLocation(
9
+ pathname: string,
10
+ ): { collection: string; id: string } | undefined {
11
+ const match = /\/content\/([^/?#]+)\/([^/?#]+)/.exec(pathname);
12
+ if (!match) return undefined;
13
+ const collection = decodeURIComponent(match[1] ?? "");
14
+ const id = decodeURIComponent(match[2] ?? "");
15
+ if (!SLUG.test(collection) || id === "new") return undefined;
16
+ return { collection, id };
17
+ }
18
+
19
+ export type ConvertResult =
20
+ | { ok: true; layout: Layout; converted: number; skipped: number; field: string }
21
+ | { ok: false; message: string };
22
+
23
+ /**
24
+ * W-912: reads the entry's saved rich-text body (the first Portable Text field, `content` first)
25
+ * and builds a starter layout from it, headed by the entry's title. Read-only: the body is never written.
26
+ */
27
+ export async function convertEntryBody(
28
+ fetcher: Fetcher,
29
+ entry: { collection: string; id: string },
30
+ ): Promise<ConvertResult> {
31
+ const schema = await readCollection(fetcher, entry.collection);
32
+ const rich = (schema?.fields ?? []).filter((f) => f.type === "portableText");
33
+ const field = rich.find((f) => f.slug === "content") ?? rich[0];
34
+ if (!field) return { ok: false, message: "This collection has no rich-text field to convert." };
35
+ const data = await requestJson<{ item: { data?: Record<string, unknown> } }>(
36
+ fetcher,
37
+ `/_emdash/api/content/${encodeURIComponent(entry.collection)}/${encodeURIComponent(entry.id)}`,
38
+ );
39
+ let body = data.item.data?.[field.slug];
40
+ if (typeof body === "string") {
41
+ try {
42
+ body = JSON.parse(body) as unknown;
43
+ } catch {
44
+ body = null;
45
+ }
46
+ }
47
+ if (!Array.isArray(body) || body.length === 0)
48
+ return { ok: false, message: `The saved ${field.slug} field is empty.` };
49
+ const title = data.item.data?.["title"];
50
+ const result = portableTextToLayout(body, typeof title === "string" ? title : "");
51
+ if (!result || result.converted === 0)
52
+ return { ok: false, message: "Nothing in the saved body could be converted." };
53
+ return { ok: true, ...result, field: field.slug };
54
+ }
@@ -0,0 +1,79 @@
1
+ import { PAGES_COLLECTION } from "../../constants.ts";
2
+ import { validateLayout, type Layout } from "../../core/index.ts";
3
+ import type { Fetcher } from "../api.ts";
4
+
5
+ /** The id the editor loads in field mode; it never exists on the server. */
6
+ export const FIELD_ENTRY_ID = "emvb-field";
7
+
8
+ const ENTRY_PATH = `/_emdash/api/content/${PAGES_COLLECTION}/${FIELD_ENTRY_ID}`;
9
+
10
+ const json = (status: number, body: unknown) =>
11
+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
12
+
13
+ /** A stored field value (object or JSON string) as a layout, or null when unreadable. */
14
+ export function readFieldLayout(value: unknown): Layout | null {
15
+ let parsed = value;
16
+ if (typeof value === "string") {
17
+ if (value.trim() === "") return null;
18
+ try {
19
+ parsed = JSON.parse(value) as unknown;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ if (parsed === null || parsed === undefined) return null;
25
+ const result = validateLayout(parsed);
26
+ return result.ok ? result.layout : null;
27
+ }
28
+
29
+ /**
30
+ * Field mode (W-900): the editor talks to a virtual draft entry held in memory, so Save draft
31
+ * stages the layout here instead of writing an EmVB page. Design, media and plugin routes go to
32
+ * the real server. `saved()` is the last staged layout, or undefined when nothing was saved.
33
+ */
34
+ export function createFieldFetcher(
35
+ base: Fetcher,
36
+ initial: { title: string; layout: Layout | null },
37
+ ): { fetcher: Fetcher; saved: () => Layout | null | undefined } {
38
+ let layout = initial.layout;
39
+ let staged: Layout | null | undefined;
40
+ let rev = 1;
41
+ const fetcher: Fetcher = async (path, init) => {
42
+ if (path !== ENTRY_PATH && !path.startsWith(`${ENTRY_PATH}/`)) return base(path, init);
43
+ const method = (init?.method ?? "GET").toUpperCase();
44
+ if (path === ENTRY_PATH && method === "GET") {
45
+ return json(200, {
46
+ data: {
47
+ item: {
48
+ id: FIELD_ENTRY_ID,
49
+ slug: "",
50
+ status: "draft",
51
+ draftRevisionId: null,
52
+ data: { title: initial.title, layout, canvas_mode: "site-layout" },
53
+ },
54
+ _rev: String(rev),
55
+ },
56
+ });
57
+ }
58
+ if (path === ENTRY_PATH && method === "PUT") {
59
+ const body = JSON.parse(typeof init?.body === "string" ? init.body : "{}") as {
60
+ data?: { layout?: unknown };
61
+ };
62
+ if (body.data && "layout" in body.data) {
63
+ // Every layout string is untrusted, including the editor's own.
64
+ const result = validateLayout(body.data.layout);
65
+ if (!result.ok) {
66
+ return json(400, { error: { code: "INVALID_LAYOUT", message: "Invalid layout." } });
67
+ }
68
+ layout = result.layout;
69
+ staged = layout;
70
+ }
71
+ rev += 1;
72
+ return json(200, { data: { _rev: String(rev) } });
73
+ }
74
+ return json(400, {
75
+ error: { code: "FIELD_MODE", message: "This isn't available while editing a field." },
76
+ });
77
+ };
78
+ return { fetcher, saved: () => staged };
79
+ }
@@ -1,4 +1,12 @@
1
- import { decodeSlug, getEmDashCollection, getEmDashEntry, getSiteSettings, getTerm } from "emdash";
1
+ import {
2
+ decodeSlug,
3
+ getEmDashCollection,
4
+ getEmDashEntry,
5
+ getI18nConfig,
6
+ getSiteSettings,
7
+ getTerm,
8
+ getTranslations,
9
+ } from "emdash";
2
10
  import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
3
11
 
4
12
  /**
@@ -12,6 +20,9 @@ export type ContentPort = {
12
20
  getTerm: typeof getTerm;
13
21
  getSiteSettings: typeof getSiteSettings;
14
22
  pluginHandler: typeof getPublicPluginApiRouteHandler;
23
+ /** W-937: an entry's languages, for the Language switcher. Optional for older fakes. */
24
+ getTranslations?: typeof getTranslations;
25
+ getI18nConfig?: typeof getI18nConfig;
15
26
  };
16
27
 
17
28
  export const emdashContent: ContentPort = {
@@ -21,4 +32,6 @@ export const emdashContent: ContentPort = {
21
32
  getTerm,
22
33
  getSiteSettings,
23
34
  pluginHandler: getPublicPluginApiRouteHandler,
35
+ getTranslations,
36
+ getI18nConfig,
24
37
  };
@@ -1,6 +1,8 @@
1
1
  export { default as EmVBPage } from "./EmVBPage.astro";
2
2
  export { resolveEmVBPage, type ResolvedEmVBPage } from "./resolve.ts";
3
3
  export type { HostVisitor } from "./visitor.ts";
4
+ export type { ResponsiveGetImage } from "./responsive-images.ts";
5
+ export type { PostCounter } from "./page-count.ts";
4
6
  export {
5
7
  resolveThemeParts,
6
8
  type RenderedThemePart,
@@ -0,0 +1,77 @@
1
+ import { MAX_ARCHIVE_PAGE } from "../core/index.ts";
2
+ import type { ContentPort } from "./content-port.ts";
3
+
4
+ /**
5
+ * W-916: how many published entries an archive has. EmDash 1.4's public query reports only
6
+ * `hasMore`, so EmVB's own counter probes; a host can pass its own (a future EmDash count API).
7
+ * `atLeast` is a count the caller already knows exists. Undefined = unknown, shown as "Page N".
8
+ */
9
+ export type PostCounter = (query: {
10
+ collection: string;
11
+ where?: Record<string, string>;
12
+ atLeast: number;
13
+ }) => Promise<number | undefined>;
14
+
15
+ /** Loops allow 50 per page, so no archive EmVB pages through holds more. */
16
+ const MAX_ENTRIES = MAX_ARCHIVE_PAGE * 50;
17
+ /** Doubling then halving over 5M entries takes about 46 one-row queries; past that, give up. */
18
+ const MAX_PROBES = 64;
19
+
20
+ /**
21
+ * Counts with one-row queries through the same public collection query the archive uses (same
22
+ * filter, published entries only): doubling past `atLeast` until a row is missing, then
23
+ * halving. Read-only, about 2·log2(n) small queries, only on sites that opt in.
24
+ */
25
+ export function probeCounter(content: ContentPort): PostCounter {
26
+ return async ({ collection, where, atLeast }) => {
27
+ let probes = 0;
28
+ const exists = async (index: number): Promise<boolean> => {
29
+ probes += 1;
30
+ if (probes > MAX_PROBES) throw new Error("too many probes");
31
+ const result = await content.getCollection(
32
+ collection as never,
33
+ {
34
+ orderBy: { published_at: "desc" },
35
+ limit: 1,
36
+ offset: index,
37
+ ...(where ? { where } : {}),
38
+ } as never,
39
+ );
40
+ if (result.error) throw result.error;
41
+ return (result.entries?.length ?? 0) > 0;
42
+ };
43
+ try {
44
+ // `lo` is an index known to exist (or -1); `hi` one known not to.
45
+ let lo = Math.max(0, atLeast) - 1;
46
+ let step = Math.max(1, atLeast);
47
+ let hi = lo + step;
48
+ // oxlint-disable-next-line no-await-in-loop -- each probe depends on the last.
49
+ while (hi < MAX_ENTRIES && (await exists(hi))) {
50
+ lo = hi;
51
+ step *= 2;
52
+ hi = lo + step;
53
+ }
54
+ if (hi >= MAX_ENTRIES) return undefined;
55
+ while (hi - lo > 1) {
56
+ const mid = Math.floor((lo + hi) / 2);
57
+ // oxlint-disable-next-line no-await-in-loop -- binary search.
58
+ if (await exists(mid)) lo = mid;
59
+ else hi = mid;
60
+ }
61
+ return lo + 1;
62
+ } catch {
63
+ return undefined;
64
+ }
65
+ };
66
+ }
67
+
68
+ /** Pages for `count` entries, or undefined when the count is unknown or below this page. */
69
+ export function totalPagesFor(
70
+ count: number | undefined,
71
+ perPage: number,
72
+ page: number,
73
+ ): number | undefined {
74
+ if (count === undefined || !Number.isInteger(count) || count < 0) return undefined;
75
+ const total = Math.min(Math.max(1, Math.ceil(count / perPage)), MAX_ARCHIVE_PAGE);
76
+ return total >= page ? total : undefined;
77
+ }
@@ -41,6 +41,7 @@ import type { HostVisitor, VisitorAstro } from "./visitor.ts";
41
41
  import { bindingDataFor } from "./request-data.ts";
42
42
  import { decodePathSegment, themeContextFrom } from "./theme-context.ts";
43
43
  import { entryTimestamp, themePostFromEntry } from "./theme-posts.ts";
44
+ import { probeCounter, totalPagesFor, type PostCounter } from "./page-count.ts";
44
45
 
45
46
  /** The landmark element for a part's wrapper (W-216); other parts get a plain div. */
46
47
  const WRAPPER_TAGS: Partial<Record<string, "header" | "footer">> = {
@@ -318,6 +319,7 @@ async function loadArchivePosts(
318
319
  perPage: number,
319
320
  content: ContentPort,
320
321
  postsTitle = "Posts",
322
+ counter?: PostCounter,
321
323
  ): Promise<{
322
324
  posts: ThemePostFields[];
323
325
  archiveTitle?: string;
@@ -354,7 +356,21 @@ async function loadArchivePosts(
354
356
  : ctx.collection === "posts"
355
357
  ? postsTitle
356
358
  : undefined;
357
- return { posts, archiveTitle, pagination: { page, hasMore, basePath: ctx.path } };
359
+ const pagination: ArchivePagination = { page, hasMore, basePath: ctx.path };
360
+ if (counter && (hasMore || result.entries.length > 0)) {
361
+ // W-916: the last page needs no count; later pages are counted past the ones seen.
362
+ const seen = (page - 1) * perPage + result.entries.length;
363
+ const count = hasMore
364
+ ? await counter({
365
+ collection: "posts",
366
+ ...(filter.where ? { where: filter.where } : {}),
367
+ atLeast: seen + 1,
368
+ })
369
+ : seen;
370
+ const totalPages = totalPagesFor(count, perPage, page);
371
+ if (totalPages !== undefined) pagination.totalPages = totalPages;
372
+ }
373
+ return { posts, archiveTitle, pagination };
358
374
  } catch {
359
375
  return { posts: [] };
360
376
  }
@@ -367,6 +383,7 @@ async function buildDynamicForContent(
367
383
  parts: StoredPart[],
368
384
  content: ContentPort,
369
385
  request?: object,
386
+ counter?: PostCounter,
370
387
  ): Promise<ThemeDynamicData | undefined> {
371
388
  const { sectionTemplates, loopTemplates } = await templatesFrom(layout, parts, request);
372
389
  const referenced: ThemeDynamicData = {
@@ -385,6 +402,7 @@ async function buildDynamicForContent(
385
402
  content,
386
403
  // W-532: the Pagination element's "Posts archive title" words it in the site's language.
387
404
  paginationArchiveTitle(layout),
405
+ counter,
388
406
  );
389
407
  return { ...referenced, posts, archiveTitle, ...(pagination ? { pagination } : {}) };
390
408
  }
@@ -407,6 +425,16 @@ export async function resolveThemeParts(
407
425
  lang?: string;
408
426
  /** Popup and float screen reader names in the site's language (W-690). */
409
427
  labels?: ChromeLabels;
428
+ /**
429
+ * W-916: count archive pages for "Page N of M" and the Last link. Off by default; `true`
430
+ * uses EmVB's own one-row probe queries, or pass a counter (e.g. an EmDash count API).
431
+ */
432
+ pageCount?: boolean | PostCounter;
433
+ /**
434
+ * W-937: the page's languages, for a Language switcher in a header or footer. Pass
435
+ * `resolveEmVBPage(...)?.translations` (or your own list of published translations).
436
+ */
437
+ translations?: readonly { locale: string; href: string; current: boolean }[];
410
438
  } = {},
411
439
  ): Promise<ResolvedThemeParts> {
412
440
  return resolveThemePartsWith(emdashContent, astro, ctx, options);
@@ -423,8 +451,24 @@ export async function resolveThemePartsWith(
423
451
  lang?: string;
424
452
  /** Popup and float screen reader names in the site's language (W-690). */
425
453
  labels?: ChromeLabels;
454
+ /**
455
+ * W-916: count archive pages for "Page N of M" and the Last link. Off by default; `true`
456
+ * uses EmVB's own one-row probe queries, or pass a counter (e.g. an EmDash count API).
457
+ */
458
+ pageCount?: boolean | PostCounter;
459
+ /**
460
+ * W-937: the page's languages, for a Language switcher in a header or footer. Pass
461
+ * `resolveEmVBPage(...)?.translations` (or your own list of published translations).
462
+ */
463
+ translations?: readonly { locale: string; href: string; current: boolean }[];
426
464
  } = {},
427
465
  ): Promise<ResolvedThemeParts> {
466
+ const counter =
467
+ typeof options.pageCount === "function"
468
+ ? options.pageCount
469
+ : options.pageCount === true
470
+ ? probeCounter(port)
471
+ : undefined;
428
472
  const context =
429
473
  ctx ??
430
474
  themeContextFrom(astro.url, {
@@ -503,7 +547,10 @@ export async function resolveThemePartsWith(
503
547
  partDynamic: ThemeDynamicData | undefined,
504
548
  bound: Awaited<ReturnType<typeof bindingDataFor>>,
505
549
  ) => {
506
- const dynamic = Object.keys(bound).length > 0 ? { ...partDynamic, ...bound } : partDynamic;
550
+ const withBound = Object.keys(bound).length > 0 ? { ...partDynamic, ...bound } : partDynamic;
551
+ const dynamic = options.translations
552
+ ? { ...withBound, translations: options.translations }
553
+ : withBound;
507
554
  const formDefinitions = await formsFor(
508
555
  astro,
509
556
  handler,
@@ -564,7 +611,15 @@ export async function resolveThemePartsWith(
564
611
  layout && winner === contentWinner
565
612
  ? {
566
613
  ...referenced,
567
- ...(await buildDynamicForContent(stored.partType, context, layout, parts, port, astro)),
614
+ ...(await buildDynamicForContent(
615
+ stored.partType,
616
+ context,
617
+ layout,
618
+ parts,
619
+ port,
620
+ astro,
621
+ counter,
622
+ )),
568
623
  }
569
624
  : referenced;
570
625
  // A page past the last one has no posts; the host answers 404 (W-221).
@@ -1,4 +1,6 @@
1
1
  import { PAGES_COLLECTION } from "../constants.ts";
2
+ import { forEachNode } from "../core/tree-ops.ts";
3
+ import type { Layout, LayoutNode } from "../core/schema/layout.ts";
2
4
  import { emdashContent, type ContentPort } from "./content-port.ts";
3
5
  import { formIdsInLayouts } from "./forms-definitions.ts";
4
6
  import { readLayout, renderStored, type RenderedPage } from "./render.ts";
@@ -6,16 +8,31 @@ import { designFor, formsFor } from "./render-session.ts";
6
8
  import { bindingDataFor } from "./request-data.ts";
7
9
  import type { HostVisitor, VisitorAstro } from "./visitor.ts";
8
10
  import { referencedTemplatesFor } from "./resolve-theme.ts";
11
+ import { withResponsiveSources, type ResponsiveGetImage } from "./responsive-images.ts";
9
12
 
10
13
  type EmDashEntry = NonNullable<Awaited<ReturnType<ContentPort["getEntry"]>>["entry"]>;
11
14
 
12
15
  export type ResolvedEmVBPage = RenderedPage & {
13
16
  /** The EmDash entry, for `getSeoMeta` and the host's layout. */
14
17
  entry: EmDashEntry;
18
+ /** The collection the entry came from: `emvb_pages`, or the host collection (W-901). */
19
+ collection: string;
15
20
  title: string;
16
21
  canvasMode: "site-layout" | "blank";
17
22
  /** A valid `_preview` token is serving the draft: don't cache the response. */
18
23
  isPreview: boolean;
24
+ /** W-935 (D-068): the locale asked for (option or Astro's), when the site has one. */
25
+ locale?: string;
26
+ /**
27
+ * W-935: set when that locale has no translation of the page and EmDash served this one from
28
+ * its fallback chain instead. Hosts can say so, or link to the requested language's home.
29
+ */
30
+ fallbackLocale?: string;
31
+ /**
32
+ * W-937: this page in each published language (the shown one marked current), when the site
33
+ * has languages. Pass it to `resolveThemeParts` for a Language switcher in the header.
34
+ */
35
+ translations?: { locale: string; href: string; current: boolean }[];
19
36
  };
20
37
 
21
38
  type AstroLike = VisitorAstro & {
@@ -40,6 +57,28 @@ export async function resolveEmVBPage(
40
57
  visitor?: HostVisitor;
41
58
  /** The page's language, e.g. "fr-CA", for Post Dates; defaults to Astro's locale (W-688). */
42
59
  lang?: string;
60
+ /**
61
+ * W-901: a host collection listed in `canvasCollections`, read instead of EmVB's own pages.
62
+ * Its entry is an EmVB page only while `field` (an emvb:canvas field) holds a layout.
63
+ */
64
+ collection?: string;
65
+ /** The emvb:canvas field of `collection` (default `"canvas"`). */
66
+ field?: string;
67
+ /**
68
+ * W-915: Astro's `getImage` from `astro:assets`. When passed, library Images get a srcset
69
+ * from the host's image service (authorise the site origin in `image.remotePatterns`).
70
+ */
71
+ getImage?: ResponsiveGetImage;
72
+ /**
73
+ * W-935: which translation to read (EmDash's row-per-locale model, D-068). Defaults to
74
+ * Astro's `currentLocale`; EmDash falls back along its chain when there is none.
75
+ */
76
+ locale?: string;
77
+ /**
78
+ * W-937: where a translation of this page lives, for the Language switcher. Defaults to
79
+ * `/<slug>` for the default locale and `/<locale>/<slug>` for the others.
80
+ */
81
+ translationHref?: (translation: { locale: string; slug: string }) => string;
43
82
  } = {},
44
83
  ): Promise<ResolvedEmVBPage | null> {
45
84
  return resolveEmVBPageWith(emdashContent, astro, options);
@@ -55,13 +94,37 @@ export async function resolveEmVBPageWith(
55
94
  visitor?: HostVisitor;
56
95
  /** The page's language, e.g. "fr-CA", for Post Dates; defaults to Astro's locale (W-688). */
57
96
  lang?: string;
97
+ /**
98
+ * W-901: a host collection listed in `canvasCollections`, read instead of EmVB's own pages.
99
+ * Its entry is an EmVB page only while `field` (an emvb:canvas field) holds a layout.
100
+ */
101
+ collection?: string;
102
+ /** The emvb:canvas field of `collection` (default `"canvas"`). */
103
+ field?: string;
104
+ /**
105
+ * W-915: Astro's `getImage` from `astro:assets`. When passed, library Images get a srcset
106
+ * from the host's image service (authorise the site origin in `image.remotePatterns`).
107
+ */
108
+ getImage?: ResponsiveGetImage;
109
+ /** W-935: which translation to read; defaults to Astro's `currentLocale`. */
110
+ locale?: string;
111
+ /**
112
+ * W-937: where a translation of this page lives, for the Language switcher. Defaults to
113
+ * `/<slug>` for the default locale and `/<locale>/<slug>` for the others.
114
+ */
115
+ translationHref?: (translation: { locale: string; slug: string }) => string;
58
116
  } = {},
59
117
  ): Promise<ResolvedEmVBPage | null> {
60
118
  const slug = options.slug ?? content.decodeSlug(astro.params[options.param ?? "slug"]);
61
119
  if (!slug) return null;
120
+ const locale = options.locale ?? astro.currentLocale;
62
121
  let found: Awaited<ReturnType<ContentPort["getEntry"]>>;
63
122
  try {
64
- found = await content.getEntry(PAGES_COLLECTION, slug);
123
+ found = await content.getEntry(
124
+ options.collection ?? PAGES_COLLECTION,
125
+ slug,
126
+ locale ? { locale } : undefined,
127
+ );
65
128
  } catch {
66
129
  // No emvb_pages collection yet (EmVB not set up): not an EmVB page.
67
130
  return null;
@@ -69,9 +132,13 @@ export async function resolveEmVBPageWith(
69
132
  const entry = found.entry;
70
133
  if (!entry) return null;
71
134
  const data = entry.data as Record<string, unknown>;
135
+ const hosted = options.collection !== undefined && options.collection !== PAGES_COLLECTION;
136
+ const stored = hosted ? data[options.field ?? "canvas"] : data["layout"];
137
+ // An empty canvas field leaves the entry to the host's own template.
138
+ if (hosted && (stored === null || stored === undefined || stored === "")) return null;
72
139
  const handler = content.pluginHandler(astro.locals as never);
73
140
  const design = await designFor(astro, handler, astro.url);
74
- const layout = readLayout(data["layout"]);
141
+ const layout = readLayout(stored);
75
142
  const referenced = layout
76
143
  ? await referencedTemplatesFor(layout, content, astro)
77
144
  : { sectionTemplates: {}, loopTemplates: {} };
@@ -88,7 +155,18 @@ export async function resolveEmVBPageWith(
88
155
  ]),
89
156
  )
90
157
  : undefined;
158
+ const translations =
159
+ content.getI18nConfig?.() ||
160
+ (layout &&
161
+ [layout, ...Object.values(sectionTemplates)].some((l) => hasType(l, "language-switcher")))
162
+ ? await translationLinks(content, {
163
+ collection: options.collection ?? PAGES_COLLECTION,
164
+ entryId: String(data["id"] ?? entry.id),
165
+ ...(options.translationHref ? { hrefOf: options.translationHref } : {}),
166
+ })
167
+ : undefined;
91
168
  const dynamic = {
169
+ ...(translations ? { translations } : {}),
92
170
  ...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
93
171
  ...(Object.keys(loopTemplates).length > 0 ? { loopTemplates } : {}),
94
172
  ...(await bindingDataFor(
@@ -102,19 +180,64 @@ export async function resolveEmVBPageWith(
102
180
  content,
103
181
  )),
104
182
  };
183
+ const responsive =
184
+ layout && options.getImage
185
+ ? await withResponsiveSources(layout, options.getImage, astro.url.origin)
186
+ : stored;
105
187
  return {
106
188
  ...renderStored(
107
- data["layout"],
189
+ responsive,
108
190
  design,
109
191
  String(data["id"] ?? slug),
110
192
  formDefinitions,
111
193
  Object.keys(dynamic).length > 0 ? dynamic : undefined,
112
194
  false,
113
- options.lang ?? astro.currentLocale,
195
+ options.lang ?? found.fallbackLocale ?? locale,
114
196
  ),
115
197
  entry,
198
+ collection: hosted ? (options.collection as string) : PAGES_COLLECTION,
116
199
  title: typeof data["title"] === "string" ? data["title"] : "",
117
- canvasMode: data["canvas_mode"] === "blank" ? "blank" : "site-layout",
200
+ canvasMode: !hosted && data["canvas_mode"] === "blank" ? "blank" : "site-layout",
118
201
  isPreview: Boolean(found.isPreview),
202
+ ...(locale ? { locale } : {}),
203
+ ...(found.fallbackLocale ? { fallbackLocale: found.fallbackLocale } : {}),
204
+ ...(translations ? { translations } : {}),
119
205
  };
120
206
  }
207
+
208
+ function hasType(layout: Layout, type: string): boolean {
209
+ let found = false;
210
+ forEachNode(layout.root as LayoutNode, (node) => {
211
+ if (node.type === type) found = true;
212
+ });
213
+ return found;
214
+ }
215
+
216
+ /**
217
+ * W-937: the page's languages for its Language switcher. Only published translations are
218
+ * linked (a draft never is); the page being shown is always listed and marked current.
219
+ */
220
+ async function translationLinks(
221
+ content: ContentPort,
222
+ input: {
223
+ collection: string;
224
+ entryId: string;
225
+ hrefOf?: (translation: { locale: string; slug: string }) => string;
226
+ },
227
+ ): Promise<{ locale: string; href: string; current: boolean }[] | undefined> {
228
+ if (!content.getTranslations) return undefined;
229
+ const found = await content.getTranslations(input.collection, input.entryId).catch(() => null);
230
+ if (!found || found.error) return undefined;
231
+ const defaultLocale = content.getI18nConfig?.()?.defaultLocale;
232
+ const hrefOf =
233
+ input.hrefOf ??
234
+ ((t: { locale: string; slug: string }) =>
235
+ t.locale === defaultLocale ? `/${t.slug}` : `/${t.locale}/${t.slug}`);
236
+ return found.translations
237
+ .filter((t) => t.slug && (t.status === "published" || t.id === input.entryId))
238
+ .map((t) => ({
239
+ locale: t.locale,
240
+ href: hrefOf({ locale: t.locale, slug: t.slug as string }),
241
+ current: t.id === input.entryId,
242
+ }));
243
+ }
@@ -0,0 +1,99 @@
1
+ import { sanitizeMediaUrl, type Layout } from "../core/index.ts";
2
+
3
+ /**
4
+ * The part of Astro's `getImage` (astro:assets) this uses. The host passes its own, so EmVB stays
5
+ * free of the virtual module and the host's image service (sharp, Cloudflare Images) does the work.
6
+ */
7
+ export type ResponsiveGetImage = (options: {
8
+ src: string;
9
+ width: number;
10
+ height: number;
11
+ widths: number[];
12
+ }) => Promise<{
13
+ src: string;
14
+ srcSet?: { values?: { url: string; descriptor?: string }[]; attribute?: string };
15
+ }>;
16
+
17
+ /** EmDash's library file path; only these pictures are the site's own to resize. */
18
+ const LIBRARY_PATH = "/_emdash/api/media/file/";
19
+ /** The layout allows six extra sizes per Image (W-344). */
20
+ const MAX_SOURCES = 6;
21
+ const BREAKPOINTS = [640, 960, 1280, 1600, 1920, 2560];
22
+
23
+ type Source = { src: string; width: number };
24
+ type Node = { type: string; props: Record<string, unknown>; children?: Node[] };
25
+
26
+ /** Widths up to 2x the shown width (for high-density screens), at most six. */
27
+ export function sourceWidths(width: number): number[] {
28
+ const cap = Math.min(width * 2, 8000);
29
+ const widths = BREAKPOINTS.filter((w) => w < cap && w !== width).slice(0, MAX_SOURCES - 1);
30
+ return [...widths, cap];
31
+ }
32
+
33
+ function candidates(result: Awaited<ReturnType<ResponsiveGetImage>>): Source[] {
34
+ const values =
35
+ result.srcSet?.values ??
36
+ (result.srcSet?.attribute ?? "").split(", ").map((part) => {
37
+ const [url = "", descriptor] = part.trim().split(/\s+/);
38
+ return { url, descriptor };
39
+ });
40
+ const sources: Source[] = [];
41
+ for (const { url, descriptor } of values) {
42
+ const width = Number(/^(\d+)w$/.exec(descriptor ?? "")?.[1]);
43
+ const safe = sanitizeMediaUrl(url);
44
+ // A space or comma would split into another srcset candidate (W-428).
45
+ if (!safe || safe.length > 2000 || /[\s,]/.test(safe)) continue;
46
+ if (!Number.isInteger(width) || width < 1 || width > 8000) continue;
47
+ if (sources.some((s) => s.width === width)) continue;
48
+ sources.push({ src: safe, width });
49
+ }
50
+ return sources.slice(0, MAX_SOURCES);
51
+ }
52
+
53
+ async function fill(node: Node, getImage: ResponsiveGetImage, origin: string): Promise<void> {
54
+ if (node.type === "image") {
55
+ const { src, width, height, sources } = node.props;
56
+ const own = Array.isArray(sources) && sources.length > 0;
57
+ if (
58
+ !own &&
59
+ typeof src === "string" &&
60
+ src.startsWith(LIBRARY_PATH) &&
61
+ typeof width === "number" &&
62
+ typeof height === "number"
63
+ ) {
64
+ try {
65
+ // Astro's services only resize absolute URLs; the host authorises its origin.
66
+ const absolute = new URL(src, origin).href;
67
+ const result = await getImage({
68
+ src: absolute,
69
+ width,
70
+ height,
71
+ widths: sourceWidths(width),
72
+ });
73
+ // Passed through unchanged: the origin isn't authorised, so a srcset would be a no-op.
74
+ if (result.src && result.src !== absolute) {
75
+ const found = candidates(result);
76
+ if (found.length > 0) node.props = { ...node.props, sources: found };
77
+ }
78
+ } catch {
79
+ // No image service, or it refused this file: the plain <img> stays.
80
+ }
81
+ }
82
+ }
83
+ await Promise.all((node.children ?? []).map((child) => fill(child, getImage, origin)));
84
+ }
85
+
86
+ /**
87
+ * W-915: a copy of the layout whose library Images (with a size and no sizes of their own) get
88
+ * `sources` from the host's image service, so the public <img> has a srcset. Opt-in: only when
89
+ * the host passes `getImage`.
90
+ */
91
+ export async function withResponsiveSources(
92
+ layout: Layout,
93
+ getImage: ResponsiveGetImage,
94
+ origin: string,
95
+ ): Promise<Layout> {
96
+ const copy = structuredClone(layout);
97
+ await fill(copy.root as unknown as Node, getImage, origin);
98
+ return copy;
99
+ }