@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
@@ -0,0 +1,127 @@
1
+ import { MAX_NODES, MAX_TEXT_LENGTH } from "./limits.ts";
2
+ import { LAYOUT_SCHEMA_VERSION, type Layout, type LayoutNode } from "./schema/layout.ts";
3
+ import { sanitizeUrl } from "./sanitize/url.ts";
4
+ import { newNodeId } from "./tree-ops.ts";
5
+ import { validateLayout } from "./validate.ts";
6
+
7
+ const IMAGE_SCHEMES: ReadonlySet<string> = new Set(["https:", "http:"]);
8
+ const LIST_ITEMS_MAX = 200;
9
+ const MEDIA_ID = /^[A-Za-z0-9_-]{1,128}$/;
10
+
11
+ type Record_ = Record<string, unknown>;
12
+ const isRecord = (value: unknown): value is Record_ =>
13
+ typeof value === "object" && value !== null && !Array.isArray(value);
14
+
15
+ /** A block's plain text: its spans' text joined. Marks and links are dropped (starter layout). */
16
+ function blockText(block: Record_): string {
17
+ const children = Array.isArray(block["children"]) ? block["children"] : [];
18
+ let text = "";
19
+ for (const child of children) {
20
+ if (isRecord(child) && typeof child["text"] === "string") text += child["text"];
21
+ }
22
+ return text.trim().slice(0, MAX_TEXT_LENGTH);
23
+ }
24
+
25
+ function imageNode(block: Record_, id: string): LayoutNode | null {
26
+ const asset = isRecord(block["asset"]) ? block["asset"] : {};
27
+ const raw = typeof asset["url"] === "string" ? asset["url"] : block["url"];
28
+ const src = typeof raw === "string" ? sanitizeUrl(raw, IMAGE_SCHEMES) : undefined;
29
+ if (!src) return null;
30
+ const alt = typeof block["alt"] === "string" ? block["alt"].trim().slice(0, 500) : "";
31
+ const ref = asset["_ref"] ?? asset["id"];
32
+ const props: Record_ = { src, alt, ...(alt ? {} : { decorative: true }) };
33
+ if (typeof ref === "string" && MEDIA_ID.test(ref)) props["mediaId"] = ref;
34
+ for (const key of ["width", "height"] as const) {
35
+ const value = block[key];
36
+ if (typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 10000)
37
+ props[key] = value;
38
+ }
39
+ return { id, type: "image", props } as LayoutNode;
40
+ }
41
+
42
+ /**
43
+ * W-912: a starter EmVB layout from an entry's Portable Text body. Headings, paragraphs, quotes,
44
+ * bullet/numbered lists and images with a safe URL come across as plain elements; everything else
45
+ * (custom blocks, marks, embeds) is left out and counted. The body is untrusted: only strings are
46
+ * copied, URLs go through the shared URL check, and the result is validated like any saved layout.
47
+ */
48
+ export function portableTextToLayout(
49
+ body: unknown,
50
+ title = "",
51
+ random?: () => number,
52
+ ): { layout: Layout; converted: number; skipped: number } | null {
53
+ if (!Array.isArray(body)) return null;
54
+ const used = new Set<string>();
55
+ const id = () => {
56
+ let next = newNodeId(random);
57
+ while (used.has(next)) next = newNodeId(random);
58
+ used.add(next);
59
+ return next;
60
+ };
61
+ const children: LayoutNode[] = [];
62
+ let skipped = 0;
63
+ let list: { ordered: boolean; items: string[] } | null = null;
64
+ const flush = () => {
65
+ if (list && list.items.length > 0)
66
+ children.push({ id: id(), type: "list", props: { ...list } } as LayoutNode);
67
+ list = null;
68
+ };
69
+ const heading = title.trim().slice(0, MAX_TEXT_LENGTH);
70
+ if (heading) children.push({ id: id(), type: "heading", props: { text: heading, level: 1 } });
71
+ for (const block of body) {
72
+ if (children.length >= MAX_NODES - 2) {
73
+ skipped++;
74
+ continue;
75
+ }
76
+ if (!isRecord(block)) {
77
+ skipped++;
78
+ continue;
79
+ }
80
+ if (block["_type"] === "image") {
81
+ flush();
82
+ const node = imageNode(block, id());
83
+ if (node) children.push(node);
84
+ else skipped++;
85
+ continue;
86
+ }
87
+ if (block["_type"] !== "block") {
88
+ flush();
89
+ skipped++;
90
+ continue;
91
+ }
92
+ const text = blockText(block);
93
+ const listItem = block["listItem"];
94
+ if (listItem === "bullet" || listItem === "number") {
95
+ const ordered = listItem === "number";
96
+ if (list && list.ordered !== ordered) flush();
97
+ list ??= { ordered, items: [] };
98
+ if (text && list.items.length < LIST_ITEMS_MAX) list.items.push(text);
99
+ else if (text) skipped++;
100
+ continue;
101
+ }
102
+ flush();
103
+ if (!text) continue;
104
+ const style = typeof block["style"] === "string" ? block["style"] : "normal";
105
+ const level = /^h([1-6])$/.exec(style);
106
+ children.push(
107
+ level
108
+ ? { id: id(), type: "heading", props: { text, level: Number(level[1]) } }
109
+ : { id: id(), type: "text", props: { text } },
110
+ );
111
+ }
112
+ flush();
113
+ const candidate = {
114
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
115
+ root: {
116
+ id: id(),
117
+ type: "container",
118
+ props: {},
119
+ style: { flexDirection: "column", gap: { value: 16, unit: "px" } },
120
+ children,
121
+ },
122
+ };
123
+ const checked = validateLayout(candidate);
124
+ if (!checked.ok) return null;
125
+ const converted = children.length - (heading ? 1 : 0);
126
+ return { layout: checked.layout, converted, skipped };
127
+ }
@@ -94,7 +94,7 @@ export function renderLoop(
94
94
  attrs: { ...attrs, "data-emvb-loop-empty": "" },
95
95
  children: [
96
96
  ...ctx.children(emptyNodes, rest),
97
- "Choose a Loop Item, or add elements here to design the item.",
97
+ "Choose a Loop item, or add elements here to design the item.",
98
98
  ],
99
99
  };
100
100
  }
@@ -1,6 +1,11 @@
1
1
  import type { PaginationNode } from "../schema/layout.ts";
2
2
  import type { ThemeDynamicData } from "../theme/dynamic.ts";
3
- import { pageCountText, paginationItems, type ArchivePagination } from "../theme/pagination.ts";
3
+ import {
4
+ lastPagePath,
5
+ pageCountText,
6
+ paginationItems,
7
+ type ArchivePagination,
8
+ } from "../theme/pagination.ts";
4
9
  import type { VNode } from "./vnode.ts";
5
10
 
6
11
  /** What the editor canvas shows: page 2 of several, links going nowhere (W-222). */
@@ -101,6 +106,20 @@ export function renderPagination(
101
106
  };
102
107
  }
103
108
  });
109
+ // W-916: the editor sample has no total, so its Last link goes nowhere like the others.
110
+ const last = editor ? "#" : lastPagePath(data);
111
+ if (node.props.showLast && last) {
112
+ const text = label(node.props.lastText, "Last");
113
+ children.push({
114
+ tag: "a",
115
+ attrs: {
116
+ class: "emvb-pagination-last",
117
+ href: last,
118
+ ...nameIfSymbols(text, label(node.props.lastLabel, "Last page")),
119
+ },
120
+ children: [text],
121
+ });
122
+ }
104
123
  if (node.props.showCount) {
105
124
  // W-309: "Page N of M", or "Page N" while the host has no total.
106
125
  children.unshift({
@@ -24,6 +24,7 @@ import type { StyleProps } from "../schema/style.ts";
24
24
  import { sanitizeMediaUrl } from "./media-url.ts";
25
25
  import { motionDeclarations, withMotion } from "./motion.ts";
26
26
  import { isRecord } from "../record.ts";
27
+ import { iconAnimationRuns } from "../icons/animation-runs.ts";
27
28
 
28
29
  const setOf = (values: readonly string[]) => new Set<string>(values);
29
30
  const VAR_ID = /^[a-z0-9-]{1,40}$/;
@@ -379,20 +380,27 @@ function cssIconShadow(value: unknown): string | undefined {
379
380
  }
380
381
 
381
382
  const ICON_ANIMATIONS: Readonly<Record<string, string>> = {
382
- spin: "emvb-icon-spin {ms} linear infinite",
383
- pulse: "emvb-icon-pulse {ms} ease-in-out infinite alternate",
383
+ spin: "emvb-icon-spin {ms} linear {runs}",
384
+ pulse: "emvb-icon-pulse {ms} ease-in-out {runs} alternate",
384
385
  };
385
386
 
386
- /** W-237: a looping spin or pulse; the Icon's base CSS turns it off for reduced motion. */
387
+ /**
388
+ * W-237: a spin or pulse; the Icon's base CSS turns it off for reduced motion. W-848: it repeats
389
+ * only for about 5 seconds (`iconAnimationRuns`), unless it loops forever (W-853).
390
+ */
387
391
  function cssIconAnimation(value: unknown): string | undefined {
388
392
  if (!isRecord(value)) return undefined;
389
- if (Object.keys(value).some((key) => key !== "type" && key !== "duration")) return undefined;
390
- const { type, duration } = value;
393
+ if (Object.keys(value).some((key) => key !== "type" && key !== "duration" && key !== "loop"))
394
+ return undefined;
395
+ const { type, duration, loop } = value;
396
+ if (loop !== undefined && (loop !== true || type === "none")) return undefined;
391
397
  // W-248: stops an animation inherited from a wider device.
392
398
  if (type === "none") return duration === undefined ? "none" : undefined;
393
399
  if (typeof type !== "string" || !Object.hasOwn(ICON_ANIMATIONS, type)) return undefined;
394
400
  if (!Number.isInteger(duration) || !inRangeNumber(duration, 200, 10_000)) return undefined;
395
- return ICON_ANIMATIONS[type]?.replace("{ms}", `${duration}ms`);
401
+ // W-853 (D-059): Loop forever keeps a spinner going, as before W-848.
402
+ const runs = loop ? "infinite" : iconAnimationRuns(type === "spin" ? "spin" : "pulse", duration);
403
+ return ICON_ANIMATIONS[type]?.replace("{ms}", `${duration}ms`).replace("{runs}", String(runs));
396
404
  }
397
405
 
398
406
  export type Declaration = { property: string; value: string };
@@ -0,0 +1,318 @@
1
+ import { addSectionNear, REASONS, withFreshIds, type Added, type Refusal } from "./arrange.ts";
2
+ import { prepareElement, prepareStyle, type Dropped } from "./clipboard.ts";
3
+ import { cleanClassName, MAX_CLASSES, nameKey } from "./design/classes.ts";
4
+ import { clipText, MAX_LAYOUT_BYTES } from "./limits.ts";
5
+ import { isRecord } from "./record.ts";
6
+ import { DESIGN_SCHEMA_VERSION, type DesignSystem } from "./schema/design.ts";
7
+ import { LAYOUT_SCHEMA_VERSION, type Layout, type LayoutNode } from "./schema/layout.ts";
8
+ import { findNode, newNodeId, nodeChildren, slugify } from "./tree-ops.ts";
9
+ import { byteLength, summarizeIssues, validateDesign, validateLayout } from "./validate.ts";
10
+
11
+ /**
12
+ * Saved sections (W-874, D-060): a named copy of an element and its children, kept per site so it
13
+ * can be inserted on any page. Each save carries a snapshot of the classes it uses, so it keeps
14
+ * its look on insert. Old saves are upgraded when read, through the same layout and design
15
+ * migrations as pages and site styles.
16
+ */
17
+ const SAVED_SECTION_VERSION = 1;
18
+ export const SAVED_SECTION_NAME_MAX = 60;
19
+ export const MAX_SAVED_SECTIONS = 200;
20
+
21
+ type StyleClass = NonNullable<DesignSystem["classes"]>[number];
22
+
23
+ /** What storage holds for one saved section. */
24
+ export type SavedSectionRecord = {
25
+ version: typeof SAVED_SECTION_VERSION;
26
+ name: string;
27
+ layout: Layout;
28
+ designSchemaVersion: number;
29
+ classes: StyleClass[];
30
+ createdAt: string;
31
+ updatedAt: string;
32
+ };
33
+
34
+ /** One saved section in a list (W-875). `damaged` rows can only be deleted. */
35
+ export type SavedSectionSummary = {
36
+ id: string;
37
+ name: string;
38
+ updatedAt: string;
39
+ classCount: number;
40
+ damaged?: true;
41
+ };
42
+
43
+ /** A saved section after it has been read, checked and upgraded. */
44
+ export type SavedSection = {
45
+ name: string;
46
+ node: LayoutNode;
47
+ classes: StyleClass[];
48
+ createdAt: string;
49
+ updatedAt: string;
50
+ };
51
+
52
+ export const SAVED_SECTION_REASONS = {
53
+ name: "Give the section a name.",
54
+ root: "Choose an element inside the page; the page itself can't be saved as a section.",
55
+ missing: REASONS.missing,
56
+ tooBig: "This section is too big to save.",
57
+ damaged: "This saved section can't be read.",
58
+ tooManyClasses: `Inserting this section would go over ${MAX_CLASSES} classes on this site.`,
59
+ } as const;
60
+
61
+ const refuse = (reason: string): Refusal => ({ ok: false, reason });
62
+ const WRAPPER_ID = "savedsection";
63
+
64
+ /** The name as stored: cleaned like a class name, at most 60 characters; "" when blank. */
65
+ export const savedSectionName = (raw: string): string =>
66
+ clipText(cleanClassName(raw), SAVED_SECTION_NAME_MAX).trim();
67
+
68
+ /** A copy without A/B test arms: a saved copy is never part of the original's test (as W-629). */
69
+ function withoutVariants(node: LayoutNode): LayoutNode {
70
+ const { variant: _variant, ...rest } = node as LayoutNode & { variant?: unknown };
71
+ const kids = nodeChildren(node);
72
+ if (kids.length === 0) return rest as LayoutNode;
73
+ return { ...rest, children: kids.map(withoutVariants) } as LayoutNode;
74
+ }
75
+
76
+ function classIdsIn(node: LayoutNode, into = new Set<string>()): Set<string> {
77
+ for (const id of node.classes ?? []) into.add(id);
78
+ for (const child of nodeChildren(node)) classIdsIn(child, into);
79
+ return into;
80
+ }
81
+
82
+ const wrap = (node: LayoutNode): Layout => ({
83
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
84
+ root: { id: WRAPPER_ID, type: "container", props: {}, children: [node] },
85
+ });
86
+
87
+ /** The record storage holds for a section that has been read (an old save comes back upgraded). */
88
+ export const savedSectionRecord = (section: SavedSection): SavedSectionRecord => ({
89
+ version: SAVED_SECTION_VERSION,
90
+ name: section.name,
91
+ layout: wrap(section.node),
92
+ designSchemaVersion: DESIGN_SCHEMA_VERSION,
93
+ classes: section.classes,
94
+ createdAt: section.createdAt,
95
+ updatedAt: section.updatedAt,
96
+ });
97
+
98
+ /** A record for `nodeId` with the classes it uses, or why it can't be saved. */
99
+ export function snapshotSection(
100
+ layout: Layout,
101
+ nodeId: string,
102
+ design: DesignSystem,
103
+ rawName: string,
104
+ now: string,
105
+ ): { ok: true; record: SavedSectionRecord } | Refusal {
106
+ const name = savedSectionName(rawName);
107
+ if (!name) return refuse(SAVED_SECTION_REASONS.name);
108
+ if (nodeId === layout.root.id) return refuse(SAVED_SECTION_REASONS.root);
109
+ const found = findNode(layout, nodeId);
110
+ if (!found) return refuse(SAVED_SECTION_REASONS.missing);
111
+ const node = withoutVariants(structuredClone(found));
112
+ const used = classIdsIn(node);
113
+ const classes = (design.classes ?? [])
114
+ .filter((c) => used.has(c.id))
115
+ .map((c) => structuredClone(c));
116
+ const record: SavedSectionRecord = {
117
+ version: SAVED_SECTION_VERSION,
118
+ name,
119
+ layout: wrap(node),
120
+ designSchemaVersion: DESIGN_SCHEMA_VERSION,
121
+ classes,
122
+ createdAt: now,
123
+ updatedAt: now,
124
+ };
125
+ if (byteLength(record) > MAX_LAYOUT_BYTES) return refuse(SAVED_SECTION_REASONS.tooBig);
126
+ const checked = validateLayout(record.layout);
127
+ if (!checked.ok) return refuse(summarizeIssues(checked.issues));
128
+ return { ok: true, record };
129
+ }
130
+
131
+ /**
132
+ * A stored record, checked and upgraded: the layout through the layout migrations, the classes
133
+ * through the design migrations. Anything that doesn't pass is refused, never half-used.
134
+ */
135
+ export function readSavedSection(raw: unknown): { ok: true; section: SavedSection } | Refusal {
136
+ if (!isRecord(raw) || raw["version"] !== SAVED_SECTION_VERSION) {
137
+ return refuse(SAVED_SECTION_REASONS.damaged);
138
+ }
139
+ const name = typeof raw["name"] === "string" ? savedSectionName(raw["name"]) : "";
140
+ const createdAt = typeof raw["createdAt"] === "string" ? raw["createdAt"] : "";
141
+ const updatedAt = typeof raw["updatedAt"] === "string" ? raw["updatedAt"] : createdAt;
142
+ if (!name || !createdAt) return refuse(SAVED_SECTION_REASONS.damaged);
143
+ const layout = validateLayout(raw["layout"]);
144
+ if (!layout.ok) return refuse(SAVED_SECTION_REASONS.damaged);
145
+ const node = layout.layout.root.children[0];
146
+ if (!node || layout.layout.root.children.length !== 1) {
147
+ return refuse(SAVED_SECTION_REASONS.damaged);
148
+ }
149
+ const version = raw["designSchemaVersion"];
150
+ const design = validateDesign({
151
+ schemaVersion: typeof version === "number" ? version : DESIGN_SCHEMA_VERSION,
152
+ variables: { colors: [] },
153
+ classes: Array.isArray(raw["classes"]) ? raw["classes"] : [],
154
+ });
155
+ if (!design.ok) return refuse(SAVED_SECTION_REASONS.damaged);
156
+ return {
157
+ ok: true,
158
+ section: { name, node, classes: design.design.classes ?? [], createdAt, updatedAt },
159
+ };
160
+ }
161
+
162
+ /** A class's look, in one comparable form (key order doesn't matter). */
163
+ function lookOf(cls: StyleClass): string {
164
+ const sorted = (value: unknown): unknown =>
165
+ Array.isArray(value)
166
+ ? value.map(sorted)
167
+ : isRecord(value)
168
+ ? Object.fromEntries(
169
+ Object.keys(value)
170
+ .toSorted()
171
+ .map((key) => [key, sorted(value[key])]),
172
+ )
173
+ : value;
174
+ const { id: _id, name: _name, ...look } = cls;
175
+ return JSON.stringify(sorted(look));
176
+ }
177
+
178
+ export type ClassMerge = {
179
+ design: DesignSystem;
180
+ /** Saved class id → the id it has on this site. */
181
+ ids: Map<string, string>;
182
+ added: string[];
183
+ reused: string[];
184
+ renamed: { from: string; to: string }[];
185
+ };
186
+
187
+ /**
188
+ * Brings a saved section's classes onto this site (D-060). Never changes a class that is already
189
+ * here: a class with the same id or name and the same look is reused; one whose look differs is
190
+ * added as a copy with a numbered name ("Card 2") and a new id; a missing one is added.
191
+ */
192
+ export function mergeSectionClasses(
193
+ design: DesignSystem,
194
+ incoming: readonly StyleClass[],
195
+ ): ClassMerge | Refusal {
196
+ const classes = [...(design.classes ?? [])];
197
+ const merge: ClassMerge = { design, ids: new Map(), added: [], reused: [], renamed: [] };
198
+ for (const raw of incoming) {
199
+ // A ref to a colour or size this site doesn't have is dropped, like on paste.
200
+ const { style } = prepareStyle(raw, design);
201
+ const cls: StyleClass = { id: raw.id, name: raw.name, style: style.style ?? {} };
202
+ if (style.states) cls.states = style.states;
203
+ if (style.devices) cls.devices = style.devices;
204
+ if (style.hiddenOn) cls.hiddenOn = style.hiddenOn;
205
+ const look = lookOf(cls);
206
+ const same = classes.find(
207
+ (c) => (c.id === cls.id || nameKey(c.name) === nameKey(cls.name)) && lookOf(c) === look,
208
+ );
209
+ if (same) {
210
+ merge.ids.set(raw.id, same.id);
211
+ merge.reused.push(same.name);
212
+ continue;
213
+ }
214
+ if (classes.length >= MAX_CLASSES) return refuse(SAVED_SECTION_REASONS.tooManyClasses);
215
+ const names = new Set(classes.map((c) => nameKey(c.name)));
216
+ let name = cls.name;
217
+ for (let n = 2; names.has(nameKey(name)); n++) {
218
+ name = `${clipText(cls.name, 54).trim()} ${n}`;
219
+ }
220
+ const ids = new Set(classes.map((c) => c.id));
221
+ const base = ids.has(cls.id)
222
+ ? slugify(name).slice(0, 34).replace(/-+$/, "") || "class"
223
+ : cls.id;
224
+ let id = base;
225
+ for (let n = 2; ids.has(id); n++) id = `${base}-${n}`.slice(0, 40);
226
+ classes.push({ ...cls, id, name });
227
+ merge.ids.set(raw.id, id);
228
+ if (name === cls.name) merge.added.push(name);
229
+ else merge.renamed.push({ from: cls.name, to: name });
230
+ }
231
+ merge.design = { ...design, classes };
232
+ return merge;
233
+ }
234
+
235
+ function withClassIds(node: LayoutNode, ids: ReadonlyMap<string, string>): LayoutNode {
236
+ const kids = nodeChildren(node);
237
+ const next = { ...node } as LayoutNode;
238
+ if (node.classes) next.classes = node.classes.map((id) => ids.get(id) ?? id);
239
+ if (kids.length > 0) {
240
+ (next as { children: LayoutNode[] }).children = kids.map((kid) => withClassIds(kid, ids));
241
+ }
242
+ return next;
243
+ }
244
+
245
+ export type PreparedSection = {
246
+ node: LayoutNode;
247
+ design: DesignSystem;
248
+ merge: ClassMerge;
249
+ dropped: Dropped;
250
+ };
251
+
252
+ /**
253
+ * The node to insert for a saved section on `layout`, and the site styles with its classes:
254
+ * classes merged as above, then the same checks as a paste (new ids, CSS ids already on the page
255
+ * dropped, links, images and SVGs sanitized).
256
+ */
257
+ export function prepareSavedSection(
258
+ section: SavedSection,
259
+ layout: Layout,
260
+ design: DesignSystem,
261
+ random: () => number = Math.random,
262
+ /** A merge already applied to `design` (its classes are saved): reused, not merged again. */
263
+ merged?: ClassMerge,
264
+ ): ({ ok: true } & PreparedSection) | Refusal {
265
+ const merge = merged ?? mergeSectionClasses(design, section.classes);
266
+ if ("ok" in merge) return merge;
267
+ const remapped = withClassIds(section.node, merge.ids);
268
+ const { node, dropped } = prepareElement(remapped, layout, merge.design, random);
269
+ return { ok: true, node, design: merge.design, merge, dropped };
270
+ }
271
+
272
+ /** Prepares and adds a saved section near the selection, like a section recipe (W-320). */
273
+ export function insertSavedSection(
274
+ section: SavedSection,
275
+ layout: Layout,
276
+ design: DesignSystem,
277
+ selectedId: string | null,
278
+ random: () => number = Math.random,
279
+ ): ({ design: DesignSystem; merge: ClassMerge; dropped: Dropped } & Added) | Refusal {
280
+ const prepared = prepareSavedSection(section, layout, design, random);
281
+ if (!prepared.ok) return prepared;
282
+ const added = addSectionNear(layout, prepared.node, selectedId);
283
+ if (!added.ok) return added;
284
+ return { ...added, design: prepared.design, merge: prepared.merge, dropped: prepared.dropped };
285
+ }
286
+
287
+ /** "Classes: 1 added, 1 renamed (Card → Card 2)" for the notice, or null when nothing changed. */
288
+ export function classMergeNotice(merge: ClassMerge): string | null {
289
+ const parts: string[] = [];
290
+ if (merge.added.length > 0) parts.push(`${merge.added.length} added`);
291
+ if (merge.renamed.length > 0) {
292
+ const list = merge.renamed.map(({ from, to }) => `${from} → ${to}`).join(", ");
293
+ parts.push(`${merge.renamed.length} added as a copy (${list})`);
294
+ }
295
+ return parts.length > 0 ? `Classes: ${parts.join("; ")}.` : null;
296
+ }
297
+
298
+ /**
299
+ * The layout of a new Section theme part for a synced section (W-876, W-098): a copy of the
300
+ * element with fresh ids and no A/B arms. Null for the page itself or an unknown id.
301
+ */
302
+ export function syncedPartLayout(
303
+ layout: Layout,
304
+ nodeId: string,
305
+ random: () => number = Math.random,
306
+ ): Layout | null {
307
+ const found = nodeId === layout.root.id ? undefined : findNode(layout, nodeId);
308
+ if (!found) return null;
309
+ return {
310
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
311
+ root: {
312
+ id: newNodeId(random),
313
+ type: "container",
314
+ props: {},
315
+ children: [withFreshIds(layout, withoutVariants(found), random)],
316
+ },
317
+ };
318
+ }
@@ -8,7 +8,7 @@ import { DeviceStyles, HiddenOn, StyleProps, StyleStates } from "./style.ts";
8
8
  * 13 since W-307, in step with layouts (the W-307 batch only adds optional fields).
9
9
  * 12 since W-160: class gradients use the same stops as layouts. v11 `{ angle, from, to }` upgrades on read.
10
10
  */
11
- export const DESIGN_SCHEMA_VERSION = 15;
11
+ export const DESIGN_SCHEMA_VERSION = 16;
12
12
 
13
13
  /** Tags a site can give a starting style. Classes and local styles still win. */
14
14
  export const DEFAULT_STYLE_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6", "p", "a", "button"] as const;
@@ -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()
@@ -645,6 +645,11 @@ export const PaginationNode = leafNode(
645
645
  showCount: z.boolean().optional(),
646
646
  /** The count's text; `{page}` and `{total}` are filled in. Unset = "Page {page} of {total}". */
647
647
  countText: z.string().max(60).optional(),
648
+ /** W-916: a link to the last page, shown when the host knows the total. */
649
+ showLast: z.boolean().optional(),
650
+ lastText: z.string().max(40).optional(),
651
+ /** The Last link's name when its text is only an arrow. Unset = "Last page". */
652
+ lastLabel: z.string().max(60).optional(),
648
653
  /**
649
654
  * The page title of archive page 2 onward (W-529); `{title}` and `{page}` are filled in.
650
655
  * Unset = "{title} – page {page}". Hosts read it with `archivePageTitle`.
@@ -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)}