@perkyzz/emvb 0.4.0 → 0.5.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 (67) hide show
  1. package/README.md +19 -3
  2. package/package.json +4 -3
  3. package/src/admin/agents-api.ts +39 -0
  4. package/src/admin/editor/CommandPalette.tsx +43 -2
  5. package/src/admin/editor/Editor.tsx +27 -0
  6. package/src/admin/editor/Timeline.tsx +108 -6
  7. package/src/admin/editor/editor-css.ts +4 -0
  8. package/src/admin/editor/feature-css.ts +22 -3
  9. package/src/admin/editor/palette.ts +6 -2
  10. package/src/admin/editor/panels/ColorControl.tsx +19 -8
  11. package/src/admin/editor/panels/ElementPanel.tsx +1 -1
  12. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  13. package/src/admin/editor/panels/color-space.ts +12 -1
  14. package/src/admin/editor/panels/settings/AdvancedFields.tsx +84 -28
  15. package/src/admin/editor/panels/settings/AudienceEditor.tsx +42 -4
  16. package/src/admin/editor/panels/settings/DraftTextField.tsx +38 -9
  17. package/src/admin/editor/panels/settings/FieldControl.tsx +6 -0
  18. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  19. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  20. package/src/admin/editor/panels/settings/MediaPicker.tsx +2 -3
  21. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  22. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  23. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  24. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  25. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  26. package/src/admin/editor/panels/variable-values.ts +4 -2
  27. package/src/admin/editor/remote-change.ts +67 -0
  28. package/src/admin/index.tsx +3 -1
  29. package/src/admin/media-api.ts +20 -0
  30. package/src/admin/pages/AgentsPage.tsx +274 -0
  31. package/src/admin/ui.ts +28 -0
  32. package/src/astro/floats/runtime.ts +10 -0
  33. package/src/astro/popups/runtime.ts +15 -0
  34. package/src/astro/tabs/runtime.ts +60 -1
  35. package/src/constants.ts +1 -1
  36. package/src/core/a11y/audit.ts +202 -26
  37. package/src/core/arrange.ts +11 -3
  38. package/src/core/css/generate.ts +9 -1
  39. package/src/core/elements/form-elements.ts +19 -3
  40. package/src/core/elements/index.ts +39 -11
  41. package/src/core/render/dynamic-post.ts +21 -5
  42. package/src/core/render/form.ts +12 -5
  43. package/src/core/render/index.ts +50 -11
  44. package/src/core/render/pagination.ts +21 -2
  45. package/src/core/sanitize/embed-url.ts +7 -1
  46. package/src/core/sanitize/href.ts +13 -1
  47. package/src/core/schema/descriptors.ts +4 -1
  48. package/src/core/schema/layout.ts +10 -3
  49. package/src/core/share/link.ts +4 -1
  50. package/src/core/theme/dynamic.ts +12 -7
  51. package/src/mcp/errors.ts +44 -0
  52. package/src/mcp/index.ts +4 -0
  53. package/src/mcp/ports.ts +78 -0
  54. package/src/mcp/prompts.ts +76 -0
  55. package/src/mcp/publish.ts +60 -0
  56. package/src/mcp/queue.ts +19 -0
  57. package/src/mcp/rate-limit.ts +80 -0
  58. package/src/mcp/read.ts +419 -0
  59. package/src/mcp/refs.ts +84 -0
  60. package/src/mcp/settings.ts +18 -0
  61. package/src/mcp/tools.ts +265 -0
  62. package/src/mcp/write.ts +582 -0
  63. package/src/server/agent-settings.ts +134 -0
  64. package/src/server/design-routes.ts +71 -17
  65. package/src/server/icon-routes.ts +5 -1
  66. package/src/server/mcp-routes.ts +265 -0
  67. package/src/server/plugin.ts +32 -2
@@ -0,0 +1,178 @@
1
+ import * as React from "react";
2
+ import type { LayoutNode } from "../../../../core/index.ts";
3
+ import { FIELD } from "../../../ui.ts";
4
+ import { savableNode } from "./DraftTextField.tsx";
5
+ import { formatStyleValue, parseStyleValue, QUERY_STYLE_KEYS } from "./query-style.ts";
6
+
7
+ type QueryStyle = NonNullable<LayoutNode["query"]>["style"];
8
+
9
+ /** Store `style` as the node's query style, or say why it can't be saved. */
10
+ function withQueryStyle(node: LayoutNode, style: Record<string, unknown>): LayoutNode | string {
11
+ const query = node.query;
12
+ if (!query) return "Set a container width first.";
13
+ const next = { ...node, query: { ...query, style: style as QueryStyle } } as LayoutNode;
14
+ return savableNode(next) || !savableNode(node) ? next : "That value can't be saved here.";
15
+ }
16
+
17
+ /** One stored property: its value commits on blur or Enter; Remove deletes it. */
18
+ function QueryStyleRow({
19
+ node,
20
+ styleKey,
21
+ onChange,
22
+ }: {
23
+ node: LayoutNode;
24
+ styleKey: string;
25
+ onChange: (node: LayoutNode) => void;
26
+ }) {
27
+ const style = (node.query?.style ?? {}) as Record<string, unknown>;
28
+ const stored = formatStyleValue(style[styleKey]);
29
+ const [draft, setDraft] = React.useState(stored);
30
+ const [error, setError] = React.useState<string | null>(null);
31
+ React.useEffect(() => {
32
+ setDraft(stored);
33
+ setError(null);
34
+ }, [stored]);
35
+ const id = React.useId();
36
+ const commit = () => {
37
+ if (draft === stored) {
38
+ setError(null);
39
+ return;
40
+ }
41
+ const parsed = parseStyleValue(styleKey, draft);
42
+ if ("error" in parsed) {
43
+ setError(parsed.error);
44
+ return;
45
+ }
46
+ const next = withQueryStyle(node, { ...style, [styleKey]: parsed.value });
47
+ if (typeof next === "string") {
48
+ setError(next);
49
+ return;
50
+ }
51
+ setError(null);
52
+ onChange(next);
53
+ };
54
+ return (
55
+ <div className="emvb-query-row" data-emvb-query-key={styleKey}>
56
+ <label className="emvb-field-label" htmlFor={id}>
57
+ {styleKey}
58
+ </label>
59
+ <input
60
+ id={id}
61
+ className={FIELD}
62
+ value={draft}
63
+ aria-invalid={error ? true : undefined}
64
+ aria-describedby={error ? `${id}-error` : undefined}
65
+ onChange={(event) => setDraft(event.target.value)}
66
+ onBlur={commit}
67
+ onKeyDown={(event) => {
68
+ if (event.key === "Enter") commit();
69
+ }}
70
+ />
71
+ <button
72
+ type="button"
73
+ className="emvb-link-button"
74
+ aria-label={`Remove ${styleKey}`}
75
+ onClick={() => {
76
+ const { [styleKey]: _gone, ...rest } = style;
77
+ const next = withQueryStyle(node, rest);
78
+ if (typeof next !== "string") onChange(next);
79
+ }}
80
+ >
81
+ Remove
82
+ </button>
83
+ {error && (
84
+ <span className="emvb-helper" id={`${id}-error`} data-emvb-query-error="">
85
+ {error}
86
+ </span>
87
+ )}
88
+ </div>
89
+ );
90
+ }
91
+
92
+ /** The container-query style, one property per row, plus a row to add one (W-398). */
93
+ export function QueryStyleRows({
94
+ node,
95
+ onChange,
96
+ }: {
97
+ node: LayoutNode;
98
+ onChange: (node: LayoutNode) => void;
99
+ }) {
100
+ const style = (node.query?.style ?? {}) as Record<string, unknown>;
101
+ const keys = Object.keys(style).filter((key) => style[key] !== undefined);
102
+ const free = QUERY_STYLE_KEYS.filter((key) => !keys.includes(key));
103
+ const [newKey, setNewKey] = React.useState("");
104
+ const [newValue, setNewValue] = React.useState("");
105
+ const [error, setError] = React.useState<string | null>(null);
106
+ const keyId = React.useId();
107
+ const valueId = React.useId();
108
+ if (!node.query) return null;
109
+ const add = () => {
110
+ if (!newKey) {
111
+ setError("Choose a property.");
112
+ return;
113
+ }
114
+ const parsed = parseStyleValue(newKey, newValue);
115
+ if ("error" in parsed) {
116
+ setError(parsed.error);
117
+ return;
118
+ }
119
+ const next = withQueryStyle(node, { ...style, [newKey]: parsed.value });
120
+ if (typeof next === "string") {
121
+ setError(next);
122
+ return;
123
+ }
124
+ setError(null);
125
+ setNewKey("");
126
+ setNewValue("");
127
+ onChange(next);
128
+ };
129
+ return (
130
+ <div className="emvb-query-style" data-emvb-query-style="">
131
+ {keys.length === 0 && <p className="emvb-helper">No styles at this width yet.</p>}
132
+ {keys.map((key) => (
133
+ <QueryStyleRow key={key} node={node} styleKey={key} onChange={onChange} />
134
+ ))}
135
+ <div className="emvb-query-add" data-emvb-query-add="">
136
+ <label className="emvb-field-label" htmlFor={keyId}>
137
+ Property
138
+ </label>
139
+ <select
140
+ id={keyId}
141
+ className={FIELD}
142
+ value={newKey}
143
+ onChange={(event) => setNewKey(event.target.value)}
144
+ >
145
+ <option value="">Choose…</option>
146
+ {free.map((key) => (
147
+ <option key={key} value={key}>
148
+ {key}
149
+ </option>
150
+ ))}
151
+ </select>
152
+ <label className="emvb-field-label" htmlFor={valueId}>
153
+ Value
154
+ </label>
155
+ <input
156
+ id={valueId}
157
+ className={FIELD}
158
+ placeholder="16px, auto, #112233, var(--space-4)"
159
+ value={newValue}
160
+ aria-invalid={error ? true : undefined}
161
+ aria-describedby={error ? `${valueId}-error` : undefined}
162
+ onChange={(event) => setNewValue(event.target.value)}
163
+ onKeyDown={(event) => {
164
+ if (event.key === "Enter") add();
165
+ }}
166
+ />
167
+ <button type="button" className="emvb-link-button" onClick={add}>
168
+ Add style
169
+ </button>
170
+ {error && (
171
+ <span className="emvb-helper" id={`${valueId}-error`} data-emvb-query-error="">
172
+ {error}
173
+ </span>
174
+ )}
175
+ </div>
176
+ </div>
177
+ );
178
+ }
@@ -26,6 +26,9 @@ export function htmlIdError(value: string, layout: Layout | null, nodeId: string
26
26
  if (!HTML_ID.test(value)) {
27
27
  return "Start with a letter; use letters, digits, - and _ only (up to 64).";
28
28
  }
29
+ // W-418: EmVB names headings (emvb-h-…), form fields and tabs with emvb- ids; reusing one
30
+ // made two elements share an id, so a contents link or a label could point at the wrong one.
31
+ if (/^emvb-/i.test(value)) return "Ids starting with emvb- are reserved; choose another.";
29
32
  if (otherHtmlIds(layout, nodeId).has(value)) return "Another element already uses this CSS id.";
30
33
  return null;
31
34
  }
@@ -0,0 +1,19 @@
1
+ import { sanitizeHref } from "../../../../core/index.ts";
2
+
3
+ const GENERIC = "Use a full URL such as https://example.com or a path such as /pricing.";
4
+
5
+ /**
6
+ * Why a typed link can't be used, or null when it can (W-429). The generic hint told people who
7
+ * had typed a full URL to type a full URL; the common causes get their own message.
8
+ */
9
+ export function hrefError(value: string, message = GENERIC): string | null {
10
+ const trimmed = value.trim();
11
+ if (sanitizeHref(trimmed)) return null;
12
+ if (/^https?:\/\/\S*\s/i.test(trimmed)) {
13
+ return "Links can't contain spaces. Replace each space with %20.";
14
+ }
15
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^(https?|mailto|tel):/i.test(trimmed)) {
16
+ return "Only web (https://), email (mailto:) and phone (tel:) links are allowed.";
17
+ }
18
+ return message;
19
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * W-436: a typed number for a settings field, or NaN. "16px" in a "(px)" field is read as 16, as
3
+ * the label invites; "0x10", "1e3" and "Infinity", which Number() read, are not numbers here.
4
+ */
5
+ export function fieldNumber(text: string, unit?: string): number {
6
+ let trimmed = text.trim();
7
+ if (unit && trimmed.toLowerCase().endsWith(unit.toLowerCase())) {
8
+ trimmed = trimmed.slice(0, -unit.length).trimEnd();
9
+ }
10
+ return /^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(trimmed) ? Number(trimmed) : Number.NaN;
11
+ }
@@ -0,0 +1,65 @@
1
+ import { StyleProps } from "../../../../core/index.ts";
2
+
3
+ /** Style keys a container-query style may set (W-398). */
4
+ export const QUERY_STYLE_KEYS: readonly string[] = Object.keys(StyleProps.shape).toSorted();
5
+
6
+ /** A stored style value as one line of text: `16px`, `auto`, `#112233`, `var(--name)` (W-398). */
7
+ export function formatStyleValue(value: unknown): string {
8
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
9
+ return String(value);
10
+ }
11
+ if (value && typeof value === "object") {
12
+ const record = value as Record<string, unknown>;
13
+ if (
14
+ Object.keys(record).length === 2 &&
15
+ typeof record["value"] === "number" &&
16
+ typeof record["unit"] === "string"
17
+ ) {
18
+ return `${record["value"]}${record["unit"]}`;
19
+ }
20
+ if (typeof record["var"] === "string" && Object.keys(record).length === 1) {
21
+ return `var(--${record["var"]})`;
22
+ }
23
+ }
24
+ return JSON.stringify(value);
25
+ }
26
+
27
+ /** Readings of `text` to try, most specific first. */
28
+ function candidates(text: string): unknown[] {
29
+ const out: unknown[] = [];
30
+ const length = /^(-?\d+(?:\.\d+)?)([a-z%]+)$/i.exec(text);
31
+ if (length) out.push({ value: Number(length[1]), unit: (length[2] as string).toLowerCase() });
32
+ const variable = /^var\(--([a-z0-9-]{1,40})\)$/.exec(text);
33
+ if (variable) out.push({ var: variable[1] });
34
+ if (/^-?\d+(?:\.\d+)?$/.test(text)) {
35
+ out.push(Number(text));
36
+ // W-404: a bare number on a length property means px, as in the Style tab.
37
+ out.push({ value: Number(text), unit: "px" });
38
+ }
39
+ // W-404: keywords are lowercase in the schema; AUTO or Row should still work.
40
+ if (/^[A-Za-z-]+$/.test(text) && text !== text.toLowerCase()) out.push(text.toLowerCase());
41
+ if (text === "true" || text === "false") out.push(text === "true");
42
+ if (text.startsWith("{") || text.startsWith("[")) {
43
+ try {
44
+ out.push(JSON.parse(text));
45
+ } catch {
46
+ // not JSON; the plain string reading below reports the error
47
+ }
48
+ }
49
+ out.push(text);
50
+ return out;
51
+ }
52
+
53
+ /** The value `key` would store for `text`, or why it can't (W-398). */
54
+ export function parseStyleValue(key: string, text: string): { value: unknown } | { error: string } {
55
+ const schema = (
56
+ StyleProps.shape as Record<string, { safeParse: (v: unknown) => { success: boolean } }>
57
+ )[key];
58
+ if (!schema) return { error: `${key} isn't a style property.` };
59
+ const trimmed = text.trim();
60
+ if (trimmed === "") return { error: "Enter a value." };
61
+ for (const candidate of candidates(trimmed)) {
62
+ if (candidate !== undefined && schema.safeParse(candidate).success) return { value: candidate };
63
+ }
64
+ return { error: `"${trimmed.slice(0, 40)}" isn't a value ${key} accepts.` };
65
+ }
@@ -1,8 +1,8 @@
1
1
  import type { VariableKind } from "../../../core/index.ts";
2
+ import { hexInput } from "./color-space.ts";
2
3
 
3
4
  export type Length = { value: number; unit: "px" | "rem" | "em" | "%" };
4
5
 
5
- const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
6
6
  const LENGTH = /^(\d+(?:\.\d+)?|\.\d+)\s*(px|rem|em|%)?$/i;
7
7
  const MAX_LENGTH = 10_000;
8
8
 
@@ -54,7 +54,9 @@ export function parseValue(
54
54
  return length ? { ok: true, value: length } : { ok: false, error: ERRORS[kind] };
55
55
  }
56
56
  if (kind === "color") {
57
- return HEX.test(trimmed) ? { ok: true, value: trimmed } : { ok: false, error: ERRORS.color };
57
+ // W-434: "1a2b3c" without "#", as design tools copy it, is accepted.
58
+ const hex = hexInput(trimmed);
59
+ return hex ? { ok: true, value: hex } : { ok: false, error: ERRORS.color };
58
60
  }
59
61
  return trimmed && trimmed.length <= 200
60
62
  ? { ok: true, value: trimmed }
@@ -0,0 +1,67 @@
1
+ import * as React from "react";
2
+ import { PLUGIN_ID } from "../../constants.ts";
3
+ import { requestJson, type Fetcher } from "../api.ts";
4
+
5
+ /** How often an idle editor checks whether the page changed elsewhere (W-466). */
6
+ const REMOTE_CHECK_MS = 20_000;
7
+
8
+ export type RemoteChange = null | "agent" | "other";
9
+
10
+ /**
11
+ * What changed the stored draft since `rev`: null when nothing did, "agent" when the newest
12
+ * version is one an AI agent saved, "other" for anyone else.
13
+ */
14
+ export async function checkRemoteChange(
15
+ fetcher: Fetcher,
16
+ collection: string,
17
+ id: string,
18
+ rev: string,
19
+ ): Promise<RemoteChange> {
20
+ const body = await requestJson<{ item?: { draftRevisionId?: string | null }; _rev?: string }>(
21
+ fetcher,
22
+ `/_emdash/api/content/${collection}/${encodeURIComponent(id)}`,
23
+ );
24
+ const stored = body["_rev"];
25
+ if (!stored || stored === rev) return null;
26
+ const draft = body.item?.draftRevisionId;
27
+ if (!draft) return "other";
28
+ const agents = await requestJson<{ versions?: { revisionId: string }[] }>(
29
+ fetcher,
30
+ `/_emdash/api/plugins/${PLUGIN_ID}/agents/page`,
31
+ { method: "POST", body: { pageId: id } },
32
+ ).catch(() => ({ versions: [] }));
33
+ return (agents.versions ?? []).some((v) => v.revisionId === draft) ? "agent" : "other";
34
+ }
35
+
36
+ /**
37
+ * Polls while the editor is idle (no unsaved edits, nothing in flight, tab visible) and reports
38
+ * when the page changed elsewhere, so the person can reload before their next save conflicts.
39
+ */
40
+ export function useRemoteChange(
41
+ fetcher: Fetcher,
42
+ collection: string,
43
+ id: string,
44
+ rev: string | null,
45
+ idle: boolean,
46
+ ): RemoteChange {
47
+ const [change, setChange] = React.useState<RemoteChange>(null);
48
+ React.useEffect(() => setChange(null), [rev]);
49
+ React.useEffect(() => {
50
+ if (!idle || !rev || change) return;
51
+ let cancelled = false;
52
+ const timer = setInterval(() => {
53
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
54
+ checkRemoteChange(fetcher, collection, id, rev).then(
55
+ (next) => {
56
+ if (!cancelled && next) setChange(next);
57
+ },
58
+ () => undefined,
59
+ );
60
+ }, REMOTE_CHECK_MS);
61
+ return () => {
62
+ cancelled = true;
63
+ clearInterval(timer);
64
+ };
65
+ }, [fetcher, collection, id, rev, idle, change]);
66
+ return change;
67
+ }
@@ -3,15 +3,17 @@ import { installSidebarShim } from "./access/sidebar-shim.ts";
3
3
  import { defaultFetcher } from "./api.ts";
4
4
  import { EditorPage } from "./pages/EditorPage.tsx";
5
5
  import { PagesPage } from "./pages/PagesPage.tsx";
6
+ import { AgentsPage } from "./pages/AgentsPage.tsx";
6
7
  import { ThemeBuilderPage } from "./pages/ThemeBuilderPage.tsx";
7
8
  import { LayoutField } from "./widgets/LayoutField.tsx";
8
9
 
9
10
  if (typeof document !== "undefined") void installSidebarShim(document, defaultFetcher);
10
11
 
11
- /** `/pages` and `/theme` are declared; `/editor` renders by URL (D-024). */
12
+ /** `/pages`, `/theme` and `/agents` are declared; `/editor` renders by URL (D-024). */
12
13
  export const pages: PluginAdminExports["pages"] = {
13
14
  "/pages": PagesPage,
14
15
  "/theme": ThemeBuilderPage,
16
+ "/agents": AgentsPage,
15
17
  "/editor": EditorPage,
16
18
  };
17
19
 
@@ -53,12 +53,32 @@ export async function uploadImage(
53
53
  return payload.data.item;
54
54
  }
55
55
 
56
+ /** Applies a pasted URL onto an image node's props; the URL is already sanitized. */
57
+ export function propsFromUrl(
58
+ current: Record<string, unknown>,
59
+ src: string,
60
+ ): Record<string, unknown> {
61
+ const next: Record<string, unknown> = { ...current, src };
62
+ delete next.mediaId;
63
+ if (current.src === src) return next;
64
+ // W-422: a different picture drops the old one's extra sizes.
65
+ delete next.sources;
66
+ // W-425: a library image's width and height describe that file, not the pasted one.
67
+ if (current.mediaId) {
68
+ delete next.width;
69
+ delete next.height;
70
+ }
71
+ return next;
72
+ }
73
+
56
74
  /** Applies a library item onto an image node's props (id, URL, alt, dimensions). */
57
75
  export function propsFromMedia(
58
76
  current: Record<string, unknown>,
59
77
  item: MediaLibraryItem,
60
78
  ): Record<string, unknown> {
61
79
  const next: Record<string, unknown> = { ...current, src: item.url, mediaId: item.id };
80
+ // W-422: extra sizes belong to the old picture; kept, the browser could still show it.
81
+ if (current.src !== item.url) delete next.sources;
62
82
  if (item.width) next.width = item.width;
63
83
  if (item.height) next.height = item.height;
64
84
  const alt = current.alt;