@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,591 @@
1
+ import { STYLE_STATES, type StyleStateName } from "../schema/state-names.ts";
2
+ import type { StyleProps } from "../schema/style.ts";
3
+ import { sanitizeMediaUrl } from "./media-url.ts";
4
+
5
+ const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
6
+ const VAR_ID = /^[a-z0-9-]{1,40}$/;
7
+ const UNITS = new Set(["px", "rem", "em", "%", "vw", "vh"]);
8
+ const FLEX_DIRECTIONS = new Set(["row", "column", "row-reverse", "column-reverse"]);
9
+ const FLEX_WRAPS = new Set(["nowrap", "wrap", "wrap-reverse"]);
10
+ const JUSTIFY = new Set([
11
+ "flex-start",
12
+ "flex-end",
13
+ "center",
14
+ "space-between",
15
+ "space-around",
16
+ "space-evenly",
17
+ ]);
18
+ const ALIGN = new Set(["stretch", "flex-start", "flex-end", "center", "baseline"]);
19
+ const TEXT_TRANSFORM = new Set(["none", "uppercase", "lowercase", "capitalize"]);
20
+ const TEXT_DECORATION = new Set(["none", "underline", "overline", "line-through"]);
21
+ const BORDER_STYLE = new Set(["none", "solid", "dashed", "dotted"]);
22
+ const OVERFLOW = new Set(["visible", "hidden", "clip", "scroll", "auto"]);
23
+ const OBJECT_FIT = new Set(["fill", "contain", "cover", "none", "scale-down"]);
24
+ const POSITION = new Set(["static", "relative", "absolute", "fixed", "sticky"]);
25
+ const CURSOR = new Set([
26
+ "default",
27
+ "pointer",
28
+ "text",
29
+ "move",
30
+ "grab",
31
+ "not-allowed",
32
+ "help",
33
+ "crosshair",
34
+ "zoom-in",
35
+ ]);
36
+ const ASPECT_RATIO = /^([1-9]\d{0,3})\/([1-9]\d{0,3})$/;
37
+ const FONT_WEIGHT = new Set(["normal", "bold", "400", "500", "600", "700"]);
38
+ const FORBIDDEN = /[{};<>\\"'`]|\/\*|url\(|expression\(|@import|javascript:/i;
39
+
40
+ /** Last line of defence on every emitted value, even ones built by the typed validators below. */
41
+ export function isSafeCssValue(value: string): boolean {
42
+ return value.length > 0 && value.length <= 200 && !FORBIDDEN.test(value) && !/[\n\r]/.test(value);
43
+ }
44
+
45
+ const FAMILY = String.raw`(?:'[\p{L}\p{N} _.-]+'|"[\p{L}\p{N} _.-]+"|[\p{L}\p{N}_-]+(?: [\p{L}\p{N}_-]+)*)`;
46
+ const FONT_STACK = new RegExp(String.raw`^${FAMILY}(?:\s*,\s*${FAMILY})*$`, "u");
47
+
48
+ /**
49
+ * A comma-separated font stack whose family names may be quoted. Quoted names hold only letters,
50
+ * digits, spaces, `_`, `.` and `-`, so a quote can never open or close anything else.
51
+ */
52
+ export function isSafeFontStack(value: string): boolean {
53
+ return (
54
+ isSafeCssValue(value) ||
55
+ (value.length <= 200 && !/[\n\r]/.test(value) && FONT_STACK.test(value))
56
+ );
57
+ }
58
+
59
+ export function colorVariableName(id: string): string | undefined {
60
+ return VAR_ID.test(id) ? `--emvb-c-${id}` : undefined;
61
+ }
62
+
63
+ export function fontVariableName(id: string): string | undefined {
64
+ return VAR_ID.test(id) ? `--emvb-f-${id}` : undefined;
65
+ }
66
+
67
+ export function fontSizeVariableName(id: string): string | undefined {
68
+ return VAR_ID.test(id) ? `--emvb-fs-${id}` : undefined;
69
+ }
70
+
71
+ export function spacingVariableName(id: string): string | undefined {
72
+ return VAR_ID.test(id) ? `--emvb-s-${id}` : undefined;
73
+ }
74
+
75
+ /** Public class selector fragment `emvb-k-<id>` (never unprefixed). */
76
+ export function styleClassName(id: string): string | undefined {
77
+ if (!/^[a-z0-9-]{1,40}$/.test(id)) return undefined;
78
+ return `emvb-k-${id}`;
79
+ }
80
+
81
+ type VarFrom = "color" | "font" | "fontSize" | "spacing";
82
+
83
+ function refOf(value: object): { id: string; from: VarFrom } | undefined {
84
+ if (!("var" in value) || typeof (value as { var?: unknown }).var !== "string") return undefined;
85
+ const id = (value as { var: string }).var;
86
+ if (!VAR_ID.test(id)) return undefined;
87
+ const from = (value as { from?: unknown }).from;
88
+ if (from === undefined || from === "color") return { id, from: "color" };
89
+ if (from === "font" || from === "fontSize" || from === "spacing") return { id, from };
90
+ return undefined;
91
+ }
92
+
93
+ export function cssColor(value: unknown): string | undefined {
94
+ if (typeof value === "string") return HEX_COLOR.test(value) ? value.toLowerCase() : undefined;
95
+ if (typeof value === "object" && value !== null) {
96
+ const ref = refOf(value);
97
+ if (!ref || ref.from !== "color") return undefined;
98
+ const name = colorVariableName(ref.id);
99
+ return name ? `var(${name})` : undefined;
100
+ }
101
+ return undefined;
102
+ }
103
+
104
+ function cssFontFamily(value: unknown): string | undefined {
105
+ if (typeof value === "string") {
106
+ return isSafeFontStack(value) && !HEX_COLOR.test(value) ? value : undefined;
107
+ }
108
+ if (typeof value === "object" && value !== null) {
109
+ const ref = refOf(value);
110
+ if (!ref || ref.from !== "font") return undefined;
111
+ const name = fontVariableName(ref.id);
112
+ return name ? `var(${name})` : undefined;
113
+ }
114
+ return undefined;
115
+ }
116
+
117
+ export function cssLength(value: unknown): string | undefined {
118
+ if (typeof value !== "object" || value === null) return undefined;
119
+ const ref = refOf(value);
120
+ if (ref) {
121
+ if (ref.from === "fontSize") {
122
+ const name = fontSizeVariableName(ref.id);
123
+ return name ? `var(${name})` : undefined;
124
+ }
125
+ if (ref.from === "spacing") {
126
+ const name = spacingVariableName(ref.id);
127
+ return name ? `var(${name})` : undefined;
128
+ }
129
+ return undefined;
130
+ }
131
+ const { value: n, unit } = value as { value?: unknown; unit?: unknown };
132
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 0 || n > 10_000) return undefined;
133
+ if (typeof unit !== "string" || !UNITS.has(unit)) return undefined;
134
+ return `${n}${unit}`;
135
+ }
136
+
137
+ /** A length, or `auto` where the property allows it (W-088). */
138
+ const cssLengthOrAuto = (value: unknown): string | undefined =>
139
+ value === "auto" ? "auto" : cssLength(value);
140
+
141
+ /** An offset: `auto`, a variable, or a length from -10000 to 10000 (W-088). */
142
+ function cssOffset(value: unknown): string | undefined {
143
+ if (value === "auto") return "auto";
144
+ if (typeof value !== "object" || value === null || "var" in value) return cssLength(value);
145
+ const { value: n, unit } = value as { value?: unknown; unit?: unknown };
146
+ if (typeof n !== "number" || !Number.isFinite(n) || n < -10_000 || n > 10_000) return undefined;
147
+ if (typeof unit !== "string" || !UNITS.has(unit)) return undefined;
148
+ return `${n}${unit}`;
149
+ }
150
+
151
+ const cssZIndex = (value: unknown): string | undefined =>
152
+ Number.isInteger(value) && (value as number) >= -9999 && (value as number) <= 9999
153
+ ? String(value)
154
+ : undefined;
155
+
156
+ const ENTRANCES = new Set(["fade", "fade-up", "fade-down", "slide-up", "slide-down", "scale"]);
157
+
158
+ /** `emvb-<type> <ms> ease-out [delay] both`. A bad trigger drops the whole entrance. */
159
+ function cssEntrance(value: unknown): string | undefined {
160
+ if (typeof value !== "object" || value === null) return undefined;
161
+ const { type, duration, delay, trigger } = value as {
162
+ type?: unknown;
163
+ duration?: unknown;
164
+ delay?: unknown;
165
+ trigger?: unknown;
166
+ };
167
+ if (typeof type !== "string" || !ENTRANCES.has(type)) return undefined;
168
+ if (!Number.isInteger(duration) || (duration as number) < 0 || (duration as number) > 2000) {
169
+ return undefined;
170
+ }
171
+ if (trigger !== undefined && trigger !== "load" && trigger !== "view") return undefined;
172
+ if (
173
+ delay !== undefined &&
174
+ (!Number.isInteger(delay) || (delay as number) < 0 || (delay as number) > 2000)
175
+ ) {
176
+ return undefined;
177
+ }
178
+ const wait = typeof delay === "number" && delay > 0 ? ` ${delay}ms` : "";
179
+ return `emvb-${type} ${duration}ms ease-out${wait} both`;
180
+ }
181
+
182
+ function cssTextAlign(value: unknown): string | undefined {
183
+ if (value === "left") return "start";
184
+ if (value === "right") return "end";
185
+ if (value === "center" || value === "justify") return value;
186
+ return undefined;
187
+ }
188
+
189
+ const cssGridSpan = (value: unknown): string | undefined =>
190
+ Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 12
191
+ ? `span ${value}`
192
+ : undefined;
193
+
194
+ const inRange = (value: unknown, min: number, max: number): value is number =>
195
+ typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
196
+
197
+ const cssOpacity = (value: unknown) => (inRange(value, 0, 1) ? String(value) : undefined);
198
+
199
+ const SHADOW_KEYS = new Set(["x", "y", "blur", "spread", "color", "inset"]);
200
+
201
+ /** `[inset] x y blur spread [colour]`, built only from checked numbers and a checked colour. */
202
+ function cssBoxShadow(value: unknown): string | undefined {
203
+ if (typeof value !== "object" || value === null) return undefined;
204
+ if (Object.keys(value).some((key) => !SHADOW_KEYS.has(key))) return undefined;
205
+ const { x, y, blur, spread, color, inset } = value as Record<string, unknown>;
206
+ if (!inRange(x, -1000, 1000) || !inRange(y, -1000, 1000)) return undefined;
207
+ if (!inRange(blur, 0, 1000) || !inRange(spread, -1000, 1000)) return undefined;
208
+ if (inset !== undefined && typeof inset !== "boolean") return undefined;
209
+ const colour = color === undefined ? undefined : cssColor(color);
210
+ if (color !== undefined && colour === undefined) return undefined;
211
+ const parts = [inset ? "inset" : "", `${x}px ${y}px ${blur}px ${spread}px`, colour ?? ""];
212
+ return parts.filter(Boolean).join(" ");
213
+ }
214
+
215
+ /** Filter functions in a fixed order, each with its own range and unit. */
216
+ const FILTERS: ReadonlyArray<[key: string, fn: string, max: number, unit: string]> = [
217
+ ["blur", "blur", 100, "px"],
218
+ ["brightness", "brightness", 300, "%"],
219
+ ["contrast", "contrast", 300, "%"],
220
+ ["saturate", "saturate", 300, "%"],
221
+ ["grayscale", "grayscale", 100, "%"],
222
+ ["hueRotate", "hue-rotate", 360, "deg"],
223
+ ];
224
+ const FILTER_KEYS = new Set(FILTERS.map(([key]) => key));
225
+
226
+ function cssFilter(value: unknown): string | undefined {
227
+ if (typeof value !== "object" || value === null) return undefined;
228
+ const filter = value as Record<string, unknown>;
229
+ if (Object.keys(filter).some((key) => !FILTER_KEYS.has(key))) return undefined;
230
+ const parts: string[] = [];
231
+ for (const [key, fn, max, unit] of FILTERS) {
232
+ const n = filter[key];
233
+ if (n === undefined) continue;
234
+ if (!inRange(n, 0, max)) return undefined;
235
+ parts.push(`${fn}(${n}${unit})`);
236
+ }
237
+ return parts.length > 0 ? parts.join(" ") : undefined;
238
+ }
239
+
240
+ function cssAspectRatio(value: unknown): string | undefined {
241
+ if (value === "auto") return "auto";
242
+ const match = typeof value === "string" ? ASPECT_RATIO.exec(value) : null;
243
+ return match ? `${match[1]} / ${match[2]}` : undefined;
244
+ }
245
+
246
+ export function cssFlexDirection(value: unknown): string | undefined {
247
+ return typeof value === "string" && FLEX_DIRECTIONS.has(value) ? value : undefined;
248
+ }
249
+
250
+ const keyword =
251
+ (allowed: Set<string>) =>
252
+ (value: unknown): string | undefined =>
253
+ typeof value === "string" && allowed.has(value) ? value : undefined;
254
+
255
+ function cssFontWeight(value: unknown): string | undefined {
256
+ if (typeof value === "number" && FONT_WEIGHT.has(String(value))) return String(value);
257
+ if (typeof value === "string" && FONT_WEIGHT.has(value)) return value;
258
+ return undefined;
259
+ }
260
+
261
+ const TRANSITION_EASINGS = new Set(["ease", "ease-in", "ease-out", "ease-in-out", "linear"]);
262
+ const TRANSITION_PROPERTIES: Readonly<Record<string, readonly string[]>> = {
263
+ all: ["all"],
264
+ colors: ["color", "background-color", "border-color"],
265
+ opacity: ["opacity"],
266
+ shadow: ["box-shadow"],
267
+ filter: ["filter"],
268
+ };
269
+ const TRANSITION_KEYS = new Set(["duration", "delay", "easing", "property"]);
270
+
271
+ const ms = (n: unknown) => (Number.isInteger(n) && inRange(n, 0, 2000) ? `${n}ms` : undefined);
272
+
273
+ /** W-089: `{ duration, delay?, easing, property }` to one transition entry per CSS property. */
274
+ function cssTransition(value: unknown): string | undefined {
275
+ if (typeof value !== "object" || value === null) return undefined;
276
+ const t = value as Record<string, unknown>;
277
+ if (Object.keys(t).some((key) => !TRANSITION_KEYS.has(key))) return undefined;
278
+ const duration = ms(t["duration"]);
279
+ const delay = t["delay"] === undefined ? "" : ms(t["delay"]);
280
+ const easing = typeof t["easing"] === "string" && TRANSITION_EASINGS.has(t["easing"]);
281
+ const properties =
282
+ typeof t["property"] === "string" && Object.hasOwn(TRANSITION_PROPERTIES, t["property"])
283
+ ? TRANSITION_PROPERTIES[t["property"]]
284
+ : undefined;
285
+ if (!duration || delay === undefined || !easing || !properties) return undefined;
286
+ const timing = `${duration} ${t["easing"] as string}${delay ? ` ${delay}` : ""}`;
287
+ return properties.map((property) => `${property} ${timing}`).join(",");
288
+ }
289
+
290
+ export type Declaration = { property: string; value: string };
291
+
292
+ const BACKGROUND_SIZE = new Set(["auto", "cover", "contain"]);
293
+ const BACKGROUND_POSITION = new Set([
294
+ "center",
295
+ "top",
296
+ "bottom",
297
+ "left",
298
+ "right",
299
+ "top left",
300
+ "top right",
301
+ "bottom left",
302
+ "bottom right",
303
+ ]);
304
+ const BACKGROUND_REPEAT = new Set(["no-repeat", "repeat", "repeat-x", "repeat-y"]);
305
+ const BACKGROUND_KEYS = new Set([
306
+ "backgroundImage",
307
+ "backgroundSize",
308
+ "backgroundPosition",
309
+ "backgroundRepeat",
310
+ "gradient",
311
+ "overlay",
312
+ "backgroundVideo",
313
+ ]);
314
+
315
+ /** Backstop for values that must contain `url()` or quotes, which `isSafeCssValue` refuses. */
316
+ function isSafeBackground(value: string): boolean {
317
+ return value.length > 0 && value.length <= 4096 && !/[{};<>\\`]|\/\*|\n|\r/.test(value);
318
+ }
319
+
320
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
321
+ typeof value === "object" && value !== null && !Array.isArray(value);
322
+
323
+ /** A media URL wrapped for CSS. The schema already refuses quotes, spaces and parentheses. */
324
+ function cssBackgroundImage(value: unknown): string | undefined {
325
+ if (typeof value !== "string") return undefined;
326
+ if (sanitizeMediaUrl(value) !== value || /[()\\\s"'`]/.test(value)) return undefined;
327
+ const css = `url("${value}")`;
328
+ return isSafeBackground(css) ? css : undefined;
329
+ }
330
+
331
+ function cssGradient(value: unknown): string | undefined {
332
+ if (!isRecord(value)) return undefined;
333
+ if (Object.keys(value).some((key) => key !== "angle" && key !== "from" && key !== "to"))
334
+ return undefined;
335
+ const { angle, from, to } = value;
336
+ if (!Number.isInteger(angle) || (angle as number) < 0 || (angle as number) > 360)
337
+ return undefined;
338
+ const start = cssColor(from);
339
+ const end = cssColor(to);
340
+ if (!start || !end) return undefined;
341
+ const css = `linear-gradient(${angle as number}deg, ${start}, ${end})`;
342
+ return isSafeBackground(css) ? css : undefined;
343
+ }
344
+
345
+ /** `#rgb` / `#rrggbb` (and an existing alpha) times `opacity`, as 8-digit hex. */
346
+ function hexWithAlpha(hex: string, opacity: number): string | undefined {
347
+ let body = hex.slice(1).toLowerCase();
348
+ if (body.length === 3 || body.length === 4) body = [...body].map((ch) => ch + ch).join("");
349
+ if (body.length !== 6 && body.length !== 8) return undefined;
350
+ const existing = body.length === 8 ? Number.parseInt(body.slice(6), 16) / 255 : 1;
351
+ const alpha = Math.round(existing * opacity * 255)
352
+ .toString(16)
353
+ .padStart(2, "0");
354
+ return `#${body.slice(0, 6)}${alpha}`;
355
+ }
356
+
357
+ function overlayPaint(color: string, opacity: number): string | undefined {
358
+ if (opacity === 1) return color;
359
+ if (color.startsWith("var(")) {
360
+ return `color-mix(in srgb, ${color} ${Math.round(opacity * 100)}%, transparent)`;
361
+ }
362
+ return HEX_COLOR.test(color) ? hexWithAlpha(color, opacity) : undefined;
363
+ }
364
+
365
+ function cssOverlay(value: unknown): string | undefined {
366
+ if (!isRecord(value)) return undefined;
367
+ if (Object.keys(value).some((key) => key !== "color" && key !== "opacity")) return undefined;
368
+ const color = cssColor(value["color"]);
369
+ const opacity = value["opacity"];
370
+ if (
371
+ !color ||
372
+ typeof opacity !== "number" ||
373
+ !Number.isFinite(opacity) ||
374
+ opacity < 0 ||
375
+ opacity > 1
376
+ )
377
+ return undefined;
378
+ const paint = overlayPaint(color, opacity);
379
+ if (!paint) return undefined;
380
+ const css = `linear-gradient(${paint}, ${paint})`;
381
+ return isSafeBackground(css) ? css : undefined;
382
+ }
383
+
384
+ /**
385
+ * Image, gradient and overlay share `background-image`. The overlay is the top layer, then the
386
+ * image, then the gradient. Size, position and repeat apply to the image; the other layers fill.
387
+ */
388
+ function composeBackground(style: Record<string, unknown>): {
389
+ declarations: Declaration[];
390
+ rejected: string[];
391
+ } {
392
+ const rejected: string[] = [];
393
+ const take = (key: string, css: string | undefined) => {
394
+ if (style[key] === undefined) return undefined;
395
+ if (!css) rejected.push(key);
396
+ return css;
397
+ };
398
+ const image = take("backgroundImage", cssBackgroundImage(style["backgroundImage"]));
399
+ const size = take("backgroundSize", keyword(BACKGROUND_SIZE)(style["backgroundSize"]));
400
+ const position = take(
401
+ "backgroundPosition",
402
+ keyword(BACKGROUND_POSITION)(style["backgroundPosition"]),
403
+ );
404
+ const repeat = take("backgroundRepeat", keyword(BACKGROUND_REPEAT)(style["backgroundRepeat"]));
405
+ const gradient = take("gradient", cssGradient(style["gradient"]));
406
+ const overlay = take("overlay", cssOverlay(style["overlay"]));
407
+
408
+ const layers: string[] = [];
409
+ const sizes: string[] = [];
410
+ const positions: string[] = [];
411
+ const repeats: string[] = [];
412
+ const push = (layer: string, layerSize: string, layerPosition: string, layerRepeat: string) => {
413
+ layers.push(layer);
414
+ sizes.push(layerSize);
415
+ positions.push(layerPosition);
416
+ repeats.push(layerRepeat);
417
+ };
418
+ if (overlay) push(overlay, "auto", "center", "no-repeat");
419
+ if (image) push(image, size ?? "cover", position ?? "center", repeat ?? "no-repeat");
420
+ if (gradient) push(gradient, "auto", "center", "no-repeat");
421
+
422
+ const declarations: Declaration[] = [];
423
+ if (layers.length > 0) {
424
+ const value = layers.join(",");
425
+ if (!isSafeBackground(value)) {
426
+ for (const key of ["overlay", "backgroundImage", "gradient"]) {
427
+ if (style[key] !== undefined && !rejected.includes(key)) rejected.push(key);
428
+ }
429
+ } else {
430
+ declarations.push({ property: "background-image", value });
431
+ if (layers.length > 1) {
432
+ declarations.push(
433
+ { property: "background-size", value: sizes.join(",") },
434
+ { property: "background-position", value: positions.join(",") },
435
+ { property: "background-repeat", value: repeats.join(",") },
436
+ );
437
+ } else if (image) {
438
+ declarations.push(
439
+ { property: "background-size", value: size ?? "cover" },
440
+ { property: "background-position", value: position ?? "center" },
441
+ { property: "background-repeat", value: repeat ?? "no-repeat" },
442
+ );
443
+ }
444
+ }
445
+ }
446
+ if (!image) {
447
+ if (size) declarations.push({ property: "background-size", value: size });
448
+ if (position) declarations.push({ property: "background-position", value: position });
449
+ if (repeat) declarations.push({ property: "background-repeat", value: repeat });
450
+ }
451
+ return { declarations, rejected };
452
+ }
453
+
454
+ const PROPERTY_MAP: {
455
+ [K in keyof Required<StyleProps>]: { css: string; toValue: (v: unknown) => string | undefined };
456
+ } = {
457
+ flexDirection: { css: "flex-direction", toValue: cssFlexDirection },
458
+ flexWrap: { css: "flex-wrap", toValue: keyword(FLEX_WRAPS) },
459
+ justifyContent: { css: "justify-content", toValue: keyword(JUSTIFY) },
460
+ alignItems: { css: "align-items", toValue: keyword(ALIGN) },
461
+ gap: { css: "gap", toValue: cssLength },
462
+ gridColumnSpan: { css: "grid-column", toValue: cssGridSpan },
463
+ gridRowSpan: { css: "grid-row", toValue: cssGridSpan },
464
+ width: { css: "width", toValue: cssLengthOrAuto },
465
+ minWidth: { css: "min-width", toValue: cssLength },
466
+ maxWidth: { css: "max-width", toValue: cssLength },
467
+ height: { css: "height", toValue: cssLengthOrAuto },
468
+ minHeight: { css: "min-height", toValue: cssLength },
469
+ maxHeight: { css: "max-height", toValue: cssLength },
470
+ overflow: { css: "overflow", toValue: keyword(OVERFLOW) },
471
+ aspectRatio: { css: "aspect-ratio", toValue: cssAspectRatio },
472
+ objectFit: { css: "object-fit", toValue: keyword(OBJECT_FIT) },
473
+ paddingTop: { css: "padding-top", toValue: cssLength },
474
+ paddingRight: { css: "padding-inline-end", toValue: cssLength },
475
+ paddingBottom: { css: "padding-bottom", toValue: cssLength },
476
+ paddingLeft: { css: "padding-inline-start", toValue: cssLength },
477
+ marginTop: { css: "margin-top", toValue: cssLengthOrAuto },
478
+ marginRight: { css: "margin-inline-end", toValue: cssLengthOrAuto },
479
+ marginBottom: { css: "margin-bottom", toValue: cssLengthOrAuto },
480
+ marginLeft: { css: "margin-inline-start", toValue: cssLengthOrAuto },
481
+ position: { css: "position", toValue: keyword(POSITION) },
482
+ top: { css: "top", toValue: cssOffset },
483
+ right: { css: "inset-inline-end", toValue: cssOffset },
484
+ bottom: { css: "bottom", toValue: cssOffset },
485
+ left: { css: "inset-inline-start", toValue: cssOffset },
486
+ zIndex: { css: "z-index", toValue: cssZIndex },
487
+ fontFamily: { css: "font-family", toValue: cssFontFamily },
488
+ fontSize: { css: "font-size", toValue: cssLength },
489
+ fontWeight: { css: "font-weight", toValue: cssFontWeight },
490
+ lineHeight: { css: "line-height", toValue: cssLength },
491
+ letterSpacing: { css: "letter-spacing", toValue: cssLength },
492
+ textAlign: { css: "text-align", toValue: cssTextAlign },
493
+ textTransform: { css: "text-transform", toValue: keyword(TEXT_TRANSFORM) },
494
+ textDecoration: { css: "text-decoration", toValue: keyword(TEXT_DECORATION) },
495
+ color: { css: "color", toValue: cssColor },
496
+ backgroundColor: { css: "background-color", toValue: cssColor },
497
+ backgroundImage: { css: "background-image", toValue: cssBackgroundImage },
498
+ backgroundSize: { css: "background-size", toValue: keyword(BACKGROUND_SIZE) },
499
+ backgroundPosition: { css: "background-position", toValue: keyword(BACKGROUND_POSITION) },
500
+ backgroundRepeat: { css: "background-repeat", toValue: keyword(BACKGROUND_REPEAT) },
501
+ backgroundVideo: { css: "background-image", toValue: () => undefined },
502
+ gradient: { css: "background-image", toValue: cssGradient },
503
+ overlay: { css: "background-image", toValue: cssOverlay },
504
+ borderWidth: { css: "border-width", toValue: cssLength },
505
+ borderStyle: { css: "border-style", toValue: keyword(BORDER_STYLE) },
506
+ borderColor: { css: "border-color", toValue: cssColor },
507
+ borderRadius: { css: "border-radius", toValue: cssLength },
508
+ opacity: { css: "opacity", toValue: cssOpacity },
509
+ boxShadow: { css: "box-shadow", toValue: cssBoxShadow },
510
+ filter: { css: "filter", toValue: cssFilter },
511
+ cursor: { css: "cursor", toValue: keyword(CURSOR) },
512
+ transition: { css: "transition", toValue: cssTransition },
513
+ entrance: { css: "animation", toValue: cssEntrance },
514
+ };
515
+
516
+ /** Exported for table-driven tests (W-017). */
517
+ export const STYLE_PROPERTY_MAP = PROPERTY_MAP;
518
+
519
+ /** Converts style props into safe declarations; anything that fails validation is dropped and reported. */
520
+ export function styleDeclarations(style: unknown): {
521
+ declarations: Declaration[];
522
+ rejected: string[];
523
+ } {
524
+ const declarations: Declaration[] = [];
525
+ const rejected: string[] = [];
526
+ if (typeof style !== "object" || style === null) return { declarations, rejected };
527
+ const record = style as Record<string, unknown>;
528
+ for (const [key, raw] of Object.entries(record)) {
529
+ if (BACKGROUND_KEYS.has(key)) continue;
530
+ const entry = Object.hasOwn(PROPERTY_MAP, key)
531
+ ? PROPERTY_MAP[key as keyof StyleProps]
532
+ : undefined;
533
+ const value = entry?.toValue(raw);
534
+ const safe =
535
+ value !== undefined &&
536
+ (entry?.css === "font-family" ? isSafeFontStack(value) : isSafeCssValue(value));
537
+ if (entry && safe) {
538
+ declarations.push({ property: entry.css, value });
539
+ if (key === "entrance") {
540
+ const trigger = (raw as { trigger?: unknown }).trigger;
541
+ if (trigger === "view") {
542
+ declarations.push(
543
+ { property: "animation-timeline", value: "view()" },
544
+ { property: "animation-range", value: "entry 0% cover 40%" },
545
+ );
546
+ }
547
+ }
548
+ } else {
549
+ rejected.push(key);
550
+ }
551
+ }
552
+ const background = composeBackground(record);
553
+ declarations.push(...background.declarations);
554
+ rejected.push(...background.rejected);
555
+ return { declarations, rejected };
556
+ }
557
+
558
+ /** Transitions are Normal only (W-089): a state's `transition` is dropped and reported. */
559
+ const withoutTransition = (style: unknown): unknown => {
560
+ if (typeof style !== "object" || style === null || !("transition" in style)) return style;
561
+ const { transition: _drop, ...rest } = style as Record<string, unknown>;
562
+ return rest;
563
+ };
564
+
565
+ export type StateDeclarations = Partial<Record<StyleStateName, Declaration[]>>;
566
+
567
+ /**
568
+ * `states` (W-089) through the same mappers and gates as `style`. Rejected keys are reported as
569
+ * `<state>.<key>`; an unknown state name is reported whole.
570
+ */
571
+ export function stateDeclarations(states: unknown): {
572
+ states: StateDeclarations;
573
+ rejected: string[];
574
+ } {
575
+ const result: StateDeclarations = {};
576
+ const rejected: string[] = [];
577
+ if (typeof states !== "object" || states === null) return { states: result, rejected };
578
+ for (const key of Object.keys(states)) {
579
+ if (!STYLE_STATES.includes(key as StyleStateName)) rejected.push(key);
580
+ }
581
+ for (const state of STYLE_STATES) {
582
+ const style = (states as Record<string, unknown>)[state];
583
+ if (style === undefined) continue;
584
+ const { declarations, rejected: bad } = styleDeclarations(withoutTransition(style));
585
+ if (typeof style === "object" && style !== null && "transition" in style)
586
+ bad.push("transition");
587
+ if (declarations.length > 0) result[state] = declarations;
588
+ for (const key of bad) rejected.push(`${state}.${key}`);
589
+ }
590
+ return { states: result, rejected };
591
+ }