@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,109 @@
1
+ import { Input } from "@cloudflare/kumo";
2
+ import * as React from "react";
3
+ import { BUNDLED_ICONS, getBundledIcon, type LayoutNode } from "../../../../core/index.ts";
4
+ import { serialize, type VNode } from "../../../../core/render/vnode.ts";
5
+ import { FIELD } from "../../../ui.ts";
6
+
7
+ const propsOf = (node: LayoutNode): Record<string, unknown> =>
8
+ node.props as Record<string, unknown>;
9
+
10
+ const withProps = (node: LayoutNode, patch: Record<string, unknown>): LayoutNode => {
11
+ const props = { ...propsOf(node), ...patch };
12
+ return { ...node, props } as LayoutNode;
13
+ };
14
+
15
+ function previewSvg(iconId: string): string {
16
+ const icon = getBundledIcon(iconId);
17
+ if (!icon) return "";
18
+ const children: VNode[] = icon.children.map((child) => ({
19
+ tag: child.tag,
20
+ attrs: { ...child.attrs },
21
+ children: [],
22
+ }));
23
+ return serialize({
24
+ tag: "svg",
25
+ attrs: {
26
+ xmlns: "http://www.w3.org/2000/svg",
27
+ width: "20",
28
+ height: "20",
29
+ viewBox: "0 0 24 24",
30
+ fill: "none",
31
+ stroke: "currentColor",
32
+ "stroke-width": "2",
33
+ "stroke-linecap": "round",
34
+ "stroke-linejoin": "round",
35
+ "aria-hidden": "true",
36
+ },
37
+ children,
38
+ });
39
+ }
40
+
41
+ /** Lucide icon grid for the Icon element (W-025 / A-04). */
42
+ export function IconPicker({
43
+ node,
44
+ onChange,
45
+ }: {
46
+ node: LayoutNode;
47
+ onChange: (node: LayoutNode) => void;
48
+ }) {
49
+ const current = typeof propsOf(node).iconId === "string" ? String(propsOf(node).iconId) : "";
50
+ const [query, setQuery] = React.useState("");
51
+ const q = query.trim().toLowerCase();
52
+ const matched = BUNDLED_ICONS.filter(
53
+ (icon) => !q || icon.id.includes(q) || icon.label.toLowerCase().includes(q),
54
+ );
55
+
56
+ return (
57
+ <div className="emvb-field-group" data-emvb-field="iconId" data-emvb-icon-picker="">
58
+ <Input
59
+ label="Search icons"
60
+ className={FIELD}
61
+ value={query}
62
+ onChange={(event) => setQuery(event.target.value)}
63
+ placeholder="Search icons"
64
+ />
65
+ {matched.length === 0 ? (
66
+ <p className="emvb-helper">No icons match &quot;{query.trim()}&quot;.</p>
67
+ ) : (
68
+ <ul className="emvb-icon-grid" role="listbox" aria-label="Icons">
69
+ {matched.map((icon) => {
70
+ const selected = icon.id === current;
71
+ return (
72
+ <li key={icon.id}>
73
+ <button
74
+ type="button"
75
+ role="option"
76
+ aria-selected={selected}
77
+ className="emvb-icon-tile"
78
+ data-emvb-icon-id={icon.id}
79
+ data-selected={selected ? "true" : undefined}
80
+ onClick={() => {
81
+ const title = propsOf(node).title;
82
+ const previous = getBundledIcon(current)?.label;
83
+ const patch: Record<string, unknown> = { iconId: icon.id };
84
+ // Keep title in sync with the glyph when it still matches the prior
85
+ // default/label (defaults ship title "Star" with iconId "star").
86
+ if (
87
+ !title ||
88
+ title === "Icon" ||
89
+ (previous !== undefined && title === previous)
90
+ ) {
91
+ patch.title = icon.label;
92
+ }
93
+ onChange(withProps(node, patch));
94
+ }}
95
+ >
96
+ <span
97
+ className="emvb-icon-preview"
98
+ dangerouslySetInnerHTML={{ __html: previewSvg(icon.id) }}
99
+ />
100
+ <span>{icon.label}</span>
101
+ </button>
102
+ </li>
103
+ );
104
+ })}
105
+ </ul>
106
+ )}
107
+ </div>
108
+ );
109
+ }
@@ -0,0 +1,181 @@
1
+ import { DropdownMenu, InputGroup } from "@cloudflare/kumo";
2
+ import { CaretDownIcon } from "@phosphor-icons/react";
3
+ import * as React from "react";
4
+ import type { DesignSystem, StyleProps } from "../../../../core/index.ts";
5
+ import { FIELD } from "../../../ui.ts";
6
+ import {
7
+ parseLengthDraft,
8
+ unitsFor,
9
+ type LengthLiteral,
10
+ type LengthUnit,
11
+ type UnitChoice,
12
+ } from "./length-units.ts";
13
+ import type { StyleKey } from "./style-sections.ts";
14
+ import { bindKind, boundRef, lengthRef, VariableButton, VariableChip } from "./VariableBinding.tsx";
15
+
16
+ const isLiteral = (value: unknown): value is LengthLiteral =>
17
+ typeof value === "object" &&
18
+ value !== null &&
19
+ typeof (value as { value?: unknown }).value === "number" &&
20
+ typeof (value as { unit?: unknown }).unit === "string";
21
+
22
+ const same = (a: unknown, b: unknown) =>
23
+ a === b || (isLiteral(a) && isLiteral(b) && a.value === b.value && a.unit === b.unit);
24
+
25
+ const firstNumeric = (units: readonly UnitChoice[]): LengthUnit =>
26
+ (units.find((u) => u !== "auto") as LengthUnit | undefined) ?? "px";
27
+
28
+ /** A length property: number input, unit menu inside its right edge, variable button (W-088). */
29
+ export function LengthRow({
30
+ styleKey,
31
+ label,
32
+ value,
33
+ design,
34
+ set,
35
+ placeholder,
36
+ onPatch,
37
+ reset,
38
+ }: {
39
+ styleKey: StyleKey;
40
+ label: string;
41
+ value: unknown;
42
+ design: DesignSystem;
43
+ set: boolean;
44
+ /** The Normal value, shown while a state is edited (W-089). */
45
+ placeholder?: string;
46
+ onPatch: (patch: Partial<StyleProps>) => void;
47
+ reset: React.ReactNode;
48
+ }) {
49
+ const units = unitsFor(styleKey);
50
+ const literal = isLiteral(value) ? value : undefined;
51
+ const numericUnit = literal?.unit ?? firstNumeric(units);
52
+ const [draft, setDraft] = React.useState(literal ? String(literal.value) : "");
53
+ const [unit, setUnit] = React.useState<UnitChoice>(value === "auto" ? "auto" : numericUnit);
54
+ const lastNumeric = React.useRef<LengthUnit>(numericUnit);
55
+ const [error, setError] = React.useState<string | null>(null);
56
+ React.useEffect(() => {
57
+ setDraft(literal ? String(literal.value) : "");
58
+ setUnit(value === "auto" ? "auto" : (literal?.unit ?? lastNumeric.current));
59
+ if (literal) lastNumeric.current = literal.unit;
60
+ setError(null);
61
+ }, [value, literal]);
62
+
63
+ const send = (next: LengthLiteral | "auto" | undefined) => {
64
+ if (!same(next, value)) onPatch({ [styleKey]: next });
65
+ };
66
+
67
+ const commit = () => {
68
+ const parsed = parseLengthDraft(draft, styleKey, unit === "auto" ? lastNumeric.current : unit);
69
+ if (!parsed.ok) {
70
+ setError(parsed.message);
71
+ return;
72
+ }
73
+ setError(null);
74
+ if (parsed.value === undefined && value === "auto") return;
75
+ send(parsed.value);
76
+ };
77
+
78
+ const pickUnit = (next: UnitChoice) => {
79
+ setError(null);
80
+ setUnit(next);
81
+ if (next === "auto") {
82
+ setDraft("");
83
+ send("auto");
84
+ return;
85
+ }
86
+ lastNumeric.current = next;
87
+ const parsed = parseLengthDraft(draft, styleKey, next);
88
+ if (parsed.ok && parsed.value !== undefined && parsed.value !== "auto") {
89
+ send({ value: parsed.value.value, unit: next });
90
+ }
91
+ };
92
+
93
+ const kind = bindKind(styleKey);
94
+ const chip = lengthRef(value);
95
+ const current = kind ? boundRef(value, kind) : null;
96
+ return (
97
+ <div
98
+ className="emvb-style-row"
99
+ data-emvb-style={styleKey}
100
+ data-set={set ? "true" : undefined}
101
+ data-inherited={!set && placeholder !== undefined ? "true" : undefined}
102
+ data-unit={chip ? undefined : unit}
103
+ >
104
+ {chip ? (
105
+ <VariableChip
106
+ label={label}
107
+ kind={chip.kind}
108
+ design={design}
109
+ id={chip.var}
110
+ onDetach={(kept) => onPatch({ [styleKey]: typeof kept === "object" ? kept : undefined })}
111
+ />
112
+ ) : (
113
+ <InputGroup
114
+ label={label}
115
+ className={`${FIELD} emvb-length`}
116
+ error={error ? { message: error, match: true } : undefined}
117
+ >
118
+ <InputGroup.Input
119
+ className="emvb-mono"
120
+ aria-label={label}
121
+ inputMode="decimal"
122
+ value={draft}
123
+ placeholder={unit === "auto" ? "auto" : placeholder}
124
+ aria-invalid={error ? true : undefined}
125
+ onChange={(event) => {
126
+ if (unit === "auto") setUnit(lastNumeric.current);
127
+ setDraft(event.target.value);
128
+ }}
129
+ onBlur={commit}
130
+ onKeyDown={(event) => {
131
+ if (event.key === "Enter") commit();
132
+ }}
133
+ />
134
+ <InputGroup.Addon align="end" className="emvb-unit-addon">
135
+ <DropdownMenu>
136
+ <DropdownMenu.Trigger>
137
+ <button
138
+ type="button"
139
+ className="emvb-unit-btn"
140
+ aria-label={`${label} unit (${unit})`}
141
+ data-emvb-unit={unit}
142
+ >
143
+ {unit}
144
+ <CaretDownIcon size={12} aria-hidden="true" />
145
+ </button>
146
+ </DropdownMenu.Trigger>
147
+ <DropdownMenu.Content data-emvb-unit-menu={styleKey}>
148
+ <DropdownMenu.RadioGroup
149
+ value={unit}
150
+ onValueChange={(next: UnitChoice) => pickUnit(next)}
151
+ >
152
+ {units.map((choice) => (
153
+ <DropdownMenu.RadioItem
154
+ key={choice}
155
+ value={choice}
156
+ closeOnClick
157
+ data-emvb-unit-option={choice}
158
+ >
159
+ <span className="emvb-mono">{choice}</span>
160
+ <DropdownMenu.RadioItemIndicator />
161
+ </DropdownMenu.RadioItem>
162
+ ))}
163
+ </DropdownMenu.RadioGroup>
164
+ </DropdownMenu.Content>
165
+ </DropdownMenu>
166
+ </InputGroup.Addon>
167
+ </InputGroup>
168
+ )}
169
+ {kind && (
170
+ <VariableButton
171
+ label={label}
172
+ kind={kind}
173
+ design={design}
174
+ current={current?.var ?? null}
175
+ onBind={(next) => onPatch({ [styleKey]: next })}
176
+ />
177
+ )}
178
+ {reset}
179
+ </div>
180
+ );
181
+ }
@@ -0,0 +1,124 @@
1
+ import { Input, Select } from "@cloudflare/kumo";
2
+ import * as React from "react";
3
+ import type { ThemePartType } from "../../../../core/index.ts";
4
+ import type { Fetcher } from "../../../api.ts";
5
+ import { listThemeParts, type ThemePartSummary } from "../../../theme-api.ts";
6
+ import { FIELD } from "../../../ui.ts";
7
+
8
+ const MANUAL = "__manual__";
9
+ const NONE = "__none__";
10
+
11
+ /**
12
+ * Loop Item theme-part binder (W-077): pick a published/draft Loop Item by title,
13
+ * keep storing the part id string for render compatibility.
14
+ */
15
+ export function LoopItemBindControl({
16
+ value,
17
+ fetcher,
18
+ onChange,
19
+ partType = "loop_item",
20
+ label = "Loop Item",
21
+ emptyLabel = "Use nested elements",
22
+ marker = "loop-item",
23
+ }: {
24
+ value: string;
25
+ fetcher: Fetcher;
26
+ onChange: (itemPartId: string) => void;
27
+ partType?: ThemePartType;
28
+ label?: string;
29
+ emptyLabel?: string;
30
+ /** `data-emvb-${marker}-bind` keeps the loop-item tests stable. */
31
+ marker?: string;
32
+ }) {
33
+ const [parts, setParts] = React.useState<ThemePartSummary[] | null>(null);
34
+ const [failed, setFailed] = React.useState(false);
35
+
36
+ React.useEffect(() => {
37
+ let cancelled = false;
38
+ void listThemeParts(fetcher)
39
+ .then((all) => {
40
+ if (cancelled) return;
41
+ setParts(all.filter((part) => part.partType === partType));
42
+ setFailed(false);
43
+ })
44
+ .catch(() => {
45
+ if (!cancelled) {
46
+ setParts(null);
47
+ setFailed(true);
48
+ }
49
+ });
50
+ return () => {
51
+ cancelled = true;
52
+ };
53
+ }, [fetcher, partType]);
54
+
55
+ if (parts && parts.length > 0) {
56
+ const known = parts.some((part) => part.id === value);
57
+ const selectValue = value === "" ? NONE : known ? value : MANUAL;
58
+ return (
59
+ <div {...{ [`data-emvb-${marker}-bind`]: "list" }}>
60
+ <Select
61
+ label={label}
62
+ className={FIELD}
63
+ value={selectValue}
64
+ onValueChange={(next) => {
65
+ if (!next || next === MANUAL) return;
66
+ if (next === NONE) {
67
+ onChange("");
68
+ return;
69
+ }
70
+ onChange(next);
71
+ }}
72
+ renderValue={(current: unknown) => {
73
+ if (current === NONE || current === "") return emptyLabel;
74
+ if (current === MANUAL) return "Current id (not in list)";
75
+ const match = parts.find((part) => part.id === String(current));
76
+ return match ? labelFor(match) : String(current);
77
+ }}
78
+ >
79
+ <Select.Option value={NONE}>{emptyLabel}</Select.Option>
80
+ {!known && value ? (
81
+ <Select.Option value={MANUAL}>Current id (not in list)</Select.Option>
82
+ ) : null}
83
+ {parts.map((part) => (
84
+ <Select.Option key={part.id} value={part.id}>
85
+ {labelFor(part)}
86
+ </Select.Option>
87
+ ))}
88
+ </Select>
89
+ <Input
90
+ label={`${label} part id`}
91
+ className={`${FIELD} emvb-mono`}
92
+ value={value}
93
+ onChange={(event) => onChange(event.target.value.trim())}
94
+ />
95
+ <p className="emvb-helper">
96
+ Optional published {label} theme part. Leave blank to use nested elements.
97
+ <a href="/_emdash/admin/plugins/emvb/theme"> Open Theme Builder</a>
98
+ </p>
99
+ </div>
100
+ );
101
+ }
102
+
103
+ return (
104
+ <div {...{ [`data-emvb-${marker}-bind`]: "manual" }}>
105
+ <Input
106
+ label={`${label} part id`}
107
+ className={`${FIELD} emvb-mono`}
108
+ value={value}
109
+ onChange={(event) => onChange(event.target.value.trim())}
110
+ />
111
+ <p className="emvb-helper">
112
+ {failed
113
+ ? `Could not load ${label} parts. Paste a theme-part id, or `
114
+ : `No ${label} theme parts yet. Paste an id, or `}
115
+ <a href="/_emdash/admin/plugins/emvb/theme">create one in Theme Builder</a>.
116
+ </p>
117
+ </div>
118
+ );
119
+ }
120
+
121
+ function labelFor(part: ThemePartSummary): string {
122
+ const status = part.status === "published" ? "" : ` (${part.status})`;
123
+ return `${part.title}${status}`;
124
+ }
@@ -0,0 +1,218 @@
1
+ import { Button, Input } from "@cloudflare/kumo";
2
+ import * as React from "react";
3
+ import { sanitizeMediaUrl, type LayoutNode } from "../../../../core/index.ts";
4
+ import type { Fetcher } from "../../../api.ts";
5
+ import {
6
+ listImages,
7
+ propsFromMedia,
8
+ uploadImage,
9
+ type MediaLibraryItem,
10
+ } from "../../../media-api.ts";
11
+ import { BUTTON, FIELD } from "../../../ui.ts";
12
+
13
+ const propsOf = (node: LayoutNode): Record<string, unknown> =>
14
+ node.props as Record<string, unknown>;
15
+
16
+ const withProps = (node: LayoutNode, props: Record<string, unknown>): LayoutNode =>
17
+ ({ ...node, props }) as LayoutNode;
18
+
19
+ type Props = {
20
+ node: LayoutNode;
21
+ fetcher: Fetcher;
22
+ onChange: (node: LayoutNode) => void;
23
+ };
24
+
25
+ /**
26
+ * Image source control (W-024 / R-007): pick from EmDash media library, upload a file,
27
+ * or paste a URL. Upload uses the same POST /_emdash/api/media path on both demos.
28
+ */
29
+ export function MediaPicker({ node, fetcher, onChange }: Props) {
30
+ const props = propsOf(node);
31
+ const src = typeof props.src === "string" ? props.src : "";
32
+ const [open, setOpen] = React.useState(false);
33
+ const [items, setItems] = React.useState<MediaLibraryItem[]>([]);
34
+ const [busy, setBusy] = React.useState(false);
35
+ const [error, setError] = React.useState<string | null>(null);
36
+ const [urlDraft, setUrlDraft] = React.useState(src);
37
+ const fileRef = React.useRef<HTMLInputElement>(null);
38
+
39
+ React.useEffect(() => {
40
+ setUrlDraft(src);
41
+ }, [src, node.id]);
42
+
43
+ const loadLibrary = React.useCallback(async () => {
44
+ setBusy(true);
45
+ setError(null);
46
+ try {
47
+ setItems(await listImages(fetcher, { limit: 40 }));
48
+ } catch (caught) {
49
+ setError(caught instanceof Error ? caught.message : "Couldn't load the media library.");
50
+ setItems([]);
51
+ } finally {
52
+ setBusy(false);
53
+ }
54
+ }, [fetcher]);
55
+
56
+ React.useEffect(() => {
57
+ if (open) void loadLibrary();
58
+ }, [open, loadLibrary]);
59
+
60
+ const applyItem = (item: MediaLibraryItem) => {
61
+ onChange(withProps(node, propsFromMedia(propsOf(node), item)));
62
+ setOpen(false);
63
+ setError(null);
64
+ };
65
+
66
+ const onUpload = async (file: File | undefined) => {
67
+ if (!file) return;
68
+ setBusy(true);
69
+ setError(null);
70
+ try {
71
+ const dims = await readImageSize(file).catch(
72
+ () => ({}) as { width?: number; height?: number },
73
+ );
74
+ const item = await uploadImage(fetcher, file, dims);
75
+ applyItem(item);
76
+ } catch (caught) {
77
+ setError(caught instanceof Error ? caught.message : "Upload failed.");
78
+ } finally {
79
+ setBusy(false);
80
+ if (fileRef.current) fileRef.current.value = "";
81
+ }
82
+ };
83
+
84
+ /** Enter always checks the field; leaving it (blur) only commits a real change (W-092). */
85
+ const commitUrl = (explicit: boolean) => {
86
+ const trimmed = urlDraft.trim();
87
+ if (!explicit && trimmed === src) {
88
+ setError(null);
89
+ return;
90
+ }
91
+ if (trimmed === "") {
92
+ setError("Choose a library image, upload a file, or enter a URL.");
93
+ return;
94
+ }
95
+ const safe = sanitizeMediaUrl(trimmed);
96
+ if (!safe) {
97
+ setError(
98
+ "Use a full URL such as https://example.com/photo.jpg or a path such as /uploads/photo.jpg.",
99
+ );
100
+ return;
101
+ }
102
+ setError(null);
103
+ if (safe === src) return;
104
+ const next: Record<string, unknown> = { ...propsOf(node), src: safe };
105
+ delete next.mediaId;
106
+ onChange(withProps(node, next));
107
+ };
108
+
109
+ return (
110
+ <div className="emvb-field-group" data-emvb-field="src" data-emvb-media-picker="">
111
+ <label className="emvb-field-label">Image</label>
112
+ {src ? (
113
+ <div className="emvb-media-preview">
114
+ <img src={src} alt="" className="emvb-media-thumb" />
115
+ <span className="emvb-helper emvb-mono">{src}</span>
116
+ </div>
117
+ ) : (
118
+ <p className="emvb-helper">No image selected yet.</p>
119
+ )}
120
+ <div className="emvb-media-actions">
121
+ <Button
122
+ type="button"
123
+ className={BUTTON}
124
+ onClick={() => setOpen(true)}
125
+ disabled={busy}
126
+ data-emvb-media-library=""
127
+ >
128
+ Choose from library
129
+ </Button>
130
+ <Button
131
+ type="button"
132
+ className={BUTTON}
133
+ variant="secondary"
134
+ onClick={() => fileRef.current?.click()}
135
+ disabled={busy}
136
+ data-emvb-media-upload-btn=""
137
+ >
138
+ Upload
139
+ </Button>
140
+ <input
141
+ ref={fileRef}
142
+ type="file"
143
+ accept="image/png,image/jpeg,image/gif,image/webp,image/avif"
144
+ className="emvb-sr-only"
145
+ data-emvb-media-upload=""
146
+ onChange={(event) => void onUpload(event.target.files?.[0])}
147
+ />
148
+ </div>
149
+ <Input
150
+ label="Or paste a URL"
151
+ className={FIELD}
152
+ value={urlDraft}
153
+ error={error ?? undefined}
154
+ data-emvb-media-url=""
155
+ onChange={(event) => setUrlDraft(event.target.value)}
156
+ onBlur={() => commitUrl(false)}
157
+ onKeyDown={(event) => {
158
+ if (event.key === "Enter") commitUrl(true);
159
+ }}
160
+ />
161
+ {open && (
162
+ <div
163
+ className="emvb-media-dialog"
164
+ role="dialog"
165
+ aria-label="Media library"
166
+ data-emvb-media-dialog=""
167
+ >
168
+ <div className="emvb-media-dialog-head">
169
+ <h3 className="emvb-panel-title">Media library</h3>
170
+ <Button
171
+ type="button"
172
+ className={BUTTON}
173
+ variant="secondary"
174
+ onClick={() => setOpen(false)}
175
+ >
176
+ Close
177
+ </Button>
178
+ </div>
179
+ {busy && <p className="emvb-helper">Loading…</p>}
180
+ {!busy && items.length === 0 && (
181
+ <p className="emvb-helper">No images yet. Upload one to get started.</p>
182
+ )}
183
+ <ul className="emvb-media-grid">
184
+ {items.map((item) => (
185
+ <li key={item.id}>
186
+ <button
187
+ type="button"
188
+ className="emvb-media-card"
189
+ data-emvb-media-id={item.id}
190
+ onClick={() => applyItem(item)}
191
+ >
192
+ <img src={item.url} alt={item.alt ?? item.filename} />
193
+ <span>{item.filename}</span>
194
+ </button>
195
+ </li>
196
+ ))}
197
+ </ul>
198
+ </div>
199
+ )}
200
+ </div>
201
+ );
202
+ }
203
+
204
+ function readImageSize(file: File): Promise<{ width: number; height: number }> {
205
+ return new Promise((resolve, reject) => {
206
+ const url = URL.createObjectURL(file);
207
+ const img = new Image();
208
+ img.addEventListener("load", () => {
209
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
210
+ URL.revokeObjectURL(url);
211
+ });
212
+ img.addEventListener("error", () => {
213
+ URL.revokeObjectURL(url);
214
+ reject(new Error("Couldn't read image dimensions."));
215
+ });
216
+ img.src = url;
217
+ });
218
+ }