@perkyzz/emvb 0.2.1 → 0.4.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 (150) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +3 -1
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/api.ts +17 -7
  6. package/src/admin/content-api.ts +7 -51
  7. package/src/admin/content-item.ts +22 -0
  8. package/src/admin/design-api.ts +30 -0
  9. package/src/admin/editor/A11yCopilot.tsx +126 -0
  10. package/src/admin/editor/CommandPalette.tsx +118 -0
  11. package/src/admin/editor/Editor.tsx +188 -152
  12. package/src/admin/editor/EditorOverlay.tsx +9 -1
  13. package/src/admin/editor/PerfMeter.tsx +121 -0
  14. package/src/admin/editor/ShareLink.tsx +164 -0
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +287 -0
  17. package/src/admin/editor/TopBar.tsx +4 -0
  18. package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
  19. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  20. package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
  21. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  22. package/src/admin/editor/canvas/drop-line.ts +24 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  24. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  25. package/src/admin/editor/collection-previews.ts +114 -0
  26. package/src/admin/editor/editor-chrome.tsx +346 -0
  27. package/src/admin/editor/editor-commands.ts +360 -0
  28. package/src/admin/editor/editor-css.ts +5 -3
  29. package/src/admin/editor/element-chrome.ts +89 -0
  30. package/src/admin/editor/feature-css.ts +105 -0
  31. package/src/admin/editor/host.ts +35 -0
  32. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  33. package/src/admin/editor/icons/library.ts +29 -19
  34. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  35. package/src/admin/editor/live-data.tsx +71 -0
  36. package/src/admin/editor/palette-items.ts +136 -0
  37. package/src/admin/editor/palette.ts +68 -0
  38. package/src/admin/editor/panels/AddPanel.tsx +48 -68
  39. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  40. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  41. package/src/admin/editor/panels/ElementPanel.tsx +74 -102
  42. package/src/admin/editor/panels/LayersPanel.tsx +72 -63
  43. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  44. package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
  45. package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
  46. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  47. package/src/admin/editor/panels/VariableSection.tsx +10 -14
  48. package/src/admin/editor/panels/inline-error.tsx +11 -0
  49. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  50. package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -0
  51. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  52. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  53. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  54. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  55. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  56. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  57. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  58. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  59. package/src/admin/editor/panels/settings/StyleRow.tsx +26 -2
  60. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  61. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  62. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  63. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  64. package/src/admin/editor/panels/settings/length-units.ts +16 -5
  65. package/src/admin/editor/panels/settings/style-sections.ts +7 -2
  66. package/src/admin/editor/panels/style-target.ts +105 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +6 -1
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +30 -14
  74. package/src/admin/editor/useNodeActions.ts +44 -16
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/theme-api.ts +5 -18
  78. package/src/admin/ui.ts +4 -4
  79. package/src/astro/content-port.ts +24 -0
  80. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  81. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  82. package/src/astro/forms/client.ts +1 -0
  83. package/src/astro/forms-definitions.ts +24 -11
  84. package/src/astro/index.ts +1 -0
  85. package/src/astro/render-session.ts +85 -0
  86. package/src/astro/request-data.ts +109 -0
  87. package/src/astro/resolve-theme.ts +184 -64
  88. package/src/astro/resolve.ts +63 -16
  89. package/src/astro/theme-posts.ts +48 -5
  90. package/src/astro/visitor.ts +204 -0
  91. package/src/constants.ts +1 -1
  92. package/src/core/a11y/audit.ts +282 -0
  93. package/src/core/arrange.ts +150 -34
  94. package/src/core/audience/rules.ts +124 -0
  95. package/src/core/audience/variants.ts +51 -0
  96. package/src/core/canvas-styles.ts +24 -0
  97. package/src/core/clipboard.ts +11 -32
  98. package/src/core/css/generate.ts +29 -2
  99. package/src/core/css/print.ts +12 -0
  100. package/src/core/css/scope.ts +3 -3
  101. package/src/core/css/trace.ts +169 -0
  102. package/src/core/css-keywords.ts +83 -0
  103. package/src/core/data/bindings.ts +255 -0
  104. package/src/core/design/classes.ts +13 -15
  105. package/src/core/design/diff.ts +55 -0
  106. package/src/core/design/merge.ts +127 -0
  107. package/src/core/design/tokens.ts +127 -0
  108. package/src/core/design/variables.ts +25 -21
  109. package/src/core/elements/dynamic-elements.ts +117 -2
  110. package/src/core/elements/form-elements.ts +1 -0
  111. package/src/core/elements/index.ts +185 -7
  112. package/src/core/forms/binding.ts +4 -13
  113. package/src/core/history/diff.ts +152 -0
  114. package/src/core/index.ts +121 -0
  115. package/src/core/local-style.ts +27 -0
  116. package/src/core/migrate/index.ts +12 -4
  117. package/src/core/nesting.ts +4 -22
  118. package/src/core/perf/meter.ts +160 -0
  119. package/src/core/perf/scripts.ts +61 -0
  120. package/src/core/recipes/index.ts +433 -0
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +1 -2
  124. package/src/core/render/form.ts +133 -10
  125. package/src/core/render/index.ts +206 -17
  126. package/src/core/render/loop.ts +54 -7
  127. package/src/core/render/pagination.ts +9 -1
  128. package/src/core/render/vnode.ts +12 -2
  129. package/src/core/sanitize/css.ts +129 -80
  130. package/src/core/sanitize/motion.ts +129 -0
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/design.ts +29 -8
  134. package/src/core/schema/layout.ts +291 -169
  135. package/src/core/schema/motion.ts +14 -0
  136. package/src/core/schema/style.ts +101 -66
  137. package/src/core/share/link.ts +187 -0
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +242 -32
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/theme/pagination.ts +56 -0
  142. package/src/core/tree-ops.ts +57 -0
  143. package/src/index.ts +14 -2
  144. package/src/server/design-routes.ts +4 -1
  145. package/src/server/icon-routes.ts +68 -16
  146. package/src/server/plugin.ts +8 -2
  147. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  148. package/src/admin/editor/icons/sets/lucide.json +0 -1
  149. package/src/admin/editor/icons/sets/remix.json +0 -1
  150. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -1,7 +1,13 @@
1
+ import type { VisitorInfo } from "../audience/rules.ts";
1
2
  import type { ArchivePagination } from "./pagination.ts";
2
3
  import type { Layout, LayoutNode } from "../schema/layout.ts";
3
- import { isParentNode } from "../schema/layout.ts";
4
+ import { LOOP_FILTER, LOOP_PERMALINK } from "../schema/layout.ts";
5
+ import { forEachNode, knownChildren } from "../tree-ops.ts";
6
+ import { isRecord } from "../record.ts";
7
+
8
+ const FIELD_SLUG = /^[a-z][a-z0-9_]{0,63}$/;
4
9
  import type { VNode } from "../render/vnode.ts";
10
+ import { sanitizeHref } from "../sanitize/href.ts";
5
11
 
6
12
  /** Normalized post fields for server-side theme binding (framework-free). */
7
13
  export type ThemePostFields = {
@@ -18,6 +24,11 @@ export type ThemePostFields = {
18
24
  /** ISO date or a display string from the post. */
19
25
  publishedAt?: string;
20
26
  authorName?: string;
27
+ /**
28
+ * The entry's other plain fields (text, numbers, true/false) by field name, for data bindings
29
+ * (W-307): a Loop over a Team collection binds a heading to `role`.
30
+ */
31
+ fields?: Readonly<Record<string, string | number | boolean>>;
21
32
  };
22
33
 
23
34
  /** Data passed into `renderPage` when resolving Single Post / Archive / Loop Item. */
@@ -40,6 +51,18 @@ export type ThemeDynamicData = {
40
51
  pagination?: ArchivePagination;
41
52
  /** Set inside a Loop's item, where a Pagination would repeat once per post (W-228). */
42
53
  inLoopItem?: boolean;
54
+ /** What the host knows about the visitor, for visitor-aware elements (W-313). */
55
+ visitor?: VisitorInfo;
56
+ /** The visitor's arm per A/B test (W-312); hosts pick it on the server. */
57
+ abArms?: Readonly<Record<string, "a" | "b">>;
58
+ /** Entries for collection Loops (W-308), keyed by the Loop's node id. Hosts fill this. */
59
+ collections?: Readonly<Record<string, ThemePostFields[]>>;
60
+ /** Site settings bound fields can read (W-307), e.g. `title`, `tagline`, `url`. */
61
+ site?: Readonly<Record<string, string>>;
62
+ /** The request's URL parameters, first value per name (W-307). */
63
+ params?: Readonly<Record<string, string>>;
64
+ /** The page's own origin, e.g. `https://example.com`: URL-parameter links stay on it (W-307). */
65
+ origin?: string;
43
66
  };
44
67
 
45
68
  /** Editor canvas placeholders when no live post is bound. */
@@ -53,22 +76,93 @@ export const SAMPLE_POST: ThemePostFields = {
53
76
  featuredImageAlt: "Featured image",
54
77
  };
55
78
 
56
- const isRecord = (value: unknown): value is Record<string, unknown> =>
57
- Boolean(value) && typeof value === "object";
79
+ const BLOCK_STYLES = new Set(["normal", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote"]);
80
+ /** Portable Text decorators kept as their HTML element (W-328). */
81
+ const DECORATORS: Record<string, string> = {
82
+ strong: "strong",
83
+ em: "em",
84
+ code: "code",
85
+ underline: "u",
86
+ "strike-through": "s",
87
+ };
88
+ const MAX_LIST_DEPTH = 6;
58
89
 
59
- const spanText = (children: unknown) =>
60
- Array.isArray(children)
61
- ? children
62
- .filter(isRecord)
63
- .map((span) => (typeof span["text"] === "string" ? span["text"] : ""))
64
- .join("")
65
- : "";
90
+ /** The links a block defines (`markDefs`), by key, with hrefs that pass the link check. */
91
+ function linkDefs(block: Record<string, unknown>): Map<string, string> {
92
+ const links = new Map<string, string>();
93
+ const defs = Array.isArray(block["markDefs"]) ? block["markDefs"] : [];
94
+ for (const def of defs) {
95
+ if (!isRecord(def) || def["_type"] !== "link" || typeof def["_key"] !== "string") continue;
96
+ const href = typeof def["href"] === "string" ? sanitizeHref(def["href"]) : undefined;
97
+ if (href) links.set(def["_key"], href);
98
+ }
99
+ return links;
100
+ }
66
101
 
67
- const HEADING_STYLES = new Set(["h1", "h2", "h3", "h4"]);
102
+ /** A span's text wrapped in its marks; unknown marks and unsafe links leave plain text. */
103
+ function spanNode(
104
+ span: Record<string, unknown>,
105
+ links: Map<string, string>,
106
+ ): VNode | string | null {
107
+ const text = typeof span["text"] === "string" ? span["text"] : "";
108
+ if (!text) return null;
109
+ const marks = Array.isArray(span["marks"])
110
+ ? span["marks"].filter((m) => typeof m === "string")
111
+ : [];
112
+ let node: VNode | string = text;
113
+ for (const mark of marks.toReversed()) {
114
+ const tag = DECORATORS[mark];
115
+ if (tag) node = { tag, attrs: {}, children: [node] };
116
+ else {
117
+ const href = links.get(mark);
118
+ if (href) node = { tag: "a", attrs: { href }, children: [node] };
119
+ }
120
+ }
121
+ return node;
122
+ }
123
+
124
+ /** A block's spans, with line breaks kept as `<br>`. */
125
+ function inlineNodes(block: Record<string, unknown>): (VNode | string)[] {
126
+ const links = linkDefs(block);
127
+ const children = Array.isArray(block["children"]) ? block["children"] : [];
128
+ const out: (VNode | string)[] = [];
129
+ for (const child of children) {
130
+ if (!isRecord(child) || (child["_type"] !== undefined && child["_type"] !== "span")) continue;
131
+ const node = spanNode(child, links);
132
+ if (node === null) continue;
133
+ if (typeof node === "string" && node.includes("\n")) {
134
+ node.split("\n").forEach((part, i) => {
135
+ if (i > 0) out.push({ tag: "br", attrs: {}, children: [] });
136
+ if (part) out.push(part);
137
+ });
138
+ } else out.push(node);
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /** Adjacent text joined, and the block's outer whitespace trimmed, as before W-328. */
144
+ function tidy(nodes: (VNode | string)[]): (VNode | string)[] {
145
+ const out: (VNode | string)[] = [];
146
+ for (const node of nodes) {
147
+ const last = out.at(-1);
148
+ if (typeof node === "string" && typeof last === "string") out[out.length - 1] = last + node;
149
+ else out.push(node);
150
+ }
151
+ const first = out[0];
152
+ if (typeof first === "string") out[0] = first.trimStart();
153
+ const end = out.at(-1);
154
+ if (typeof end === "string") out[out.length - 1] = end.trimEnd();
155
+ return out.filter((node) => node !== "");
156
+ }
157
+
158
+ const hasText = (nodes: readonly (VNode | string)[]): boolean =>
159
+ nodes.some((n) => (typeof n === "string" ? n.trim() !== "" : hasText(n.children)));
68
160
 
69
161
  /**
70
- * Convert Portable Text (or a plain string) into safe VNodes.
71
- * Marks are flattened to escaped text; only block structure is preserved.
162
+ * Convert Portable Text (or a plain string) into safe VNodes (W-328). Kept: paragraphs, headings
163
+ * (h1–h6), block quotes, bulleted and numbered lists (nested by level), bold, italic, code,
164
+ * underline, strike-through and links whose href passes the link check. Everything else (custom
165
+ * blocks, images, embeds, raw HTML) is left out; text is always escaped by the serializer.
72
166
  */
73
167
  export function portableTextToVNodes(value: unknown): VNode[] {
74
168
  if (typeof value === "string") {
@@ -76,33 +170,152 @@ export function portableTextToVNodes(value: unknown): VNode[] {
76
170
  return trimmed ? [{ tag: "p", attrs: {}, children: [trimmed] }] : [];
77
171
  }
78
172
  if (!Array.isArray(value)) return [];
79
- return value.flatMap((block): VNode[] => {
80
- if (!isRecord(block) || block["_type"] !== "block") return [];
81
- const text = spanText(block["children"]).trim();
82
- if (!text) return [];
83
- const style = block["style"];
84
- const tag = typeof style === "string" && HEADING_STYLES.has(style) ? style : "p";
85
- return [{ tag, attrs: {}, children: [text] }];
86
- });
173
+ const out: VNode[] = [];
174
+ // The open lists, outermost first, while consecutive list items continue them.
175
+ let lists: VNode[] = [];
176
+ for (const block of value) {
177
+ if (!isRecord(block) || block["_type"] !== "block") {
178
+ lists = [];
179
+ continue;
180
+ }
181
+ const inline = tidy(inlineNodes(block));
182
+ const listItem = block["listItem"];
183
+ if (listItem === "bullet" || listItem === "number") {
184
+ const tag = listItem === "number" ? "ol" : "ul";
185
+ const rawLevel = typeof block["level"] === "number" ? Math.floor(block["level"]) : 1;
186
+ const level = Math.min(Math.max(rawLevel, 1), MAX_LIST_DEPTH);
187
+ lists = lists.slice(0, level);
188
+ if (lists.length === level && lists[level - 1]?.tag !== tag)
189
+ lists = lists.slice(0, level - 1);
190
+ while (lists.length < level) {
191
+ const list: VNode = { tag, attrs: {}, children: [] };
192
+ const parent = lists.at(-1);
193
+ if (parent) {
194
+ const lastItem = parent.children.at(-1);
195
+ if (lastItem && typeof lastItem !== "string") lastItem.children.push(list);
196
+ else parent.children.push({ tag: "li", attrs: {}, children: [list] });
197
+ } else out.push(list);
198
+ lists.push(list);
199
+ }
200
+ if (hasText(inline))
201
+ lists[level - 1]?.children.push({ tag: "li", attrs: {}, children: inline });
202
+ continue;
203
+ }
204
+ lists = [];
205
+ if (!hasText(inline)) continue;
206
+ const style =
207
+ typeof block["style"] === "string" && BLOCK_STYLES.has(block["style"])
208
+ ? block["style"]
209
+ : "normal";
210
+ const tag = style === "normal" ? "p" : style;
211
+ out.push({ tag, attrs: {}, children: inline });
212
+ }
213
+ return out.filter((node) =>
214
+ node.tag !== "ul" && node.tag !== "ol" ? true : node.children.length > 0,
215
+ );
87
216
  }
88
217
 
89
218
  /** Collect `loop.itemPartId` values so hosts can load Loop Item templates. */
90
219
  export function collectLoopItemPartIds(layout: Layout): string[] {
91
220
  const ids = new Set<string>();
92
- const walk = (node: LayoutNode): void => {
93
- if (node.type === "loop") {
221
+ forEachNode(
222
+ layout.root,
223
+ (node) => {
224
+ if (node.type !== "loop") return;
94
225
  const id =
95
226
  typeof (node.props as { itemPartId?: unknown }).itemPartId === "string"
96
227
  ? (node.props as { itemPartId: string }).itemPartId.trim()
97
228
  : "";
98
229
  if (id) ids.add(id);
99
- }
100
- if (isParentNode(node)) {
101
- for (const child of node.children) walk(child);
230
+ },
231
+ knownChildren,
232
+ );
233
+ return [...ids];
234
+ }
235
+
236
+ /** A Loop that lists a collection (W-308): what hosts fetch for it. */
237
+ export type CollectionLoop = {
238
+ nodeId: string;
239
+ collection: string;
240
+ limit: number;
241
+ order: "newest" | "oldest" | "title";
242
+ /** W-330: where entries link, the image and excerpt fields, and `field = value` filters. */
243
+ permalink?: string;
244
+ imageField?: string;
245
+ excerptField?: string;
246
+ where?: Record<string, string | string[]>;
247
+ };
248
+
249
+ const MAX_LOOP_FILTERS = 5;
250
+
251
+ /**
252
+ * `category=news; team=design` → `{ category: "news", team: "design" }` (W-330); the same field
253
+ * twice becomes a list (either value). At most 5 pairs; anything malformed is left out.
254
+ */
255
+ export function parseLoopFilter(text: unknown): Record<string, string | string[]> | undefined {
256
+ if (typeof text !== "string" || !LOOP_FILTER.test(text)) return undefined;
257
+ const where: Record<string, string | string[]> = {};
258
+ let count = 0;
259
+ for (const pair of text.split(";")) {
260
+ const at = pair.indexOf("=");
261
+ if (at < 0) continue;
262
+ const field = pair.slice(0, at).trim();
263
+ const value = pair.slice(at + 1).trim();
264
+ if (!field || !value || count >= MAX_LOOP_FILTERS) continue;
265
+ count += 1;
266
+ const had = where[field];
267
+ where[field] = had === undefined ? value : [...(Array.isArray(had) ? had : [had]), value];
268
+ }
269
+ return count > 0 ? where : undefined;
270
+ }
271
+
272
+ /** An entry's link from a Loop's pattern (W-330): `{slug}` and `{id}` filled in, URL-encoded. */
273
+ export function loopPermalink(pattern: string, entry: { slug: string; id: string }): string {
274
+ return pattern
275
+ .replaceAll("{slug}", encodeURIComponent(entry.slug))
276
+ .replaceAll("{id}", encodeURIComponent(entry.id));
277
+ }
278
+
279
+ /** Every collection Loop in a layout, so hosts can fetch their entries (W-308). */
280
+ export function collectCollectionLoops(layout: Layout): CollectionLoop[] {
281
+ const loops: CollectionLoop[] = [];
282
+ const walk = (node: LayoutNode): void => {
283
+ if (node.type === "loop" && loops.length < 20) {
284
+ const props = node.props as {
285
+ collection?: unknown;
286
+ limit?: unknown;
287
+ order?: unknown;
288
+ permalink?: unknown;
289
+ imageField?: unknown;
290
+ excerptField?: unknown;
291
+ filter?: unknown;
292
+ };
293
+ if (typeof props.collection === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(props.collection)) {
294
+ const limit =
295
+ typeof props.limit === "number" && props.limit >= 1 && props.limit <= 50
296
+ ? Math.floor(props.limit)
297
+ : 6;
298
+ const order = props.order === "oldest" || props.order === "title" ? props.order : "newest";
299
+ const loop: CollectionLoop = {
300
+ nodeId: node.id,
301
+ collection: props.collection,
302
+ limit,
303
+ order,
304
+ };
305
+ if (typeof props.permalink === "string" && LOOP_PERMALINK.test(props.permalink))
306
+ loop.permalink = props.permalink;
307
+ if (typeof props.imageField === "string" && FIELD_SLUG.test(props.imageField))
308
+ loop.imageField = props.imageField;
309
+ if (typeof props.excerptField === "string" && FIELD_SLUG.test(props.excerptField))
310
+ loop.excerptField = props.excerptField;
311
+ const where = parseLoopFilter(props.filter);
312
+ if (where) loop.where = where;
313
+ loops.push(loop);
314
+ }
102
315
  }
103
316
  };
104
- walk(layout.root);
105
- return [...ids];
317
+ forEachNode(layout.root, walk, knownChildren);
318
+ return loops;
106
319
  }
107
320
 
108
321
  /** Collect `section.partId` values so hosts can load Section templates. */
@@ -116,11 +329,8 @@ export function collectSectionPartIds(layout: Layout): string[] {
116
329
  : "";
117
330
  if (id) ids.add(id);
118
331
  }
119
- if (isParentNode(node)) {
120
- for (const child of node.children) walk(child);
121
- }
122
332
  };
123
- walk(layout.root);
333
+ forEachNode(layout.root, walk, knownChildren);
124
334
  return [...ids];
125
335
  }
126
336
 
@@ -100,7 +100,7 @@ export function wrapFloatMarkup(
100
100
  ): string {
101
101
  const safeId = escapeAttr(id);
102
102
  const label = escapeAttr(title.trim() || "Notice");
103
- const edge = settings.edge;
103
+ const edge = escapeAttr(settings.edge);
104
104
  const close = settings.dismiss
105
105
  ? `<button type="button" class="emvb-float__close" data-emvb-float-dismiss aria-label="Close"><span aria-hidden="true">×</span></button>`
106
106
  : "";
@@ -13,8 +13,40 @@ export type ArchivePagination = {
13
13
  hasMore: boolean;
14
14
  /** The archive's own path without `/page/N`, e.g. `/posts` or `/category/news`. */
15
15
  basePath: string;
16
+ /**
17
+ * How many pages there are, when the host knows (W-309). EmDash 1.2's public collection query
18
+ * gives no total, so its hosts leave this out and "Page N of M" shows "Page N".
19
+ */
20
+ totalPages?: number;
16
21
  };
17
22
 
23
+ /** A usable total page count, or undefined (W-309). */
24
+ function knownTotal(p: ArchivePagination): number | undefined {
25
+ const total = p.totalPages;
26
+ return typeof total === "number" && Number.isInteger(total) && total >= p.page && total >= 1
27
+ ? Math.min(total, MAX_ARCHIVE_PAGE)
28
+ : undefined;
29
+ }
30
+
31
+ /**
32
+ * The "Page N of M" text (W-309). `{page}` and `{total}` are filled in; without a known total
33
+ * the text stops before ` of {total}` (or drops `{total}`), so it never shows a wrong count.
34
+ */
35
+ export function pageCountText(p: ArchivePagination, template: string | undefined): string {
36
+ const text = template?.trim() || "Page {page} of {total}";
37
+ const total = knownTotal(p);
38
+ if (total !== undefined) {
39
+ return text.replaceAll("{page}", String(p.page)).replaceAll("{total}", String(total));
40
+ }
41
+ const cut = text.indexOf("{total}");
42
+ const before =
43
+ cut === -1
44
+ ? text
45
+ : text.slice(0, cut).replace(/\s*(of|\/|from|sur|de|von|di|van|из)?\s*$/i, "");
46
+ // A template that starts with {total} ("{total} pages · page {page}") keeps at least the number.
47
+ return before.replaceAll("{page}", String(p.page)).trim() || String(p.page);
48
+ }
49
+
18
50
  /** The URL path of page `n` of an archive; page 1 is the bare archive path (W-221). */
19
51
  export function archivePagePath(basePath: string, n: number): string {
20
52
  const base = basePath.replace(/\/+$/, "") || "/";
@@ -76,6 +108,8 @@ export type PaginationItem =
76
108
  * with a gap after 1 when the current page is far in (W-222).
77
109
  */
78
110
  export function paginationItems(p: ArchivePagination): PaginationItem[] {
111
+ const total = knownTotal(p);
112
+ if (total !== undefined) return totalItems(p, total);
79
113
  if (p.page <= 1 && !p.hasMore) return [];
80
114
  const items: PaginationItem[] = [];
81
115
  const page = (n: number): PaginationItem => ({
@@ -95,3 +129,25 @@ export function paginationItems(p: ArchivePagination): PaginationItem[] {
95
129
  }
96
130
  return items;
97
131
  }
132
+
133
+ /** With a known total (W-309): 1, a window around the current page, and the last page. */
134
+ function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
135
+ if (total <= 1) return [];
136
+ const items: PaginationItem[] = [];
137
+ const page = (n: number): PaginationItem => ({
138
+ kind: "page",
139
+ n,
140
+ href: archivePagePath(p.basePath, n),
141
+ current: n === p.page,
142
+ });
143
+ if (p.page > 1) items.push({ kind: "prev", href: archivePagePath(p.basePath, p.page - 1) });
144
+ const from = Math.max(1, p.page - 2);
145
+ const to = Math.min(total, p.page + 2);
146
+ if (from > 1) items.push(page(1));
147
+ if (from > 2) items.push({ kind: "gap" });
148
+ for (let n = from; n <= to; n++) items.push(page(n));
149
+ if (to < total - 1) items.push({ kind: "gap" });
150
+ if (to < total) items.push(page(total));
151
+ if (p.page < total) items.push({ kind: "next", href: archivePagePath(p.basePath, p.page + 1) });
152
+ return items;
153
+ }
@@ -14,6 +14,63 @@ export const nodeChildren = (node: LayoutNode): LayoutNode[] => {
14
14
  return [];
15
15
  };
16
16
 
17
+ /** Children of a known parent only. Unknown nodes are not descended into (W-353). */
18
+ export const knownChildren = (node: LayoutNode): readonly LayoutNode[] =>
19
+ isParentNode(node) ? node.children : [];
20
+
21
+ /** Visit `node` and every node under it. Pass `knownChildren` to skip unknown nodes. */
22
+ export function forEachNode(
23
+ node: LayoutNode,
24
+ visit: (node: LayoutNode) => void,
25
+ children: (node: LayoutNode) => readonly LayoutNode[] = nodeChildren,
26
+ ): void {
27
+ visit(node);
28
+ for (const child of children(node)) forEachNode(child, visit, children);
29
+ }
30
+
31
+ /** True when `test` matches `node` or anything under it. Same descent choice as `forEachNode`. */
32
+ export function someNode(
33
+ node: LayoutNode,
34
+ test: (node: LayoutNode) => boolean,
35
+ children: (node: LayoutNode) => readonly LayoutNode[] = nodeChildren,
36
+ ): boolean {
37
+ return test(node) || children(node).some((child) => someNode(child, test, children));
38
+ }
39
+
40
+ export type LayoutIndex = {
41
+ byId: Map<string, LayoutNode>;
42
+ /** Parent id for a node under a container or form. A child of an unknown node has none. */
43
+ parentOf: Map<string, string>;
44
+ };
45
+
46
+ const indexes = new WeakMap<Layout, LayoutIndex>();
47
+
48
+ /**
49
+ * One walk for later id and parent lookups. The same layout object keeps the result, so a render
50
+ * that asks many times walks once. A page stays within 2000 elements and 24 levels.
51
+ */
52
+ export function indexLayout(layout: Layout): LayoutIndex {
53
+ const cached = indexes.get(layout);
54
+ if (cached) return cached;
55
+ const byId = new Map<string, LayoutNode>();
56
+ const parents = new Map<string, string>();
57
+ const seen = new Set<LayoutNode>();
58
+ const walk = (node: LayoutNode, parentId: string | undefined) => {
59
+ if (seen.has(node)) return;
60
+ seen.add(node);
61
+ if (!byId.has(node.id)) {
62
+ byId.set(node.id, node);
63
+ if (parentId) parents.set(node.id, parentId);
64
+ }
65
+ const nextParent = isParentNode(node) ? node.id : undefined;
66
+ for (const child of nodeChildren(node)) walk(child, nextParent);
67
+ };
68
+ walk(layout.root, undefined);
69
+ const index: LayoutIndex = { byId, parentOf: parents };
70
+ indexes.set(layout, index);
71
+ return index;
72
+ }
73
+
17
74
  /** Where a removed node was, so it can be put back exactly (the Restore toast, D-025). */
18
75
  export type Removed = { node: LayoutNode; parentId: string; index: number };
19
76
 
package/src/index.ts CHANGED
@@ -1,16 +1,28 @@
1
1
  import type { PluginDescriptor } from "emdash";
2
2
  import { ADMIN_ENTRY, PACKAGE_NAME, PLUGIN_ID, PLUGIN_VERSION } from "./constants.ts";
3
+ import { canvasStyleUrls } from "./core/canvas-styles.ts";
3
4
  import { createPlugin } from "./server/plugin.ts";
4
5
 
6
+ /** Options a host site passes to `emvb()` in astro.config. */
7
+ export type EmVBOptions = {
8
+ /**
9
+ * Stylesheets the editor canvas loads before EmVB's CSS (W-327): the site's fonts and base
10
+ * styles, so pages look in the editor as on the site. `https:` URLs or site paths
11
+ * (`/styles/site.css`); anything else is ignored.
12
+ */
13
+ canvasStyles?: string[];
14
+ };
15
+
5
16
  /** Descriptor that host sites add to `emdash({ plugins: [...] })` in astro.config. */
6
- export function emvb(): PluginDescriptor {
17
+ export function emvb(options: EmVBOptions = {}): PluginDescriptor {
18
+ const canvasStyles = canvasStyleUrls(options.canvasStyles);
7
19
  return {
8
20
  id: PLUGIN_ID,
9
21
  version: PLUGIN_VERSION,
10
22
  format: "native",
11
23
  entrypoint: PACKAGE_NAME,
12
24
  adminEntry: ADMIN_ENTRY,
13
- options: {},
25
+ options: canvasStyles.length > 0 ? { canvasStyles } : {},
14
26
  };
15
27
  }
16
28
 
@@ -49,15 +49,18 @@ export const designDraftRoute: PluginRoute = {
49
49
  const published = await readDesign(ctx, DESIGN_KEY);
50
50
  const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
51
51
  if (draft.status !== "ok") {
52
+ const revision = draft.revision;
52
53
  return {
53
54
  design: published.design,
54
- revision: null,
55
+ published: published.design,
56
+ revision,
55
57
  publishedRevision: published.revision,
56
58
  unpublished: false,
57
59
  };
58
60
  }
59
61
  return {
60
62
  design: draft.design,
63
+ published: published.design,
61
64
  revision: draft.revision,
62
65
  publishedRevision: published.revision,
63
66
  unpublished: JSON.stringify(draft.design) !== JSON.stringify(published.design),
@@ -2,6 +2,8 @@ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
2
  import { z } from "zod";
3
3
  import {
4
4
  prepareUploadedSvg,
5
+ sanitizeSvgMarkup,
6
+ serialize,
5
7
  UPLOAD_SVG_MAX_BYTES,
6
8
  type UploadedIcon,
7
9
  type UploadedIconItem,
@@ -15,7 +17,9 @@ import {
15
17
  */
16
18
 
17
19
  type IconStore = {
20
+ get(id: string): Promise<UploadedIcon | null>;
18
21
  put(id: string, data: UploadedIcon): Promise<void>;
22
+ delete(id: string): Promise<boolean>;
19
23
  query(options?: {
20
24
  orderBy?: Record<string, "asc" | "desc">;
21
25
  limit?: number;
@@ -27,7 +31,31 @@ const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as
27
31
  /** The most recent uploads the picker lists. */
28
32
  const UPLOAD_LIST_LIMIT = 100;
29
33
 
30
- /** Editors and above: the uploaded icons, newest first. */
34
+ /** A file name without its folder or extension, as the icon's label. */
35
+ export const uploadName = (name: string) =>
36
+ name
37
+ .replace(/^.*[\\/]/, "")
38
+ .replace(/\.svg$/i, "")
39
+ .trim()
40
+ .slice(0, 80) || "Uploaded icon";
41
+
42
+ /**
43
+ * One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
44
+ * is left out, so a row written past the upload route cannot carry a script into the picker.
45
+ */
46
+ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIconItem | undefined {
47
+ if (typeof data.svg !== "string") return undefined;
48
+ const tree = sanitizeSvgMarkup(data.svg);
49
+ if (!tree) return undefined;
50
+ return {
51
+ id,
52
+ name: uploadName(typeof data.name === "string" ? data.name : ""),
53
+ svg: serialize(tree),
54
+ uploadedAt: typeof data.uploadedAt === "string" ? data.uploadedAt : "",
55
+ };
56
+ }
57
+
58
+ /** Editors and above: the uploaded icons, newest first. A row that fails the allowlist is omitted. */
31
59
  export const iconsRoute: PluginRoute = {
32
60
  permission: "content:edit_any",
33
61
  handler: async (ctx) => {
@@ -35,25 +63,14 @@ export const iconsRoute: PluginRoute = {
35
63
  orderBy: { uploadedAt: "desc" },
36
64
  limit: UPLOAD_LIST_LIMIT,
37
65
  });
38
- // Only the known fields, whatever else a stored row might carry.
39
- const items: UploadedIconItem[] = page.items.map(({ id, data }) => ({
40
- id,
41
- name: data.name,
42
- svg: data.svg,
43
- uploadedAt: data.uploadedAt,
44
- }));
66
+ const items = page.items.flatMap(({ id, data }) => {
67
+ const item = publicUploadedIcon(id, data);
68
+ return item ? [item] : [];
69
+ });
45
70
  return { items };
46
71
  },
47
72
  };
48
73
 
49
- /** A file name without its folder or extension, as the icon's label. */
50
- export const uploadName = (name: string) =>
51
- name
52
- .replace(/^.*[\\/]/, "")
53
- .replace(/\.svg$/i, "")
54
- .trim()
55
- .slice(0, 80) || "Uploaded icon";
56
-
57
74
  const UploadInput = z.object({
58
75
  name: z.string().max(255),
59
76
  // A JSON string: the file plus escaping room is still bounded by the route body limit.
@@ -77,3 +94,38 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
77
94
  return { item: { id, ...item }, imagesLeftOut: prepared.imagesLeftOut };
78
95
  },
79
96
  };
97
+
98
+ const IdInput = z.object({
99
+ id: z.string().regex(/^[0-9a-f]{16}$/, "Unknown icon"),
100
+ });
101
+
102
+ const RenameInput = IdInput.extend({
103
+ name: z.string().min(1).max(255),
104
+ });
105
+
106
+ /** Editors and above. Renames an upload. Pages keep the SVG they already stored. */
107
+ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
108
+ permission: "content:edit_any",
109
+ input: RenameInput,
110
+ handler: async (ctx) => {
111
+ const current = await store(ctx).get(ctx.input.id);
112
+ if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
113
+ const name = uploadName(ctx.input.name);
114
+ await store(ctx).put(ctx.input.id, { ...current, name });
115
+ return { item: { id: ctx.input.id, ...current, name } };
116
+ },
117
+ };
118
+
119
+ /**
120
+ * Editors and above. Removes an upload from My uploads. Icons already placed on a page keep
121
+ * their own copy of the SVG, so those pages do not change.
122
+ */
123
+ export const iconDeleteRoute: PluginRoute<z.infer<typeof IdInput>> = {
124
+ permission: "content:edit_any",
125
+ input: IdInput,
126
+ handler: async (ctx) => {
127
+ const removed = await store(ctx).delete(ctx.input.id);
128
+ if (!removed) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
129
+ return { id: ctx.input.id };
130
+ },
131
+ };