@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,209 @@
1
+ import { Button, DropdownMenu, Input } from "@cloudflare/kumo";
2
+ import { DotsThreeIcon, PlusIcon, type Icon } from "@phosphor-icons/react";
3
+ import * as React from "react";
4
+ import { slugify } from "../../../core/index.ts";
5
+ import { BUTTON, FIELD, SOLID_PRIMARY } from "../../ui.ts";
6
+
7
+ /** A slug of `name` (or `fallback`) that no id in `taken` uses yet: `x`, then `x-2`, `x-3`… */
8
+ export function uniqueId(name: string, fallback: string, taken: Iterable<string>): string {
9
+ const base = slugify(name).slice(0, 34) || fallback;
10
+ const used = new Set(taken);
11
+ let id = base;
12
+ for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
13
+ return id;
14
+ }
15
+
16
+ /** Whether any of `fields` contains the lowercased query `q`. */
17
+ export const matches = (q: string, ...fields: string[]) =>
18
+ fields.some((field) => field.toLowerCase().includes(q));
19
+
20
+ /** A Site styles section heading with its item count and New button. */
21
+ export function SectionHead({
22
+ title,
23
+ count,
24
+ countProps,
25
+ onNew,
26
+ newDisabled,
27
+ }: {
28
+ title: React.ReactNode;
29
+ count: number;
30
+ countProps?: Record<string, string>;
31
+ onNew: () => void;
32
+ newDisabled?: boolean;
33
+ }) {
34
+ return (
35
+ <div className="emvb-site-section-head">
36
+ <h3 className="emvb-field-label">
37
+ {title}
38
+ <span className="emvb-site-count" {...countProps}>
39
+ {count}
40
+ </span>
41
+ </h3>
42
+ <Button
43
+ type="button"
44
+ variant="ghost"
45
+ size="sm"
46
+ className={BUTTON}
47
+ icon={<PlusIcon aria-hidden="true" />}
48
+ onClick={onNew}
49
+ disabled={newDisabled}
50
+ >
51
+ New
52
+ </Button>
53
+ </div>
54
+ );
55
+ }
56
+
57
+ /** The inline create form at the end of a Site styles list. */
58
+ export function CreateRow({
59
+ rowProps,
60
+ submitLabel,
61
+ onCancel,
62
+ onCreate,
63
+ children,
64
+ }: {
65
+ rowProps: Record<string, string>;
66
+ submitLabel: string;
67
+ onCancel: () => void;
68
+ onCreate: () => void;
69
+ children: React.ReactNode;
70
+ }) {
71
+ return (
72
+ <div className="emvb-site-create emvb-site-elevated" {...rowProps}>
73
+ {children}
74
+ <div className="emvb-dialog-actions">
75
+ <Button type="button" variant="secondary" className={BUTTON} onClick={onCancel}>
76
+ Cancel
77
+ </Button>
78
+ <Button
79
+ type="button"
80
+ variant="primary"
81
+ className={BUTTON}
82
+ style={SOLID_PRIMARY}
83
+ onClick={onCreate}
84
+ >
85
+ {submitLabel}
86
+ </Button>
87
+ </div>
88
+ </div>
89
+ );
90
+ }
91
+
92
+ /** Search shown once a Site styles list is long enough to need it. */
93
+ export function SiteSearch({
94
+ label,
95
+ value,
96
+ onChange,
97
+ ...rest
98
+ }: {
99
+ label: string;
100
+ value: string;
101
+ onChange: (value: string) => void;
102
+ } & Record<`data-${string}`, string>) {
103
+ return (
104
+ <div className="emvb-site-search" {...rest}>
105
+ <Input
106
+ aria-label={label}
107
+ className={FIELD}
108
+ type="search"
109
+ value={value}
110
+ placeholder={`${label}…`}
111
+ onChange={(event) => onChange(event.target.value)}
112
+ onKeyDown={(event) => {
113
+ if (event.key === "Escape" && value) {
114
+ event.stopPropagation();
115
+ onChange("");
116
+ }
117
+ }}
118
+ />
119
+ </div>
120
+ );
121
+ }
122
+
123
+ /**
124
+ * The name field that replaces a row's name while renaming: Enter or blur saves once, Escape
125
+ * cancels. `onDone` gets the trimmed new name, or null when nothing changed.
126
+ */
127
+ export function RenameInput({
128
+ name,
129
+ label,
130
+ onDone,
131
+ }: {
132
+ name: string;
133
+ label: string;
134
+ onDone: (next: string | null) => void;
135
+ }) {
136
+ const ended = React.useRef(false);
137
+ const finish = (next: string | null) => {
138
+ if (ended.current) return;
139
+ ended.current = true;
140
+ const trimmed = next?.trim();
141
+ onDone(trimmed && trimmed !== name ? trimmed : null);
142
+ };
143
+ return (
144
+ <input
145
+ className="emvb-site-rename"
146
+ aria-label={label}
147
+ defaultValue={name}
148
+ maxLength={60}
149
+ // oxlint-disable-next-line jsx-a11y/no-autofocus -- the user asked to rename; focus moves into the field
150
+ autoFocus
151
+ onFocus={(event) => event.currentTarget.select()}
152
+ onKeyDown={(event) => {
153
+ if (event.key === "Enter") finish(event.currentTarget.value);
154
+ else if (event.key === "Escape") {
155
+ event.stopPropagation();
156
+ finish(null);
157
+ }
158
+ }}
159
+ onBlur={(event) => finish(event.currentTarget.value)}
160
+ />
161
+ );
162
+ }
163
+
164
+ export type RowAction = {
165
+ label: string;
166
+ icon: Icon;
167
+ onSelect: () => void;
168
+ /** Run once the menu has closed and handed focus back (Rename moves focus into a field). */
169
+ afterClose?: boolean;
170
+ danger?: boolean;
171
+ };
172
+
173
+ /** A Site styles row's ⋮ menu. A danger action sits last, after a separator. */
174
+ export function RowMenu({ label, actions }: { label: string; actions: RowAction[] }) {
175
+ const pending = React.useRef<(() => void) | null>(null);
176
+ return (
177
+ <DropdownMenu
178
+ onOpenChangeComplete={(open) => {
179
+ const run = pending.current;
180
+ if (open || !run) return;
181
+ pending.current = null;
182
+ requestAnimationFrame(run);
183
+ }}
184
+ >
185
+ <DropdownMenu.Trigger>
186
+ <button type="button" className="emvb-site-menu-btn" aria-label={label}>
187
+ <DotsThreeIcon size={16} weight="bold" aria-hidden="true" />
188
+ </button>
189
+ </DropdownMenu.Trigger>
190
+ <DropdownMenu.Content>
191
+ {actions.map((action) => (
192
+ <React.Fragment key={action.label}>
193
+ {action.danger && <DropdownMenu.Separator />}
194
+ <DropdownMenu.Item
195
+ icon={action.icon}
196
+ variant={action.danger ? "danger" : "default"}
197
+ onClick={() => {
198
+ if (action.afterClose) pending.current = action.onSelect;
199
+ else action.onSelect();
200
+ }}
201
+ >
202
+ {action.label}
203
+ </DropdownMenu.Item>
204
+ </React.Fragment>
205
+ ))}
206
+ </DropdownMenu.Content>
207
+ </DropdownMenu>
208
+ );
209
+ }
@@ -0,0 +1,73 @@
1
+ import type { VariableKind } from "../../../core/index.ts";
2
+
3
+ export type Length = { value: number; unit: "px" | "rem" | "em" | "%" };
4
+
5
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
6
+ const LENGTH = /^(\d+(?:\.\d+)?|\.\d+)\s*(px|rem|em|%)?$/i;
7
+ const MAX_LENGTH = 10_000;
8
+
9
+ export const isLengthKind = (kind: VariableKind) => kind === "fontSize" || kind === "spacing";
10
+
11
+ /** "16", "16px", "1.5rem", "2em" or "50%" as a length (px when no unit); undefined otherwise. */
12
+ export function parseLength(text: string): Length | undefined {
13
+ const match = LENGTH.exec(text.trim());
14
+ if (!match) return undefined;
15
+ const value = Number(match[1]);
16
+ if (!Number.isFinite(value) || value > MAX_LENGTH) return undefined;
17
+ const unit = (match[2]?.toLowerCase() ?? "px") as Length["unit"];
18
+ return { value, unit };
19
+ }
20
+
21
+ const formatLength = (length: Length) => `${length.value}${length.unit}`;
22
+
23
+ /** The length in px for previews: rem and em at 16 px, % as the 16 px base. */
24
+ export function lengthPx(length: Length): number {
25
+ if (length.unit === "px") return length.value;
26
+ if (length.unit === "%") return (length.value / 100) * 16;
27
+ return length.value * 16;
28
+ }
29
+
30
+ /** The value the field shows for a stored variable value. */
31
+ export function valueText(value: unknown): string {
32
+ if (typeof value === "string") return value;
33
+ if (value && typeof value === "object" && "value" in value && "unit" in value) {
34
+ return formatLength(value as Length);
35
+ }
36
+ return "";
37
+ }
38
+
39
+ const ERRORS: Record<VariableKind, string> = {
40
+ color: "Enter a hex color such as #1a2b3c.",
41
+ font: "Enter a font stack such as Inter, sans-serif.",
42
+ fontSize: "Enter a size such as 16, 16px or 1.5rem.",
43
+ spacing: "Enter a length such as 16, 16px or 1.5rem.",
44
+ };
45
+
46
+ /** The stored value for `text`, or the message that explains how to fix it. */
47
+ export function parseValue(
48
+ kind: VariableKind,
49
+ text: string,
50
+ ): { ok: true; value: string | Length } | { ok: false; error: string } {
51
+ const trimmed = text.trim();
52
+ if (isLengthKind(kind)) {
53
+ const length = parseLength(trimmed);
54
+ return length ? { ok: true, value: length } : { ok: false, error: ERRORS[kind] };
55
+ }
56
+ if (kind === "color") {
57
+ return HEX.test(trimmed) ? { ok: true, value: trimmed } : { ok: false, error: ERRORS.color };
58
+ }
59
+ return trimmed && trimmed.length <= 200
60
+ ? { ok: true, value: trimmed }
61
+ : { ok: false, error: ERRORS.font };
62
+ }
63
+
64
+ /** A 6-digit hex for `<input type="color">`, which can't show 3, 4 or 8-digit forms. */
65
+ export function pickerHex(hex: string): string {
66
+ const h = hex.trim().toLowerCase();
67
+ if (/^#[0-9a-f]{6}$/.test(h)) return h;
68
+ if (/^#[0-9a-f]{8}$/.test(h)) return h.slice(0, 7);
69
+ if (/^#[0-9a-f]{3,4}$/.test(h)) {
70
+ return `#${Array.from(h.slice(1, 4), (c) => c + c).join("")}`;
71
+ }
72
+ return "#000000";
73
+ }
@@ -0,0 +1,80 @@
1
+ import type { DesignSystem, Layout, VariableKind } from "../../core/index.ts";
2
+
3
+ type Variables = DesignSystem["variables"];
4
+ type ListKey = keyof Variables;
5
+ type StyleClass = NonNullable<DesignSystem["classes"]>[number];
6
+ type AnyVariable = NonNullable<Variables[ListKey]>[number];
7
+
8
+ const LIST: Record<VariableKind, ListKey> = {
9
+ color: "colors",
10
+ font: "fonts",
11
+ fontSize: "fontSizes",
12
+ spacing: "spacings",
13
+ };
14
+
15
+ /** A variable or class deleted from Site styles, where it stood, and the page just before. */
16
+ export type Deletion = {
17
+ before: Layout;
18
+ index: number;
19
+ } & (
20
+ | { kind: "variable"; variableKind: VariableKind; variable: AnyVariable }
21
+ | { kind: "class"; cls: StyleClass }
22
+ );
23
+
24
+ /** The deletion of `id` from `design`, or undefined when the design doesn't have it. */
25
+ export function deletionOf(
26
+ design: DesignSystem,
27
+ before: Layout,
28
+ target:
29
+ | { kind: "variable"; id: string; variableKind: VariableKind }
30
+ | { kind: "class"; id: string },
31
+ ): Deletion | undefined {
32
+ if (target.kind === "class") {
33
+ const classes = design.classes ?? [];
34
+ const index = classes.findIndex((c) => c.id === target.id);
35
+ const cls = classes[index];
36
+ return cls ? { kind: "class", cls, index, before } : undefined;
37
+ }
38
+ const list: readonly AnyVariable[] = design.variables[LIST[target.variableKind]] ?? [];
39
+ const index = list.findIndex((v) => v.id === target.id);
40
+ const variable = list[index];
41
+ return variable
42
+ ? { kind: "variable", variableKind: target.variableKind, variable, index, before }
43
+ : undefined;
44
+ }
45
+
46
+ /**
47
+ * W-252: Site styles changes aren't undo steps, but deleting a variable or class also clears its
48
+ * uses on the page, which is one. Undoing that brought the uses back with nothing defining them.
49
+ * When the page is again exactly the one from before a deletion (undo restores that object), the
50
+ * deleted items go back into the design where they were. Null when nothing needs restoring.
51
+ */
52
+ export function restoreOnUndo(
53
+ design: DesignSystem,
54
+ layout: Layout,
55
+ deletions: readonly Deletion[],
56
+ ): DesignSystem | null {
57
+ const classes = [...(design.classes ?? [])];
58
+ const variables: Partial<Record<ListKey, AnyVariable[]>> = {};
59
+ let classRestored = false;
60
+ for (const deletion of deletions) {
61
+ if (deletion.before !== layout) continue;
62
+ if (deletion.kind === "class") {
63
+ if (classes.some((c) => c.id === deletion.cls.id)) continue;
64
+ classes.splice(Math.min(deletion.index, classes.length), 0, deletion.cls);
65
+ classRestored = true;
66
+ } else {
67
+ const key = LIST[deletion.variableKind];
68
+ const list = variables[key] ?? [...(design.variables[key] ?? [])];
69
+ if (list.some((v) => v.id === deletion.variable.id)) continue;
70
+ list.splice(Math.min(deletion.index, list.length), 0, deletion.variable);
71
+ variables[key] = list;
72
+ }
73
+ }
74
+ if (!classRestored && Object.keys(variables).length === 0) return null;
75
+ return {
76
+ ...design,
77
+ ...(classRestored ? { classes } : {}),
78
+ variables: { ...design.variables, ...variables } as Variables,
79
+ };
80
+ }
@@ -0,0 +1,50 @@
1
+ import * as React from "react";
2
+ import { collectSectionPartIds, type Layout } from "../../core/index.ts";
3
+ import type { Fetcher } from "../api.ts";
4
+ import { themePartLayout } from "../theme-api.ts";
5
+
6
+ const MAX_DEPTH = 8;
7
+
8
+ /** Section theme parts referenced by the open layout, so the canvas shows the synced contents. */
9
+ export function useSectionTemplates(
10
+ layout: Layout | null,
11
+ fetcher: Fetcher,
12
+ ): Record<string, Layout> {
13
+ const key = layout ? collectSectionPartIds(layout).join("\0") : "";
14
+ const [templates, setTemplates] = React.useState<Record<string, Layout>>({});
15
+
16
+ React.useEffect(() => {
17
+ const ids = key ? key.split("\0") : [];
18
+ if (ids.length === 0) {
19
+ setTemplates({});
20
+ return;
21
+ }
22
+ let cancelled = false;
23
+ const load = async () => {
24
+ const acc: Record<string, Layout> = {};
25
+ const walk = async (next: string[], depth: number) => {
26
+ if (depth > MAX_DEPTH) return;
27
+ for (const id of next) {
28
+ if (acc[id]) continue;
29
+ // Each nested section id comes from the part just loaded.
30
+ // oxlint-disable-next-line no-await-in-loop
31
+ const part = await themePartLayout(fetcher, id, "section");
32
+ if (!part) continue;
33
+ acc[id] = part;
34
+ // oxlint-disable-next-line no-await-in-loop
35
+ await walk(collectSectionPartIds(part), depth + 1);
36
+ }
37
+ };
38
+ await walk(ids, 0);
39
+ if (!cancelled) setTemplates(acc);
40
+ };
41
+ void load().catch(() => {
42
+ if (!cancelled) setTemplates({});
43
+ });
44
+ return () => {
45
+ cancelled = true;
46
+ };
47
+ }, [key, fetcher]);
48
+
49
+ return templates;
50
+ }
@@ -0,0 +1,20 @@
1
+ /** The editor's keyboard shortcuts, shown in the Shortcuts dialog. */
2
+ export const SHORTCUTS: readonly { action: string; keys: string }[] = [
3
+ { action: "Move focus between regions", keys: "Tab / Shift+Tab" },
4
+ { action: "Next or previous element", keys: "↑ / ↓" },
5
+ { action: "Select first child / parent", keys: "Enter / Shift+Enter" },
6
+ { action: "Clear selection", keys: "Esc" },
7
+ { action: "Expand or collapse (Layers)", keys: "← / →" },
8
+ { action: "Move up / down", keys: "Alt+↑ / Alt+↓" },
9
+ { action: "Move out / in", keys: "Alt+← / Alt+→" },
10
+ { action: "Duplicate", keys: "Ctrl/Cmd+D" },
11
+ { action: "Copy / paste element", keys: "Ctrl/Cmd+C / Ctrl/Cmd+V" },
12
+ { action: "Paste style", keys: "Ctrl/Cmd+Shift+V" },
13
+ { action: "Delete", keys: "Delete or Backspace" },
14
+ { action: "Undo / redo", keys: "Ctrl/Cmd+Z / Ctrl/Cmd+Shift+Z" },
15
+ { action: "Save draft", keys: "Ctrl/Cmd+S" },
16
+ ];
17
+
18
+ /** Ctrl/Cmd+K opens the host command palette, which would stack over the editor (S0-6). */
19
+ export const isPaletteShortcut = (event: KeyboardEvent) =>
20
+ (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "k";
@@ -0,0 +1,240 @@
1
+ import {
2
+ addNode,
3
+ findNode,
4
+ insertNode,
5
+ moveNode,
6
+ selectionAfterDelete,
7
+ newNodeId,
8
+ removeNode,
9
+ updateNode,
10
+ type Arranged,
11
+ type DesignSystem,
12
+ type Layout,
13
+ type LayoutNode,
14
+ type Removed,
15
+ LAYOUT_SCHEMA_VERSION,
16
+ } from "../../core/index.ts";
17
+ import { withPageHeadingLevel } from "./dnd/new-element.ts";
18
+ import type { PageDraft } from "../content-api.ts";
19
+
20
+ /** Editor state (A-07): a pure reducer, so every edit is testable without a browser. */
21
+ export type EditorState = {
22
+ id: string;
23
+ page: PageDraft;
24
+ status: string;
25
+ rev: string | null;
26
+ design: DesignSystem;
27
+ designRevision: string | null;
28
+ /** CAS token for the published design. Absent until the editor has loaded a draft (W-100). */
29
+ publishedRevision?: string | null;
30
+ /** True after a style edit that has not been published. */
31
+ designUnpublished?: boolean;
32
+ selectedId: string | null;
33
+ /** Bumped on every page edit. A save only clears `dirty` if nothing changed while it ran. */
34
+ version: number;
35
+ savedVersion: number;
36
+ /**
37
+ * The highest version handed out so far. Undo restores an older `version`, so the next edit
38
+ * numbers from here; reusing a number could match `savedVersion` with unsaved content (W-255).
39
+ */
40
+ lastVersion?: number;
41
+ /** The most recent delete, for the one-step Restore toast (D-025). */
42
+ lastDeleted: Removed | null;
43
+ };
44
+
45
+ export type PagePatch = Partial<Omit<PageDraft, "layout">>;
46
+
47
+ export type EditorAction =
48
+ | { type: "set-page"; patch: PagePatch }
49
+ | { type: "select"; id: string | null }
50
+ | { type: "update-node"; id: string; update: (node: LayoutNode) => LayoutNode }
51
+ | { type: "delete-node"; id: string }
52
+ | { type: "restore" }
53
+ | { type: "add-root-container" }
54
+ | { type: "add-node"; node: LayoutNode; parentId: string; index: number }
55
+ | { type: "move-node"; id: string; parentId: string; index: number }
56
+ | { type: "apply-arranged"; layout: Layout; selected: string }
57
+ | { type: "saved"; rev: string; version: number }
58
+ | { type: "published"; rev: string }
59
+ | { type: "set-design"; design: DesignSystem; revision: string | null }
60
+ | { type: "publish-design"; revision: string }
61
+ /** The site styles as saved elsewhere, after a refused save (W-212). */
62
+ | {
63
+ type: "load-design";
64
+ design: DesignSystem;
65
+ revision: string | null;
66
+ publishedRevision: string | null;
67
+ unpublished: boolean;
68
+ }
69
+ | { type: "reset"; state: EditorState };
70
+
71
+ export const isDirty = (state: EditorState) => state.version !== state.savedVersion;
72
+
73
+ const edited = (state: EditorState, page: PageDraft): EditorState => {
74
+ const version = Math.max(state.version, state.lastVersion ?? 0) + 1;
75
+ return { ...state, page, version, lastVersion: version };
76
+ };
77
+
78
+ /** A layout edit that also moves the selection. */
79
+ const withLayout = (
80
+ state: EditorState,
81
+ layout: Layout,
82
+ selectedId: string | null,
83
+ lastDeleted = state.lastDeleted,
84
+ ): EditorState => ({ ...edited(state, { ...state.page, layout }), selectedId, lastDeleted });
85
+
86
+ /** Applies an arrange result; a refused one leaves the state unchanged. */
87
+ const arranged = (state: EditorState, result: Arranged): EditorState =>
88
+ result.ok ? withLayout(state, result.layout, result.selected) : state;
89
+
90
+ /** Page edits kept for undo. Save, publish and design stay on the live state (D-035, proposed). */
91
+ const PAGE_HISTORY_LIMIT = 100;
92
+
93
+ type PageSnapshot = {
94
+ page: PageDraft;
95
+ selectedId: string | null;
96
+ lastDeleted: Removed | null;
97
+ version: number;
98
+ };
99
+
100
+ export type EditorHistory = {
101
+ present: EditorState;
102
+ past: readonly PageSnapshot[];
103
+ future: readonly PageSnapshot[];
104
+ };
105
+
106
+ export type HistoryAction = EditorAction | { type: "undo" } | { type: "redo" };
107
+
108
+ const snapshotOf = (state: EditorState): PageSnapshot => ({
109
+ page: state.page,
110
+ selectedId: state.selectedId,
111
+ lastDeleted: state.lastDeleted,
112
+ version: state.version,
113
+ });
114
+
115
+ const withSnapshot = (state: EditorState, snap: PageSnapshot): EditorState => ({
116
+ ...state,
117
+ page: snap.page,
118
+ selectedId: snap.selectedId,
119
+ lastDeleted: snap.lastDeleted,
120
+ version: snap.version,
121
+ });
122
+
123
+ export const emptyHistory = (present: EditorState): EditorHistory => ({
124
+ present,
125
+ past: [],
126
+ future: [],
127
+ });
128
+
129
+ /**
130
+ * Wraps `editorReducer`. A page edit (version bump) pushes the previous page onto `past` and
131
+ * clears `redo`. Selection, save, publish and design updates replace `present` only. `reset`
132
+ * drops both stacks. Undo restores the page and leaves the current revision and saved version.
133
+ */
134
+ export function historyReducer(history: EditorHistory, action: HistoryAction): EditorHistory {
135
+ if (action.type === "undo") {
136
+ const snap = history.past.at(-1);
137
+ if (!snap) return history;
138
+ return {
139
+ present: withSnapshot(history.present, snap),
140
+ past: history.past.slice(0, -1),
141
+ future: [snapshotOf(history.present), ...history.future],
142
+ };
143
+ }
144
+ if (action.type === "redo") {
145
+ const snap = history.future.at(0);
146
+ if (!snap) return history;
147
+ return {
148
+ present: withSnapshot(history.present, snap),
149
+ past: [...history.past, snapshotOf(history.present)],
150
+ future: history.future.slice(1),
151
+ };
152
+ }
153
+ if (action.type === "reset") return emptyHistory(action.state);
154
+ const next = editorReducer(history.present, action);
155
+ if (next === history.present) return history;
156
+ if (next.version === history.present.version) return { ...history, present: next };
157
+ const past = [...history.past, snapshotOf(history.present)];
158
+ return {
159
+ present: next,
160
+ past: past.length > PAGE_HISTORY_LIMIT ? past.slice(-PAGE_HISTORY_LIMIT) : past,
161
+ future: [],
162
+ };
163
+ }
164
+
165
+ export function editorReducer(state: EditorState, action: EditorAction): EditorState {
166
+ switch (action.type) {
167
+ case "set-page":
168
+ return edited(state, { ...state.page, ...action.patch });
169
+ case "select":
170
+ return { ...state, selectedId: action.id };
171
+ case "update-node":
172
+ if (!state.page.layout || !findNode(state.page.layout, action.id)) return state;
173
+ return edited(state, {
174
+ ...state.page,
175
+ layout: updateNode(state.page.layout, action.id, action.update),
176
+ });
177
+ case "delete-node": {
178
+ if (!state.page.layout) return state;
179
+ const nextSelected =
180
+ state.selectedId === action.id
181
+ ? selectionAfterDelete(state.page.layout, action.id)
182
+ : state.selectedId;
183
+ const { layout, removed } = removeNode(state.page.layout, action.id);
184
+ if (!removed) return state;
185
+ return withLayout(state, layout, nextSelected, removed);
186
+ }
187
+ case "restore": {
188
+ const removed = state.lastDeleted;
189
+ if (!removed || !state.page.layout) return state;
190
+ const layout = insertNode(state.page.layout, removed.parentId, removed.index, removed.node);
191
+ return withLayout(state, layout, removed.node.id, null);
192
+ }
193
+ case "add-root-container": {
194
+ if (state.page.layout) return state;
195
+ const id = newNodeId();
196
+ const root = { id, type: "container" as const, props: {}, children: [] };
197
+ return withLayout(state, { schemaVersion: LAYOUT_SCHEMA_VERSION, root }, id);
198
+ }
199
+ case "add-node": {
200
+ if (!state.page.layout) return state;
201
+ const place = { parentId: action.parentId, index: action.index };
202
+ const node = withPageHeadingLevel(action.node, state.page.layout);
203
+ return arranged(state, addNode(state.page.layout, node, place));
204
+ }
205
+ case "move-node":
206
+ if (!state.page.layout) return state;
207
+ return arranged(state, moveNode(state.page.layout, action.id, action.parentId, action.index));
208
+ case "apply-arranged":
209
+ return withLayout(state, action.layout, action.selected);
210
+ case "saved":
211
+ // A saved draft on a published entry is not live until Publish (W-190).
212
+ return {
213
+ ...state,
214
+ rev: action.rev,
215
+ savedVersion: action.version,
216
+ status: state.status === "published" ? "changed" : state.status,
217
+ };
218
+ case "published":
219
+ return { ...state, rev: action.rev, status: "published" };
220
+ case "set-design":
221
+ return {
222
+ ...state,
223
+ design: action.design,
224
+ designRevision: action.revision,
225
+ designUnpublished: true,
226
+ };
227
+ case "publish-design":
228
+ return { ...state, designUnpublished: false, publishedRevision: action.revision };
229
+ case "load-design":
230
+ return {
231
+ ...state,
232
+ design: action.design,
233
+ designRevision: action.revision,
234
+ publishedRevision: action.publishedRevision,
235
+ designUnpublished: action.unpublished,
236
+ };
237
+ case "reset":
238
+ return action.state;
239
+ }
240
+ }