@perkyzz/emvb 0.7.0 → 0.9.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 (97) hide show
  1. package/README.md +3 -3
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +7 -7
  4. package/src/admin/editor/DialogCloseButton.tsx +16 -0
  5. package/src/admin/editor/Editor.tsx +71 -1
  6. package/src/admin/editor/FieldPreview.tsx +164 -0
  7. package/src/admin/editor/PerfMeter.tsx +3 -9
  8. package/src/admin/editor/SavedSectionDialogs.tsx +169 -0
  9. package/src/admin/editor/ShareLink.tsx +2 -7
  10. package/src/admin/editor/ShortcutsDialog.tsx +19 -11
  11. package/src/admin/editor/Timeline.tsx +2 -7
  12. package/src/admin/editor/TopBar.tsx +32 -1
  13. package/src/admin/editor/dialogs.tsx +3 -14
  14. package/src/admin/editor/editor-chrome.tsx +8 -24
  15. package/src/admin/editor/editor-commands.ts +15 -1
  16. package/src/admin/editor/editor-css.ts +6 -2
  17. package/src/admin/editor/feature-css.ts +11 -1
  18. package/src/admin/editor/focus-when-lost.ts +23 -0
  19. package/src/admin/editor/host.ts +6 -0
  20. package/src/admin/editor/icons/IconLibraryDialog.tsx +2 -7
  21. package/src/admin/editor/palette-items.ts +17 -0
  22. package/src/admin/editor/panels/AddPanel.tsx +9 -1
  23. package/src/admin/editor/panels/ElementPanel.tsx +4 -1
  24. package/src/admin/editor/panels/LayersPanel.tsx +6 -1
  25. package/src/admin/editor/panels/LeftPanel.tsx +9 -1
  26. package/src/admin/editor/panels/SavedSectionsGroup.tsx +246 -0
  27. package/src/admin/editor/panels/SiteStylesDrawer.tsx +54 -10
  28. package/src/admin/editor/panels/TokenScales.tsx +16 -16
  29. package/src/admin/editor/panels/TriggersEditor.tsx +1 -1
  30. package/src/admin/editor/panels/color-space.ts +14 -26
  31. package/src/admin/editor/panels/settings/AudienceEditor.tsx +36 -39
  32. package/src/admin/editor/panels/settings/BackgroundControls.tsx +4 -5
  33. package/src/admin/editor/panels/settings/IconControls.tsx +21 -5
  34. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
  35. package/src/admin/editor/panels/settings/MediaPicker.tsx +5 -5
  36. package/src/admin/editor/panels/settings/length-units.ts +2 -1
  37. package/src/admin/editor/shortcuts.ts +14 -0
  38. package/src/admin/editor/useSavedSections.ts +197 -0
  39. package/src/admin/image-editor/Canvas.tsx +61 -17
  40. package/src/admin/image-editor/ImageEditorDialog.tsx +130 -1
  41. package/src/admin/image-editor/image-editor-css.ts +11 -8
  42. package/src/admin/image-editor/parts.tsx +18 -17
  43. package/src/admin/image-editor/save.ts +31 -1
  44. package/src/admin/index.tsx +5 -1
  45. package/src/admin/media-api.ts +27 -0
  46. package/src/admin/pages/AgentsPage.tsx +3 -3
  47. package/src/admin/pages/CollectionsPage.tsx +215 -0
  48. package/src/admin/pages/ThemePartList.tsx +32 -4
  49. package/src/admin/saved-sections-api.ts +51 -0
  50. package/src/admin/setup/host-collections.ts +100 -0
  51. package/src/admin/theme-api.ts +3 -2
  52. package/src/admin/ui.ts +9 -0
  53. package/src/admin/widgets/CanvasField.tsx +202 -0
  54. package/src/admin/widgets/convert-body.ts +54 -0
  55. package/src/admin/widgets/field-fetcher.ts +79 -0
  56. package/src/astro/index.ts +2 -0
  57. package/src/astro/page-count.ts +77 -0
  58. package/src/astro/popups/runtime.ts +8 -6
  59. package/src/astro/resolve-theme.ts +44 -2
  60. package/src/astro/resolve.ts +40 -4
  61. package/src/astro/responsive-images.ts +99 -0
  62. package/src/constants.ts +1 -1
  63. package/src/core/a11y/audit.ts +32 -7
  64. package/src/core/arrange.ts +21 -6
  65. package/src/core/canvas-collections.ts +20 -0
  66. package/src/core/css/print.ts +5 -0
  67. package/src/core/design/classes.ts +23 -9
  68. package/src/core/design/devices.ts +7 -13
  69. package/src/core/design/states.ts +7 -13
  70. package/src/core/elements/dynamic-elements.ts +27 -12
  71. package/src/core/elements/index.ts +1 -1
  72. package/src/core/elements/menu.ts +3 -0
  73. package/src/core/icons/animation-runs.ts +11 -0
  74. package/src/core/index.ts +22 -0
  75. package/src/core/migrate/index.ts +3 -0
  76. package/src/core/portable-text.ts +127 -0
  77. package/src/core/render/loop.ts +1 -1
  78. package/src/core/render/pagination.ts +20 -1
  79. package/src/core/sanitize/css.ts +14 -6
  80. package/src/core/saved-sections.ts +318 -0
  81. package/src/core/schema/design.ts +1 -1
  82. package/src/core/schema/layout.ts +6 -1
  83. package/src/core/schema/style.ts +4 -2
  84. package/src/core/theme/float.ts +3 -0
  85. package/src/core/theme/pagination.ts +34 -24
  86. package/src/core/theme/part-types.ts +4 -4
  87. package/src/index.ts +11 -1
  88. package/src/mcp/ports.ts +22 -1
  89. package/src/mcp/read.ts +1 -1
  90. package/src/mcp/sections.ts +183 -0
  91. package/src/mcp/tools.ts +44 -0
  92. package/src/mcp/write.ts +4 -4
  93. package/src/server/agent-settings.ts +16 -1
  94. package/src/server/hooks.ts +81 -0
  95. package/src/server/mcp-routes.ts +2 -0
  96. package/src/server/plugin.ts +34 -5
  97. package/src/server/saved-sections.ts +163 -0
@@ -122,28 +122,39 @@ export type PaginationItem =
122
122
  | { kind: "page"; n: number; href: string; current: boolean }
123
123
  | { kind: "gap" };
124
124
 
125
- /**
126
- * The links a Pagination element shows. Empty when there is only one page. EmDash gives no
127
- * total count, so the numbers run from 1 to one past the current page (when there is one),
128
- * with a gap after 1 when the current page is far in (W-222).
129
- */
130
- export function paginationItems(p: ArchivePagination): PaginationItem[] {
131
- const total = knownTotal(p);
132
- if (total !== undefined) return totalItems(p, total);
133
- if (p.page <= 1 && !p.hasMore) return [];
134
- const items: PaginationItem[] = [];
135
- const page = (n: number): PaginationItem => ({
125
+ const pageItem =
126
+ (p: ArchivePagination) =>
127
+ (n: number): PaginationItem => ({
136
128
  kind: "page",
137
129
  n,
138
130
  href: archivePagePath(p.basePath, n),
139
131
  current: n === p.page,
140
132
  });
133
+
134
+ /** Previous, then page 1 and a gap (or page 2) before the window that starts at `from`. */
135
+ function leadingItems(p: ArchivePagination, from: number): PaginationItem[] {
136
+ const page = pageItem(p);
137
+ const items: PaginationItem[] = [];
141
138
  if (p.page > 1) items.push({ kind: "prev", href: archivePagePath(p.basePath, p.page - 1) });
142
- const from = Math.max(1, p.page - 2);
143
139
  if (from > 1) items.push(page(1));
144
140
  // W-600: "1 … 3" hides just page 2; show it instead of a gap.
145
141
  if (from === 3) items.push(page(2));
146
142
  if (from > 3) items.push({ kind: "gap" });
143
+ return items;
144
+ }
145
+
146
+ /**
147
+ * The links a Pagination element shows. Empty when there is only one page. EmDash gives no
148
+ * total count, so the numbers run from 1 to one past the current page (when there is one),
149
+ * with a gap after 1 when the current page is far in (W-222).
150
+ */
151
+ export function paginationItems(p: ArchivePagination): PaginationItem[] {
152
+ const total = knownTotal(p);
153
+ if (total !== undefined) return totalItems(p, total);
154
+ if (p.page <= 1 && !p.hasMore) return [];
155
+ const page = pageItem(p);
156
+ const from = Math.max(1, p.page - 2);
157
+ const items = leadingItems(p, from);
147
158
  for (let n = from; n <= p.page; n++) items.push(page(n));
148
159
  if (p.hasMore) {
149
160
  items.push(page(p.page + 1));
@@ -155,20 +166,10 @@ export function paginationItems(p: ArchivePagination): PaginationItem[] {
155
166
  /** With a known total (W-309): 1, a window around the current page, and the last page. */
156
167
  function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
157
168
  if (total <= 1) return [];
158
- const items: PaginationItem[] = [];
159
- const page = (n: number): PaginationItem => ({
160
- kind: "page",
161
- n,
162
- href: archivePagePath(p.basePath, n),
163
- current: n === p.page,
164
- });
165
- if (p.page > 1) items.push({ kind: "prev", href: archivePagePath(p.basePath, p.page - 1) });
169
+ const page = pageItem(p);
166
170
  const from = Math.max(1, p.page - 2);
171
+ const items = leadingItems(p, from);
167
172
  const to = Math.min(total, p.page + 2);
168
- if (from > 1) items.push(page(1));
169
- // W-600: "1 … 3" hides just page 2; show it instead of a gap.
170
- if (from === 3) items.push(page(2));
171
- if (from > 3) items.push({ kind: "gap" });
172
173
  for (let n = from; n <= to; n++) items.push(page(n));
173
174
  if (to === total - 2) items.push(page(total - 1));
174
175
  if (to < total - 2) items.push({ kind: "gap" });
@@ -177,6 +178,15 @@ function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
177
178
  return items;
178
179
  }
179
180
 
181
+ /**
182
+ * W-916: the last page's path when the total is known and this isn't it. Without a total there
183
+ * is no Last link: a guessed one could point past the end.
184
+ */
185
+ export function lastPagePath(p: ArchivePagination): string | undefined {
186
+ const total = knownTotal(p);
187
+ return total !== undefined && p.page < total ? archivePagePath(p.basePath, total) : undefined;
188
+ }
189
+
180
190
  /** A text prop of the first Pagination element in an archive layout, if set (W-529, W-532). */
181
191
  function paginationText(layout: Layout, key: "titleText" | "archiveTitle"): string | undefined {
182
192
  let found: string | undefined;
@@ -45,11 +45,11 @@ export const THEME_PART_TYPE_LABELS: Record<ThemePartType, string> = {
45
45
  header: "Header",
46
46
  footer: "Footer",
47
47
  error_404: "Error 404",
48
- search_results: "Search Results",
49
- single_page: "Single Page",
50
- single_post: "Single Post",
48
+ search_results: "Search results",
49
+ single_page: "Single page",
50
+ single_post: "Single post",
51
51
  archive: "Archive",
52
- loop_item: "Loop Item",
52
+ loop_item: "Loop item",
53
53
  section: "Section",
54
54
  page_template: "Page template",
55
55
  popup: "Popup",
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { PluginDescriptor } from "emdash";
2
2
  import { ADMIN_ENTRY, PACKAGE_NAME, PLUGIN_ID, PLUGIN_VERSION } from "./constants.ts";
3
+ import { canvasCollectionSlugs } from "./core/canvas-collections.ts";
3
4
  import { canvasStyleUrls } from "./core/canvas-styles.ts";
4
5
  import { createPlugin } from "./server/plugin.ts";
5
6
 
@@ -11,18 +12,27 @@ export type EmVBOptions = {
11
12
  * (`/styles/site.css`); anything else is ignored.
12
13
  */
13
14
  canvasStyles?: string[];
15
+ /**
16
+ * Host collections (such as `pages`) whose entries can hold an `emvb:canvas` "Edit with EmVB"
17
+ * field (W-897). EmVB validates and guards that field on save and publish for these only.
18
+ */
19
+ canvasCollections?: string[];
14
20
  };
15
21
 
16
22
  /** Descriptor that host sites add to `emdash({ plugins: [...] })` in astro.config. */
17
23
  export function emvb(options: EmVBOptions = {}): PluginDescriptor {
18
24
  const canvasStyles = canvasStyleUrls(options.canvasStyles);
25
+ const canvasCollections = canvasCollectionSlugs(options.canvasCollections);
19
26
  return {
20
27
  id: PLUGIN_ID,
21
28
  version: PLUGIN_VERSION,
22
29
  format: "native",
23
30
  entrypoint: PACKAGE_NAME,
24
31
  adminEntry: ADMIN_ENTRY,
25
- options: canvasStyles.length > 0 ? { canvasStyles } : {},
32
+ options: {
33
+ ...(canvasStyles.length > 0 ? { canvasStyles } : {}),
34
+ ...(canvasCollections.length > 0 ? { canvasCollections } : {}),
35
+ },
26
36
  };
27
37
  }
28
38
 
package/src/mcp/ports.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  import type { AgentSettings } from "./settings.ts";
2
2
  import type { RateClass } from "./rate-limit.ts";
3
- import type { DesignSystem, Layout, RequiredFieldInfo } from "../core/index.ts";
3
+ import type {
4
+ DesignSystem,
5
+ Layout,
6
+ Refusal,
7
+ RequiredFieldInfo,
8
+ SavedSection,
9
+ SavedSectionRecord,
10
+ SavedSectionSummary,
11
+ } from "../core/index.ts";
4
12
 
5
13
  /** A page as the tool core sees it: the current draft (or published) data and its revision. */
6
14
  export type PageRecord = {
@@ -82,4 +90,17 @@ export interface EmvbPorts {
82
90
  formFields?(
83
91
  formIds: readonly string[],
84
92
  ): Promise<ReadonlyMap<string, readonly RequiredFieldInfo[]>>;
93
+ /** W-875: saved sections; without it the saved-section tools answer NOT_SET_UP. */
94
+ savedSections?: SavedSectionsPort;
95
+ }
96
+
97
+ /** Saved sections in plugin storage `emvb_saved_sections` (W-875, D-060). */
98
+ export interface SavedSectionsPort {
99
+ list(): Promise<SavedSectionSummary[]>;
100
+ /** The section read and upgraded; null when there is none; a Refusal when it can't be read. */
101
+ get(id: string): Promise<SavedSection | Refusal | null>;
102
+ /** Stores a new section; a Refusal when the list is full. */
103
+ create(record: SavedSectionRecord): Promise<{ id: string } | Refusal>;
104
+ rename(id: string, name: string): Promise<SavedSectionSummary | Refusal | null>;
105
+ remove(id: string): Promise<boolean>;
85
106
  }
package/src/mcp/read.ts CHANGED
@@ -46,7 +46,7 @@ async function loadPage(
46
46
  return { page, layout: result.layout };
47
47
  }
48
48
 
49
- export type OutlineNode = { id: string; type: string; label?: string; children?: OutlineNode[] };
49
+ type OutlineNode = { id: string; type: string; label?: string; children?: OutlineNode[] };
50
50
 
51
51
  /** The tree without props or styles: cheap orientation for an agent (plan § 3 get_layout). */
52
52
  function outlineOf(node: LayoutNode): OutlineNode {
@@ -0,0 +1,183 @@
1
+ import { z } from "zod";
2
+ import {
3
+ addNode,
4
+ classMergeNotice,
5
+ mergeSectionClasses,
6
+ prepareSavedSection,
7
+ snapshotSection,
8
+ validateDesign,
9
+ validateLayout,
10
+ type SavedSection,
11
+ } from "../core/index.ts";
12
+ import { McpToolError } from "./errors.ts";
13
+ import type { EmvbPorts, SavedSectionsPort } from "./ports.ts";
14
+ import { queued } from "./queue.ts";
15
+ import { mutatePage, NodeIdInput, PageId, Rev, WriteOutput } from "./write.ts";
16
+
17
+ /**
18
+ * Saved-section tools (W-875, D-060). Saves are copies; synced sections are theme parts made in
19
+ * the editor. Inserting brings the section's classes into the site styles draft first (never
20
+ * overwriting a class), then adds the copy to the page, each through its write queue.
21
+ */
22
+
23
+ const SectionId = z.string().regex(/^[0-9a-f]{16}$/, "Section ids are 16 hex characters");
24
+
25
+ const portOf = (ports: EmvbPorts): SavedSectionsPort => {
26
+ if (!ports.savedSections) {
27
+ throw new McpToolError("NOT_SET_UP", "Saved sections aren't available on this site.");
28
+ }
29
+ return ports.savedSections;
30
+ };
31
+
32
+ const SectionSummary = z.object({
33
+ id: z.string(),
34
+ name: z.string(),
35
+ updatedAt: z.string(),
36
+ classCount: z.number(),
37
+ damaged: z.literal(true).optional(),
38
+ });
39
+
40
+ export const ListSavedSectionsInput = z.strictObject({});
41
+ export const ListSavedSectionsOutput = z.object({ sections: z.array(SectionSummary) });
42
+
43
+ export const listSavedSections = async (ports: EmvbPorts) => ({
44
+ sections: await portOf(ports).list(),
45
+ });
46
+
47
+ export const SaveSectionInput = z.strictObject({
48
+ pageId: PageId,
49
+ elementId: NodeIdInput,
50
+ name: z.string().min(1).max(255),
51
+ });
52
+ export const SaveSectionOutput = z.object({
53
+ id: z.string(),
54
+ name: z.string(),
55
+ summary: z.string(),
56
+ });
57
+
58
+ export async function saveSection(ports: EmvbPorts, input: z.infer<typeof SaveSectionInput>) {
59
+ const port = portOf(ports);
60
+ const page = await ports.getPage(input.pageId);
61
+ if (!page) {
62
+ throw new McpToolError("NOT_FOUND", `No EmVB page with id ${input.pageId}. Call list_pages.`);
63
+ }
64
+ const layout = validateLayout(page.layout);
65
+ if (!layout.ok) {
66
+ throw new McpToolError(
67
+ "INVALID_LAYOUT",
68
+ "The stored layout can't be read. Repair it in the editor.",
69
+ );
70
+ }
71
+ const { design } = await ports.getDesign();
72
+ const now = new Date().toISOString();
73
+ const snap = snapshotSection(layout.layout, input.elementId, design, input.name, now);
74
+ if (!snap.ok) throw new McpToolError("REFUSED", snap.reason);
75
+ const made = await port.create(snap.record);
76
+ if ("ok" in made) throw new McpToolError("REFUSED", made.reason);
77
+ const summary = `Saved ${input.elementId} as the section "${snap.record.name}"`;
78
+ return { id: made.id, name: snap.record.name, summary };
79
+ }
80
+
81
+ async function sectionOf(port: SavedSectionsPort, id: string): Promise<SavedSection> {
82
+ const found = await port.get(id);
83
+ if (!found) {
84
+ throw new McpToolError("NOT_FOUND", `No saved section ${id}. Call list_saved_sections.`);
85
+ }
86
+ if ("ok" in found) throw new McpToolError("REFUSED", found.reason);
87
+ return found;
88
+ }
89
+
90
+ export const InsertSavedSectionInput = z.strictObject({
91
+ pageId: PageId,
92
+ sectionId: SectionId,
93
+ parentId: NodeIdInput.optional(),
94
+ index: z.number().int().min(0).optional(),
95
+ expectedRev: Rev.optional(),
96
+ });
97
+ export const InsertSavedSectionOutput = WriteOutput.extend({ classes: z.string().nullable() });
98
+
99
+ export async function insertSavedSection(
100
+ ports: EmvbPorts,
101
+ input: z.infer<typeof InsertSavedSectionInput>,
102
+ ) {
103
+ const section = await sectionOf(portOf(ports), input.sectionId);
104
+ const place = (root: string) => ({
105
+ parentId: input.parentId ?? root,
106
+ index: input.index ?? Number.MAX_SAFE_INTEGER,
107
+ });
108
+ return queued("styles", async () => {
109
+ const state = await ports.getDesign();
110
+ const page = await ports.getPage(input.pageId);
111
+ if (!page) {
112
+ throw new McpToolError("NOT_FOUND", `No EmVB page with id ${input.pageId}. Call list_pages.`);
113
+ }
114
+ // A stale rev would refuse the page write after the classes were added (W-879).
115
+ if (input.expectedRev !== undefined && page.rev !== input.expectedRev) {
116
+ throw new McpToolError(
117
+ "CONFLICT",
118
+ "The page changed since you read it. Call get_layout again and retry with its rev.",
119
+ { rev: page.rev },
120
+ );
121
+ }
122
+ const current = validateLayout(page.layout);
123
+ if (!current.ok) {
124
+ throw new McpToolError(
125
+ "INVALID_LAYOUT",
126
+ "The stored layout can't be read. Repair it in the editor.",
127
+ );
128
+ }
129
+ // Dry run first, so a refused place never leaves new classes in the styles draft.
130
+ const tried = prepareSavedSection(section, current.layout, state.design);
131
+ if (!tried.ok) throw new McpToolError("REFUSED", tried.reason);
132
+ const fits = addNode(current.layout, tried.node, place(current.layout.root.id));
133
+ if (!fits.ok) throw new McpToolError("REFUSED", fits.reason);
134
+ const merge = mergeSectionClasses(state.design, section.classes);
135
+ if ("ok" in merge) throw new McpToolError("REFUSED", merge.reason);
136
+ const notice = classMergeNotice(merge);
137
+ if (notice) {
138
+ const checked = validateDesign(merge.design);
139
+ if (!checked.ok) throw new McpToolError("REFUSED", "The section's classes can't be added.");
140
+ await ports.saveDesign(checked.design, state.revision);
141
+ await ports.log({ target: "styles", tool: "insert_saved_section", summary: notice });
142
+ }
143
+ const design = merge.design;
144
+ const result = await mutatePage(
145
+ ports,
146
+ "insert_saved_section",
147
+ input.pageId,
148
+ input.expectedRev,
149
+ (layout) => {
150
+ // The merge already in the saved styles: merging again would add "Card 3" (W-875).
151
+ const prepared = prepareSavedSection(section, layout, design, Math.random, merge);
152
+ if (!prepared.ok) throw new McpToolError("REFUSED", prepared.reason);
153
+ const added = addNode(layout, prepared.node, place(layout.root.id));
154
+ if (!added.ok) throw new McpToolError("REFUSED", added.reason);
155
+ return {
156
+ layout: added.layout,
157
+ changed: [prepared.node.id],
158
+ summary: `Added the saved section "${section.name}" as ${prepared.node.id}`,
159
+ };
160
+ },
161
+ );
162
+ return { ...result, classes: notice };
163
+ });
164
+ }
165
+
166
+ export const DeleteSavedSectionInput = z.strictObject({ sectionId: SectionId });
167
+ export const DeleteSavedSectionOutput = z.object({ id: z.string(), summary: z.string() });
168
+
169
+ export async function deleteSavedSection(
170
+ ports: EmvbPorts,
171
+ input: z.infer<typeof DeleteSavedSectionInput>,
172
+ ) {
173
+ if (!(await portOf(ports).remove(input.sectionId))) {
174
+ throw new McpToolError(
175
+ "NOT_FOUND",
176
+ `No saved section ${input.sectionId}. Call list_saved_sections.`,
177
+ );
178
+ }
179
+ return {
180
+ id: input.sectionId,
181
+ summary: "Deleted the saved section. Pages that already use a copy keep it.",
182
+ };
183
+ }
package/src/mcp/tools.ts CHANGED
@@ -3,6 +3,7 @@ import type { EmvbPorts } from "./ports.ts";
3
3
  import * as read from "./read.ts";
4
4
  import * as write from "./write.ts";
5
5
  import * as publish from "./publish.ts";
6
+ import * as sections from "./sections.ts";
6
7
  import { McpToolError } from "./errors.ts";
7
8
  import { rateClassOf } from "./rate-limit.ts";
8
9
 
@@ -122,6 +123,17 @@ const READ_TOOLS: ToolDef[] = [
122
123
  destructive: false,
123
124
  run: (ports, input) => read.listVersions(ports, input),
124
125
  }),
126
+ tool({
127
+ name: "list_saved_sections",
128
+ title: "List saved sections",
129
+ description:
130
+ "Lists the site's saved sections (My sections) by id and name, newest first. Insert one with insert_saved_section.",
131
+ input: sections.ListSavedSectionsInput,
132
+ output: sections.ListSavedSectionsOutput,
133
+ readOnly: true,
134
+ destructive: false,
135
+ run: (ports) => sections.listSavedSections(ports),
136
+ }),
125
137
  ];
126
138
 
127
139
  /** Draft-only write tools (W-457, W-458). Nothing here publishes (D-055). */
@@ -213,6 +225,38 @@ const WRITE_TOOLS: ToolDef[] = [
213
225
  destructive: false,
214
226
  run: (ports, input) => write.restoreVersion(ports, input),
215
227
  }),
228
+ tool({
229
+ name: "save_section",
230
+ title: "Save an element as a section",
231
+ description:
232
+ "Saves a copy of an element and its children, with the classes they use, to My sections under a name. Copies only: synced sections are made in the editor.",
233
+ input: sections.SaveSectionInput,
234
+ output: sections.SaveSectionOutput,
235
+ readOnly: false,
236
+ destructive: false,
237
+ run: (ports, input) => sections.saveSection(ports, input),
238
+ }),
239
+ tool({
240
+ name: "insert_saved_section",
241
+ title: "Insert a saved section",
242
+ description:
243
+ "Adds a copy of a saved section at parentId/index (default: end of the page). Classes it uses are added to the site styles draft when missing; a class with the same name but a different look is added as a numbered copy, never overwritten.",
244
+ input: sections.InsertSavedSectionInput,
245
+ output: sections.InsertSavedSectionOutput,
246
+ readOnly: false,
247
+ destructive: false,
248
+ run: (ports, input) => sections.insertSavedSection(ports, input),
249
+ }),
250
+ tool({
251
+ name: "delete_saved_section",
252
+ title: "Delete a saved section",
253
+ description: "Removes a section from My sections. Pages that already hold a copy keep it.",
254
+ input: sections.DeleteSavedSectionInput,
255
+ output: sections.DeleteSavedSectionOutput,
256
+ readOnly: false,
257
+ destructive: true,
258
+ run: (ports, input) => sections.deleteSavedSection(ports, input),
259
+ }),
216
260
  ];
217
261
 
218
262
  /** Publish tools (W-464). They refuse unless the admin allowed agent publishing (D-055). */
package/src/mcp/write.ts CHANGED
@@ -35,9 +35,9 @@ import {
35
35
  type VariableKind,
36
36
  } from "../core/design/variables.ts";
37
37
 
38
- const PageId = z.string().min(1).max(128);
39
- const NodeIdInput = z.string().min(1).max(64);
40
- const Rev = z.string().min(1).max(256);
38
+ export const PageId = z.string().min(1).max(128);
39
+ export const NodeIdInput = z.string().min(1).max(64);
40
+ export const Rev = z.string().min(1).max(256);
41
41
 
42
42
  /** The editor's save checks, run here because plugin writes skip `content:beforeSave` (R1 P0b). */
43
43
  function checkLayout(candidate: unknown): Layout {
@@ -87,7 +87,7 @@ export const WriteOutput = z.object({
87
87
  * Read → apply → validate → save with `_rev`, one write per page at a time (D-058). Without
88
88
  * `expectedRev`, a conflict re-reads and re-applies the operation once; with it, never.
89
89
  */
90
- async function mutatePage(
90
+ export async function mutatePage(
91
91
  ports: EmvbPorts,
92
92
  tool: string,
93
93
  pageId: string,
@@ -7,6 +7,7 @@ import {
7
7
  } from "emdash";
8
8
  import { z } from "zod";
9
9
  import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../constants.ts";
10
+ import { canvasFieldSlugs } from "./hooks.ts";
10
11
  import { AgentSettings, DEFAULT_AGENT_SETTINGS } from "../mcp/settings.ts";
11
12
 
12
13
  /** Plugin KV key of the agent settings (plan § 4, D-055). */
@@ -145,10 +146,14 @@ const OWNED = new Set([PAGES_COLLECTION, THEME_PARTS_COLLECTION]);
145
146
  export async function beforePublish(
146
147
  event: ContentPolicyEvent,
147
148
  ctx: PluginContext,
149
+ canvasCollections: readonly string[] = [],
148
150
  ): Promise<ContentPolicyDecision> {
149
- if (!OWNED.has(event.collection)) return undefined;
151
+ const hostEntry = canvasCollections.includes(event.collection);
152
+ if (!OWNED.has(event.collection) && !hostEntry) return undefined;
150
153
  const source = event.origin.source === "mcp" || event.actor?.source === "mcp";
151
154
  if (!source) return undefined;
155
+ // W-899: a host entry falls under the EmVB rule only while it holds an EmVB layout.
156
+ if (hostEntry && !(await holdsCanvasLayout(event, ctx))) return undefined;
152
157
  const { settings } = await readAgentSettings(ctx);
153
158
  if (settings.mcpEnabled && settings.publishPages) return undefined;
154
159
  return {
@@ -157,3 +162,13 @@ export async function beforePublish(
157
162
  "Agents may not publish EmVB pages on this site. An admin can allow it in Pages VisualBuilder → AI agents.",
158
163
  };
159
164
  }
165
+
166
+ async function holdsCanvasLayout(event: ContentPolicyEvent, ctx: PluginContext): Promise<boolean> {
167
+ const record = event.content;
168
+ const data =
169
+ record["data"] && typeof record["data"] === "object"
170
+ ? (record["data"] as Record<string, unknown>)
171
+ : record;
172
+ const slugs = await canvasFieldSlugs(ctx, event.collection);
173
+ return slugs.some((slug) => data[slug] !== null && data[slug] !== undefined && data[slug] !== "");
174
+ }
@@ -58,7 +58,9 @@ const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation, string?][]
58
58
  export async function beforeSave(
59
59
  event: ContentHookEvent,
60
60
  ctx: PluginContext,
61
+ canvasCollections: readonly string[] = [],
61
62
  ): Promise<Record<string, unknown> | void> {
63
+ if (canvasCollections.includes(event.collection)) return canvasFieldsBeforeSave(event, ctx);
62
64
  if (!OWNED.has(event.collection)) return;
63
65
  const pageId = event.id ?? null;
64
66
  const kind = event.collection === THEME_PARTS_COLLECTION ? "theme part" : "page";
@@ -118,3 +120,82 @@ export async function beforeSave(
118
120
 
119
121
  return next;
120
122
  }
123
+
124
+ /** Widget id a host field picks for "Edit with EmVB" (W-P02). */
125
+ const CANVAS_WIDGET = "emvb:canvas";
126
+
127
+ /** Slugs of the collection's fields that use the `emvb:canvas` widget. */
128
+ export async function canvasFieldSlugs(ctx: PluginContext, collection: string): Promise<string[]> {
129
+ const info = await ctx.schema?.getCollection(collection);
130
+ return (info?.fields ?? []).filter((f) => f.widget === CANVAS_WIDGET).map((f) => f.slug);
131
+ }
132
+
133
+ function isEmpty(value: unknown): boolean {
134
+ return value === null || value === undefined || value === "";
135
+ }
136
+
137
+ /** Same value whether it arrives as a JSON string or an object. */
138
+ function sameValue(a: unknown, b: unknown): boolean {
139
+ const left = parseJsonField(a);
140
+ const right = parseJsonField(b);
141
+ if (isEmpty(left) && isEmpty(right)) return true;
142
+ return JSON.stringify(left) === JSON.stringify(right);
143
+ }
144
+
145
+ /**
146
+ * W-898: `emvb:canvas` fields in host collections listed in `canvasCollections`. Editors and above
147
+ * may set, change or clear them, and a set value must be a valid layout. Lower roles may still
148
+ * save the entry, but the field must stay as stored (D-061), so they can't clear or wipe it.
149
+ */
150
+ async function canvasFieldsBeforeSave(
151
+ event: ContentHookEvent,
152
+ ctx: PluginContext,
153
+ ): Promise<Record<string, unknown> | void> {
154
+ const pageId = event.id ?? null;
155
+ const fields = (await canvasFieldSlugs(ctx, event.collection)).filter(
156
+ (slug) => event.content[slug] !== undefined,
157
+ );
158
+ if (fields.length === 0) return;
159
+
160
+ const lowerRole = event.actor !== undefined && event.actor.role < EDITOR_ROLE;
161
+ if (lowerRole) {
162
+ const stored = event.id ? await ctx.content?.get(event.collection, event.id) : null;
163
+ for (const slug of fields) {
164
+ if (sameValue(event.content[slug], stored?.data[slug])) continue;
165
+ ctx.log.warn("emvb: canvas field save rejected", { pageId, code: "role" });
166
+ throw new ContentSaveRejectedError(
167
+ "Only editors and administrators can change an EmVB layout. Your other changes were not saved.",
168
+ );
169
+ }
170
+ return;
171
+ }
172
+
173
+ let next: Record<string, unknown> | undefined;
174
+ for (const slug of fields) {
175
+ const raw = parseJsonField(event.content[slug]);
176
+ if (isEmpty(raw)) continue;
177
+ const result = validateLayout(raw);
178
+ if (!result.ok) {
179
+ ctx.log.warn("emvb: canvas field save rejected", {
180
+ pageId,
181
+ code: result.issues[0]?.code ?? "invalid",
182
+ });
183
+ throw new ContentSaveRejectedError(
184
+ `The EmVB layout is invalid. ${summarizeIssues(result.issues)}`,
185
+ );
186
+ }
187
+ const wrongPlace = nestingIssues(result.layout, 3);
188
+ if (wrongPlace.length > 0) {
189
+ ctx.log.warn("emvb: canvas field save rejected", { pageId, code: "nesting" });
190
+ throw new ContentSaveRejectedError(
191
+ `The EmVB layout has elements in the wrong place. ${wrongPlace
192
+ .map((issue) => issue.message)
193
+ .join("; ")}`,
194
+ );
195
+ }
196
+ if (result.layout.schemaVersion !== result.upgradedFrom) {
197
+ next = { ...(next ?? event.content), [slug]: result.layout };
198
+ }
199
+ }
200
+ return next;
201
+ }
@@ -1,4 +1,5 @@
1
1
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { portOf } from "./saved-sections.ts";
2
3
  import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
3
4
  import { McpToolError } from "../mcp/errors.ts";
4
5
  import type { RequiredFieldInfo } from "../core/index.ts";
@@ -135,6 +136,7 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
135
136
  };
136
137
  return {
137
138
  caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
139
+ savedSections: portOf(ctx),
138
140
  formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
139
141
  async rateLimit(cls) {
140
142
  await hitRateLimit(