@perkyzz/emvb 0.2.1 → 0.4.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 (150) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +3 -1
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/api.ts +17 -7
  6. package/src/admin/content-api.ts +7 -51
  7. package/src/admin/content-item.ts +22 -0
  8. package/src/admin/design-api.ts +30 -0
  9. package/src/admin/editor/A11yCopilot.tsx +126 -0
  10. package/src/admin/editor/CommandPalette.tsx +118 -0
  11. package/src/admin/editor/Editor.tsx +188 -152
  12. package/src/admin/editor/EditorOverlay.tsx +9 -1
  13. package/src/admin/editor/PerfMeter.tsx +121 -0
  14. package/src/admin/editor/ShareLink.tsx +164 -0
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +287 -0
  17. package/src/admin/editor/TopBar.tsx +4 -0
  18. package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
  19. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  20. package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
  21. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  22. package/src/admin/editor/canvas/drop-line.ts +24 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  24. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  25. package/src/admin/editor/collection-previews.ts +114 -0
  26. package/src/admin/editor/editor-chrome.tsx +346 -0
  27. package/src/admin/editor/editor-commands.ts +360 -0
  28. package/src/admin/editor/editor-css.ts +5 -3
  29. package/src/admin/editor/element-chrome.ts +89 -0
  30. package/src/admin/editor/feature-css.ts +105 -0
  31. package/src/admin/editor/host.ts +35 -0
  32. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  33. package/src/admin/editor/icons/library.ts +29 -19
  34. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  35. package/src/admin/editor/live-data.tsx +71 -0
  36. package/src/admin/editor/palette-items.ts +136 -0
  37. package/src/admin/editor/palette.ts +68 -0
  38. package/src/admin/editor/panels/AddPanel.tsx +48 -68
  39. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  40. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  41. package/src/admin/editor/panels/ElementPanel.tsx +74 -102
  42. package/src/admin/editor/panels/LayersPanel.tsx +72 -63
  43. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  44. package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
  45. package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
  46. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  47. package/src/admin/editor/panels/VariableSection.tsx +10 -14
  48. package/src/admin/editor/panels/inline-error.tsx +11 -0
  49. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  50. package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -0
  51. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  52. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  53. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  54. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  55. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  56. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  57. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  58. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  59. package/src/admin/editor/panels/settings/StyleRow.tsx +26 -2
  60. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  61. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  62. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  63. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  64. package/src/admin/editor/panels/settings/length-units.ts +16 -5
  65. package/src/admin/editor/panels/settings/style-sections.ts +7 -2
  66. package/src/admin/editor/panels/style-target.ts +105 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +6 -1
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +30 -14
  74. package/src/admin/editor/useNodeActions.ts +44 -16
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/theme-api.ts +5 -18
  78. package/src/admin/ui.ts +4 -4
  79. package/src/astro/content-port.ts +24 -0
  80. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  81. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  82. package/src/astro/forms/client.ts +1 -0
  83. package/src/astro/forms-definitions.ts +24 -11
  84. package/src/astro/index.ts +1 -0
  85. package/src/astro/render-session.ts +85 -0
  86. package/src/astro/request-data.ts +109 -0
  87. package/src/astro/resolve-theme.ts +184 -64
  88. package/src/astro/resolve.ts +63 -16
  89. package/src/astro/theme-posts.ts +48 -5
  90. package/src/astro/visitor.ts +204 -0
  91. package/src/constants.ts +1 -1
  92. package/src/core/a11y/audit.ts +282 -0
  93. package/src/core/arrange.ts +150 -34
  94. package/src/core/audience/rules.ts +124 -0
  95. package/src/core/audience/variants.ts +51 -0
  96. package/src/core/canvas-styles.ts +24 -0
  97. package/src/core/clipboard.ts +11 -32
  98. package/src/core/css/generate.ts +29 -2
  99. package/src/core/css/print.ts +12 -0
  100. package/src/core/css/scope.ts +3 -3
  101. package/src/core/css/trace.ts +169 -0
  102. package/src/core/css-keywords.ts +83 -0
  103. package/src/core/data/bindings.ts +255 -0
  104. package/src/core/design/classes.ts +13 -15
  105. package/src/core/design/diff.ts +55 -0
  106. package/src/core/design/merge.ts +127 -0
  107. package/src/core/design/tokens.ts +127 -0
  108. package/src/core/design/variables.ts +25 -21
  109. package/src/core/elements/dynamic-elements.ts +117 -2
  110. package/src/core/elements/form-elements.ts +1 -0
  111. package/src/core/elements/index.ts +185 -7
  112. package/src/core/forms/binding.ts +4 -13
  113. package/src/core/history/diff.ts +152 -0
  114. package/src/core/index.ts +121 -0
  115. package/src/core/local-style.ts +27 -0
  116. package/src/core/migrate/index.ts +12 -4
  117. package/src/core/nesting.ts +4 -22
  118. package/src/core/perf/meter.ts +160 -0
  119. package/src/core/perf/scripts.ts +61 -0
  120. package/src/core/recipes/index.ts +433 -0
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +1 -2
  124. package/src/core/render/form.ts +133 -10
  125. package/src/core/render/index.ts +206 -17
  126. package/src/core/render/loop.ts +54 -7
  127. package/src/core/render/pagination.ts +9 -1
  128. package/src/core/render/vnode.ts +12 -2
  129. package/src/core/sanitize/css.ts +129 -80
  130. package/src/core/sanitize/motion.ts +129 -0
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/design.ts +29 -8
  134. package/src/core/schema/layout.ts +291 -169
  135. package/src/core/schema/motion.ts +14 -0
  136. package/src/core/schema/style.ts +101 -66
  137. package/src/core/share/link.ts +187 -0
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +242 -32
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/theme/pagination.ts +56 -0
  142. package/src/core/tree-ops.ts +57 -0
  143. package/src/index.ts +14 -2
  144. package/src/server/design-routes.ts +4 -1
  145. package/src/server/icon-routes.ts +68 -16
  146. package/src/server/plugin.ts +8 -2
  147. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  148. package/src/admin/editor/icons/sets/lucide.json +0 -1
  149. package/src/admin/editor/icons/sets/remix.json +0 -1
  150. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -0,0 +1,94 @@
1
+ import {
2
+ traceStyle,
3
+ type DesignSystem,
4
+ type LayoutNode,
5
+ type StyleSource,
6
+ type TraceDevice,
7
+ } from "../../../../core/index.ts";
8
+
9
+ /** "backgroundColor" → "Background color". */
10
+ const propertyName = (key: string) => {
11
+ const words = key.replace(/([A-Z])/g, " $1").toLowerCase();
12
+ return words.charAt(0).toUpperCase() + words.slice(1);
13
+ };
14
+
15
+ /** A short, readable value: a colour, a length, a variable, or JSON cut short. */
16
+ export function sourceValue(value: unknown, design?: DesignSystem): string {
17
+ if (typeof value === "string" || typeof value === "number") return String(value);
18
+ if (value && typeof value === "object") {
19
+ if ("var" in value) {
20
+ const id = (value as { var: string }).var;
21
+ const { colors, fonts, fontSizes, spacings } = design?.variables ?? { colors: [] };
22
+ const named = [...colors, ...(fonts ?? []), ...(fontSizes ?? []), ...(spacings ?? [])].find(
23
+ (v) => v.id === id,
24
+ );
25
+ return named ? named.name : `var ${id}`;
26
+ }
27
+ if ("value" in value && "unit" in value) {
28
+ const v = value as { value: number; unit: string };
29
+ return `${v.value}${v.unit}`;
30
+ }
31
+ }
32
+ const json = JSON.stringify(value) ?? "";
33
+ return json.length > 32 ? `${json.slice(0, 31)}…` : json;
34
+ }
35
+
36
+ const where = (s: StyleSource) => (s.layer === "Desktop" ? s.label : `${s.label} · ${s.layer}`);
37
+
38
+ /**
39
+ * Style inheritance inspector (W-318): every property that applies to this element here, the
40
+ * layer it comes from (site default, a class, this element; Desktop, Tablet, Mobile or a state)
41
+ * and what it overrides.
42
+ */
43
+ export function StyleSources({
44
+ node,
45
+ design,
46
+ device,
47
+ state,
48
+ }: {
49
+ node: LayoutNode;
50
+ design: DesignSystem;
51
+ device: TraceDevice;
52
+ state: "normal" | "hover" | "focus" | "active";
53
+ }) {
54
+ const trace = traceStyle(node, design, device, state);
55
+ const keys = Object.keys(trace).toSorted();
56
+ const fromElsewhere = keys.filter((key) => trace[key]?.winner.kind !== "local").length;
57
+ return (
58
+ <details className="emvb-sources" data-emvb-style-sources="">
59
+ <summary>
60
+ Where styles come from
61
+ <span className="emvb-sources-count">
62
+ {keys.length === 0
63
+ ? "nothing set"
64
+ : `${keys.length} set${fromElsewhere > 0 ? `, ${fromElsewhere} inherited` : ""}`}
65
+ </span>
66
+ </summary>
67
+ {keys.length === 0 ? (
68
+ <p className="emvb-helper">No styles apply yet beyond the element's defaults.</p>
69
+ ) : (
70
+ <ul>
71
+ {keys.map((key) => {
72
+ const t = trace[key];
73
+ if (!t) return null;
74
+ return (
75
+ <li key={key} data-emvb-source={key} data-kind={t.winner.kind}>
76
+ <span className="emvb-sources-prop">{propertyName(key)}</span>
77
+ <span className="emvb-sources-value">{sourceValue(t.winner.value, design)}</span>
78
+ <span className="emvb-sources-from">{where(t.winner)}</span>
79
+ {t.overridden.length > 0 && (
80
+ <span className="emvb-sources-over">
81
+ overrides{" "}
82
+ {t.overridden
83
+ .map((o) => `${where(o)} (${sourceValue(o.value, design)})`)
84
+ .join(", ")}
85
+ </span>
86
+ )}
87
+ </li>
88
+ );
89
+ })}
90
+ </ul>
91
+ )}
92
+ </details>
93
+ );
94
+ }
@@ -126,7 +126,7 @@ export function VariableButton({
126
126
  }
127
127
 
128
128
  /**
129
- * The variable chip that stands in for a bound value: the kind icon, the variable's
129
+ * The variable chip that stands in for a bound value (DESIGN.md): the kind icon, the variable's
130
130
  * name and an × that detaches it, keeping the variable's current value as a literal.
131
131
  */
132
132
  export function VariableChip({
@@ -0,0 +1,83 @@
1
+ import {
2
+ createVariantB,
3
+ endAbTest,
4
+ type Arranged,
5
+ type Layout,
6
+ type LayoutNode,
7
+ } from "../../../../core/index.ts";
8
+
9
+ /** Types that can't be an A/B arm: items of a list that has its own rules, and the root. */
10
+ const NO_VARIANT = new Set(["tab-panel", "accordion-item", "loop-empty", "option"]);
11
+
12
+ /**
13
+ * Edge A/B test (W-312): make this element arm A and a copy arm B. The server picks one per
14
+ * visitor and a cookie keeps it, so nothing flickers and no script loads.
15
+ */
16
+ export function VariantEditor({
17
+ node,
18
+ isRoot,
19
+ onChange,
20
+ onArrange,
21
+ }: {
22
+ node: LayoutNode;
23
+ isRoot: boolean;
24
+ onChange: (node: LayoutNode) => void;
25
+ onArrange?: (run: (layout: Layout) => Arranged) => void;
26
+ }) {
27
+ if (isRoot || NO_VARIANT.has(node.type) || !onArrange) return null;
28
+ const v = node.variant;
29
+ return (
30
+ <section className="emvb-bind" data-emvb-variant-editor="">
31
+ <h3 className="emvb-bind-title">A/B test</h3>
32
+ {!v ? (
33
+ <>
34
+ <p className="emvb-helper">
35
+ Show half of your visitors a different version. The server picks the version, so nothing
36
+ flickers and no script loads.
37
+ </p>
38
+ <button
39
+ type="button"
40
+ className="emvb-link-button"
41
+ data-emvb-create-variant=""
42
+ onClick={() => onArrange((layout) => createVariantB(layout, node.id))}
43
+ >
44
+ Create variant B
45
+ </button>
46
+ </>
47
+ ) : (
48
+ <>
49
+ <p className="emvb-helper" data-emvb-variant-arm={v.arm}>
50
+ Variant {v.arm.toUpperCase()} of test <b>{v.test}</b>. The canvas shows every variant;
51
+ visitors see one.
52
+ </p>
53
+ {v.arm === "b" && (
54
+ <label className="emvb-bind-row">
55
+ <span className="emvb-bind-label">Visitors who see B (%)</span>
56
+ <input
57
+ className="emvb-native-input"
58
+ type="number"
59
+ min={1}
60
+ max={99}
61
+ value={v.split ?? 50}
62
+ data-emvb-variant-split=""
63
+ onChange={(event) => {
64
+ const n = Math.round(Number(event.currentTarget.value));
65
+ if (!Number.isFinite(n) || n < 1 || n > 99) return;
66
+ onChange({ ...node, variant: { ...v, split: n } } as LayoutNode);
67
+ }}
68
+ />
69
+ </label>
70
+ )}
71
+ <button
72
+ type="button"
73
+ className="emvb-link-button"
74
+ data-emvb-end-test=""
75
+ onClick={() => onArrange((layout) => endAbTest(layout, node.id))}
76
+ >
77
+ Keep this variant and end the test
78
+ </button>
79
+ </>
80
+ )}
81
+ </section>
82
+ );
83
+ }
@@ -1,10 +1,5 @@
1
- import {
2
- findNode,
3
- isFormNode,
4
- parentOf,
5
- type Layout,
6
- type LayoutNode,
7
- } from "../../../../core/index.ts";
1
+ import { isFormNode, type Layout, type LayoutNode } from "../../../../core/index.ts";
2
+ import { indexLayout } from "../../../../core/tree-ops.ts";
8
3
 
9
4
  const fieldOf = (node: LayoutNode): string => {
10
5
  const value = (node.props as Record<string, unknown> | undefined)?.field;
@@ -16,12 +11,13 @@ const fieldOf = (node: LayoutNode): string => {
16
11
  * one value would overwrite the other. Controls outside any form are not checked.
17
12
  */
18
13
  export function duplicateFieldName(layout: Layout, nodeId: string): boolean {
19
- const self = findNode(layout, nodeId);
14
+ const index = indexLayout(layout);
15
+ const self = index.byId.get(nodeId);
20
16
  const name = self ? fieldOf(self) : "";
21
17
  if (!name) return false;
22
- let current = parentOf(layout, nodeId);
18
+ let current = index.parentOf.get(nodeId);
23
19
  while (current) {
24
- const form = findNode(layout, current);
20
+ const form = index.byId.get(current);
25
21
  if (form && isFormNode(form)) {
26
22
  let count = 0;
27
23
  const walk = (node: LayoutNode) => {
@@ -32,7 +28,7 @@ export function duplicateFieldName(layout: Layout, nodeId: string): boolean {
32
28
  walk(form);
33
29
  return count > 1;
34
30
  }
35
- current = parentOf(layout, current);
31
+ current = index.parentOf.get(current);
36
32
  }
37
33
  return false;
38
34
  }
@@ -1,14 +1,14 @@
1
1
  import { STYLE_LABELS, type StyleKey } from "./style-sections.ts";
2
2
 
3
- export type LengthUnit = "px" | "rem" | "em" | "%" | "vw" | "vh";
3
+ export type LengthUnit = "px" | "rem" | "em" | "%" | "vw" | "vh" | "ch";
4
4
  /** `x` is a unitless number, for Line height only (W-213). */
5
5
  export type UnitChoice = LengthUnit | "auto" | "x";
6
6
  export type LengthLiteral = { value: number; unit: LengthUnit };
7
7
 
8
- const BOX: readonly UnitChoice[] = ["px", "%", "rem", "em", "vw", "vh"];
8
+ const BOX: readonly UnitChoice[] = ["px", "%", "rem", "em", "vw", "vh", "ch"];
9
9
  const BOX_AUTO: readonly UnitChoice[] = [...BOX, "auto"];
10
10
 
11
- /** Units each length property offers in its unit menu. */
11
+ /** Units each length property offers in its unit menu (DESIGN.md § Inputs). */
12
12
  const UNITS: Partial<Record<StyleKey, readonly UnitChoice[]>> = {
13
13
  width: BOX_AUTO,
14
14
  height: BOX_AUTO,
@@ -38,13 +38,24 @@ const UNITS: Partial<Record<StyleKey, readonly UnitChoice[]>> = {
38
38
 
39
39
  export const unitsFor = (key: StyleKey): readonly UnitChoice[] => UNITS[key] ?? BOX;
40
40
 
41
- const NEGATIVE = new Set<StyleKey>(["top", "right", "bottom", "left", "letterSpacing"]);
41
+ /** Keys that take a negative number; margins since W-331. */
42
+ const NEGATIVE = new Set<StyleKey>([
43
+ "top",
44
+ "right",
45
+ "bottom",
46
+ "left",
47
+ "letterSpacing",
48
+ "marginTop",
49
+ "marginRight",
50
+ "marginBottom",
51
+ "marginLeft",
52
+ ]);
42
53
 
43
54
  export type ParsedLength =
44
55
  | { ok: true; value: LengthLiteral | "auto" | number | undefined }
45
56
  | { ok: false; message: string };
46
57
 
47
- const DRAFT = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*(px|rem|em|%|vw|vh)?$/i;
58
+ const DRAFT = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*(px|rem|em|%|vw|vh|ch)?$/i;
48
59
  /** A number with a unit EmVB doesn't take ("100dvh", "12pt"), or a comma decimal ("1,5") (W-262). */
49
60
  const OTHER_UNIT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)\s*[a-z%]+$/i;
50
61
  const COMMA_DECIMAL = /^[+-]?\d*,\d+\s*[a-z%]*$/i;
@@ -148,7 +148,9 @@ const SECTION_KEYS: Record<StyleSectionId, StyleKey[]> = {
148
148
  "alignItems",
149
149
  "gap",
150
150
  "gridColumnSpan",
151
+ "gridColumnStart",
151
152
  "gridRowSpan",
153
+ "gridRowStart",
152
154
  ],
153
155
  spacing: [
154
156
  "paddingTop",
@@ -207,7 +209,7 @@ const SECTION_KEYS: Record<StyleSectionId, StyleKey[]> = {
207
209
  "borderBottomRightRadius",
208
210
  "borderBottomLeftRadius",
209
211
  ],
210
- effects: ["opacity", "boxShadow", "filter", "cursor", "entrance", "transition"],
212
+ effects: ["opacity", "boxShadow", "filter", "cursor", "entrance", "scrollMotion", "transition"],
211
213
  icon: ["iconRotate", "iconFlip", "iconScale", "iconStrokeWidth", "iconShadow", "iconAnimation"],
212
214
  advanced: [],
213
215
  };
@@ -228,7 +230,7 @@ const ONLY_FOR: Partial<Record<StyleKey, string[]>> = {
228
230
  ),
229
231
  };
230
232
 
231
- const SPANS: StyleKey[] = ["gridColumnSpan", "gridRowSpan"];
233
+ const SPANS: StyleKey[] = ["gridColumnSpan", "gridColumnStart", "gridRowSpan", "gridRowStart"];
232
234
 
233
235
  /**
234
236
  * Direction, wrap, justify, align and gap only where the element's own box is a flex or grid
@@ -323,7 +325,9 @@ export const STYLE_LABELS: Record<StyleKey, string> = {
323
325
  alignItems: "Align",
324
326
  gap: "Gap",
325
327
  gridColumnSpan: "Column span",
328
+ gridColumnStart: "Column start",
326
329
  gridRowSpan: "Row span",
330
+ gridRowStart: "Row start",
327
331
  width: "Width",
328
332
  minWidth: "Min width",
329
333
  maxWidth: "Max width",
@@ -381,6 +385,7 @@ export const STYLE_LABELS: Record<StyleKey, string> = {
381
385
  filter: "Filters",
382
386
  cursor: "Cursor",
383
387
  entrance: "Entrance",
388
+ scrollMotion: "Scroll motion",
384
389
  iconRotate: "Rotate",
385
390
  iconFlip: "Flip",
386
391
  iconScale: "Scale",
@@ -0,0 +1,105 @@
1
+ import {
2
+ patchClassDevices,
3
+ patchClassState,
4
+ patchClassStyle,
5
+ patchDeviceStyle,
6
+ patchStates,
7
+ type DesignSystem,
8
+ type DeviceStyles,
9
+ type LayoutNode,
10
+ type PopupDevice,
11
+ type StyleProps,
12
+ type StyleStateName,
13
+ type StyleStates,
14
+ } from "../../../core/index.ts";
15
+ import type { StyleStateChoice } from "./settings/StateSwitcher.tsx";
16
+
17
+ export type StyleSlot =
18
+ | { owner: "element" | "class"; slot: "style" }
19
+ | { owner: "element" | "class"; slot: "state"; state: StyleStateName }
20
+ | { owner: "element" | "class"; slot: "device"; device: "tablet" | "mobile" };
21
+
22
+ /** Which style object a patch writes: the element's own, a class, a state, or a device. */
23
+ export function styleTarget({
24
+ classId,
25
+ device,
26
+ state,
27
+ }: {
28
+ classId: string | null;
29
+ device: PopupDevice;
30
+ state: StyleStateChoice;
31
+ }): StyleSlot {
32
+ const owner = classId ? "class" : "element";
33
+ if (device !== "desktop") return { owner, slot: "device", device };
34
+ if (state === "normal") return { owner, slot: "style" };
35
+ return { owner, slot: "state", state };
36
+ }
37
+
38
+ const withStyle = (node: LayoutNode, patch: Partial<StyleProps>): LayoutNode => {
39
+ const style: Record<string, unknown> = { ...node.style, ...patch };
40
+ for (const key of Object.keys(style)) if (style[key] === undefined) delete style[key];
41
+ return {
42
+ ...node,
43
+ style: Object.keys(style).length > 0 ? (style as StyleProps) : undefined,
44
+ };
45
+ };
46
+
47
+ const withDevices = (node: LayoutNode, devices: DeviceStyles | undefined): LayoutNode => {
48
+ const { devices: _old, ...rest } = node;
49
+ return (devices ? { ...rest, devices } : rest) as LayoutNode;
50
+ };
51
+
52
+ const withStates = (node: LayoutNode, states: StyleStates | undefined): LayoutNode => {
53
+ const { states: _old, ...rest } = node;
54
+ return (states ? { ...rest, states } : rest) as LayoutNode;
55
+ };
56
+
57
+ export type StyleWrite =
58
+ | { kind: "node"; node: LayoutNode }
59
+ | { kind: "design"; design: DesignSystem };
60
+
61
+ /** Apply a style patch to the slot `styleTarget` names. */
62
+ export function applyStylePatch({
63
+ node,
64
+ design,
65
+ classId,
66
+ device,
67
+ state,
68
+ patch,
69
+ }: {
70
+ node: LayoutNode;
71
+ design: DesignSystem;
72
+ classId: string | null;
73
+ device: PopupDevice;
74
+ state: StyleStateChoice;
75
+ patch: Partial<StyleProps>;
76
+ }): StyleWrite {
77
+ const target = styleTarget({ classId, device, state });
78
+ if (target.slot === "device") {
79
+ if (!classId) {
80
+ return {
81
+ kind: "node",
82
+ node: withDevices(node, patchDeviceStyle(node.devices, target.device, patch)),
83
+ };
84
+ }
85
+ return {
86
+ kind: "design",
87
+ design: patchClassDevices(design, classId, target.device, patch),
88
+ };
89
+ }
90
+ if (!classId) {
91
+ return {
92
+ kind: "node",
93
+ node:
94
+ state === "normal"
95
+ ? withStyle(node, patch)
96
+ : withStates(node, patchStates(node.states, state, patch)),
97
+ };
98
+ }
99
+ const cls = { id: classId };
100
+ const next =
101
+ state === "normal"
102
+ ? patchClassStyle(design, cls.id, patch)
103
+ : patchClassState(design, cls.id, state, patch);
104
+ return { kind: "design", design: next };
105
+ }
@@ -5,6 +5,41 @@ import { themePartLayout } from "../theme-api.ts";
5
5
 
6
6
  const MAX_DEPTH = 8;
7
7
 
8
+ /**
9
+ * Loads section parts one depth at a time. Siblings load together. A part that fails is left out;
10
+ * the ones that loaded stay.
11
+ */
12
+ export async function loadSectionTemplates(
13
+ fetcher: Fetcher,
14
+ ids: readonly string[],
15
+ read: (id: string) => Promise<Layout | null> = (id) => themePartLayout(fetcher, id, "section"),
16
+ ): Promise<Record<string, Layout>> {
17
+ const acc: Record<string, Layout> = {};
18
+ const walk = async (next: readonly string[], depth: number): Promise<void> => {
19
+ if (depth > MAX_DEPTH) return;
20
+ const pending = next.filter((id) => !acc[id]);
21
+ if (pending.length === 0) return;
22
+ const loaded = await Promise.all(
23
+ pending.map(async (id) => {
24
+ try {
25
+ return [id, await read(id)] as const;
26
+ } catch {
27
+ return [id, null] as const;
28
+ }
29
+ }),
30
+ );
31
+ const nested: string[] = [];
32
+ for (const [id, part] of loaded) {
33
+ if (!part || acc[id]) continue;
34
+ acc[id] = part;
35
+ nested.push(...collectSectionPartIds(part));
36
+ }
37
+ await walk(nested, depth + 1);
38
+ };
39
+ await walk(ids, 0);
40
+ return acc;
41
+ }
42
+
8
43
  /** Section theme parts referenced by the open layout, so the canvas shows the synced contents. */
9
44
  export function useSectionTemplates(
10
45
  layout: Layout | null,
@@ -20,27 +55,14 @@ export function useSectionTemplates(
20
55
  return;
21
56
  }
22
57
  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
- });
58
+ void loadSectionTemplates(fetcher, ids).then(
59
+ (acc) => {
60
+ if (!cancelled) setTemplates(acc);
61
+ },
62
+ () => {
63
+ if (!cancelled) setTemplates({});
64
+ },
65
+ );
44
66
  return () => {
45
67
  cancelled = true;
46
68
  };
@@ -1,5 +1,6 @@
1
- /** The editor's keyboard shortcuts, shown in the Shortcuts dialog. */
1
+ /** The editor's keyboard shortcuts (DESIGN_BRIEF), shown in the Shortcuts dialog. */
2
2
  export const SHORTCUTS: readonly { action: string; keys: string }[] = [
3
+ { action: "Command palette: insert, jump, apply a class, run an action", keys: "Ctrl/Cmd+K" },
3
4
  { action: "Move focus between regions", keys: "Tab / Shift+Tab" },
4
5
  { action: "Next or previous element", keys: "↑ / ↓" },
5
6
  { action: "Select first child / parent", keys: "Enter / Shift+Enter" },
@@ -18,3 +19,7 @@ export const SHORTCUTS: readonly { action: string; keys: string }[] = [
18
19
  /** Ctrl/Cmd+K opens the host command palette, which would stack over the editor (S0-6). */
19
20
  export const isPaletteShortcut = (event: KeyboardEvent) =>
20
21
  (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "k";
22
+
23
+ /** Focus is inside an open dialog, where only Save fires. */
24
+ export const inDialog = (target: EventTarget | null) =>
25
+ !!(target as HTMLElement | null)?.closest?.('[role="dialog"], [role="alertdialog"]');
@@ -29,6 +29,8 @@ export type EditorState = {
29
29
  publishedRevision?: string | null;
30
30
  /** True after a style edit that has not been published. */
31
31
  designUnpublished?: boolean;
32
+ /** Published design, so Publish styles can list what will change (W-340). */
33
+ publishedDesign?: DesignSystem;
32
34
  selectedId: string | null;
33
35
  /** Bumped on every page edit. A save only clears `dirty` if nothing changed while it ran. */
34
36
  version: number;
@@ -65,6 +67,7 @@ export type EditorAction =
65
67
  revision: string | null;
66
68
  publishedRevision: string | null;
67
69
  unpublished: boolean;
70
+ published?: DesignSystem;
68
71
  }
69
72
  | { type: "reset"; state: EditorState };
70
73
 
@@ -225,7 +228,12 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
225
228
  designUnpublished: true,
226
229
  };
227
230
  case "publish-design":
228
- return { ...state, designUnpublished: false, publishedRevision: action.revision };
231
+ return {
232
+ ...state,
233
+ designUnpublished: false,
234
+ publishedRevision: action.revision,
235
+ publishedDesign: state.design,
236
+ };
229
237
  case "load-design":
230
238
  return {
231
239
  ...state,
@@ -233,6 +241,7 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
233
241
  designRevision: action.revision,
234
242
  publishedRevision: action.publishedRevision,
235
243
  designUnpublished: action.unpublished,
244
+ ...(action.published ? { publishedDesign: action.published } : {}),
236
245
  };
237
246
  case "reset":
238
247
  return action.state;
@@ -19,7 +19,7 @@ import {
19
19
  type PasteMode,
20
20
  } from "../../core/index.ts";
21
21
  import { readClipboardText, useClipboardText, writeClipboardText } from "./clipboard-store.ts";
22
- import { ELEMENT_NAMES } from "./panels/ElementPanel.tsx";
22
+ import { ELEMENT_NAMES } from "./element-chrome.ts";
23
23
  import type { EditorAction, EditorState } from "./store.ts";
24
24
 
25
25
  const NOTICE_TIMEOUT_MS = 4000;
@@ -1,6 +1,11 @@
1
1
  import * as React from "react";
2
2
  import type { createKumoToastManager } from "@cloudflare/kumo";
3
- import { DEVICE_PREVIEW_PX, type DesignSystem, type PopupDevice } from "../../core/index.ts";
3
+ import {
4
+ DEVICE_PREVIEW_PX,
5
+ mergeDesign,
6
+ type DesignSystem,
7
+ type PopupDevice,
8
+ } from "../../core/index.ts";
4
9
  import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../../constants.ts";
5
10
  import { ApiError, type Fetcher } from "../api.ts";
6
11
  import { previewUrl, publishDesign, saveDesign } from "../content-api.ts";
@@ -138,27 +143,68 @@ export function useEditorCommands({
138
143
  previewWindowFeatures(device),
139
144
  );
140
145
 
141
- const changeDesign = async (next: DesignSystem) => {
146
+ // W-325: design saves run one at a time, each against the newest revision, like page saves.
147
+ // Two quick edits used to both send the revision the editor started with, so the second one
148
+ // was refused with a 409 by the first. `written` remembers the revision a save produced until
149
+ // the store catches up (the ref updates on the next render).
150
+ const designQueue = React.useRef<Promise<unknown>>(Promise.resolve());
151
+ const written = React.useRef<{ from: string | null; to: string } | null>(null);
152
+ const baseRevision = () => {
153
+ const current = latest.current.designRevision;
154
+ const last = written.current;
155
+ return last && last.from === current ? last.to : current;
156
+ };
157
+ const queueDesign = <T>(task: () => Promise<T>): Promise<T> => {
158
+ const run = designQueue.current.then(task, task);
159
+ designQueue.current = run.catch(() => undefined);
160
+ return run;
161
+ };
162
+
163
+ const changeDesign = (next: DesignSystem) => queueDesign(() => saveDesignNow(next));
164
+
165
+ const saveDesignNow = async (next: DesignSystem) => {
142
166
  try {
143
- const revision = await saveDesign(fetcher, next, latest.current.designRevision);
167
+ const from = latest.current.designRevision;
168
+ const revision = await saveDesign(fetcher, next, baseRevision());
169
+ written.current = { from, to: revision };
144
170
  dispatch({ type: "set-design", design: next, revision });
145
171
  } catch (error) {
172
+ written.current = null;
146
173
  if (error instanceof ApiError && error.status === 409) {
147
- // W-212: take the styles saved elsewhere (another editor tab, say), so the next change
148
- // can save, instead of every change failing until a reload that drops page edits.
174
+ // W-333: replay this tab's edit onto the styles saved elsewhere when those keys
175
+ // were not also changed there. A real clash still loads the server copy (W-212).
149
176
  try {
150
177
  const fresh = await loadDesign(fetcher);
151
- dispatch({ type: "load-design", ...fresh });
152
- } catch {
178
+ const merged = mergeDesign(latest.current.design, next, fresh.design);
179
+ const names = merged.conflicts.map((conflict) => conflict.name).join(", ");
180
+ if (merged.conflicts.length > 0) {
181
+ dispatch({ type: "load-design", ...fresh });
182
+ throw new Error(
183
+ `Site styles were changed in another tab or window (${names}). The latest styles are loaded now: make your change again.`,
184
+ { cause: error },
185
+ );
186
+ }
187
+ const unchanged = JSON.stringify(merged.design) === JSON.stringify(fresh.design);
188
+ if (unchanged) {
189
+ dispatch({ type: "load-design", ...fresh });
190
+ return;
191
+ }
192
+ const revision = await saveDesign(fetcher, merged.design, fresh.revision);
193
+ written.current = { from: latest.current.designRevision, to: revision };
194
+ dispatch({ type: "set-design", design: merged.design, revision });
195
+ return;
196
+ } catch (retry) {
197
+ if (
198
+ retry instanceof Error &&
199
+ retry.message.includes("The latest styles are loaded now")
200
+ ) {
201
+ throw retry;
202
+ }
153
203
  throw new Error(
154
204
  "Site styles were changed somewhere else. Reload the editor and try again.",
155
- { cause: error },
205
+ { cause: retry },
156
206
  );
157
207
  }
158
- throw new Error(
159
- "Site styles were changed in another tab or window. The latest styles are loaded now: make your change again.",
160
- { cause: error },
161
- );
162
208
  }
163
209
  throw new Error(
164
210
  error instanceof ApiError
@@ -169,7 +215,9 @@ export function useEditorCommands({
169
215
  }
170
216
  };
171
217
 
172
- const publishStyles = async () => {
218
+ const publishStyles = () => queueDesign(publishStylesNow);
219
+
220
+ const publishStylesNow = async () => {
173
221
  try {
174
222
  const revision = await publishDesign(fetcher, latest.current.publishedRevision ?? null);
175
223
  dispatch({ type: "publish-design", revision });