@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,504 @@
1
+ import {
2
+ addNode,
3
+ canDrop,
4
+ parentOf,
5
+ withFreshIds,
6
+ REASONS,
7
+ type Arranged,
8
+ type Place,
9
+ type Refusal,
10
+ } from "./arrange.ts";
11
+ import type { VariableKind } from "./design/variables.ts";
12
+ import { clearVariableRefs } from "./design/variables.ts";
13
+ import { ELEMENT_DESCRIPTORS, ELEMENTS, type ElementType } from "./elements/index.ts";
14
+ import { MAX_LAYOUT_BYTES } from "./limits.ts";
15
+ import { serialize } from "./render/vnode.ts";
16
+ import { sanitizeHref } from "./sanitize/href.ts";
17
+ import { sanitizeMediaUrl } from "./sanitize/media-url.ts";
18
+ import { sanitizeSvgReport } from "./sanitize/svg.ts";
19
+ import type { DesignSystem } from "./schema/design.ts";
20
+ import {
21
+ isParentNode,
22
+ LAYOUT_SCHEMA_VERSION,
23
+ type ContainerNode,
24
+ type Layout,
25
+ type LayoutNode,
26
+ } from "./schema/layout.ts";
27
+ import { STYLE_STATES } from "./schema/state-names.ts";
28
+ import type { DeviceStyles, HiddenOn, StyleProps, StyleStates } from "./schema/style.ts";
29
+ import { findNode, nodeChildren } from "./tree-ops.ts";
30
+ import { summarizeIssues, validateLayout } from "./validate.ts";
31
+
32
+ /**
33
+ * Copy and paste of elements and styles (W-093, D-033). The clipboard holds a versioned envelope
34
+ * as JSON text; everything read back goes through the layout validator and the URL and SVG
35
+ * sanitizers before it can reach a page, because another tab, an older or newer EmVB, or a
36
+ * hand-edited value may have written it.
37
+ */
38
+ export const CLIPBOARD_FORMAT = "emvb-clipboard";
39
+ export const CLIPBOARD_VERSION = 1;
40
+
41
+ /** A node's local style: `style` (with its transition) and the hover, focus and active states. */
42
+ export type CopiedStyle = {
43
+ style?: StyleProps;
44
+ states?: StyleStates;
45
+ devices?: DeviceStyles;
46
+ hiddenOn?: HiddenOn;
47
+ };
48
+
49
+ export type ClipEnvelope = {
50
+ format: typeof CLIPBOARD_FORMAT;
51
+ version: typeof CLIPBOARD_VERSION;
52
+ schemaVersion: number;
53
+ } & ({ kind: "element"; node: LayoutNode } | ({ kind: "style" } & CopiedStyle));
54
+
55
+ export type Clip = { kind: "element"; node: LayoutNode } | { kind: "style"; style: CopiedStyle };
56
+
57
+ export const CLIP_REASONS = {
58
+ empty: "Nothing has been copied yet.",
59
+ unreadable: "The clipboard doesn't hold an EmVB element or style.",
60
+ newer: "This was copied from a newer EmVB. Update EmVB to paste it.",
61
+ tooLarge: "The copied element is too large to paste.",
62
+ noElement: "The clipboard holds a style, not an element. Use Paste style.",
63
+ } as const;
64
+
65
+ /** The wrapper's id has an underscore, which generated node ids never have. */
66
+ const WRAPPER_ID = "emvb_clip";
67
+
68
+ const header = () =>
69
+ ({
70
+ format: CLIPBOARD_FORMAT,
71
+ version: CLIPBOARD_VERSION,
72
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
73
+ }) as const;
74
+
75
+ /** The local style of a node; classes stay behind (D-033). */
76
+ export function styleOf(node: LayoutNode): CopiedStyle {
77
+ const copied: CopiedStyle = {};
78
+ if (node.style) copied.style = structuredClone(node.style);
79
+ if (node.states) copied.states = structuredClone(node.states);
80
+ if (node.devices) copied.devices = structuredClone(node.devices);
81
+ if (node.hiddenOn) copied.hiddenOn = structuredClone(node.hiddenOn);
82
+ return copied;
83
+ }
84
+
85
+ export const elementClip = (node: LayoutNode): ClipEnvelope => ({
86
+ ...header(),
87
+ kind: "element",
88
+ node: structuredClone(node),
89
+ });
90
+
91
+ export const styleClip = (node: LayoutNode): ClipEnvelope => ({
92
+ ...header(),
93
+ kind: "style",
94
+ ...styleOf(node),
95
+ });
96
+
97
+ export const encodeClip = (clip: ClipEnvelope): string => JSON.stringify(clip);
98
+
99
+ export type ReadClip = { ok: true; clip: Clip } | Refusal;
100
+
101
+ const refuse = (reason: string): Refusal => ({ ok: false, reason });
102
+
103
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
104
+ !!value && typeof value === "object" && !Array.isArray(value);
105
+
106
+ const isCount = (value: unknown): value is number =>
107
+ typeof value === "number" && Number.isInteger(value) && value >= 1;
108
+
109
+ /** What kind of clip the text holds, without validating it (for enabling menu items). */
110
+ export function peekClipKind(raw: string | null): Clip["kind"] | null {
111
+ if (!raw) return null;
112
+ try {
113
+ const data: unknown = JSON.parse(raw);
114
+ if (!isRecord(data) || data["format"] !== CLIPBOARD_FORMAT) return null;
115
+ return data["kind"] === "element" || data["kind"] === "style" ? data["kind"] : null;
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /** Validates the copied node or style as part of a page, so the same rules apply as on save. */
122
+ function validated(schemaVersion: number, root: Record<string, unknown>): Layout | Refusal {
123
+ const checked = validateLayout({
124
+ schemaVersion,
125
+ root: { id: WRAPPER_ID, type: "container", props: {}, children: [], ...root },
126
+ });
127
+ if (checked.ok) return checked.layout;
128
+ const issues = checked.issues.map((issue) =>
129
+ Object.assign({}, issue, {
130
+ path: issue.path.replace(/^root\.children\[0\]\.?/, "").replace(/^root\.?/, ""),
131
+ }),
132
+ );
133
+ return refuse(`The copied content isn't valid: ${summarizeIssues(issues, 1)}`);
134
+ }
135
+
136
+ /** Reads clipboard text back into a clip, or says why it can't be pasted. */
137
+ export function readClip(raw: string | null): ReadClip {
138
+ if (!raw) return refuse(CLIP_REASONS.empty);
139
+ if (raw.length > MAX_LAYOUT_BYTES) return refuse(CLIP_REASONS.tooLarge);
140
+ let data: unknown;
141
+ try {
142
+ data = JSON.parse(raw);
143
+ } catch {
144
+ return refuse(CLIP_REASONS.unreadable);
145
+ }
146
+ if (!isRecord(data) || data["format"] !== CLIPBOARD_FORMAT)
147
+ return refuse(CLIP_REASONS.unreadable);
148
+ const { version, schemaVersion, kind } = data;
149
+ if (!isCount(version) || !isCount(schemaVersion)) return refuse(CLIP_REASONS.unreadable);
150
+ if (version > CLIPBOARD_VERSION || schemaVersion > LAYOUT_SCHEMA_VERSION)
151
+ return refuse(CLIP_REASONS.newer);
152
+ if (kind === "element") {
153
+ const layout = validated(schemaVersion, { children: [data["node"]] });
154
+ if ("ok" in layout) return layout;
155
+ const node = layout.root.children[0];
156
+ return node ? { ok: true, clip: { kind, node } } : refuse(CLIP_REASONS.unreadable);
157
+ }
158
+ if (kind === "style") {
159
+ const own: Record<string, unknown> = {};
160
+ if (data["style"] !== undefined) own["style"] = data["style"];
161
+ if (data["states"] !== undefined) own["states"] = data["states"];
162
+ if (data["devices"] !== undefined) own["devices"] = data["devices"];
163
+ if (data["hiddenOn"] !== undefined) own["hiddenOn"] = data["hiddenOn"];
164
+ const layout = validated(schemaVersion, own);
165
+ if ("ok" in layout) return layout;
166
+ return { ok: true, clip: { kind, style: styleOf(layout.root) } };
167
+ }
168
+ return refuse(CLIP_REASONS.unreadable);
169
+ }
170
+
171
+ /** The style a clip pastes: a style clip's own, or an element clip's element's local style. */
172
+ export const clipStyle = (clip: Clip): CopiedStyle =>
173
+ clip.kind === "style" ? clip.style : styleOf(clip.node);
174
+
175
+ /** What a paste left out because the target page or site doesn't allow or have it. */
176
+ export type Dropped = {
177
+ classes: number;
178
+ variables: number;
179
+ htmlIds: number;
180
+ unsafe: number;
181
+ /** W-231: `<image>`s left out of pasted SVGs because they point outside the site. */
182
+ images?: number;
183
+ };
184
+
185
+ const none = (): Dropped => ({ classes: 0, variables: 0, htmlIds: 0, unsafe: 0 });
186
+
187
+ const VARIABLE_LISTS = {
188
+ color: "colors",
189
+ font: "fonts",
190
+ fontSize: "fontSizes",
191
+ spacing: "spacings",
192
+ } as const;
193
+
194
+ type Ref = { var: string; kind: VariableKind };
195
+
196
+ const asRef = (value: unknown): Ref | null =>
197
+ isRecord(value) && typeof value["var"] === "string"
198
+ ? { var: value["var"], kind: (value["from"] as VariableKind | undefined) ?? "color" }
199
+ : null;
200
+
201
+ /** Every variable ref in a style: each value, plus nested colours (shadows, gradient, overlay). */
202
+ function refsInStyle(style: StyleProps | undefined): Ref[] {
203
+ if (!style) return [];
204
+ const values: unknown[] = [
205
+ ...Object.values(style),
206
+ style.boxShadow?.color,
207
+ style.iconShadow?.color,
208
+ ...(style.gradient?.stops ?? []).map((stop) => stop.color),
209
+ style.overlay?.color,
210
+ ];
211
+ return values.map(asRef).filter((ref): ref is Ref => ref !== null);
212
+ }
213
+
214
+ const refsOf = (owner: CopiedStyle): Ref[] => [
215
+ ...refsInStyle(owner.style),
216
+ ...STYLE_STATES.flatMap((state) => refsInStyle(owner.states?.[state])),
217
+ ...refsInStyle(owner.devices?.tablet),
218
+ ...refsInStyle(owner.devices?.mobile),
219
+ ];
220
+
221
+ const hasVariable = (design: DesignSystem, ref: Ref) =>
222
+ (design.variables[VARIABLE_LISTS[ref.kind]] ?? []).some((v) => v.id === ref.var);
223
+
224
+ /** Removes refs to variables the design doesn't have, counting each. */
225
+ function withKnownVariables<T extends LayoutNode>(
226
+ node: T,
227
+ design: DesignSystem,
228
+ dropped: Dropped,
229
+ ): T {
230
+ const missing = refsOf(node).filter((ref) => !hasVariable(design, ref));
231
+ if (missing.length === 0) return node;
232
+ dropped.variables += missing.length;
233
+ let wrapper: Layout = {
234
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
235
+ root: { id: WRAPPER_ID, type: "container", props: {}, children: [node] },
236
+ };
237
+ for (const ref of missing) wrapper = clearVariableRefs(wrapper, ref.var, ref.kind);
238
+ return wrapper.root.children[0] as T;
239
+ }
240
+
241
+ const SANITIZERS = {
242
+ href: sanitizeHref,
243
+ media: sanitizeMediaUrl,
244
+ } as const;
245
+
246
+ /** Props the sanitizers refuse fall back to the element's default, or go when optional. */
247
+ function withSafeProps(node: LayoutNode, dropped: Dropped): LayoutNode {
248
+ const type = node.type as ElementType;
249
+ if (!(type in ELEMENTS)) return node;
250
+ const props = { ...(node.props as Record<string, unknown>) };
251
+ const defaults = (ELEMENTS[type].defaults() as { props: Record<string, unknown> }).props;
252
+ let changed = false;
253
+ const fallBack = (key: string, optional: boolean | undefined) => {
254
+ dropped.unsafe++;
255
+ changed = true;
256
+ if (optional || defaults[key] === undefined) delete props[key];
257
+ else props[key] = defaults[key];
258
+ };
259
+ const fields = ELEMENT_DESCRIPTORS.find((d) => d.type === type)?.fields ?? [];
260
+ for (const field of fields) {
261
+ if (field.kind !== "href" && field.kind !== "media") continue;
262
+ const value = props[field.key];
263
+ if (typeof value !== "string" || value.trim() === "") continue;
264
+ const safe = SANITIZERS[field.kind](value);
265
+ if (safe === undefined) fallBack(field.key, field.optional);
266
+ else if (safe !== value) {
267
+ props[field.key] = safe;
268
+ changed = true;
269
+ }
270
+ }
271
+ // W-234: a library icon's SVG gets the same check; a refused one leaves the icon on its id.
272
+ if (type === "icon" && typeof props["iconSvg"] === "string") {
273
+ const report = sanitizeSvgReport(props["iconSvg"]);
274
+ if (!report.tree) {
275
+ dropped.unsafe++;
276
+ changed = true;
277
+ delete props["iconSvg"];
278
+ } else if (report.images > 0) {
279
+ props["iconSvg"] = serialize(report.tree);
280
+ dropped.images = (dropped.images ?? 0) + report.images;
281
+ changed = true;
282
+ }
283
+ }
284
+ if (type === "svg" && typeof props["markup"] === "string") {
285
+ const report = sanitizeSvgReport(props["markup"]);
286
+ if (!report.tree) fallBack("markup", false);
287
+ else if (report.images > 0) {
288
+ // Store what will render, so the pasted copy no longer names the external picture.
289
+ props["markup"] = serialize(report.tree);
290
+ dropped.images = (dropped.images ?? 0) + report.images;
291
+ changed = true;
292
+ }
293
+ }
294
+ return changed ? ({ ...node, props } as LayoutNode) : node;
295
+ }
296
+
297
+ function htmlIdsOf(node: LayoutNode, into = new Set<string>()): Set<string> {
298
+ if (node.htmlId) into.add(node.htmlId);
299
+ for (const child of nodeChildren(node)) htmlIdsOf(child, into);
300
+ return into;
301
+ }
302
+
303
+ /** The checks above on one node, then on each of its children. */
304
+ function cleanNode(
305
+ node: LayoutNode,
306
+ design: DesignSystem,
307
+ usedHtmlIds: Set<string>,
308
+ dropped: Dropped,
309
+ ): LayoutNode {
310
+ let next = withSafeProps(withKnownVariables(node, design, dropped), dropped);
311
+ if (next.classes) {
312
+ const known = new Set((design.classes ?? []).map((cls) => cls.id));
313
+ const kept = next.classes.filter((id) => known.has(id));
314
+ if (kept.length !== next.classes.length) {
315
+ dropped.classes += next.classes.length - kept.length;
316
+ next = { ...next, classes: kept };
317
+ if (kept.length === 0) delete next.classes;
318
+ }
319
+ }
320
+ if (next.htmlId && usedHtmlIds.has(next.htmlId)) {
321
+ dropped.htmlIds++;
322
+ next = { ...next };
323
+ delete next.htmlId;
324
+ }
325
+ const kids = nodeChildren(next);
326
+ if (kids.length === 0) return next;
327
+ return {
328
+ ...next,
329
+ children: kids.map((child) => cleanNode(child, design, usedHtmlIds, dropped)),
330
+ } as LayoutNode;
331
+ }
332
+
333
+ /**
334
+ * The node a paste inserts: new ids that aren't used on `layout` (like Duplicate), class and
335
+ * variable refs the design doesn't have removed, CSS ids already on the page removed, and
336
+ * values the sanitizers refuse replaced. `dropped` counts what was left out, for the notice.
337
+ */
338
+ export function prepareElement(
339
+ node: LayoutNode,
340
+ layout: Layout,
341
+ design: DesignSystem,
342
+ random: () => number = Math.random,
343
+ ): { node: LayoutNode; dropped: Dropped } {
344
+ const dropped = none();
345
+ const cleaned = cleanNode(node, design, htmlIdsOf(layout.root), dropped);
346
+ return { node: withFreshIds(layout, cleaned, random), dropped };
347
+ }
348
+
349
+ /** A copied style with refs to variables the design doesn't have removed. */
350
+ export function prepareStyle(
351
+ style: CopiedStyle,
352
+ design: DesignSystem,
353
+ ): { style: CopiedStyle; dropped: Dropped } {
354
+ const dropped = none();
355
+ const holder = withKnownVariables(
356
+ { id: WRAPPER_ID, type: "divider", props: {}, ...style } as LayoutNode,
357
+ design,
358
+ dropped,
359
+ );
360
+ return { style: styleOf(holder), dropped };
361
+ }
362
+
363
+ /** The Icon's glyph keys (W-237): they style an Icon's `<svg>` and do nothing anywhere else. */
364
+ const ICON_STYLE_KEYS = [
365
+ "iconRotate",
366
+ "iconFlip",
367
+ "iconScale",
368
+ "iconStrokeWidth",
369
+ "iconShadow",
370
+ "iconAnimation",
371
+ ] as const;
372
+
373
+ /** `style` without the Icon glyph keys; undefined when nothing else was set. */
374
+ function withoutIconKeys(style: object | undefined): object | undefined {
375
+ if (!style) return style;
376
+ const next: Record<string, unknown> = { ...style };
377
+ let removed = false;
378
+ for (const key of ICON_STYLE_KEYS) {
379
+ if (key in next) {
380
+ delete next[key];
381
+ removed = true;
382
+ }
383
+ }
384
+ if (!removed) return style;
385
+ return Object.keys(next).length > 0 ? next : undefined;
386
+ }
387
+
388
+ /** A copied style ready for `type`: Icon glyph keys stay only on an Icon (W-292). */
389
+ function styleFor(type: string, style: CopiedStyle): CopiedStyle {
390
+ if (type === "icon") return style;
391
+ const out: CopiedStyle = { ...style };
392
+ out.style = withoutIconKeys(style.style) as CopiedStyle["style"];
393
+ for (const [field, groups] of [
394
+ ["states", style.states],
395
+ ["devices", style.devices],
396
+ ] as const) {
397
+ if (!groups) continue;
398
+ const kept: Record<string, unknown> = {};
399
+ for (const [name, value] of Object.entries(groups)) {
400
+ const cleaned = withoutIconKeys(value);
401
+ if (cleaned) kept[name] = cleaned;
402
+ }
403
+ (out as Record<string, unknown>)[field] = Object.keys(kept).length > 0 ? kept : undefined;
404
+ }
405
+ for (const key of ["style", "states", "devices"] as const) {
406
+ if (out[key] === undefined) delete out[key];
407
+ }
408
+ return out;
409
+ }
410
+
411
+ /**
412
+ * Replaces the node's local style, states and device overrides; props, classes and children stay.
413
+ * Icon glyph keys are left out on anything but an Icon (W-292).
414
+ */
415
+ export function applyStyle<T extends LayoutNode>(node: T, copied: CopiedStyle): T {
416
+ const style = styleFor(node.type, copied);
417
+ const next = { ...node };
418
+ delete next.style;
419
+ delete next.states;
420
+ delete next.devices;
421
+ delete next.hiddenOn;
422
+ if (style.style) next.style = structuredClone(style.style);
423
+ if (style.states) next.states = structuredClone(style.states);
424
+ if (style.devices) next.devices = structuredClone(style.devices);
425
+ if (style.hiddenOn) next.hiddenOn = structuredClone(style.hiddenOn);
426
+ return next;
427
+ }
428
+
429
+ export type PasteMode = "auto" | "inside";
430
+
431
+ /**
432
+ * Where a pasted node goes (W-093). `auto`: right after the selected element; if the drop rules
433
+ * refuse that, inside it at the end (a field pasted on a form, a panel on Tabs); with nothing
434
+ * selected, or the page's outer container selected, at the end of the page. `inside`: at the end
435
+ * of the selected element. A refusal carries the drop rule's reason.
436
+ */
437
+ export function pastePlace(
438
+ layout: Layout,
439
+ node: LayoutNode,
440
+ selectedId: string | null,
441
+ mode: PasteMode = "auto",
442
+ ): { ok: true; place: Place } | Refusal {
443
+ const target = (selectedId && findNode(layout, selectedId)) || layout.root;
444
+ const source = { kind: "new" as const, node };
445
+ const inside = (): { ok: true; place: Place } | Refusal => {
446
+ const allowed = canDrop(layout, source, target.id);
447
+ if (!allowed.ok) return allowed;
448
+ return {
449
+ ok: true,
450
+ place: { parentId: target.id, index: (target as ContainerNode).children.length },
451
+ };
452
+ };
453
+ const parentId = parentOf(layout, target.id);
454
+ if (mode === "inside" || !parentId) {
455
+ return isParentNode(target) ? inside() : refuse(REASONS.notContainer);
456
+ }
457
+ const after = canDrop(layout, source, parentId);
458
+ if (after.ok) {
459
+ const parent = findNode(layout, parentId) as ContainerNode;
460
+ const index = parent.children.findIndex((child) => child.id === target.id);
461
+ return { ok: true, place: { parentId, index: index + 1 } };
462
+ }
463
+ if (isParentNode(target)) {
464
+ const into = inside();
465
+ if (into.ok) return into;
466
+ }
467
+ return after;
468
+ }
469
+
470
+ /** Pastes a prepared node where `pastePlace` says, or returns the refusal. */
471
+ export function pasteNode(
472
+ layout: Layout,
473
+ node: LayoutNode,
474
+ selectedId: string | null,
475
+ mode: PasteMode = "auto",
476
+ ): Arranged {
477
+ const where = pastePlace(layout, node, selectedId, mode);
478
+ return where.ok ? addNode(layout, node, where.place) : where;
479
+ }
480
+
481
+ /** The notice after a paste that left something out, or null when nothing was. */
482
+ export function droppedNotice(dropped: Dropped): string | null {
483
+ const parts: string[] = [];
484
+ const count = (n: number, one: string, many: string) => {
485
+ if (n > 0) parts.push(`${n} ${n === 1 ? one : many}`);
486
+ };
487
+ count(dropped.classes, "class", "classes");
488
+ count(dropped.variables, "variable", "variables");
489
+ count(dropped.htmlIds, "CSS id already used on this page", "CSS ids already used on this page");
490
+ count(
491
+ dropped.unsafe,
492
+ "link, image or SVG that isn't allowed",
493
+ "links, images or SVGs that aren't allowed",
494
+ );
495
+ count(dropped.images ?? 0, "external image", "external images");
496
+ if (parts.length === 0) return null;
497
+ const list =
498
+ parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
499
+ const missing =
500
+ dropped.classes + dropped.variables > 0
501
+ ? " Classes and variables this site doesn't have were removed."
502
+ : "";
503
+ return `Left out ${list}.${missing}`;
504
+ }