@perkyzz/emvb 0.0.0-stage → 0.1.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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/package.json +72 -4
  4. package/src/admin/access/RequireEditor.tsx +39 -0
  5. package/src/admin/access/role.ts +36 -0
  6. package/src/admin/access/sidebar-shim.ts +108 -0
  7. package/src/admin/api.ts +48 -0
  8. package/src/admin/content-api.ts +147 -0
  9. package/src/admin/editor/Editor.tsx +457 -0
  10. package/src/admin/editor/EditorOverlay.tsx +54 -0
  11. package/src/admin/editor/ShortcutsDialog.tsx +30 -0
  12. package/src/admin/editor/SmallScreenNotice.tsx +20 -0
  13. package/src/admin/editor/TopBar.tsx +179 -0
  14. package/src/admin/editor/canvas/CanvasFrame.tsx +355 -0
  15. package/src/admin/editor/canvas/CanvasTextEdit.tsx +87 -0
  16. package/src/admin/editor/canvas/DeviceBar.tsx +50 -0
  17. package/src/admin/editor/canvas/EmptyCanvas.tsx +49 -0
  18. package/src/admin/editor/canvas/SelectionOverlay.tsx +185 -0
  19. package/src/admin/editor/canvas/canvas-events.ts +232 -0
  20. package/src/admin/editor/canvas/state-preview.ts +19 -0
  21. package/src/admin/editor/canvas/tab-reveal.ts +35 -0
  22. package/src/admin/editor/canvas/vnode-react.tsx +49 -0
  23. package/src/admin/editor/clipboard-store.ts +44 -0
  24. package/src/admin/editor/dialogs.tsx +125 -0
  25. package/src/admin/editor/dnd/drag-stash.ts +27 -0
  26. package/src/admin/editor/dnd/drop-target.ts +101 -0
  27. package/src/admin/editor/dnd/new-element.ts +32 -0
  28. package/src/admin/editor/editor-css.ts +539 -0
  29. package/src/admin/editor/exit.ts +27 -0
  30. package/src/admin/editor/panels/AddPanel.tsx +142 -0
  31. package/src/admin/editor/panels/ClassesSection.tsx +334 -0
  32. package/src/admin/editor/panels/ColorControl.tsx +230 -0
  33. package/src/admin/editor/panels/ConditionsEditor.tsx +201 -0
  34. package/src/admin/editor/panels/ElementPanel.tsx +629 -0
  35. package/src/admin/editor/panels/LayersPanel.tsx +336 -0
  36. package/src/admin/editor/panels/LeftPanel.tsx +77 -0
  37. package/src/admin/editor/panels/PageSettings.tsx +126 -0
  38. package/src/admin/editor/panels/SettingsPanel.tsx +101 -0
  39. package/src/admin/editor/panels/SiteStylesDrawer.tsx +392 -0
  40. package/src/admin/editor/panels/TriggerSettings.tsx +132 -0
  41. package/src/admin/editor/panels/TriggersEditor.tsx +197 -0
  42. package/src/admin/editor/panels/VariableSection.tsx +492 -0
  43. package/src/admin/editor/panels/settings/BackgroundControls.tsx +320 -0
  44. package/src/admin/editor/panels/settings/ClassChip.tsx +167 -0
  45. package/src/admin/editor/panels/settings/ClassChipInput.tsx +349 -0
  46. package/src/admin/editor/panels/settings/DraftTextField.tsx +201 -0
  47. package/src/admin/editor/panels/settings/EffectsControls.tsx +347 -0
  48. package/src/admin/editor/panels/settings/FieldBindControl.tsx +83 -0
  49. package/src/admin/editor/panels/settings/FieldControl.tsx +150 -0
  50. package/src/admin/editor/panels/settings/FormBindControl.tsx +97 -0
  51. package/src/admin/editor/panels/settings/IconPicker.tsx +109 -0
  52. package/src/admin/editor/panels/settings/LengthRow.tsx +181 -0
  53. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +124 -0
  54. package/src/admin/editor/panels/settings/MediaPicker.tsx +218 -0
  55. package/src/admin/editor/panels/settings/NumberRow.tsx +154 -0
  56. package/src/admin/editor/panels/settings/StateSwitcher.tsx +87 -0
  57. package/src/admin/editor/panels/settings/StyleRow.tsx +480 -0
  58. package/src/admin/editor/panels/settings/VariableBinding.tsx +167 -0
  59. package/src/admin/editor/panels/settings/class-suggest.ts +51 -0
  60. package/src/admin/editor/panels/settings/length-units.ts +83 -0
  61. package/src/admin/editor/panels/settings/node-props.ts +11 -0
  62. package/src/admin/editor/panels/settings/style-sections.ts +291 -0
  63. package/src/admin/editor/panels/site-list.tsx +206 -0
  64. package/src/admin/editor/panels/variable-values.ts +73 -0
  65. package/src/admin/editor/section-templates.ts +50 -0
  66. package/src/admin/editor/shortcuts.ts +20 -0
  67. package/src/admin/editor/store.ts +212 -0
  68. package/src/admin/editor/useClipboardActions.ts +136 -0
  69. package/src/admin/editor/useEditorCommands.ts +142 -0
  70. package/src/admin/editor/useEditorData.ts +167 -0
  71. package/src/admin/editor/useEditorShortcuts.ts +148 -0
  72. package/src/admin/editor/useMediaQuery.ts +20 -0
  73. package/src/admin/editor/useNodeActions.ts +122 -0
  74. package/src/admin/editor/useSave.ts +185 -0
  75. package/src/admin/forms-api.ts +73 -0
  76. package/src/admin/index.tsx +20 -0
  77. package/src/admin/media-api.ts +68 -0
  78. package/src/admin/pages/CreateDialog.tsx +150 -0
  79. package/src/admin/pages/EditorPage.tsx +57 -0
  80. package/src/admin/pages/NewPageDialog.tsx +83 -0
  81. package/src/admin/pages/NewThemePartDialog.tsx +61 -0
  82. package/src/admin/pages/PageList.tsx +71 -0
  83. package/src/admin/pages/PagesPage.tsx +25 -0
  84. package/src/admin/pages/SetupShell.tsx +90 -0
  85. package/src/admin/pages/ThemeBuilderPage.tsx +25 -0
  86. package/src/admin/pages/ThemePartList.tsx +202 -0
  87. package/src/admin/pages/list-kit.tsx +75 -0
  88. package/src/admin/setup/plan.ts +150 -0
  89. package/src/admin/setup/run.ts +61 -0
  90. package/src/admin/setup/spec.ts +100 -0
  91. package/src/admin/setup/useSetupStatus.ts +62 -0
  92. package/src/admin/theme-api.ts +186 -0
  93. package/src/admin/ui.ts +231 -0
  94. package/src/admin/widgets/LayoutField.tsx +67 -0
  95. package/src/astro/EmVBPage.astro +37 -0
  96. package/src/astro/env.d.ts +5 -0
  97. package/src/astro/forms/EmVBFormsRuntime.astro +9 -0
  98. package/src/astro/forms/index.ts +1 -0
  99. package/src/astro/forms-definitions.ts +104 -0
  100. package/src/astro/index.ts +15 -0
  101. package/src/astro/popups/EmVBPopupsRuntime.astro +9 -0
  102. package/src/astro/popups/index.ts +1 -0
  103. package/src/astro/popups/runtime.ts +246 -0
  104. package/src/astro/render.ts +74 -0
  105. package/src/astro/resolve-theme.ts +371 -0
  106. package/src/astro/resolve.ts +65 -0
  107. package/src/astro/tabs/EmVBTabsRuntime.astro +10 -0
  108. package/src/astro/tabs/index.ts +1 -0
  109. package/src/astro/tabs/runtime.ts +111 -0
  110. package/src/astro/theme-context.ts +81 -0
  111. package/src/astro/theme-posts.ts +84 -0
  112. package/src/constants.ts +12 -0
  113. package/src/core/arrange.ts +360 -0
  114. package/src/core/clipboard.ts +422 -0
  115. package/src/core/css/generate.ts +219 -0
  116. package/src/core/css/scope.ts +88 -0
  117. package/src/core/design/cascade.ts +28 -0
  118. package/src/core/design/classes.ts +138 -0
  119. package/src/core/design/devices.ts +56 -0
  120. package/src/core/design/states.ts +49 -0
  121. package/src/core/design/transfer.ts +33 -0
  122. package/src/core/design/variables.ts +319 -0
  123. package/src/core/elements/definition.ts +12 -0
  124. package/src/core/elements/dynamic-elements.ts +173 -0
  125. package/src/core/elements/form-elements.ts +204 -0
  126. package/src/core/elements/index.ts +742 -0
  127. package/src/core/elements/plain-text.ts +32 -0
  128. package/src/core/forms/binding.ts +61 -0
  129. package/src/core/forms/definition.ts +34 -0
  130. package/src/core/forms/success-layout.ts +63 -0
  131. package/src/core/icons/catalog.ts +273 -0
  132. package/src/core/index.ts +316 -0
  133. package/src/core/limits.ts +7 -0
  134. package/src/core/migrate/index.ts +76 -0
  135. package/src/core/render/context.ts +14 -0
  136. package/src/core/render/dynamic-post.ts +147 -0
  137. package/src/core/render/extras.ts +79 -0
  138. package/src/core/render/form.ts +137 -0
  139. package/src/core/render/index.ts +274 -0
  140. package/src/core/render/loop.ts +36 -0
  141. package/src/core/render/section.ts +33 -0
  142. package/src/core/render/tabs.ts +72 -0
  143. package/src/core/render/vnode.ts +87 -0
  144. package/src/core/sanitize/css.ts +591 -0
  145. package/src/core/sanitize/embed-url.ts +103 -0
  146. package/src/core/sanitize/escape.ts +10 -0
  147. package/src/core/sanitize/href.ts +6 -0
  148. package/src/core/sanitize/media-url.ts +7 -0
  149. package/src/core/sanitize/svg.ts +293 -0
  150. package/src/core/sanitize/url.ts +31 -0
  151. package/src/core/schema/descriptors.ts +33 -0
  152. package/src/core/schema/design.ts +88 -0
  153. package/src/core/schema/layout.ts +817 -0
  154. package/src/core/schema/state-names.ts +4 -0
  155. package/src/core/schema/style.ts +257 -0
  156. package/src/core/stats.ts +18 -0
  157. package/src/core/tabs/presence.ts +16 -0
  158. package/src/core/theme/conditions.ts +321 -0
  159. package/src/core/theme/dynamic.ts +133 -0
  160. package/src/core/theme/parse-doc.ts +36 -0
  161. package/src/core/theme/part-types.ts +79 -0
  162. package/src/core/theme/popup-markup.ts +39 -0
  163. package/src/core/theme/popup-rules.ts +61 -0
  164. package/src/core/theme/triggers.ts +104 -0
  165. package/src/core/tree-ops.ts +139 -0
  166. package/src/core/validate.ts +185 -0
  167. package/src/index.ts +18 -0
  168. package/src/server/design-routes.ts +125 -0
  169. package/src/server/hooks.ts +98 -0
  170. package/src/server/plugin.ts +39 -0
@@ -0,0 +1,84 @@
1
+ import type { ThemePostFields } from "../core/index.ts";
2
+
3
+ type MediaLike = {
4
+ src?: unknown;
5
+ url?: unknown;
6
+ previewUrl?: unknown;
7
+ alt?: unknown;
8
+ };
9
+
10
+ /** Pull a sanitized-ready image URL + alt from an EmDash media / image field value. */
11
+ export function mediaFieldsFrom(value: unknown): {
12
+ featuredImageUrl?: string;
13
+ featuredImageAlt?: string;
14
+ } {
15
+ if (!value || typeof value !== "object") return {};
16
+ const media = value as MediaLike;
17
+ const candidates = [media.src, media.url, media.previewUrl];
18
+ let featuredImageUrl: string | undefined;
19
+ for (const candidate of candidates) {
20
+ if (typeof candidate === "string" && candidate.trim()) {
21
+ featuredImageUrl = candidate.trim();
22
+ break;
23
+ }
24
+ }
25
+ const featuredImageAlt =
26
+ typeof media.alt === "string" && media.alt.trim() ? media.alt.trim() : undefined;
27
+ return { featuredImageUrl, featuredImageAlt };
28
+ }
29
+
30
+ /**
31
+ * Normalize an EmDash posts collection entry (or plain data bag) into ThemePostFields.
32
+ * Permalink defaults to `/posts/{slug}` to match the demo routes.
33
+ */
34
+ export function themePostFromEntry(
35
+ entry: { id?: string; data?: Record<string, unknown> } | Record<string, unknown>,
36
+ options: { permalinkPrefix?: string } = {},
37
+ ): ThemePostFields | null {
38
+ const data =
39
+ "data" in entry && entry.data && typeof entry.data === "object"
40
+ ? (entry.data as Record<string, unknown>)
41
+ : (entry as Record<string, unknown>);
42
+ const id = String(data["id"] ?? ("id" in entry ? entry.id : "") ?? "");
43
+ const slug = typeof data["slug"] === "string" ? data["slug"] : id;
44
+ if (!slug && !id) return null;
45
+ const title = typeof data["title"] === "string" ? data["title"] : "";
46
+ const excerpt = typeof data["excerpt"] === "string" ? data["excerpt"] : "";
47
+ const content = data["content"] ?? "";
48
+ const prefix = options.permalinkPrefix ?? "/posts";
49
+ const permalink = `${prefix.replace(/\/$/, "")}/${slug || id}`;
50
+ const media = mediaFieldsFrom(data["featured_image"]);
51
+ const publishedAt = firstString(data, ["published_at", "publishedAt", "date"]);
52
+ const authorName = authorFrom(data);
53
+ return {
54
+ id: id || slug,
55
+ slug: slug || id,
56
+ title,
57
+ excerpt,
58
+ content,
59
+ permalink,
60
+ ...(publishedAt ? { publishedAt } : {}),
61
+ ...(authorName ? { authorName } : {}),
62
+ ...media,
63
+ };
64
+ }
65
+
66
+ function firstString(data: Record<string, unknown>, keys: string[]): string | undefined {
67
+ for (const key of keys) {
68
+ const value = data[key];
69
+ if (typeof value === "string" && value.trim()) return value.trim();
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ function authorFrom(data: Record<string, unknown>): string | undefined {
75
+ const direct = firstString(data, ["author_name", "authorName"]);
76
+ if (direct) return direct;
77
+ const author = data["author"];
78
+ if (typeof author === "string" && author.trim()) return author.trim();
79
+ if (author && typeof author === "object" && "name" in author) {
80
+ const name = (author as { name?: unknown }).name;
81
+ if (typeof name === "string" && name.trim()) return name.trim();
82
+ }
83
+ return undefined;
84
+ }
@@ -0,0 +1,12 @@
1
+ export const PLUGIN_ID = "emvb";
2
+ export const PLUGIN_VERSION = "0.1.0";
3
+ export const PACKAGE_NAME = "@perkyzz/emvb";
4
+ export const ADMIN_ENTRY = `${PACKAGE_NAME}/admin`;
5
+ export const PAGES_COLLECTION = "emvb_pages";
6
+ /** Hidden collection for Header/Footer theme parts (D-TB-03). Not public URLs. */
7
+ export const THEME_PARTS_COLLECTION = "emvb_theme_parts";
8
+ /** EDITOR in EmDash's RBAC (`packages/auth/src/rbac.ts`); EmVB is for editors and above (D-020). */
9
+ export const EDITOR_ROLE = 40;
10
+ export const DESIGN_KEY = "system";
11
+ /** Editor working copy. The public route keeps reading `DESIGN_KEY` (W-100). */
12
+ export const DESIGN_DRAFT_KEY = "draft";
@@ -0,0 +1,360 @@
1
+ import { MAX_DEPTH, MAX_NODES } from "./limits.ts";
2
+ import {
3
+ isContainerNode,
4
+ isFormFieldType,
5
+ isFormNode,
6
+ isParentNode,
7
+ isLayoutParentNode,
8
+ LAYOUT_SCHEMA_VERSION,
9
+ type ContainerNode,
10
+ type FormNode,
11
+ type LoopNode,
12
+ type Layout,
13
+ type LayoutNode,
14
+ } from "./schema/layout.ts";
15
+ import {
16
+ findNode,
17
+ insertNode,
18
+ newNodeId,
19
+ nodeChildren,
20
+ removeNode,
21
+ starterLayout,
22
+ } from "./tree-ops.ts";
23
+
24
+ /** A refused operation, with the reason shown or announced to the user (R-003). */
25
+ export type Refusal = { ok: false; reason: string };
26
+ export type Arranged = { ok: true; layout: Layout; selected: string } | Refusal;
27
+ export type Allowed = { ok: true } | Refusal;
28
+
29
+ /** What is being dropped: an element already on the page, or a new one from the Add panel. */
30
+ export type DragSource = { kind: "existing"; id: string } | { kind: "new"; node: LayoutNode };
31
+
32
+ export type Place = { parentId: string; index: number };
33
+
34
+ type ArrangeParent = Extract<LayoutNode, { children: LayoutNode[] }>;
35
+
36
+ type Located = {
37
+ node: LayoutNode;
38
+ parent?: ArrangeParent;
39
+ index: number;
40
+ depth: number;
41
+ };
42
+
43
+ export const REASONS = {
44
+ intoItself: "A container can't go inside itself.",
45
+ notContainer: "Only layout containers, forms, and loops can hold other elements.",
46
+ rootFixed: "The page's outer container can't be moved.",
47
+ rootCopy: "The page's outer container can't be duplicated.",
48
+ missing: "That element is no longer on the page.",
49
+ tooDeep: `Elements can be nested at most ${MAX_DEPTH} levels deep.`,
50
+ tooMany: `A page can have at most ${MAX_NODES} elements.`,
51
+ first: "It's already first in its container.",
52
+ last: "It's already last in its container.",
53
+ top: "It's already at the top level.",
54
+ noContainerAbove: "There's no container just above it to move into.",
55
+ nestedForm: "A form can't go inside another form.",
56
+ fieldOutsideForm: "Form fields must be placed inside a form.",
57
+ formIntoField: "A form can only go inside a layout container.",
58
+ tabOutsideTabs: "Tab panels can only go inside Tabs.",
59
+ onlyTabPanels: "Tabs can only hold tab panels.",
60
+ itemOutsideAccordion: "Accordion items can only go inside an Accordion.",
61
+ onlyAccordionItems: "An accordion can only hold accordion items.",
62
+ } as const;
63
+
64
+ const refuse = (reason: string): Refusal => ({ ok: false, reason });
65
+
66
+ const isContainer = (node: LayoutNode): node is ContainerNode => node.type === "container";
67
+
68
+ function locate(layout: Layout, id: string): Located | undefined {
69
+ const walk = (
70
+ node: LayoutNode,
71
+ parent: ArrangeParent | undefined,
72
+ index: number,
73
+ depth: number,
74
+ ): Located | undefined => {
75
+ if (node.id === id) return { node, parent, index, depth };
76
+ // Containers and forms are drop/arrange parents. Still descend into unknown
77
+ // children so nested ids can be found (they are not rearrangeable).
78
+ if (isParentNode(node)) {
79
+ for (const [i, child] of node.children.entries()) {
80
+ const found = walk(child, node as ArrangeParent, i, depth + 1);
81
+ if (found) return found;
82
+ }
83
+ return undefined;
84
+ }
85
+ for (const child of nodeChildren(node)) {
86
+ const found = walk(child, undefined, -1, depth + 1);
87
+ if (found) return found;
88
+ }
89
+ return undefined;
90
+ };
91
+ return walk(layout.root, undefined, 0, 1);
92
+ }
93
+
94
+ const size = (node: LayoutNode): number =>
95
+ 1 + nodeChildren(node).reduce((n, child) => n + size(child), 0);
96
+
97
+ const height = (node: LayoutNode): number => {
98
+ const kids = nodeChildren(node);
99
+ return 1 + (kids.length > 0 ? Math.max(...kids.map(height)) : 0);
100
+ };
101
+
102
+ const contains = (node: LayoutNode, id: string): boolean =>
103
+ node.id === id || nodeChildren(node).some((child) => contains(child, id));
104
+
105
+ /** Whether `parentId` is a form or sits inside one. */
106
+ function underForm(layout: Layout, parentId: string): boolean {
107
+ let current: string | undefined = parentId;
108
+ while (current) {
109
+ const found = locate(layout, current);
110
+ if (!found) return false;
111
+ if (isFormNode(found.node)) return true;
112
+ current = found.parent?.id;
113
+ }
114
+ return false;
115
+ }
116
+
117
+ type Drop = { layout: Layout; node: LayoutNode; into: Located; isNew: boolean };
118
+
119
+ /** Placement rules in the order their reasons take precedence (R-003, W-034, W-074). */
120
+ const DROP_RULES: [breaks: (drop: Drop) => boolean, reason: string][] = [
121
+ [
122
+ ({ node, into }) => node.type === "tab-panel" && into.node.type !== "tabs",
123
+ REASONS.tabOutsideTabs,
124
+ ],
125
+ [
126
+ ({ node, into }) => into.node.type === "tabs" && node.type !== "tab-panel",
127
+ REASONS.onlyTabPanels,
128
+ ],
129
+ [
130
+ ({ node, into }) => node.type === "accordion-item" && into.node.type !== "accordion",
131
+ REASONS.itemOutsideAccordion,
132
+ ],
133
+ [
134
+ ({ node, into }) => into.node.type === "accordion" && node.type !== "accordion-item",
135
+ REASONS.onlyAccordionItems,
136
+ ],
137
+ [
138
+ ({ node, into, layout }) => isFormNode(node) && underForm(layout, into.node.id),
139
+ REASONS.nestedForm,
140
+ ],
141
+ [({ node, into }) => isFormNode(node) && !isLayoutParentNode(into.node), REASONS.formIntoField],
142
+ [
143
+ ({ node, into, layout }) => isFormFieldType(node.type) && !underForm(layout, into.node.id),
144
+ REASONS.fieldOutsideForm,
145
+ ],
146
+ [({ node, into }) => into.depth + height(node) > MAX_DEPTH, REASONS.tooDeep],
147
+ [
148
+ ({ node, layout, isNew }) => isNew && size(layout.root) + size(node) > MAX_NODES,
149
+ REASONS.tooMany,
150
+ ],
151
+ ];
152
+
153
+ /** The node being dragged, or why an existing one can't move into `parentId`. */
154
+ function dragged(
155
+ layout: Layout,
156
+ source: DragSource,
157
+ parentId: string,
158
+ ): { ok: true; node: LayoutNode } | Refusal {
159
+ if (source.kind === "new") return { ok: true, node: source.node };
160
+ const moving = locate(layout, source.id);
161
+ if (!moving) return refuse(REASONS.missing);
162
+ if (!moving.parent) return refuse(REASONS.rootFixed);
163
+ if (contains(moving.node, parentId)) return refuse(REASONS.intoItself);
164
+ return { ok: true, node: moving.node };
165
+ }
166
+
167
+ /** Whether `source` may go into parent `parentId` (R-003 invalid drops). */
168
+ export function canDrop(layout: Layout, source: DragSource, parentId: string): Allowed {
169
+ const into = locate(layout, parentId);
170
+ if (!into) return refuse(REASONS.missing);
171
+ const moving = dragged(layout, source, parentId);
172
+ if (!moving.ok) return moving;
173
+ if (!isParentNode(into.node)) return refuse(REASONS.notContainer);
174
+ const drop: Drop = { layout, node: moving.node, into, isNew: source.kind === "new" };
175
+ const broken = DROP_RULES.find(([breaks]) => breaks(drop));
176
+ return broken ? refuse(broken[1]) : { ok: true };
177
+ }
178
+
179
+ /**
180
+ * Moves an element into `parentId` at `index`, where `index` counts the target's children as they
181
+ * are before the move (what a drop indicator points at).
182
+ */
183
+ export function moveNode(layout: Layout, id: string, parentId: string, index: number): Arranged {
184
+ const allowed = canDrop(layout, { kind: "existing", id }, parentId);
185
+ if (!allowed.ok) return allowed;
186
+ const from = locate(layout, id) as Located & { parent: ContainerNode | FormNode | LoopNode };
187
+ const sameParent = from.parent.id === parentId;
188
+ const at = sameParent && from.index < index ? index - 1 : index;
189
+ const { layout: without, removed } = removeNode(layout, id);
190
+ if (!removed) return refuse(REASONS.missing);
191
+ return { ok: true, layout: insertNode(without, parentId, at, removed.node), selected: id };
192
+ }
193
+
194
+ /** Adds a new element (from the Add panel) into `parentId` at `index`. */
195
+ export function addNode(layout: Layout, node: LayoutNode, place: Place): Arranged {
196
+ const allowed = canDrop(layout, { kind: "new", node }, place.parentId);
197
+ if (!allowed.ok) return allowed;
198
+ return {
199
+ ok: true,
200
+ layout: insertNode(layout, place.parentId, place.index, node),
201
+ selected: node.id,
202
+ };
203
+ }
204
+
205
+ function withNewIds(node: LayoutNode, taken: Set<string>, random: () => number): LayoutNode {
206
+ let id = newNodeId(random);
207
+ while (taken.has(id)) id = newNodeId(random);
208
+ taken.add(id);
209
+ const kids = nodeChildren(node);
210
+ const copy = { ...structuredClone(node), id } as LayoutNode;
211
+ if (kids.length === 0) return copy;
212
+ return { ...copy, children: kids.map((child) => withNewIds(child, taken, random)) } as LayoutNode;
213
+ }
214
+
215
+ function allIds(node: LayoutNode, into = new Set<string>()): Set<string> {
216
+ into.add(node.id);
217
+ for (const child of nodeChildren(node)) allIds(child, into);
218
+ return into;
219
+ }
220
+
221
+ /** A deep copy of `node` whose ids (its own and every descendant's) are new and unused on `layout`. */
222
+ export const withFreshIds = (
223
+ layout: Layout,
224
+ node: LayoutNode,
225
+ random: () => number = Math.random,
226
+ ): LayoutNode => withNewIds(node, allIds(layout.root), random);
227
+
228
+ /**
229
+ * A new page from a Page template theme part.
230
+ * Ids are fresh, so editing the page does not rewrite the template or other pages.
231
+ */
232
+ export function layoutFromPageTemplate(source: Layout, random: () => number = Math.random): Layout {
233
+ if (!isContainerNode(source.root)) return starterLayout("Page", random);
234
+ const blank: Layout = {
235
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
236
+ root: { id: "tplblank", type: "container", props: {}, children: [] },
237
+ };
238
+ const root = withFreshIds(blank, source.root, random);
239
+ if (!isContainerNode(root)) return starterLayout("Page", random);
240
+ return { schemaVersion: LAYOUT_SCHEMA_VERSION, root };
241
+ }
242
+
243
+ /** A deep copy with new unique ids, inserted right after the original and selected. */
244
+ export function duplicateNode(
245
+ layout: Layout,
246
+ id: string,
247
+ random: () => number = Math.random,
248
+ ): Arranged {
249
+ const found = locate(layout, id);
250
+ if (!found) return refuse(REASONS.missing);
251
+ if (!found.parent) return refuse(REASONS.rootCopy);
252
+ if (size(layout.root) + size(found.node) > MAX_NODES) return refuse(REASONS.tooMany);
253
+ const copy = withNewIds(found.node, allIds(layout.root), random);
254
+ return {
255
+ ok: true,
256
+ layout: insertNode(layout, found.parent.id, found.index + 1, copy),
257
+ selected: copy.id,
258
+ };
259
+ }
260
+
261
+ /** Where click-to-add puts a new element: into a selected container, after a selected element, or at the end. */
262
+ export function insertionPoint(layout: Layout, selectedId: string | null): Place {
263
+ const found = selectedId ? locate(layout, selectedId) : undefined;
264
+ if (found && isParentNode(found.node))
265
+ return { parentId: found.node.id, index: found.node.children.length };
266
+ if (found?.parent) return { parentId: found.parent.id, index: found.index + 1 };
267
+ return { parentId: layout.root.id, index: layout.root.children.length };
268
+ }
269
+
270
+ type Child = Located & { parent: NonNullable<Located["parent"]> };
271
+
272
+ /** Moves a non-root element to where `place` says, or returns the first refusal. */
273
+ function moveChild(layout: Layout, id: string, place: (found: Child) => Place | Refusal): Arranged {
274
+ const found = locate(layout, id);
275
+ if (!found) return refuse(REASONS.missing);
276
+ if (!found.parent) return refuse(REASONS.rootFixed);
277
+ const to = place(found as Child);
278
+ return "ok" in to ? to : moveNode(layout, id, to.parentId, to.index);
279
+ }
280
+
281
+ /** Alt+↑: one place earlier among its siblings. */
282
+ export const moveUp = (layout: Layout, id: string): Arranged =>
283
+ moveChild(layout, id, ({ parent, index }) =>
284
+ index === 0 ? refuse(REASONS.first) : { parentId: parent.id, index: index - 1 },
285
+ );
286
+
287
+ /** Alt+↓: one place later among its siblings. */
288
+ export const moveDown = (layout: Layout, id: string): Arranged =>
289
+ moveChild(layout, id, ({ parent, index }) =>
290
+ index === parent.children.length - 1
291
+ ? refuse(REASONS.last)
292
+ : { parentId: parent.id, index: index + 2 },
293
+ );
294
+
295
+ /** Alt+←: out of its container, right after it. */
296
+ export const moveOut = (layout: Layout, id: string): Arranged =>
297
+ moveChild(layout, id, ({ parent }) => {
298
+ const outer = locate(layout, parent.id);
299
+ return outer?.parent
300
+ ? { parentId: outer.parent.id, index: outer.index + 1 }
301
+ : refuse(REASONS.top);
302
+ });
303
+
304
+ /** Alt+→: into the container just above it, as its last child. */
305
+ export const moveIn = (layout: Layout, id: string): Arranged =>
306
+ moveChild(layout, id, ({ parent, index }) => {
307
+ const above = parent.children[index - 1];
308
+ return above && isContainer(above)
309
+ ? { parentId: above.id, index: above.children.length }
310
+ : refuse(REASONS.noContainerAbove);
311
+ });
312
+
313
+ function documentOrder(layout: Layout): string[] {
314
+ const ids: string[] = [];
315
+ const walk = (node: LayoutNode) => {
316
+ ids.push(node.id);
317
+ nodeChildren(node).forEach(walk);
318
+ };
319
+ walk(layout.root);
320
+ return ids;
321
+ }
322
+
323
+ /** ↓ on the canvas: the next element in document order, or the same one at the end. */
324
+ export function nextInOrder(layout: Layout, id: string): string {
325
+ const ids = documentOrder(layout);
326
+ const at = ids.indexOf(id);
327
+ return at === -1 ? layout.root.id : (ids[at + 1] ?? id);
328
+ }
329
+
330
+ /** ↑ on the canvas: the previous element in document order, or the same one at the start. */
331
+ export function previousInOrder(layout: Layout, id: string): string {
332
+ const ids = documentOrder(layout);
333
+ const at = ids.indexOf(id);
334
+ return at === -1 ? layout.root.id : (ids[at - 1] ?? id);
335
+ }
336
+
337
+ /** Enter: the first child of a container, if it has one. */
338
+ export function firstChild(layout: Layout, id: string): string | undefined {
339
+ const node = findNode(layout, id);
340
+ return node && isContainer(node) ? node.children[0]?.id : undefined;
341
+ }
342
+
343
+ /** Shift+Enter: the parent container, if any. */
344
+ export function parentOf(layout: Layout, id: string): string | undefined {
345
+ return locate(layout, id)?.parent?.id;
346
+ }
347
+
348
+ /** Who gets the selection after `id` is deleted: the next sibling, else the previous one, else the parent. */
349
+ export function selectionAfterDelete(layout: Layout, id: string): string | null {
350
+ const found = locate(layout, id);
351
+ if (!found?.parent) return null;
352
+ const siblings = found.parent.children;
353
+ return (siblings[found.index + 1] ?? siblings[found.index - 1] ?? found.parent).id;
354
+ }
355
+
356
+ /** How many elements a deletion removes (the element plus everything inside it). */
357
+ export function subtreeSize(layout: Layout, id: string): number {
358
+ const node = findNode(layout, id);
359
+ return node ? size(node) : 0;
360
+ }