@perkyzz/emvb 0.7.0 → 0.8.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 (71) hide show
  1. package/README.md +2 -2
  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 +33 -0
  6. package/src/admin/editor/PerfMeter.tsx +3 -9
  7. package/src/admin/editor/SavedSectionDialogs.tsx +169 -0
  8. package/src/admin/editor/ShareLink.tsx +2 -7
  9. package/src/admin/editor/ShortcutsDialog.tsx +19 -11
  10. package/src/admin/editor/Timeline.tsx +2 -7
  11. package/src/admin/editor/dialogs.tsx +3 -14
  12. package/src/admin/editor/editor-chrome.tsx +8 -24
  13. package/src/admin/editor/editor-commands.ts +15 -1
  14. package/src/admin/editor/editor-css.ts +3 -2
  15. package/src/admin/editor/feature-css.ts +11 -1
  16. package/src/admin/editor/focus-when-lost.ts +23 -0
  17. package/src/admin/editor/icons/IconLibraryDialog.tsx +2 -7
  18. package/src/admin/editor/palette-items.ts +17 -0
  19. package/src/admin/editor/panels/AddPanel.tsx +9 -1
  20. package/src/admin/editor/panels/LayersPanel.tsx +6 -1
  21. package/src/admin/editor/panels/LeftPanel.tsx +9 -1
  22. package/src/admin/editor/panels/SavedSectionsGroup.tsx +246 -0
  23. package/src/admin/editor/panels/SiteStylesDrawer.tsx +54 -10
  24. package/src/admin/editor/panels/TokenScales.tsx +16 -16
  25. package/src/admin/editor/panels/TriggersEditor.tsx +1 -1
  26. package/src/admin/editor/panels/color-space.ts +14 -26
  27. package/src/admin/editor/panels/settings/AudienceEditor.tsx +36 -39
  28. package/src/admin/editor/panels/settings/IconControls.tsx +21 -5
  29. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
  30. package/src/admin/editor/shortcuts.ts +14 -0
  31. package/src/admin/editor/useSavedSections.ts +197 -0
  32. package/src/admin/image-editor/Canvas.tsx +61 -17
  33. package/src/admin/image-editor/ImageEditorDialog.tsx +130 -1
  34. package/src/admin/image-editor/image-editor-css.ts +11 -8
  35. package/src/admin/image-editor/parts.tsx +18 -17
  36. package/src/admin/image-editor/save.ts +31 -1
  37. package/src/admin/pages/ThemePartList.tsx +32 -4
  38. package/src/admin/saved-sections-api.ts +51 -0
  39. package/src/admin/theme-api.ts +3 -2
  40. package/src/admin/ui.ts +9 -0
  41. package/src/astro/popups/runtime.ts +8 -6
  42. package/src/constants.ts +1 -1
  43. package/src/core/a11y/audit.ts +32 -7
  44. package/src/core/arrange.ts +21 -6
  45. package/src/core/css/print.ts +5 -0
  46. package/src/core/design/classes.ts +23 -9
  47. package/src/core/design/devices.ts +7 -13
  48. package/src/core/design/states.ts +7 -13
  49. package/src/core/elements/dynamic-elements.ts +11 -11
  50. package/src/core/elements/index.ts +1 -1
  51. package/src/core/elements/menu.ts +3 -0
  52. package/src/core/icons/animation-runs.ts +11 -0
  53. package/src/core/index.ts +20 -0
  54. package/src/core/migrate/index.ts +3 -0
  55. package/src/core/render/loop.ts +1 -1
  56. package/src/core/sanitize/css.ts +14 -6
  57. package/src/core/saved-sections.ts +318 -0
  58. package/src/core/schema/design.ts +1 -1
  59. package/src/core/schema/layout.ts +1 -1
  60. package/src/core/schema/style.ts +4 -2
  61. package/src/core/theme/float.ts +3 -0
  62. package/src/core/theme/pagination.ts +25 -24
  63. package/src/core/theme/part-types.ts +4 -4
  64. package/src/mcp/ports.ts +22 -1
  65. package/src/mcp/read.ts +1 -1
  66. package/src/mcp/sections.ts +183 -0
  67. package/src/mcp/tools.ts +44 -0
  68. package/src/mcp/write.ts +4 -4
  69. package/src/server/mcp-routes.ts +2 -0
  70. package/src/server/plugin.ts +14 -0
  71. package/src/server/saved-sections.ts +163 -0
@@ -17,7 +17,7 @@ import { DeviceStyles, HiddenOn, Length, StyleProps, StyleStates } from "./style
17
17
  * (`{ angle, from, to }`) become a linear gradient on read.
18
18
  * 11 since W-156 and W-157 (D-045): the layout Section element and an editor-only node label.
19
19
  */
20
- export const LAYOUT_SCHEMA_VERSION = 16;
20
+ export const LAYOUT_SCHEMA_VERSION = 17;
21
21
 
22
22
  export const NodeId = z
23
23
  .string()
@@ -266,14 +266,16 @@ export const StyleProps = z.strictObject({
266
266
  })
267
267
  .optional(),
268
268
  /**
269
- * A looping spin or pulse; off for visitors who prefer reduced motion. `{ type: "none" }`
270
- * (W-248) stops an animation a device would otherwise inherit from a wider one.
269
+ * A spin or pulse; off for visitors who prefer reduced motion. It stops after about 5 s
270
+ * (W-848) unless `loop` is true (W-853, D-059). `{ type: "none" }` (W-248) stops an animation a
271
+ * device would otherwise inherit from a wider one.
271
272
  */
272
273
  iconAnimation: z
273
274
  .union([
274
275
  z.strictObject({
275
276
  type: z.enum(["spin", "pulse"]),
276
277
  duration: z.number().int().min(200).max(10_000),
278
+ loop: z.literal(true).optional(),
277
279
  }),
278
280
  z.strictObject({ type: z.literal("none") }),
279
281
  ])
@@ -47,6 +47,8 @@ export function validateFloatSettings(raw: unknown): FloatValidation {
47
47
  * W-759: a corner float keeps its 1rem gap on both sides and never grows past the screen; a long
48
48
  * one scrolls inside (on a phone it ran off the top, taking its close button and heading with it).
49
49
  * Bars reserve their height through the two custom properties the runtime sets.
50
+ * W-844 (D-053): a top or bottom bar is capped at half the screen and its body scrolls, so a
51
+ * tall bar can't cover a phone.
50
52
  */
51
53
  export const FLOAT_CHROME_CSS = `
52
54
  .emvb-float{position:fixed;z-index:9000;box-sizing:border-box;max-width:100%;display:flex;align-items:flex-start;gap:.35rem}.emvb-float:hover,.emvb-float:focus-within{z-index:9001}
@@ -62,6 +64,7 @@ export const FLOAT_CHROME_CSS = `
62
64
  .emvb-float__body{min-width:0;flex:1}
63
65
  .emvb-float:is(.emvb-float--start-top,.emvb-float--end-top,.emvb-float--start-bottom,.emvb-float--end-bottom){max-width:calc(100% - 2rem)}
64
66
  .emvb-float:is(.emvb-float--start-top,.emvb-float--end-top,.emvb-float--start-bottom,.emvb-float--end-bottom) .emvb-float__body{max-height:calc(100vh - 3.5rem);max-height:calc(100dvh - 3.5rem);overflow:auto}
67
+ .emvb-float:is(.emvb-float--top,.emvb-float--bottom) .emvb-float__body{max-height:50vh;max-height:50dvh;overflow:auto}
65
68
  .emvb-float__close{flex:none;width:2rem;height:2rem;border:0;border-radius:999px;background:transparent;color:inherit;font-size:1.5rem;line-height:1;cursor:pointer}
66
69
  .emvb-float__close:focus-visible{outline:2px solid #2563eb;outline-offset:2px}
67
70
  html{--emvb-float-top:0px;--emvb-float-bottom:0px;scroll-padding-top:var(--emvb-float-top);scroll-padding-bottom:var(--emvb-float-bottom)}
@@ -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" });
@@ -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/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,
@@ -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(
@@ -6,6 +6,13 @@ import {
6
6
  designRoute,
7
7
  designSaveRoute,
8
8
  } from "./design-routes.ts";
9
+ import {
10
+ savedSectionDeleteRoute,
11
+ savedSectionGetRoute,
12
+ savedSectionRenameRoute,
13
+ savedSectionSaveRoute,
14
+ savedSectionsRoute,
15
+ } from "./saved-sections.ts";
9
16
  import { iconDeleteRoute, iconRenameRoute, iconUploadRoute, iconsRoute } from "./icon-routes.ts";
10
17
  import { beforeSave } from "./hooks.ts";
11
18
  import {
@@ -37,6 +44,8 @@ export function createPlugin(options: { canvasStyles?: unknown } = {}) {
37
44
  // D-057: agent changes and the site styles history.
38
45
  agentlog: { indexes: ["at", "pageId"] },
39
46
  designhistory: { indexes: ["at"] },
47
+ // W-875 (D-060): saved sections, by name, per site.
48
+ emvb_saved_sections: { indexes: ["updatedAt"] },
40
49
  },
41
50
  hooks: {
42
51
  "content:beforeSave": { handler: beforeSave, errorPolicy: "abort" },
@@ -64,6 +73,11 @@ export function createPlugin(options: { canvasStyles?: unknown } = {}) {
64
73
  "design/save": designSaveRoute,
65
74
  "design/publish": designPublishRoute,
66
75
  icons: iconsRoute,
76
+ "saved-sections": savedSectionsRoute,
77
+ "saved-sections/get": savedSectionGetRoute,
78
+ "saved-sections/save": savedSectionSaveRoute,
79
+ "saved-sections/rename": savedSectionRenameRoute,
80
+ "saved-sections/delete": savedSectionDeleteRoute,
67
81
  "icons/upload": iconUploadRoute,
68
82
  "icons/rename": iconRenameRoute,
69
83
  "icons/delete": iconDeleteRoute,
@@ -0,0 +1,163 @@
1
+ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { z } from "zod";
3
+ import {
4
+ MAX_SAVED_SECTIONS,
5
+ readSavedSection,
6
+ savedSectionName,
7
+ savedSectionRecord,
8
+ SAVED_SECTION_REASONS,
9
+ type SavedSectionRecord,
10
+ type SavedSectionSummary,
11
+ } from "../core/index.ts";
12
+ import type { SavedSectionsPort } from "../mcp/ports.ts";
13
+ import { queued } from "../mcp/queue.ts";
14
+
15
+ /**
16
+ * Saved sections (W-875, D-060): named copies of an element kept per site in plugin storage
17
+ * `emvb_saved_sections`. Every row read goes through `readSavedSection`, so an old save comes
18
+ * back upgraded and a damaged or hand-written one is never inserted. Writes take the same
19
+ * per-isolate queue as the MCP tools.
20
+ */
21
+ const SAVED_SECTIONS_COLLECTION = "emvb_saved_sections";
22
+
23
+ type SavedSectionStore = {
24
+ get(id: string): Promise<unknown>;
25
+ put(id: string, data: SavedSectionRecord): Promise<void>;
26
+ delete(id: string): Promise<boolean>;
27
+ query(options?: {
28
+ orderBy?: Record<string, "asc" | "desc">;
29
+ limit?: number;
30
+ }): Promise<{ items: Array<{ id: string; data: unknown }>; hasMore: boolean }>;
31
+ };
32
+
33
+ const QUEUE = "saved-sections";
34
+ const ID = /^[0-9a-f]{16}$/;
35
+ const FULL_REASON = `My sections holds up to ${MAX_SAVED_SECTIONS} sections. Delete one you no longer use, then save again.`;
36
+
37
+ function summaryOf(id: string, data: unknown): SavedSectionSummary {
38
+ const read = readSavedSection(data);
39
+ if (read.ok) {
40
+ const { name, updatedAt, classes } = read.section;
41
+ return { id, name, updatedAt, classCount: classes.length };
42
+ }
43
+ const raw = (data ?? {}) as { name?: unknown; updatedAt?: unknown };
44
+ return {
45
+ id,
46
+ name: (typeof raw.name === "string" && savedSectionName(raw.name)) || "Damaged section",
47
+ updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : "",
48
+ classCount: 0,
49
+ damaged: true,
50
+ };
51
+ }
52
+
53
+ /** The port the routes and the MCP tools share, on a plugin storage collection. */
54
+ function savedSectionsPort(store: SavedSectionStore): SavedSectionsPort {
55
+ const all = () => store.query({ orderBy: { updatedAt: "desc" }, limit: MAX_SAVED_SECTIONS });
56
+ return {
57
+ async list() {
58
+ const page = await all();
59
+ return page.items.map(({ id, data }) => summaryOf(id, data));
60
+ },
61
+ async get(id) {
62
+ if (!ID.test(id)) return null;
63
+ const data = await store.get(id);
64
+ if (data === null || data === undefined) return null;
65
+ const read = readSavedSection(data);
66
+ return read.ok ? read.section : read;
67
+ },
68
+ create: (record) =>
69
+ queued(QUEUE, async () => {
70
+ const read = readSavedSection(record);
71
+ if (!read.ok) return read;
72
+ if ((await all()).items.length >= MAX_SAVED_SECTIONS) {
73
+ return { ok: false as const, reason: FULL_REASON };
74
+ }
75
+ const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
76
+ await store.put(id, savedSectionRecord(read.section));
77
+ return { id };
78
+ }),
79
+ rename: (id, rawName) =>
80
+ queued(QUEUE, async () => {
81
+ if (!ID.test(id)) return null;
82
+ const data = await store.get(id);
83
+ if (data === null || data === undefined) return null;
84
+ const name = savedSectionName(rawName);
85
+ if (!name) return { ok: false as const, reason: SAVED_SECTION_REASONS.name };
86
+ const read = readSavedSection(data);
87
+ if (!read.ok) return read;
88
+ const section = { ...read.section, name, updatedAt: new Date().toISOString() };
89
+ await store.put(id, savedSectionRecord(section));
90
+ return summaryOf(id, savedSectionRecord(section));
91
+ }),
92
+ remove: (id) => queued(QUEUE, async () => ID.test(id) && (await store.delete(id))),
93
+ };
94
+ }
95
+
96
+ export const portOf = (ctx: RouteContext<unknown>) =>
97
+ savedSectionsPort(ctx.storage[SAVED_SECTIONS_COLLECTION] as unknown as SavedSectionStore);
98
+
99
+ const NOT_FOUND = "That section is not in My sections.";
100
+ const refusedError = (reason: string) => new PluginRouteError("REFUSED", reason, 422);
101
+
102
+ /** Editors and above: the saved sections, newest first, by name. */
103
+ export const savedSectionsRoute: PluginRoute = {
104
+ permission: "content:edit_any",
105
+ handler: async (ctx) => ({ items: await portOf(ctx).list() }),
106
+ };
107
+
108
+ const IdInput = z.object({ id: z.string().regex(ID, "Unknown section") });
109
+
110
+ /** Editors and above: one section, read and upgraded, ready for `prepareSavedSection`. */
111
+ export const savedSectionGetRoute: PluginRoute<z.infer<typeof IdInput>> = {
112
+ permission: "content:edit_any",
113
+ input: IdInput,
114
+ handler: async (ctx) => {
115
+ const section = await portOf(ctx).get(ctx.input.id);
116
+ if (!section) throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
117
+ if ("ok" in section) throw refusedError(section.reason);
118
+ return { section };
119
+ },
120
+ };
121
+
122
+ /** A record from the editor; the server checks it again, whatever the client did. */
123
+ const SaveInput = z.object({ record: z.record(z.string(), z.unknown()) });
124
+
125
+ export const savedSectionSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
126
+ permission: "content:edit_any",
127
+ input: SaveInput,
128
+ handler: async (ctx) => {
129
+ const now = new Date().toISOString();
130
+ const record = { ...ctx.input.record, createdAt: now, updatedAt: now };
131
+ const made = await portOf(ctx).create(record as SavedSectionRecord);
132
+ if ("ok" in made) {
133
+ const full = made.reason === FULL_REASON;
134
+ throw new PluginRouteError(full ? "SECTIONS_FULL" : "REFUSED", made.reason, full ? 409 : 422);
135
+ }
136
+ return { id: made.id };
137
+ },
138
+ };
139
+
140
+ const RenameInput = IdInput.extend({ name: z.string().min(1).max(255) });
141
+
142
+ export const savedSectionRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
143
+ permission: "content:edit_any",
144
+ input: RenameInput,
145
+ handler: async (ctx) => {
146
+ const item = await portOf(ctx).rename(ctx.input.id, ctx.input.name);
147
+ if (!item) throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
148
+ if ("ok" in item) throw refusedError(item.reason);
149
+ return { item };
150
+ },
151
+ };
152
+
153
+ /** Pages that already hold an inserted copy keep it: a copy is not linked to its source. */
154
+ export const savedSectionDeleteRoute: PluginRoute<z.infer<typeof IdInput>> = {
155
+ permission: "content:edit_any",
156
+ input: IdInput,
157
+ handler: async (ctx) => {
158
+ if (!(await portOf(ctx).remove(ctx.input.id))) {
159
+ throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
160
+ }
161
+ return { id: ctx.input.id };
162
+ },
163
+ };