@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,422 @@
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 { sanitizeHref } from "./sanitize/href.ts";
16
+ import { sanitizeMediaUrl } from "./sanitize/media-url.ts";
17
+ import { isSafeSvgMarkup } from "./sanitize/svg.ts";
18
+ import type { DesignSystem } from "./schema/design.ts";
19
+ import {
20
+ isParentNode,
21
+ LAYOUT_SCHEMA_VERSION,
22
+ type ContainerNode,
23
+ type Layout,
24
+ type LayoutNode,
25
+ } from "./schema/layout.ts";
26
+ import { STYLE_STATES } from "./schema/state-names.ts";
27
+ import type { DeviceStyles, HiddenOn, StyleProps, StyleStates } from "./schema/style.ts";
28
+ import { findNode, nodeChildren } from "./tree-ops.ts";
29
+ import { summarizeIssues, validateLayout } from "./validate.ts";
30
+
31
+ /**
32
+ * Copy and paste of elements and styles (W-093, D-033). The clipboard holds a versioned envelope
33
+ * as JSON text; everything read back goes through the layout validator and the URL and SVG
34
+ * sanitizers before it can reach a page, because another tab, an older or newer EmVB, or a
35
+ * hand-edited value may have written it.
36
+ */
37
+ export const CLIPBOARD_FORMAT = "emvb-clipboard";
38
+ export const CLIPBOARD_VERSION = 1;
39
+
40
+ /** A node's local style: `style` (with its transition) and the hover, focus and active states. */
41
+ export type CopiedStyle = {
42
+ style?: StyleProps;
43
+ states?: StyleStates;
44
+ devices?: DeviceStyles;
45
+ hiddenOn?: HiddenOn;
46
+ };
47
+
48
+ export type ClipEnvelope = {
49
+ format: typeof CLIPBOARD_FORMAT;
50
+ version: typeof CLIPBOARD_VERSION;
51
+ schemaVersion: number;
52
+ } & ({ kind: "element"; node: LayoutNode } | ({ kind: "style" } & CopiedStyle));
53
+
54
+ export type Clip = { kind: "element"; node: LayoutNode } | { kind: "style"; style: CopiedStyle };
55
+
56
+ export const CLIP_REASONS = {
57
+ empty: "Nothing has been copied yet.",
58
+ unreadable: "The clipboard doesn't hold an EmVB element or style.",
59
+ newer: "This was copied from a newer EmVB. Update EmVB to paste it.",
60
+ tooLarge: "The copied element is too large to paste.",
61
+ noElement: "The clipboard holds a style, not an element. Use Paste style.",
62
+ } as const;
63
+
64
+ /** The wrapper's id has an underscore, which generated node ids never have. */
65
+ const WRAPPER_ID = "emvb_clip";
66
+
67
+ const header = () =>
68
+ ({
69
+ format: CLIPBOARD_FORMAT,
70
+ version: CLIPBOARD_VERSION,
71
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
72
+ }) as const;
73
+
74
+ /** The local style of a node; classes stay behind (D-033). */
75
+ export function styleOf(node: LayoutNode): CopiedStyle {
76
+ const copied: CopiedStyle = {};
77
+ if (node.style) copied.style = structuredClone(node.style);
78
+ if (node.states) copied.states = structuredClone(node.states);
79
+ if (node.devices) copied.devices = structuredClone(node.devices);
80
+ if (node.hiddenOn) copied.hiddenOn = structuredClone(node.hiddenOn);
81
+ return copied;
82
+ }
83
+
84
+ export const elementClip = (node: LayoutNode): ClipEnvelope => ({
85
+ ...header(),
86
+ kind: "element",
87
+ node: structuredClone(node),
88
+ });
89
+
90
+ export const styleClip = (node: LayoutNode): ClipEnvelope => ({
91
+ ...header(),
92
+ kind: "style",
93
+ ...styleOf(node),
94
+ });
95
+
96
+ export const encodeClip = (clip: ClipEnvelope): string => JSON.stringify(clip);
97
+
98
+ export type ReadClip = { ok: true; clip: Clip } | Refusal;
99
+
100
+ const refuse = (reason: string): Refusal => ({ ok: false, reason });
101
+
102
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
103
+ !!value && typeof value === "object" && !Array.isArray(value);
104
+
105
+ const isCount = (value: unknown): value is number =>
106
+ typeof value === "number" && Number.isInteger(value) && value >= 1;
107
+
108
+ /** What kind of clip the text holds, without validating it (for enabling menu items). */
109
+ export function peekClipKind(raw: string | null): Clip["kind"] | null {
110
+ if (!raw) return null;
111
+ try {
112
+ const data: unknown = JSON.parse(raw);
113
+ if (!isRecord(data) || data["format"] !== CLIPBOARD_FORMAT) return null;
114
+ return data["kind"] === "element" || data["kind"] === "style" ? data["kind"] : null;
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
120
+ /** Validates the copied node or style as part of a page, so the same rules apply as on save. */
121
+ function validated(schemaVersion: number, root: Record<string, unknown>): Layout | Refusal {
122
+ const checked = validateLayout({
123
+ schemaVersion,
124
+ root: { id: WRAPPER_ID, type: "container", props: {}, children: [], ...root },
125
+ });
126
+ if (checked.ok) return checked.layout;
127
+ const issues = checked.issues.map((issue) =>
128
+ Object.assign({}, issue, {
129
+ path: issue.path.replace(/^root\.children\[0\]\.?/, "").replace(/^root\.?/, ""),
130
+ }),
131
+ );
132
+ return refuse(`The copied content isn't valid: ${summarizeIssues(issues, 1)}`);
133
+ }
134
+
135
+ /** Reads clipboard text back into a clip, or says why it can't be pasted. */
136
+ export function readClip(raw: string | null): ReadClip {
137
+ if (!raw) return refuse(CLIP_REASONS.empty);
138
+ if (raw.length > MAX_LAYOUT_BYTES) return refuse(CLIP_REASONS.tooLarge);
139
+ let data: unknown;
140
+ try {
141
+ data = JSON.parse(raw);
142
+ } catch {
143
+ return refuse(CLIP_REASONS.unreadable);
144
+ }
145
+ if (!isRecord(data) || data["format"] !== CLIPBOARD_FORMAT)
146
+ return refuse(CLIP_REASONS.unreadable);
147
+ const { version, schemaVersion, kind } = data;
148
+ if (!isCount(version) || !isCount(schemaVersion)) return refuse(CLIP_REASONS.unreadable);
149
+ if (version > CLIPBOARD_VERSION || schemaVersion > LAYOUT_SCHEMA_VERSION)
150
+ return refuse(CLIP_REASONS.newer);
151
+ if (kind === "element") {
152
+ const layout = validated(schemaVersion, { children: [data["node"]] });
153
+ if ("ok" in layout) return layout;
154
+ const node = layout.root.children[0];
155
+ return node ? { ok: true, clip: { kind, node } } : refuse(CLIP_REASONS.unreadable);
156
+ }
157
+ if (kind === "style") {
158
+ const own: Record<string, unknown> = {};
159
+ if (data["style"] !== undefined) own["style"] = data["style"];
160
+ if (data["states"] !== undefined) own["states"] = data["states"];
161
+ if (data["devices"] !== undefined) own["devices"] = data["devices"];
162
+ if (data["hiddenOn"] !== undefined) own["hiddenOn"] = data["hiddenOn"];
163
+ const layout = validated(schemaVersion, own);
164
+ if ("ok" in layout) return layout;
165
+ return { ok: true, clip: { kind, style: styleOf(layout.root) } };
166
+ }
167
+ return refuse(CLIP_REASONS.unreadable);
168
+ }
169
+
170
+ /** The style a clip pastes: a style clip's own, or an element clip's element's local style. */
171
+ export const clipStyle = (clip: Clip): CopiedStyle =>
172
+ clip.kind === "style" ? clip.style : styleOf(clip.node);
173
+
174
+ /** What a paste left out because the target page or site doesn't allow or have it. */
175
+ export type Dropped = { classes: number; variables: number; htmlIds: number; unsafe: number };
176
+
177
+ const none = (): Dropped => ({ classes: 0, variables: 0, htmlIds: 0, unsafe: 0 });
178
+
179
+ const VARIABLE_LISTS = {
180
+ color: "colors",
181
+ font: "fonts",
182
+ fontSize: "fontSizes",
183
+ spacing: "spacings",
184
+ } as const;
185
+
186
+ type Ref = { var: string; kind: VariableKind };
187
+
188
+ const asRef = (value: unknown): Ref | null =>
189
+ isRecord(value) && typeof value["var"] === "string"
190
+ ? { var: value["var"], kind: (value["from"] as VariableKind | undefined) ?? "color" }
191
+ : null;
192
+
193
+ /** Every variable ref in a style: each value, plus nested colours (shadow, gradient, overlay). */
194
+ function refsInStyle(style: StyleProps | undefined): Ref[] {
195
+ if (!style) return [];
196
+ const values: unknown[] = [
197
+ ...Object.values(style),
198
+ style.boxShadow?.color,
199
+ style.gradient?.from,
200
+ style.gradient?.to,
201
+ style.overlay?.color,
202
+ ];
203
+ return values.map(asRef).filter((ref): ref is Ref => ref !== null);
204
+ }
205
+
206
+ const refsOf = (owner: CopiedStyle): Ref[] => [
207
+ ...refsInStyle(owner.style),
208
+ ...STYLE_STATES.flatMap((state) => refsInStyle(owner.states?.[state])),
209
+ ...refsInStyle(owner.devices?.tablet),
210
+ ...refsInStyle(owner.devices?.mobile),
211
+ ];
212
+
213
+ const hasVariable = (design: DesignSystem, ref: Ref) =>
214
+ (design.variables[VARIABLE_LISTS[ref.kind]] ?? []).some((v) => v.id === ref.var);
215
+
216
+ /** Removes refs to variables the design doesn't have, counting each. */
217
+ function withKnownVariables<T extends LayoutNode>(
218
+ node: T,
219
+ design: DesignSystem,
220
+ dropped: Dropped,
221
+ ): T {
222
+ const missing = refsOf(node).filter((ref) => !hasVariable(design, ref));
223
+ if (missing.length === 0) return node;
224
+ dropped.variables += missing.length;
225
+ let wrapper: Layout = {
226
+ schemaVersion: LAYOUT_SCHEMA_VERSION,
227
+ root: { id: WRAPPER_ID, type: "container", props: {}, children: [node] },
228
+ };
229
+ for (const ref of missing) wrapper = clearVariableRefs(wrapper, ref.var, ref.kind);
230
+ return wrapper.root.children[0] as T;
231
+ }
232
+
233
+ const SANITIZERS = {
234
+ href: sanitizeHref,
235
+ media: sanitizeMediaUrl,
236
+ } as const;
237
+
238
+ /** Props the sanitizers refuse fall back to the element's default, or go when optional. */
239
+ function withSafeProps(node: LayoutNode, dropped: Dropped): LayoutNode {
240
+ const type = node.type as ElementType;
241
+ if (!(type in ELEMENTS)) return node;
242
+ const props = { ...(node.props as Record<string, unknown>) };
243
+ const defaults = (ELEMENTS[type].defaults() as { props: Record<string, unknown> }).props;
244
+ let changed = false;
245
+ const fallBack = (key: string, optional: boolean | undefined) => {
246
+ dropped.unsafe++;
247
+ changed = true;
248
+ if (optional || defaults[key] === undefined) delete props[key];
249
+ else props[key] = defaults[key];
250
+ };
251
+ const fields = ELEMENT_DESCRIPTORS.find((d) => d.type === type)?.fields ?? [];
252
+ for (const field of fields) {
253
+ if (field.kind !== "href" && field.kind !== "media") continue;
254
+ const value = props[field.key];
255
+ if (typeof value !== "string" || value.trim() === "") continue;
256
+ const safe = SANITIZERS[field.kind](value);
257
+ if (safe === undefined) fallBack(field.key, field.optional);
258
+ else if (safe !== value) {
259
+ props[field.key] = safe;
260
+ changed = true;
261
+ }
262
+ }
263
+ if (type === "svg" && typeof props["markup"] === "string" && !isSafeSvgMarkup(props["markup"]))
264
+ fallBack("markup", false);
265
+ return changed ? ({ ...node, props } as LayoutNode) : node;
266
+ }
267
+
268
+ function htmlIdsOf(node: LayoutNode, into = new Set<string>()): Set<string> {
269
+ if (node.htmlId) into.add(node.htmlId);
270
+ for (const child of nodeChildren(node)) htmlIdsOf(child, into);
271
+ return into;
272
+ }
273
+
274
+ /** The checks above on one node, then on each of its children. */
275
+ function cleanNode(
276
+ node: LayoutNode,
277
+ design: DesignSystem,
278
+ usedHtmlIds: Set<string>,
279
+ dropped: Dropped,
280
+ ): LayoutNode {
281
+ let next = withSafeProps(withKnownVariables(node, design, dropped), dropped);
282
+ if (next.classes) {
283
+ const known = new Set((design.classes ?? []).map((cls) => cls.id));
284
+ const kept = next.classes.filter((id) => known.has(id));
285
+ if (kept.length !== next.classes.length) {
286
+ dropped.classes += next.classes.length - kept.length;
287
+ next = { ...next, classes: kept };
288
+ if (kept.length === 0) delete next.classes;
289
+ }
290
+ }
291
+ if (next.htmlId && usedHtmlIds.has(next.htmlId)) {
292
+ dropped.htmlIds++;
293
+ next = { ...next };
294
+ delete next.htmlId;
295
+ }
296
+ const kids = nodeChildren(next);
297
+ if (kids.length === 0) return next;
298
+ return {
299
+ ...next,
300
+ children: kids.map((child) => cleanNode(child, design, usedHtmlIds, dropped)),
301
+ } as LayoutNode;
302
+ }
303
+
304
+ /**
305
+ * The node a paste inserts: new ids that aren't used on `layout` (like Duplicate), class and
306
+ * variable refs the design doesn't have removed, CSS ids already on the page removed, and
307
+ * values the sanitizers refuse replaced. `dropped` counts what was left out, for the notice.
308
+ */
309
+ export function prepareElement(
310
+ node: LayoutNode,
311
+ layout: Layout,
312
+ design: DesignSystem,
313
+ random: () => number = Math.random,
314
+ ): { node: LayoutNode; dropped: Dropped } {
315
+ const dropped = none();
316
+ const cleaned = cleanNode(node, design, htmlIdsOf(layout.root), dropped);
317
+ return { node: withFreshIds(layout, cleaned, random), dropped };
318
+ }
319
+
320
+ /** A copied style with refs to variables the design doesn't have removed. */
321
+ export function prepareStyle(
322
+ style: CopiedStyle,
323
+ design: DesignSystem,
324
+ ): { style: CopiedStyle; dropped: Dropped } {
325
+ const dropped = none();
326
+ const holder = withKnownVariables(
327
+ { id: WRAPPER_ID, type: "divider", props: {}, ...style } as LayoutNode,
328
+ design,
329
+ dropped,
330
+ );
331
+ return { style: styleOf(holder), dropped };
332
+ }
333
+
334
+ /** Replaces the node's local style, states and device overrides; props, classes and children stay. */
335
+ export function applyStyle<T extends LayoutNode>(node: T, style: CopiedStyle): T {
336
+ const next = { ...node };
337
+ delete next.style;
338
+ delete next.states;
339
+ delete next.devices;
340
+ delete next.hiddenOn;
341
+ if (style.style) next.style = structuredClone(style.style);
342
+ if (style.states) next.states = structuredClone(style.states);
343
+ if (style.devices) next.devices = structuredClone(style.devices);
344
+ if (style.hiddenOn) next.hiddenOn = structuredClone(style.hiddenOn);
345
+ return next;
346
+ }
347
+
348
+ export type PasteMode = "auto" | "inside";
349
+
350
+ /**
351
+ * Where a pasted node goes (W-093). `auto`: right after the selected element; if the drop rules
352
+ * refuse that, inside it at the end (a field pasted on a form, a panel on Tabs); with nothing
353
+ * selected, or the page's outer container selected, at the end of the page. `inside`: at the end
354
+ * of the selected element. A refusal carries the drop rule's reason.
355
+ */
356
+ export function pastePlace(
357
+ layout: Layout,
358
+ node: LayoutNode,
359
+ selectedId: string | null,
360
+ mode: PasteMode = "auto",
361
+ ): { ok: true; place: Place } | Refusal {
362
+ const target = (selectedId && findNode(layout, selectedId)) || layout.root;
363
+ const source = { kind: "new" as const, node };
364
+ const inside = (): { ok: true; place: Place } | Refusal => {
365
+ const allowed = canDrop(layout, source, target.id);
366
+ if (!allowed.ok) return allowed;
367
+ return {
368
+ ok: true,
369
+ place: { parentId: target.id, index: (target as ContainerNode).children.length },
370
+ };
371
+ };
372
+ const parentId = parentOf(layout, target.id);
373
+ if (mode === "inside" || !parentId) {
374
+ return isParentNode(target) ? inside() : refuse(REASONS.notContainer);
375
+ }
376
+ const after = canDrop(layout, source, parentId);
377
+ if (after.ok) {
378
+ const parent = findNode(layout, parentId) as ContainerNode;
379
+ const index = parent.children.findIndex((child) => child.id === target.id);
380
+ return { ok: true, place: { parentId, index: index + 1 } };
381
+ }
382
+ if (isParentNode(target)) {
383
+ const into = inside();
384
+ if (into.ok) return into;
385
+ }
386
+ return after;
387
+ }
388
+
389
+ /** Pastes a prepared node where `pastePlace` says, or returns the refusal. */
390
+ export function pasteNode(
391
+ layout: Layout,
392
+ node: LayoutNode,
393
+ selectedId: string | null,
394
+ mode: PasteMode = "auto",
395
+ ): Arranged {
396
+ const where = pastePlace(layout, node, selectedId, mode);
397
+ return where.ok ? addNode(layout, node, where.place) : where;
398
+ }
399
+
400
+ /** The notice after a paste that left something out, or null when nothing was. */
401
+ export function droppedNotice(dropped: Dropped): string | null {
402
+ const parts: string[] = [];
403
+ const count = (n: number, one: string, many: string) => {
404
+ if (n > 0) parts.push(`${n} ${n === 1 ? one : many}`);
405
+ };
406
+ count(dropped.classes, "class", "classes");
407
+ count(dropped.variables, "variable", "variables");
408
+ count(dropped.htmlIds, "CSS id already used on this page", "CSS ids already used on this page");
409
+ count(
410
+ dropped.unsafe,
411
+ "link, image or SVG that isn't allowed",
412
+ "links, images or SVGs that aren't allowed",
413
+ );
414
+ if (parts.length === 0) return null;
415
+ const list =
416
+ parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
417
+ const missing =
418
+ dropped.classes + dropped.variables > 0
419
+ ? " Classes and variables this site doesn't have were removed."
420
+ : "";
421
+ return `Left out ${list}.${missing}`;
422
+ }
@@ -0,0 +1,219 @@
1
+ import type { DesignSystem } from "../schema/design.ts";
2
+ import { DEFAULT_STYLE_TAGS } from "../schema/design.ts";
3
+ import {
4
+ colorVariableName,
5
+ fontSizeVariableName,
6
+ fontVariableName,
7
+ isSafeCssValue,
8
+ isSafeFontStack,
9
+ spacingVariableName,
10
+ stateDeclarations,
11
+ styleClassName,
12
+ styleDeclarations,
13
+ type Declaration,
14
+ type StateDeclarations,
15
+ } from "../sanitize/css.ts";
16
+ import { STYLE_STATES, type StyleStateName } from "../schema/state-names.ts";
17
+ import { DEVICE_MEDIA, type PopupDevice } from "../theme/popup-rules.ts";
18
+
19
+ export type CssInput = {
20
+ design: DesignSystem;
21
+ usedTypes: ReadonlySet<string>;
22
+ baseCss: ReadonlyMap<string, string>;
23
+ localRules: ReadonlyArray<{
24
+ id: string;
25
+ declarations: Declaration[];
26
+ states?: StateDeclarations;
27
+ /** Tablet and mobile overrides (W-096). Desktop stays in `declarations`. */
28
+ tablet?: Declaration[];
29
+ mobile?: Declaration[];
30
+ hiddenOn?: readonly PopupDevice[];
31
+ }>;
32
+ /** Editor canvas only: repeat each state rule for `[data-emvb-state="<state>"]` (W-089). */
33
+ previewStates?: boolean;
34
+ /** When a node rendered a background video (W-110). */
35
+ backgroundVideo?: boolean;
36
+ /**
37
+ * Editor canvas only (W-116): the device the canvas previews. Device rules then follow this
38
+ * device instead of the frame's width, so the Desktop canvas never picks up tablet styles in a
39
+ * narrow window. Without it, the rules sit in their media queries as usual.
40
+ */
41
+ previewDevice?: PopupDevice;
42
+ };
43
+
44
+ /** Focus is keyboard focus (W-089): `:focus-visible`, never `:focus`. */
45
+ const STATE_PSEUDO: Readonly<Record<StyleStateName, string>> = {
46
+ hover: ":hover",
47
+ focus: ":focus-visible",
48
+ active: ":active",
49
+ };
50
+
51
+ const block = (selector: string, declarations: Declaration[]) =>
52
+ declarations.length === 0
53
+ ? ""
54
+ : `${selector}{${declarations.map((d) => `${d.property}:${d.value}`).join(";")}}`;
55
+
56
+ /** Tag defaults sit under `:where` so a class (0,1,0) still beats the tag (0,0,1). */
57
+ function tagDefaultCss(design: DesignSystem): string {
58
+ const defaults = design.defaults;
59
+ if (!defaults) return "";
60
+ let css = "";
61
+ for (const tag of DEFAULT_STYLE_TAGS) {
62
+ const style = defaults[tag];
63
+ if (!style) continue;
64
+ const { declarations } = styleDeclarations(style);
65
+ css += block(`:where(.emvb-root) ${tag}`, declarations);
66
+ }
67
+ return css;
68
+ }
69
+
70
+ const safe = (value: string) => (isSafeCssValue(value) ? value : undefined);
71
+
72
+ const fontStack = (value: string) => (isSafeFontStack(value) ? value : undefined);
73
+
74
+ const lengthCss = (length: { value: number; unit: string }) =>
75
+ safe(`${length.value}${length.unit}`);
76
+
77
+ /** One custom property per variable whose id and value are both safe to emit. */
78
+ function declare<T extends { id: string }>(
79
+ variables: readonly T[] | undefined,
80
+ name: (id: string) => string | undefined,
81
+ value: (variable: T) => string | undefined,
82
+ ): Declaration[] {
83
+ return (variables ?? []).flatMap((variable) => {
84
+ const property = name(variable.id);
85
+ const css = value(variable);
86
+ return property && css ? [{ property, value: css }] : [];
87
+ });
88
+ }
89
+
90
+ /**
91
+ * Cascade order (R-021 / W-030 / W-089): variables on `.emvb-root`, base CSS, shared
92
+ * `.emvb-k-<id>` class rules, then local `.emvb-e-<id>` (local wins). Each selector's `:hover`,
93
+ * `:focus-visible` and `:active` rules follow its base rule in that order, so a state beats Normal,
94
+ * local states beat class states, and Active beats Hover when both apply. Transitions sit on the
95
+ * base rule, and one closing `prefers-reduced-motion: reduce` block turns them all off.
96
+ */
97
+ export function generateCss({
98
+ design,
99
+ usedTypes,
100
+ baseCss,
101
+ localRules,
102
+ previewStates = false,
103
+ backgroundVideo = false,
104
+ previewDevice,
105
+ }: CssInput): string {
106
+ const { colors, fonts, fontSizes, spacings } = design.variables;
107
+ const variables = [
108
+ ...declare(colors, colorVariableName, (color) => safe(color.value)),
109
+ ...declare(fonts, fontVariableName, (font) => fontStack(font.value)),
110
+ ...declare(fontSizes, fontSizeVariableName, (size) => lengthCss(size.value)),
111
+ ...declare(spacings, spacingVariableName, (space) => lengthCss(space.value)),
112
+ ];
113
+ const animated: string[] = [];
114
+ const entrances: string[] = [];
115
+ const rules = (selector: string, declarations: Declaration[], states: StateDeclarations) => [
116
+ block(selector, declarations),
117
+ ...STYLE_STATES.map((state) =>
118
+ block(
119
+ previewStates
120
+ ? `${selector}${STATE_PSEUDO[state]},${selector}[data-emvb-state="${state}"]`
121
+ : `${selector}${STATE_PSEUDO[state]}`,
122
+ states[state] ?? [],
123
+ ),
124
+ ),
125
+ ];
126
+ const track = (selector: string, declarations: Declaration[]) => {
127
+ if (declarations.some((d) => d.property === "transition")) animated.push(selector);
128
+ if (declarations.some((d) => d.property === "animation")) entrances.push(selector);
129
+ return declarations;
130
+ };
131
+ const classes = (design.classes ?? []).flatMap((cls) => {
132
+ const className = styleClassName(cls.id);
133
+ return className
134
+ ? rules(
135
+ `.${className}`,
136
+ track(`.${className}`, styleDeclarations(cls.style).declarations),
137
+ stateDeclarations(cls.states).states,
138
+ )
139
+ : [];
140
+ });
141
+ const locals = localRules.flatMap((rule) =>
142
+ rules(`.emvb-e-${rule.id}`, track(`.emvb-e-${rule.id}`, rule.declarations), rule.states ?? {}),
143
+ );
144
+ const responsive = [
145
+ ...(design.classes ?? []).flatMap((cls) => {
146
+ const className = styleClassName(cls.id);
147
+ return className
148
+ ? [
149
+ {
150
+ selector: `.${className}`,
151
+ tablet: styleDeclarations(cls.devices?.tablet).declarations,
152
+ mobile: styleDeclarations(cls.devices?.mobile).declarations,
153
+ hiddenOn: cls.hiddenOn,
154
+ },
155
+ ]
156
+ : [];
157
+ }),
158
+ ...localRules.map((rule) => ({
159
+ selector: `.emvb-e-${rule.id}`,
160
+ tablet: rule.tablet ?? [],
161
+ mobile: rule.mobile ?? [],
162
+ hiddenOn: rule.hiddenOn,
163
+ })),
164
+ ];
165
+ /** A device block: in its media query, or, for a previewed device, on or off outright. */
166
+ const forDevices = (devices: readonly PopupDevice[], query: string, body: string) => {
167
+ if (!body) return "";
168
+ if (previewDevice === undefined) return `@media ${query}{${body}}`;
169
+ return devices.includes(previewDevice) ? body : "";
170
+ };
171
+ const at = (query: string, which: "tablet" | "mobile") =>
172
+ forDevices(
173
+ which === "tablet" ? ["tablet", "mobile"] : ["mobile"],
174
+ query,
175
+ responsive.map((rule) => block(rule.selector, rule[which])).join(""),
176
+ );
177
+ const hide = (device: PopupDevice, query: string) => {
178
+ const selectors = responsive
179
+ .filter((rule) => rule.hiddenOn?.includes(device))
180
+ .map((rule) => rule.selector);
181
+ return forDevices(
182
+ [device],
183
+ query,
184
+ selectors.length > 0 ? `${selectors.join(",")}{display:none}` : "",
185
+ );
186
+ };
187
+ for (const rule of responsive) {
188
+ if (
189
+ !entrances.includes(rule.selector) &&
190
+ [...rule.tablet, ...rule.mobile].some((d) => d.property === "animation")
191
+ ) {
192
+ entrances.push(rule.selector);
193
+ }
194
+ }
195
+ return [
196
+ entrances.length > 0
197
+ ? "@keyframes emvb-fade{from{opacity:0}to{opacity:1}}@keyframes emvb-fade-up{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}@keyframes emvb-fade-down{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}@keyframes emvb-slide-up{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:none}}@keyframes emvb-slide-down{from{opacity:0;transform:translateY(-16px)}to{opacity:1;transform:none}}@keyframes emvb-scale{from{opacity:0;transform:scale(0.96)}to{opacity:1;transform:none}}"
198
+ : "",
199
+ block(".emvb-root", variables),
200
+ tagDefaultCss(design),
201
+ backgroundVideo
202
+ ? ".emvb-has-bg-video{position:relative;overflow:hidden}.emvb-bg-video{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:0;pointer-events:none}.emvb-has-bg-video>:not(.emvb-bg-video){position:relative;z-index:1}"
203
+ : "",
204
+ ...[...usedTypes].toSorted().map((type) => baseCss.get(type) ?? ""),
205
+ ...classes,
206
+ ...locals,
207
+ at(DEVICE_MEDIA.tablet, "tablet"),
208
+ at(DEVICE_MEDIA.mobile, "mobile"),
209
+ hide("desktop", DEVICE_MEDIA.hideDesktop),
210
+ hide("tablet", DEVICE_MEDIA.hideTablet),
211
+ hide("mobile", DEVICE_MEDIA.hideMobile),
212
+ animated.length > 0
213
+ ? `@media (prefers-reduced-motion: reduce){${animated.join(",")}{transition:none}}`
214
+ : "",
215
+ entrances.length > 0
216
+ ? `@media (prefers-reduced-motion: reduce){${entrances.join(",")}{animation:none}}`
217
+ : "",
218
+ ].join("");
219
+ }