@perkyzz/emvb 0.0.0-stage → 0.2.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/THIRD_PARTY_NOTICES.md +32 -0
  4. package/licenses/fontawesome-free.LICENSE +165 -0
  5. package/licenses/lucide-static.LICENSE +43 -0
  6. package/licenses/remixicon.LICENSE +201 -0
  7. package/licenses/tabler-icons.LICENSE +21 -0
  8. package/package.json +76 -4
  9. package/src/admin/access/RequireEditor.tsx +39 -0
  10. package/src/admin/access/role.ts +36 -0
  11. package/src/admin/access/sidebar-shim.ts +108 -0
  12. package/src/admin/api.ts +75 -0
  13. package/src/admin/content-api.ts +210 -0
  14. package/src/admin/editor/Editor.tsx +532 -0
  15. package/src/admin/editor/EditorOverlay.tsx +66 -0
  16. package/src/admin/editor/ShortcutsDialog.tsx +30 -0
  17. package/src/admin/editor/SmallScreenNotice.tsx +21 -0
  18. package/src/admin/editor/TopBar.tsx +243 -0
  19. package/src/admin/editor/canvas/CanvasFrame.tsx +536 -0
  20. package/src/admin/editor/canvas/CanvasTextEdit.tsx +87 -0
  21. package/src/admin/editor/canvas/DeviceBar.tsx +91 -0
  22. package/src/admin/editor/canvas/EmptyCanvas.tsx +49 -0
  23. package/src/admin/editor/canvas/SelectionOverlay.tsx +239 -0
  24. package/src/admin/editor/canvas/canvas-events.ts +245 -0
  25. package/src/admin/editor/canvas/state-preview.ts +19 -0
  26. package/src/admin/editor/canvas/tab-reveal.ts +101 -0
  27. package/src/admin/editor/canvas/vnode-react.tsx +69 -0
  28. package/src/admin/editor/clipboard-store.ts +44 -0
  29. package/src/admin/editor/dialogs.tsx +164 -0
  30. package/src/admin/editor/dnd/drag-stash.ts +27 -0
  31. package/src/admin/editor/dnd/drop-target.ts +148 -0
  32. package/src/admin/editor/dnd/new-element.ts +107 -0
  33. package/src/admin/editor/editor-css.ts +625 -0
  34. package/src/admin/editor/exit.ts +27 -0
  35. package/src/admin/editor/host.ts +30 -0
  36. package/src/admin/editor/icons/IconLibraryDialog.tsx +850 -0
  37. package/src/admin/editor/icons/library.ts +243 -0
  38. package/src/admin/editor/icons/set-format.ts +29 -0
  39. package/src/admin/editor/icons/sets/fontawesome.json +1 -0
  40. package/src/admin/editor/icons/sets/lucide.json +1 -0
  41. package/src/admin/editor/icons/sets/remix.json +1 -0
  42. package/src/admin/editor/icons/sets/tabler.json +1 -0
  43. package/src/admin/editor/panels/AddPanel.tsx +146 -0
  44. package/src/admin/editor/panels/ClassesSection.tsx +372 -0
  45. package/src/admin/editor/panels/ColorControl.tsx +477 -0
  46. package/src/admin/editor/panels/ConditionsEditor.tsx +201 -0
  47. package/src/admin/editor/panels/ElementPanel.tsx +773 -0
  48. package/src/admin/editor/panels/LayersPanel.tsx +573 -0
  49. package/src/admin/editor/panels/LeftPanel.tsx +81 -0
  50. package/src/admin/editor/panels/PageSettings.tsx +255 -0
  51. package/src/admin/editor/panels/SettingsPanel.tsx +113 -0
  52. package/src/admin/editor/panels/SiteStylesDrawer.tsx +548 -0
  53. package/src/admin/editor/panels/TriggerSettings.tsx +132 -0
  54. package/src/admin/editor/panels/TriggersEditor.tsx +214 -0
  55. package/src/admin/editor/panels/VariableSection.tsx +530 -0
  56. package/src/admin/editor/panels/color-space.ts +195 -0
  57. package/src/admin/editor/panels/settings/AdvancedFields.tsx +119 -0
  58. package/src/admin/editor/panels/settings/BackgroundControls.tsx +418 -0
  59. package/src/admin/editor/panels/settings/BackgroundFill.tsx +221 -0
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +271 -0
  61. package/src/admin/editor/panels/settings/ChoiceGroup.tsx +138 -0
  62. package/src/admin/editor/panels/settings/ClassChip.tsx +167 -0
  63. package/src/admin/editor/panels/settings/ClassChipInput.tsx +451 -0
  64. package/src/admin/editor/panels/settings/DraftTextField.tsx +242 -0
  65. package/src/admin/editor/panels/settings/EffectsControls.tsx +354 -0
  66. package/src/admin/editor/panels/settings/FieldBindControl.tsx +119 -0
  67. package/src/admin/editor/panels/settings/FieldControl.tsx +270 -0
  68. package/src/admin/editor/panels/settings/FormBindControl.tsx +106 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +438 -0
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +170 -0
  71. package/src/admin/editor/panels/settings/ItemList.tsx +199 -0
  72. package/src/admin/editor/panels/settings/LengthRow.tsx +217 -0
  73. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +130 -0
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +220 -0
  75. package/src/admin/editor/panels/settings/NumberRow.tsx +154 -0
  76. package/src/admin/editor/panels/settings/StateSwitcher.tsx +87 -0
  77. package/src/admin/editor/panels/settings/StyleRow.tsx +563 -0
  78. package/src/admin/editor/panels/settings/VariableBinding.tsx +171 -0
  79. package/src/admin/editor/panels/settings/advanced-rules.ts +63 -0
  80. package/src/admin/editor/panels/settings/background-mode.ts +112 -0
  81. package/src/admin/editor/panels/settings/box-link-name.ts +38 -0
  82. package/src/admin/editor/panels/settings/box-sides.ts +153 -0
  83. package/src/admin/editor/panels/settings/button-url.ts +27 -0
  84. package/src/admin/editor/panels/settings/class-suggest.ts +53 -0
  85. package/src/admin/editor/panels/settings/form-names.ts +38 -0
  86. package/src/admin/editor/panels/settings/heading-warning.ts +25 -0
  87. package/src/admin/editor/panels/settings/image-alt.ts +25 -0
  88. package/src/admin/editor/panels/settings/length-units.ts +116 -0
  89. package/src/admin/editor/panels/settings/loop-context.ts +26 -0
  90. package/src/admin/editor/panels/settings/node-props.ts +11 -0
  91. package/src/admin/editor/panels/settings/style-sections.ts +394 -0
  92. package/src/admin/editor/panels/settings/svg-images.ts +14 -0
  93. package/src/admin/editor/panels/site-list.tsx +209 -0
  94. package/src/admin/editor/panels/variable-values.ts +73 -0
  95. package/src/admin/editor/restore-deleted.ts +80 -0
  96. package/src/admin/editor/section-templates.ts +50 -0
  97. package/src/admin/editor/shortcuts.ts +20 -0
  98. package/src/admin/editor/store.ts +240 -0
  99. package/src/admin/editor/useClipboardActions.ts +136 -0
  100. package/src/admin/editor/useEditorCommands.ts +203 -0
  101. package/src/admin/editor/useEditorData.ts +193 -0
  102. package/src/admin/editor/useEditorShortcuts.ts +180 -0
  103. package/src/admin/editor/useMediaQuery.ts +20 -0
  104. package/src/admin/editor/useNodeActions.ts +184 -0
  105. package/src/admin/editor/useSave.ts +242 -0
  106. package/src/admin/entry-status.ts +19 -0
  107. package/src/admin/forms-api.ts +73 -0
  108. package/src/admin/icon-uploads-api.ts +44 -0
  109. package/src/admin/index.tsx +20 -0
  110. package/src/admin/media-api.ts +68 -0
  111. package/src/admin/pages/CreateDialog.tsx +150 -0
  112. package/src/admin/pages/EditorPage.tsx +57 -0
  113. package/src/admin/pages/NewPageDialog.tsx +83 -0
  114. package/src/admin/pages/NewThemePartDialog.tsx +61 -0
  115. package/src/admin/pages/PageList.tsx +91 -0
  116. package/src/admin/pages/PagesPage.tsx +25 -0
  117. package/src/admin/pages/SetupShell.tsx +90 -0
  118. package/src/admin/pages/ThemeBuilderPage.tsx +25 -0
  119. package/src/admin/pages/ThemePartList.tsx +221 -0
  120. package/src/admin/pages/list-kit.tsx +125 -0
  121. package/src/admin/setup/plan.ts +150 -0
  122. package/src/admin/setup/run.ts +61 -0
  123. package/src/admin/setup/spec.ts +107 -0
  124. package/src/admin/setup/useSetupStatus.ts +62 -0
  125. package/src/admin/theme-api.ts +233 -0
  126. package/src/admin/ui.ts +244 -0
  127. package/src/admin/widgets/LayoutField.tsx +67 -0
  128. package/src/astro/EmVBPage.astro +63 -0
  129. package/src/astro/env.d.ts +5 -0
  130. package/src/astro/floats/EmVBFloatsRuntime.astro +9 -0
  131. package/src/astro/floats/index.ts +1 -0
  132. package/src/astro/floats/runtime.ts +78 -0
  133. package/src/astro/forms/EmVBFormsRuntime.astro +9 -0
  134. package/src/astro/forms/index.ts +1 -0
  135. package/src/astro/forms-definitions.ts +126 -0
  136. package/src/astro/index.ts +16 -0
  137. package/src/astro/menu/EmVBMenuRuntime.astro +9 -0
  138. package/src/astro/menu/index.ts +1 -0
  139. package/src/astro/menu/runtime.ts +37 -0
  140. package/src/astro/popups/EmVBPopupsRuntime.astro +9 -0
  141. package/src/astro/popups/index.ts +1 -0
  142. package/src/astro/popups/runtime.ts +296 -0
  143. package/src/astro/render.ts +108 -0
  144. package/src/astro/resolve-theme.ts +515 -0
  145. package/src/astro/resolve.ts +65 -0
  146. package/src/astro/tabs/EmVBTabsRuntime.astro +10 -0
  147. package/src/astro/tabs/index.ts +1 -0
  148. package/src/astro/tabs/runtime.ts +116 -0
  149. package/src/astro/theme-context.ts +89 -0
  150. package/src/astro/theme-posts.ts +84 -0
  151. package/src/constants.ts +12 -0
  152. package/src/core/arrange.ts +448 -0
  153. package/src/core/clipboard.ts +504 -0
  154. package/src/core/css/generate.ts +236 -0
  155. package/src/core/css/scope.ts +88 -0
  156. package/src/core/design/cascade.ts +28 -0
  157. package/src/core/design/classes.ts +224 -0
  158. package/src/core/design/devices.ts +56 -0
  159. package/src/core/design/states.ts +49 -0
  160. package/src/core/design/transfer.ts +132 -0
  161. package/src/core/design/variables.ts +359 -0
  162. package/src/core/elements/definition.ts +12 -0
  163. package/src/core/elements/dynamic-elements.ts +225 -0
  164. package/src/core/elements/field-id.ts +6 -0
  165. package/src/core/elements/form-elements.ts +219 -0
  166. package/src/core/elements/index.ts +960 -0
  167. package/src/core/elements/menu.ts +190 -0
  168. package/src/core/elements/plain-text.ts +32 -0
  169. package/src/core/forms/binding.ts +61 -0
  170. package/src/core/forms/definition.ts +45 -0
  171. package/src/core/forms/success-layout.ts +63 -0
  172. package/src/core/icons/catalog.ts +273 -0
  173. package/src/core/index.ts +380 -0
  174. package/src/core/limits.ts +9 -0
  175. package/src/core/migrate/index.ts +126 -0
  176. package/src/core/nesting.ts +51 -0
  177. package/src/core/render/context.ts +21 -0
  178. package/src/core/render/dynamic-post.ts +175 -0
  179. package/src/core/render/extras.ts +98 -0
  180. package/src/core/render/form.ts +235 -0
  181. package/src/core/render/index.ts +372 -0
  182. package/src/core/render/loop.ts +43 -0
  183. package/src/core/render/pagination.ts +76 -0
  184. package/src/core/render/section.ts +37 -0
  185. package/src/core/render/tabs.ts +76 -0
  186. package/src/core/render/vnode.ts +87 -0
  187. package/src/core/sanitize/css.ts +771 -0
  188. package/src/core/sanitize/embed-url.ts +160 -0
  189. package/src/core/sanitize/escape.ts +10 -0
  190. package/src/core/sanitize/href.ts +6 -0
  191. package/src/core/sanitize/media-url.ts +7 -0
  192. package/src/core/sanitize/svg-upload.ts +203 -0
  193. package/src/core/sanitize/svg.ts +374 -0
  194. package/src/core/sanitize/url.ts +31 -0
  195. package/src/core/schema/descriptors.ts +37 -0
  196. package/src/core/schema/design.ts +93 -0
  197. package/src/core/schema/layout.ts +1008 -0
  198. package/src/core/schema/state-names.ts +4 -0
  199. package/src/core/schema/style.ts +336 -0
  200. package/src/core/stats.ts +18 -0
  201. package/src/core/tabs/presence.ts +25 -0
  202. package/src/core/theme/conditions.ts +324 -0
  203. package/src/core/theme/dynamic.ts +143 -0
  204. package/src/core/theme/float.ts +113 -0
  205. package/src/core/theme/pagination.ts +97 -0
  206. package/src/core/theme/parse-doc.ts +36 -0
  207. package/src/core/theme/part-types.ts +81 -0
  208. package/src/core/theme/popup-markup.ts +41 -0
  209. package/src/core/theme/popup-rules.ts +62 -0
  210. package/src/core/theme/triggers.ts +104 -0
  211. package/src/core/tree-ops.ts +139 -0
  212. package/src/core/validate.ts +185 -0
  213. package/src/index.ts +18 -0
  214. package/src/server/design-routes.ts +125 -0
  215. package/src/server/hooks.ts +118 -0
  216. package/src/server/icon-routes.ts +79 -0
  217. package/src/server/plugin.ts +43 -0
@@ -0,0 +1,448 @@
1
+ import { MAX_DEPTH, MAX_NODES, MAX_TABS } 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
+ /** `note`, when set, is announced after the change (W-133: a CSS id left on the original). */
27
+ export type Arranged = { ok: true; layout: Layout; selected: string; note?: string } | Refusal;
28
+ export type Allowed = { ok: true } | Refusal;
29
+
30
+ /** What is being dropped: an element already on the page, or a new one from the Add panel. */
31
+ export type DragSource = { kind: "existing"; id: string } | { kind: "new"; node: LayoutNode };
32
+
33
+ export type Place = { parentId: string; index: number };
34
+
35
+ type ArrangeParent = Extract<LayoutNode, { children: LayoutNode[] }>;
36
+
37
+ type Located = {
38
+ node: LayoutNode;
39
+ parent?: ArrangeParent;
40
+ index: number;
41
+ depth: number;
42
+ };
43
+
44
+ export const REASONS = {
45
+ intoItself: "A container can't go inside itself.",
46
+ notContainer: "Only layout containers, forms, and loops can hold other elements.",
47
+ rootFixed: "The page's outer container can't be moved.",
48
+ rootCopy: "The page's outer container can't be duplicated.",
49
+ missing: "That element is no longer on the page.",
50
+ tooDeep: `Elements can be nested at most ${MAX_DEPTH} levels deep.`,
51
+ tooMany: `A page can have at most ${MAX_NODES} elements.`,
52
+ tooManyTabs: `Tabs can show up to ${MAX_TABS} tabs.`,
53
+ first: "It's already first in its container.",
54
+ last: "It's already last in its container.",
55
+ top: "It's already at the top level.",
56
+ noContainerAbove: "There's no container just above it to move into.",
57
+ nestedForm: "A form can't go inside another form.",
58
+ fieldOutsideForm: "Form fields must be placed inside a form.",
59
+ formIntoField: "A form can only go inside a layout container.",
60
+ tabOutsideTabs: "Tab panels can only go inside Tabs.",
61
+ onlyTabPanels: "Tabs can only hold tab panels.",
62
+ itemOutsideAccordion: "Accordion items can only go inside an Accordion.",
63
+ onlyAccordionItems: "An accordion can only hold accordion items.",
64
+ itemOutsideMenu: "Menu items can only go inside a Menu.",
65
+ onlyMenuItems: "A menu can only hold menu items.",
66
+ } as const;
67
+
68
+ const refuse = (reason: string): Refusal => ({ ok: false, reason });
69
+
70
+ function locate(layout: Layout, id: string): Located | undefined {
71
+ const walk = (
72
+ node: LayoutNode,
73
+ parent: ArrangeParent | undefined,
74
+ index: number,
75
+ depth: number,
76
+ ): Located | undefined => {
77
+ if (node.id === id) return { node, parent, index, depth };
78
+ // Containers and forms are drop/arrange parents. Still descend into unknown
79
+ // children so nested ids can be found (they are not rearrangeable).
80
+ if (isParentNode(node)) {
81
+ for (const [i, child] of node.children.entries()) {
82
+ const found = walk(child, node as ArrangeParent, i, depth + 1);
83
+ if (found) return found;
84
+ }
85
+ return undefined;
86
+ }
87
+ for (const child of nodeChildren(node)) {
88
+ const found = walk(child, undefined, -1, depth + 1);
89
+ if (found) return found;
90
+ }
91
+ return undefined;
92
+ };
93
+ return walk(layout.root, undefined, 0, 1);
94
+ }
95
+
96
+ const size = (node: LayoutNode): number =>
97
+ 1 + nodeChildren(node).reduce((n, child) => n + size(child), 0);
98
+
99
+ const height = (node: LayoutNode): number => {
100
+ const kids = nodeChildren(node);
101
+ return 1 + (kids.length > 0 ? Math.max(...kids.map(height)) : 0);
102
+ };
103
+
104
+ const contains = (node: LayoutNode, id: string): boolean =>
105
+ node.id === id || nodeChildren(node).some((child) => contains(child, id));
106
+
107
+ /** Whether `parentId` is a form or sits inside one. */
108
+ function underForm(layout: Layout, parentId: string): boolean {
109
+ let current: string | undefined = parentId;
110
+ while (current) {
111
+ const found = locate(layout, current);
112
+ if (!found) return false;
113
+ if (isFormNode(found.node)) return true;
114
+ current = found.parent?.id;
115
+ }
116
+ return false;
117
+ }
118
+
119
+ type Drop = { layout: Layout; node: LayoutNode; into: Located; isNew: boolean };
120
+
121
+ /** Placement rules in the order their reasons take precedence (R-003, W-034, W-074). */
122
+ const DROP_RULES: [breaks: (drop: Drop) => boolean, reason: string][] = [
123
+ [
124
+ ({ node, into }) => node.type === "tab-panel" && into.node.type !== "tabs",
125
+ REASONS.tabOutsideTabs,
126
+ ],
127
+ [
128
+ ({ node, into }) => into.node.type === "tabs" && node.type !== "tab-panel",
129
+ REASONS.onlyTabPanels,
130
+ ],
131
+ [
132
+ ({ node, into }) => node.type === "accordion-item" && into.node.type !== "accordion",
133
+ REASONS.itemOutsideAccordion,
134
+ ],
135
+ [
136
+ ({ node, into }) => into.node.type === "accordion" && node.type !== "accordion-item",
137
+ REASONS.onlyAccordionItems,
138
+ ],
139
+ [
140
+ ({ node, into }) =>
141
+ node.type === "menu-item" && into.node.type !== "menu" && into.node.type !== "menu-item",
142
+ REASONS.itemOutsideMenu,
143
+ ],
144
+ [
145
+ ({ node, into }) => into.node.type === "menu" && node.type !== "menu-item",
146
+ REASONS.onlyMenuItems,
147
+ ],
148
+ [
149
+ ({ node, into, layout }) => isFormNode(node) && underForm(layout, into.node.id),
150
+ REASONS.nestedForm,
151
+ ],
152
+ [({ node, into }) => isFormNode(node) && !isLayoutParentNode(into.node), REASONS.formIntoField],
153
+ [
154
+ ({ node, into, layout }) => isFormFieldType(node.type) && !underForm(layout, into.node.id),
155
+ REASONS.fieldOutsideForm,
156
+ ],
157
+ // A 13th panel would be stored but never shown (W-188); moving within the same Tabs is fine.
158
+ [
159
+ ({ node, into }) =>
160
+ into.node.type === "tabs" &&
161
+ !nodeChildren(into.node).some((child) => child.id === node.id) &&
162
+ nodeChildren(into.node).length >= MAX_TABS,
163
+ REASONS.tooManyTabs,
164
+ ],
165
+ [({ node, into }) => into.depth + height(node) > MAX_DEPTH, REASONS.tooDeep],
166
+ [
167
+ ({ node, layout, isNew }) => isNew && size(layout.root) + size(node) > MAX_NODES,
168
+ REASONS.tooMany,
169
+ ],
170
+ ];
171
+
172
+ /** The node being dragged, or why an existing one can't move into `parentId`. */
173
+ function dragged(
174
+ layout: Layout,
175
+ source: DragSource,
176
+ parentId: string,
177
+ ): { ok: true; node: LayoutNode } | Refusal {
178
+ if (source.kind === "new") return { ok: true, node: source.node };
179
+ const moving = locate(layout, source.id);
180
+ if (!moving) return refuse(REASONS.missing);
181
+ if (!moving.parent) return refuse(REASONS.rootFixed);
182
+ if (contains(moving.node, parentId)) return refuse(REASONS.intoItself);
183
+ return { ok: true, node: moving.node };
184
+ }
185
+
186
+ /** Whether `source` may go into parent `parentId` (R-003 invalid drops). */
187
+ export function canDrop(layout: Layout, source: DragSource, parentId: string): Allowed {
188
+ const into = locate(layout, parentId);
189
+ if (!into) return refuse(REASONS.missing);
190
+ const moving = dragged(layout, source, parentId);
191
+ if (!moving.ok) return moving;
192
+ if (!isParentNode(into.node)) return refuse(REASONS.notContainer);
193
+ const drop: Drop = { layout, node: moving.node, into, isNew: source.kind === "new" };
194
+ const broken = DROP_RULES.find(([breaks]) => breaks(drop));
195
+ return broken ? refuse(broken[1]) : { ok: true };
196
+ }
197
+
198
+ /**
199
+ * Moves an element into `parentId` at `index`, where `index` counts the target's children as they
200
+ * are before the move (what a drop indicator points at).
201
+ */
202
+ export function moveNode(layout: Layout, id: string, parentId: string, index: number): Arranged {
203
+ const allowed = canDrop(layout, { kind: "existing", id }, parentId);
204
+ if (!allowed.ok) return allowed;
205
+ const from = locate(layout, id) as Located & { parent: ContainerNode | FormNode | LoopNode };
206
+ const sameParent = from.parent.id === parentId;
207
+ const at = sameParent && from.index < index ? index - 1 : index;
208
+ const { layout: without, removed } = removeNode(layout, id);
209
+ if (!removed) return refuse(REASONS.missing);
210
+ return { ok: true, layout: insertNode(without, parentId, at, removed.node), selected: id };
211
+ }
212
+
213
+ /** Adds a new element (from the Add panel) into `parentId` at `index`. */
214
+ export function addNode(layout: Layout, node: LayoutNode, place: Place): Arranged {
215
+ const allowed = canDrop(layout, { kind: "new", node }, place.parentId);
216
+ if (!allowed.ok) return allowed;
217
+ return {
218
+ ok: true,
219
+ layout: insertNode(layout, place.parentId, place.index, node),
220
+ selected: node.id,
221
+ };
222
+ }
223
+
224
+ function withNewIds(node: LayoutNode, taken: Set<string>, random: () => number): LayoutNode {
225
+ let id = newNodeId(random);
226
+ while (taken.has(id)) id = newNodeId(random);
227
+ taken.add(id);
228
+ const kids = nodeChildren(node);
229
+ const copy = { ...structuredClone(node), id } as LayoutNode;
230
+ if (kids.length === 0) return copy;
231
+ return { ...copy, children: kids.map((child) => withNewIds(child, taken, random)) } as LayoutNode;
232
+ }
233
+
234
+ function allIds(node: LayoutNode, into = new Set<string>()): Set<string> {
235
+ into.add(node.id);
236
+ for (const child of nodeChildren(node)) allIds(child, into);
237
+ return into;
238
+ }
239
+
240
+ /** A deep copy of `node` whose ids (its own and every descendant's) are new and unused on `layout`. */
241
+ export const withFreshIds = (
242
+ layout: Layout,
243
+ node: LayoutNode,
244
+ random: () => number = Math.random,
245
+ ): LayoutNode => withNewIds(node, allIds(layout.root), random);
246
+
247
+ /**
248
+ * A new page from a Page template theme part.
249
+ * Ids are fresh, so editing the page does not rewrite the template or other pages.
250
+ */
251
+ export function layoutFromPageTemplate(source: Layout, random: () => number = Math.random): Layout {
252
+ if (!isContainerNode(source.root)) return starterLayout("Page", random);
253
+ const blank: Layout = {
254
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
255
+ root: { id: "tplblank", type: "container", props: {}, children: [] },
256
+ };
257
+ const root = withFreshIds(blank, source.root, random);
258
+ if (!isContainerNode(root)) return starterLayout("Page", random);
259
+ return { schemaVersion: LAYOUT_SCHEMA_VERSION, root };
260
+ }
261
+
262
+ /** Announced when a duplicate leaves its CSS ids on the original (W-133). */
263
+ export const CSS_ID_KEPT = "The CSS id stays on the original: CSS ids must be unique on the page.";
264
+
265
+ /** `node` without the CSS id on it or any descendant; returns how many it dropped. */
266
+ function withoutHtmlIds(node: LayoutNode): { node: LayoutNode; dropped: number } {
267
+ let dropped = node.htmlId ? 1 : 0;
268
+ const { htmlId: _htmlId, ...rest } = node;
269
+ const kids = nodeChildren(node);
270
+ if (kids.length === 0) return { node: rest as LayoutNode, dropped };
271
+ const children = kids.map((child) => {
272
+ const cleaned = withoutHtmlIds(child);
273
+ dropped += cleaned.dropped;
274
+ return cleaned.node;
275
+ });
276
+ return { node: { ...rest, children } as LayoutNode, dropped };
277
+ }
278
+
279
+ /**
280
+ * A deep copy with new unique ids, inserted right after the original and selected. CSS ids stay
281
+ * on the original: a copied one made the page fail to save, so edits to the copy never reached
282
+ * the site (W-133).
283
+ */
284
+ export function duplicateNode(
285
+ layout: Layout,
286
+ id: string,
287
+ random: () => number = Math.random,
288
+ ): Arranged {
289
+ const found = locate(layout, id);
290
+ if (!found) return refuse(REASONS.missing);
291
+ if (!found.parent) return refuse(REASONS.rootCopy);
292
+ if (size(layout.root) + size(found.node) > MAX_NODES) return refuse(REASONS.tooMany);
293
+ if (found.parent.type === "tabs" && nodeChildren(found.parent).length >= MAX_TABS) {
294
+ return refuse(REASONS.tooManyTabs);
295
+ }
296
+ const { node: copy, dropped } = withoutHtmlIds(
297
+ withNewIds(found.node, allIds(layout.root), random),
298
+ );
299
+ return {
300
+ ok: true,
301
+ layout: insertNode(layout, found.parent.id, found.index + 1, copy),
302
+ selected: copy.id,
303
+ ...(dropped > 0 ? { note: CSS_ID_KEPT } : {}),
304
+ };
305
+ }
306
+
307
+ /** Where click-to-add puts a new element: into a selected container, after a selected element, or at the end. */
308
+ export function insertionPoint(layout: Layout, selectedId: string | null): Place {
309
+ const found = selectedId ? locate(layout, selectedId) : undefined;
310
+ if (found && isParentNode(found.node))
311
+ return { parentId: found.node.id, index: found.node.children.length };
312
+ if (found?.parent) return { parentId: found.parent.id, index: found.index + 1 };
313
+ return { parentId: layout.root.id, index: layout.root.children.length };
314
+ }
315
+
316
+ /** Where an Add-panel element went. `after` and `refused` are set when it fell back (W-175). */
317
+ export type Added = {
318
+ ok: true;
319
+ layout: Layout;
320
+ selected: string;
321
+ parentId: string;
322
+ fallback?: { after: string; refused: string };
323
+ };
324
+
325
+ /**
326
+ * Adds a new element where `insertionPoint` says. When that place refuses it, the element goes
327
+ * right after the nearest ancestor of that place whose own parent takes it, and `fallback` keeps
328
+ * the first reason so the editor can say where it went and why (W-175). Refused only when no
329
+ * ancestor can take it (a form field with no form on the way up, say).
330
+ */
331
+ export function addNodeNear(
332
+ layout: Layout,
333
+ node: LayoutNode,
334
+ selectedId: string | null,
335
+ ): Added | Refusal {
336
+ const first = insertionPoint(layout, selectedId);
337
+ const tried = addNode(layout, node, first);
338
+ if (tried.ok) return { ...tried, parentId: first.parentId };
339
+ let refusing = locate(layout, first.parentId);
340
+ while (refusing?.parent) {
341
+ const place = { parentId: refusing.parent.id, index: refusing.index + 1 };
342
+ const next = addNode(layout, node, place);
343
+ if (next.ok) {
344
+ const fallback = { after: refusing.node.id, refused: tried.reason };
345
+ return { ...next, parentId: place.parentId, fallback };
346
+ }
347
+ refusing = locate(layout, refusing.parent.id);
348
+ }
349
+ return tried;
350
+ }
351
+
352
+ type Child = Located & { parent: NonNullable<Located["parent"]> };
353
+
354
+ /** Moves a non-root element to where `place` says, or returns the first refusal. */
355
+ function moveChild(layout: Layout, id: string, place: (found: Child) => Place | Refusal): Arranged {
356
+ const found = locate(layout, id);
357
+ if (!found) return refuse(REASONS.missing);
358
+ if (!found.parent) return refuse(REASONS.rootFixed);
359
+ const to = place(found as Child);
360
+ return "ok" in to ? to : moveNode(layout, id, to.parentId, to.index);
361
+ }
362
+
363
+ /** Alt+↑: one place earlier among its siblings. */
364
+ export const moveUp = (layout: Layout, id: string): Arranged =>
365
+ moveChild(layout, id, ({ parent, index }) =>
366
+ index === 0 ? refuse(REASONS.first) : { parentId: parent.id, index: index - 1 },
367
+ );
368
+
369
+ /** Alt+↓: one place later among its siblings. */
370
+ export const moveDown = (layout: Layout, id: string): Arranged =>
371
+ moveChild(layout, id, ({ parent, index }) =>
372
+ index === parent.children.length - 1
373
+ ? refuse(REASONS.last)
374
+ : { parentId: parent.id, index: index + 2 },
375
+ );
376
+
377
+ /** Alt+←: out of its container, right after it. */
378
+ export const moveOut = (layout: Layout, id: string): Arranged =>
379
+ moveChild(layout, id, ({ parent }) => {
380
+ const outer = locate(layout, parent.id);
381
+ return outer?.parent
382
+ ? { parentId: outer.parent.id, index: outer.index + 1 }
383
+ : refuse(REASONS.top);
384
+ });
385
+
386
+ /** Alt+→: into the container just above it, as its last child. */
387
+ export const moveIn = (layout: Layout, id: string): Arranged =>
388
+ moveChild(layout, id, ({ parent, index }) => {
389
+ const above = parent.children[index - 1];
390
+ // W-211: any element that holds children (Flexbox, Grid, Form, Accordion item…), not only a
391
+ // Container; moveNode refuses what can't go there, with the reason.
392
+ const kids =
393
+ above && "children" in above && Array.isArray(above.children) ? above.children : null;
394
+ return above && kids
395
+ ? { parentId: above.id, index: kids.length }
396
+ : refuse(REASONS.noContainerAbove);
397
+ });
398
+
399
+ function documentOrder(layout: Layout): string[] {
400
+ const ids: string[] = [];
401
+ const walk = (node: LayoutNode) => {
402
+ ids.push(node.id);
403
+ nodeChildren(node).forEach(walk);
404
+ };
405
+ walk(layout.root);
406
+ return ids;
407
+ }
408
+
409
+ /** ↓ on the canvas: the next element in document order, or the same one at the end. */
410
+ export function nextInOrder(layout: Layout, id: string): string {
411
+ const ids = documentOrder(layout);
412
+ const at = ids.indexOf(id);
413
+ return at === -1 ? layout.root.id : (ids[at + 1] ?? id);
414
+ }
415
+
416
+ /** ↑ on the canvas: the previous element in document order, or the same one at the start. */
417
+ export function previousInOrder(layout: Layout, id: string): string {
418
+ const ids = documentOrder(layout);
419
+ const at = ids.indexOf(id);
420
+ return at === -1 ? layout.root.id : (ids[at - 1] ?? id);
421
+ }
422
+
423
+ /** Enter: the first child of any element that holds children, if it has one (W-211). */
424
+ export function firstChild(layout: Layout, id: string): string | undefined {
425
+ const node = findNode(layout, id);
426
+ return node && "children" in node && Array.isArray(node.children)
427
+ ? node.children[0]?.id
428
+ : undefined;
429
+ }
430
+
431
+ /** Shift+Enter: the parent container, if any. */
432
+ export function parentOf(layout: Layout, id: string): string | undefined {
433
+ return locate(layout, id)?.parent?.id;
434
+ }
435
+
436
+ /** Who gets the selection after `id` is deleted: the next sibling, else the previous one, else the parent. */
437
+ export function selectionAfterDelete(layout: Layout, id: string): string | null {
438
+ const found = locate(layout, id);
439
+ if (!found?.parent) return null;
440
+ const siblings = found.parent.children;
441
+ return (siblings[found.index + 1] ?? siblings[found.index - 1] ?? found.parent).id;
442
+ }
443
+
444
+ /** How many elements a deletion removes (the element plus everything inside it). */
445
+ export function subtreeSize(layout: Layout, id: string): number {
446
+ const node = findNode(layout, id);
447
+ return node ? size(node) : 0;
448
+ }