@perkyzz/emvb 0.2.0 → 0.3.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 (80) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -2
  3. package/src/admin/editor/A11yCopilot.tsx +126 -0
  4. package/src/admin/editor/CommandPalette.tsx +118 -0
  5. package/src/admin/editor/Editor.tsx +274 -12
  6. package/src/admin/editor/EditorOverlay.tsx +6 -0
  7. package/src/admin/editor/PerfMeter.tsx +121 -0
  8. package/src/admin/editor/ShareLink.tsx +164 -0
  9. package/src/admin/editor/Timeline.tsx +274 -0
  10. package/src/admin/editor/TopBar.tsx +4 -0
  11. package/src/admin/editor/canvas/CanvasFrame.tsx +12 -3
  12. package/src/admin/editor/canvas/SelectionOverlay.tsx +1 -1
  13. package/src/admin/editor/collection-previews.ts +91 -0
  14. package/src/admin/editor/editor-css.ts +5 -3
  15. package/src/admin/editor/feature-css.ts +105 -0
  16. package/src/admin/editor/host.ts +2 -0
  17. package/src/admin/editor/live-data.tsx +71 -0
  18. package/src/admin/editor/palette-items.ts +105 -0
  19. package/src/admin/editor/palette.ts +67 -0
  20. package/src/admin/editor/panels/AddPanel.tsx +47 -2
  21. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  22. package/src/admin/editor/panels/ElementPanel.tsx +34 -3
  23. package/src/admin/editor/panels/LayersPanel.tsx +38 -1
  24. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  25. package/src/admin/editor/panels/SettingsPanel.tsx +12 -0
  26. package/src/admin/editor/panels/SiteStylesDrawer.tsx +2 -0
  27. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  28. package/src/admin/editor/panels/VariableSection.tsx +9 -4
  29. package/src/admin/editor/panels/settings/AudienceEditor.tsx +215 -0
  30. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  31. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  32. package/src/admin/editor/panels/settings/EffectsControls.tsx +4 -2
  33. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  34. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  35. package/src/admin/editor/panels/settings/StyleRow.tsx +12 -0
  36. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  37. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  38. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  39. package/src/admin/editor/panels/settings/length-units.ts +1 -1
  40. package/src/admin/editor/panels/settings/style-sections.ts +2 -1
  41. package/src/admin/editor/shortcuts.ts +2 -1
  42. package/src/admin/editor/useEditorShortcuts.ts +8 -0
  43. package/src/admin/editor/useNodeActions.ts +38 -15
  44. package/src/admin/ui.ts +4 -4
  45. package/src/astro/request-data.ts +97 -0
  46. package/src/astro/resolve-theme.ts +39 -9
  47. package/src/astro/resolve.ts +8 -2
  48. package/src/astro/theme-context.ts +14 -2
  49. package/src/astro/theme-posts.ts +51 -1
  50. package/src/astro/visitor.ts +142 -0
  51. package/src/constants.ts +1 -1
  52. package/src/core/a11y/audit.ts +282 -0
  53. package/src/core/arrange.ts +91 -0
  54. package/src/core/audience/rules.ts +104 -0
  55. package/src/core/audience/variants.ts +51 -0
  56. package/src/core/css/generate.ts +20 -2
  57. package/src/core/css/trace.ts +169 -0
  58. package/src/core/data/bindings.ts +257 -0
  59. package/src/core/design/tokens.ts +127 -0
  60. package/src/core/elements/dynamic-elements.ts +87 -2
  61. package/src/core/elements/index.ts +2 -0
  62. package/src/core/history/diff.ts +152 -0
  63. package/src/core/index.ts +111 -0
  64. package/src/core/migrate/index.ts +4 -1
  65. package/src/core/nesting.ts +1 -0
  66. package/src/core/perf/meter.ts +160 -0
  67. package/src/core/perf/scripts.ts +58 -0
  68. package/src/core/recipes/index.ts +433 -0
  69. package/src/core/render/index.ts +51 -4
  70. package/src/core/render/loop.ts +54 -7
  71. package/src/core/render/pagination.ts +9 -1
  72. package/src/core/sanitize/css.ts +39 -3
  73. package/src/core/sanitize/motion.ts +129 -0
  74. package/src/core/schema/design.ts +25 -2
  75. package/src/core/schema/layout.ts +168 -18
  76. package/src/core/schema/motion.ts +14 -0
  77. package/src/core/schema/style.ts +48 -3
  78. package/src/core/share/link.ts +147 -0
  79. package/src/core/theme/dynamic.ts +49 -0
  80. package/src/core/theme/pagination.ts +56 -0
@@ -40,6 +40,8 @@ import {
40
40
  type DesignSystem,
41
41
  type ElementDescriptor,
42
42
  type Layout,
43
+ type Arranged,
44
+ inheritedStyle,
43
45
  type LayoutNode,
44
46
  patchClassDevices,
45
47
  patchClassState,
@@ -53,11 +55,16 @@ import {
53
55
  iconHasAdjustableStroke,
54
56
  iconHasOwnColors,
55
57
  resolveCascade,
58
+ SAMPLE_POST,
56
59
  STYLE_STATES,
57
60
  type StyleProps,
58
61
  type StyleStates,
59
62
  } from "../../../core/index.ts";
60
63
  import { FieldControl } from "./settings/FieldControl.tsx";
64
+ import { BindingsEditor } from "./settings/BindingsEditor.tsx";
65
+ import { VariantEditor } from "./settings/VariantEditor.tsx";
66
+ import { AudienceEditor } from "./settings/AudienceEditor.tsx";
67
+ import { StyleSources } from "./settings/StyleSources.tsx";
61
68
  import { BoxControl } from "./settings/BoxControl.tsx";
62
69
  import { boxGroupOf } from "./settings/box-sides.ts";
63
70
  import { IconShapeRow, IconSingleColorRow } from "./settings/IconControls.tsx";
@@ -164,11 +171,16 @@ const countSet = (type: string, style: StyleProps | undefined, section: StyleSec
164
171
  const sectionHasStates = (type: string, states: StyleStates | undefined, section: StyleSectionId) =>
165
172
  STYLE_STATES.some((state) => countSet(type, states?.[state], section) > 0);
166
173
 
167
- /** Sections where a state change moves things around. */
174
+ /** Sections where a state change moves things around (DESIGN.md § State styles). */
168
175
  const JUMPY = new Set<StyleSectionId>(["layout", "size", "position"]);
169
176
 
170
177
  /** Set on Normal only (W-089, W-101, W-237); a state's Style tab leaves them out. */
171
- const NORMAL_ONLY_KEYS = new Set<StyleKey>(["transition", "entrance", "iconAnimation"]);
178
+ const NORMAL_ONLY_KEYS = new Set<StyleKey>([
179
+ "transition",
180
+ "entrance",
181
+ "iconAnimation",
182
+ "scrollMotion",
183
+ ]);
172
184
 
173
185
  const JUMP_HELP: Record<Exclude<StyleStateChoice, "normal">, string> = {
174
186
  hover: "Changing size or position on hover can make the page jump.",
@@ -244,6 +256,8 @@ type Props = {
244
256
  items?: ItemActions;
245
257
  /** The theme part being edited, if any, for the H1 warning (W-208). */
246
258
  partType?: ThemePartType;
259
+ /** Layout-wide changes from the panel, e.g. creating an A/B variant (W-312). */
260
+ onArrange?: (run: (layout: Layout) => Arranged) => void;
247
261
  };
248
262
 
249
263
  /** What an item's content is, since it has no content field of its own (W-130). */
@@ -364,6 +378,7 @@ function KnownElementPanel({
364
378
  items,
365
379
  partType,
366
380
  descriptor,
381
+ onArrange,
367
382
  }: Props & { descriptor: ElementDescriptor }) {
368
383
  const ui = STYLE_UI[node.type] ?? DEFAULT_UI;
369
384
  const [tab, setTab] = React.useState(descriptor.defaultTab);
@@ -384,7 +399,7 @@ function KnownElementPanel({
384
399
  : styleState === "normal"
385
400
  ? normal
386
401
  : states?.[styleState];
387
- const inherited = responsive
402
+ const ownInherited = responsive
388
403
  ? {
389
404
  ...normal,
390
405
  ...(responsive === "mobile" ? ownerDevices?.tablet : undefined),
@@ -392,6 +407,13 @@ function KnownElementPanel({
392
407
  : styleState === "normal"
393
408
  ? undefined
394
409
  : normal;
410
+ // W-318: an element's own styles sit on its classes and its tag's Site styles default, so the
411
+ // controls show what those give as the inherited value.
412
+ const fromBelow = cls ? undefined : inheritedStyle(node, design, device, styleState);
413
+ const inherited =
414
+ fromBelow && Object.keys(fromBelow).length > 0
415
+ ? { ...fromBelow, ...ownInherited }
416
+ : ownInherited;
395
417
  const position = positionInEffect(node, design, cls);
396
418
  const iconSvg =
397
419
  node.type === "icon" && typeof node.props.iconSvg === "string" ? node.props.iconSvg : undefined;
@@ -536,6 +558,14 @@ function KnownElementPanel({
536
558
  />
537
559
  ))
538
560
  )}
561
+ <BindingsEditor node={node} onChange={onChange} post={SAMPLE_POST} />
562
+ <AudienceEditor node={node} isRoot={layout?.root.id === node.id} onChange={onChange} />
563
+ <VariantEditor
564
+ node={node}
565
+ isRoot={layout?.root.id === node.id}
566
+ onChange={onChange}
567
+ onArrange={onArrange}
568
+ />
539
569
  {ITEM_NOTES[node.type] && <p className="emvb-helper">{ITEM_NOTES[node.type]}</p>}
540
570
  {svgImagesLeftOut(node) > 0 && (
541
571
  <p className="emvb-helper" data-emvb-svg-images>
@@ -604,6 +634,7 @@ function KnownElementPanel({
604
634
  These override Desktop. State styles apply on every device.
605
635
  </p>
606
636
  )}
637
+ {!cls && <StyleSources node={node} design={design} device={device} state={styleState} />}
607
638
  {designError && <Alert>{designError}</Alert>}
608
639
  {!cls && styleState === "normal" && node.type === "spacer" && (
609
640
  <FieldControl field={SPACER_HEIGHT} node={node} onChange={onChange} fetcher={fetcher} />
@@ -15,6 +15,10 @@ import {
15
15
  previousInOrder,
16
16
  type Layout,
17
17
  type LayoutNode,
18
+ nodeScript,
19
+ audienceSummary,
20
+ SCRIPT_LABELS,
21
+ type PageScript,
18
22
  } from "../../../core/index.ts";
19
23
  import { EXISTING_ELEMENT_MIME } from "../dnd/drop-target.ts";
20
24
  import { ELEMENT_NAMES } from "./ElementPanel.tsx";
@@ -67,6 +71,20 @@ const pasteHint = (clip: ClipboardActions | undefined) =>
67
71
  clip ? (clip.pasteStyleBlocked ?? clip.pasteBlocked) : null;
68
72
 
69
73
  /** The ··· menu: clipboard items, then Duplicate and the moves; the root row gets what applies to it. */
74
+ /** W-311: an element that makes the page load a script says so; everything else is zero-JS. */
75
+ function JsBadge({ script }: { script: PageScript | undefined }) {
76
+ if (!script) return null;
77
+ return (
78
+ <span
79
+ className="emvb-js-badge"
80
+ title={`Adds a script: ${SCRIPT_LABELS[script]}`}
81
+ aria-hidden="true"
82
+ >
83
+ JS
84
+ </span>
85
+ );
86
+ }
87
+
70
88
  function menuItems(
71
89
  node: LayoutNode,
72
90
  isRoot: boolean,
@@ -162,7 +180,7 @@ function focusSelectedRow(tree: Element | null): void {
162
180
 
163
181
  /** Layers list (IA / W-018): tree with collapse, keyboard navigation, auto-expand to selection. */
164
182
 
165
- /** Props whose text tells same-type elements apart in Layers (the layer-row preview, W-143). */
183
+ /** Props whose text tells same-type elements apart in Layers (DESIGN.md, layer-row preview; W-143). */
166
184
  const PREVIEW_PROP: Partial<Record<string, string>> = {
167
185
  heading: "text",
168
186
  text: "text",
@@ -476,6 +494,25 @@ const LayerRow = React.memo(function LayerRow({
476
494
  <span className="emvb-layer-name">{name}</span>
477
495
  {preview ? <span className="emvb-layer-preview">{preview}</span> : null}
478
496
  {hasStateStyles(node) && <StateDot />}
497
+ <JsBadge script={nodeScript(node)} />
498
+ {node.audience && (
499
+ <span
500
+ className="emvb-js-badge emvb-ab-badge"
501
+ title={audienceSummary(node.audience)}
502
+ aria-hidden="true"
503
+ >
504
+ ◎
505
+ </span>
506
+ )}
507
+ {node.variant && (
508
+ <span
509
+ className="emvb-js-badge emvb-ab-badge"
510
+ title={`A/B test ${node.variant.test}, variant ${node.variant.arm.toUpperCase()}`}
511
+ aria-hidden="true"
512
+ >
513
+ {node.variant.arm.toUpperCase()}
514
+ </span>
515
+ )}
479
516
  </button>
480
517
  )}
481
518
  {(!isRoot || hasClipboard) && (
@@ -13,6 +13,7 @@ export function LeftPanel({
13
13
  selectedId,
14
14
  onSelect,
15
15
  onAdd,
16
+ onRecipe,
16
17
  onDuplicate,
17
18
  onMoveUp,
18
19
  onMoveDown,
@@ -25,6 +26,8 @@ export function LeftPanel({
25
26
  selectedId: string | null;
26
27
  onSelect: (id: string) => void;
27
28
  onAdd: (type: ElementType) => void;
29
+ /** Adds a section recipe (W-320). */
30
+ onRecipe?: (id: string) => void;
28
31
  onDuplicate: (id: string) => void;
29
32
  onMoveUp: (id: string) => void;
30
33
  onMoveDown: (id: string) => void;
@@ -62,7 +65,7 @@ export function LeftPanel({
62
65
  onValueChange={changeTab}
63
66
  />
64
67
  {tab === "add" ? (
65
- <AddPanel onAdd={onAdd} formsAvailable={formsAvailable} />
68
+ <AddPanel onAdd={onAdd} onRecipe={onRecipe} formsAvailable={formsAvailable} />
66
69
  ) : (
67
70
  <LayersPanel
68
71
  layout={layout}
@@ -95,6 +95,18 @@ export function SettingsPanel({
95
95
  device={device}
96
96
  items={items}
97
97
  partType={state.page.partType}
98
+ onArrange={(run) => {
99
+ const layout = state.page.layout;
100
+ if (!layout) return;
101
+ const result = run(layout);
102
+ if (result.ok) {
103
+ dispatch({
104
+ type: "apply-arranged",
105
+ layout: result.layout,
106
+ selected: result.selected,
107
+ });
108
+ }
109
+ }}
98
110
  />
99
111
  ) : (
100
112
  <PageSettings
@@ -26,6 +26,7 @@ import { ClassesSection } from "./ClassesSection.tsx";
26
26
  import { stopEditorShortcuts } from "./settings/ClassChip.tsx";
27
27
  import { StyleRow } from "./settings/StyleRow.tsx";
28
28
  import { FIELD } from "../../ui.ts";
29
+ import { TokenScales } from "./TokenScales.tsx";
29
30
  import { VariableSection } from "./VariableSection.tsx";
30
31
 
31
32
  const STYLE_NOTE = "Style changes stay unpublished until you publish styles.";
@@ -244,6 +245,7 @@ export function SiteStylesDrawer({
244
245
  setConfirm({ kind: "variable", variableKind: "spacing", id, name })
245
246
  }
246
247
  />
248
+ <TokenScales design={design} onSave={save} />
247
249
  </div>
248
250
  )}
249
251
  {tab === "classes" && (
@@ -0,0 +1,168 @@
1
+ import * as React from "react";
2
+ import {
3
+ applyTokens,
4
+ fluidClamp,
5
+ SCALE_RATIOS,
6
+ spaceScale,
7
+ typeScale,
8
+ type DesignSystem,
9
+ } from "../../../core/index.ts";
10
+
11
+ const num = (text: string): number | undefined => {
12
+ const n = Number(text);
13
+ return text.trim() !== "" && Number.isFinite(n) ? n : undefined;
14
+ };
15
+
16
+ /**
17
+ * Design tokens (W-316): build a type scale from a base size and a ratio, or a spacing scale
18
+ * from one gap, optionally fluid between a small-screen and a large-screen base. They land in
19
+ * Font sizes and Spacing as ordinary variables; ones with the same id are updated in place.
20
+ */
21
+ export function TokenScales({
22
+ design,
23
+ onSave,
24
+ }: {
25
+ design: DesignSystem;
26
+ onSave: (design: DesignSystem) => Promise<void>;
27
+ }) {
28
+ const [kind, setKind] = React.useState<"type" | "space">("type");
29
+ const [base, setBase] = React.useState("18");
30
+ const [minBase, setMinBase] = React.useState("16");
31
+ const [fluid, setFluid] = React.useState(true);
32
+ const [ratio, setRatio] = React.useState(String(SCALE_RATIOS[2].value));
33
+ const [done, setDone] = React.useState<string | null>(null);
34
+ const input = {
35
+ base: num(base) ?? Number.NaN,
36
+ ...(fluid && num(minBase) !== undefined ? { minBase: num(minBase) } : {}),
37
+ };
38
+ const tokens =
39
+ kind === "type"
40
+ ? typeScale({
41
+ ...input,
42
+ ratio: num(ratio) ?? Number.NaN,
43
+ ...(fluid ? { minRatio: Math.max(1.05, (num(ratio) ?? 1.2) - 0.05) } : {}),
44
+ })
45
+ : spaceScale(input);
46
+ const range = design.fluidRange;
47
+ const list = kind === "type" ? "fontSizes" : "spacings";
48
+ const updating = tokens.filter((t) =>
49
+ (design.variables[list] ?? []).some((v) => v.id === t.id),
50
+ ).length;
51
+ return (
52
+ <section className="emvb-site-section emvb-tokens" data-emvb-tokens="">
53
+ <h3 className="emvb-bind-title">Scales</h3>
54
+ <p className="emvb-helper">
55
+ Generate a whole scale from two numbers. Fluid sizes grow smoothly from small to large
56
+ screens with CSS clamp(), no breakpoints.
57
+ </p>
58
+ <div className="emvb-tokens-grid">
59
+ <label>
60
+ <span className="emvb-bind-label">Scale</span>
61
+ <select
62
+ className="emvb-native-select"
63
+ value={kind}
64
+ data-emvb-tokens-kind=""
65
+ onChange={(event) => setKind(event.currentTarget.value === "space" ? "space" : "type")}
66
+ >
67
+ <option value="type">Type scale</option>
68
+ <option value="space">Spacing scale</option>
69
+ </select>
70
+ </label>
71
+ <label>
72
+ <span className="emvb-bind-label">{kind === "type" ? "Body size" : "Base gap"} (px)</span>
73
+ <input
74
+ className="emvb-native-input"
75
+ inputMode="decimal"
76
+ value={base}
77
+ data-emvb-tokens-base=""
78
+ onChange={(event) => setBase(event.currentTarget.value)}
79
+ />
80
+ </label>
81
+ {kind === "type" && (
82
+ <label>
83
+ <span className="emvb-bind-label">Ratio</span>
84
+ <select
85
+ className="emvb-native-select"
86
+ value={ratio}
87
+ data-emvb-tokens-ratio=""
88
+ onChange={(event) => setRatio(event.currentTarget.value)}
89
+ >
90
+ {SCALE_RATIOS.map((r) => (
91
+ <option key={r.value} value={String(r.value)}>
92
+ {r.label}
93
+ </option>
94
+ ))}
95
+ </select>
96
+ </label>
97
+ )}
98
+ <label className="emvb-tokens-fluid">
99
+ <input
100
+ type="checkbox"
101
+ checked={fluid}
102
+ data-emvb-tokens-fluid=""
103
+ onChange={(event) => setFluid(event.currentTarget.checked)}
104
+ />{" "}
105
+ Fluid
106
+ </label>
107
+ {fluid && (
108
+ <label>
109
+ <span className="emvb-bind-label">On small screens (px)</span>
110
+ <input
111
+ className="emvb-native-input"
112
+ inputMode="decimal"
113
+ value={minBase}
114
+ data-emvb-tokens-min=""
115
+ onChange={(event) => setMinBase(event.currentTarget.value)}
116
+ />
117
+ </label>
118
+ )}
119
+ </div>
120
+ {tokens.length === 0 ? (
121
+ <p className="emvb-helper" role="alert">
122
+ {kind === "type" ? "Use a body size from 8 to 64 px." : "Use a base gap from 2 to 64 px."}
123
+ </p>
124
+ ) : (
125
+ <ol className="emvb-tokens-preview" data-emvb-tokens-preview="">
126
+ {tokens.map((t) => (
127
+ <li key={t.id}>
128
+ <span
129
+ className="emvb-tokens-sample"
130
+ style={
131
+ kind === "type"
132
+ ? { fontSize: `${Math.min(t.value.value, 40)}px` }
133
+ : { width: `${Math.min(t.value.value, 120)}px` }
134
+ }
135
+ >
136
+ {kind === "type" ? "Aa" : ""}
137
+ </span>
138
+ <span>{t.name}</span>
139
+ <code className="emvb-mono">
140
+ {t.fluid ? fluidClamp(t.fluid.min, t.fluid.max, range) : `${t.value.value}px`}
141
+ </code>
142
+ </li>
143
+ ))}
144
+ </ol>
145
+ )}
146
+ <button
147
+ type="button"
148
+ className="emvb-link-button"
149
+ disabled={tokens.length === 0}
150
+ data-emvb-tokens-apply=""
151
+ onClick={() => {
152
+ void onSave(applyTokens(design, list, tokens)).then(() =>
153
+ setDone(
154
+ `${tokens.length - updating} added${updating ? `, ${updating} updated` : ""} in ${kind === "type" ? "Font sizes" : "Spacing"}.`,
155
+ ),
156
+ );
157
+ }}
158
+ >
159
+ {updating > 0 ? "Update the scale in site styles" : "Add the scale to site styles"}
160
+ </button>
161
+ {done && (
162
+ <p className="emvb-helper" role="status">
163
+ {done}
164
+ </p>
165
+ )}
166
+ </section>
167
+ );
168
+ }
@@ -265,9 +265,12 @@ export function VariableSection({
265
265
  ...design,
266
266
  variables: {
267
267
  ...design.variables,
268
- [listKey]: items.map((entry) =>
269
- entry.id === id ? Object.assign({}, entry, { value: next }) : entry,
270
- ),
268
+ [listKey]: items.map((entry) => {
269
+ if (entry.id !== id) return entry;
270
+ // W-316: typing a fixed size ends a token's fluid sizing.
271
+ const { fluid: _fluid, ...fixed } = entry as typeof entry & { fluid?: unknown };
272
+ return Object.assign({}, fixed, { value: next });
273
+ }),
271
274
  },
272
275
  });
273
276
 
@@ -359,7 +362,9 @@ export function VariableSection({
359
362
  const inClasses = new Set(
360
363
  findVariableUsagesInDesign(design, item.id, kind).map((u) => u.classId),
361
364
  ).size;
362
- const text = valueText(item.value);
365
+ // W-316: a fluid token reads "14 → 18 px".
366
+ const fluid = (item as { fluid?: { min: number; max: number } }).fluid;
367
+ const text = fluid ? `${fluid.min} → ${fluid.max} px fluid` : valueText(item.value);
363
368
  return (
364
369
  <li
365
370
  key={item.id}
@@ -0,0 +1,215 @@
1
+ import * as React from "react";
2
+ import { AUDIENCE_DEVICES, type Audience, type LayoutNode } from "../../../../core/index.ts";
3
+
4
+ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
5
+ const COUNTRY = /^[A-Z]{2}$/;
6
+
7
+ type Mode = "everyone" | "only" | "except";
8
+
9
+ /** "ca, us fr" → ["CA", "US", "FR"]; anything else is left out. */
10
+ export function parseCountries(text: string): string[] {
11
+ const codes = text
12
+ .toUpperCase()
13
+ .split(/[\s,;]+/)
14
+ .filter((code) => COUNTRY.test(code));
15
+ return [...new Set(codes)].slice(0, 50);
16
+ }
17
+
18
+ /** Drops empty rules so the stored audience stays valid (W-313). */
19
+ function tidy(audience: Audience): Audience | undefined {
20
+ const next: Audience = { ...audience };
21
+ if (next.countries?.length === 0) delete next.countries;
22
+ if (next.devices?.length === 0) delete next.devices;
23
+ if (next.days?.length === 0) delete next.days;
24
+ if (!next.timeZone) delete next.timeZone;
25
+ if (!next.hide) delete next.hide;
26
+ return next;
27
+ }
28
+
29
+ const ruleCount = (a: Audience) =>
30
+ [a.countries, a.devices, a.visitor, a.hours, a.days].filter((r) => r !== undefined).length;
31
+
32
+ /**
33
+ * Visitors (W-313): show or hide this element by country, device, new or returning visitor,
34
+ * and time. The server decides, so it costs no script; the canvas shows it outlined.
35
+ */
36
+ export function AudienceEditor({
37
+ node,
38
+ isRoot,
39
+ onChange,
40
+ }: {
41
+ node: LayoutNode;
42
+ isRoot: boolean;
43
+ onChange: (node: LayoutNode) => void;
44
+ }) {
45
+ const [countryText, setCountryText] = React.useState(node.audience?.countries?.join(", ") ?? "");
46
+ React.useEffect(() => {
47
+ setCountryText(node.audience?.countries?.join(", ") ?? "");
48
+ }, [node.id]);
49
+ if (isRoot) return null;
50
+ const audience = node.audience;
51
+ const mode: Mode = !audience ? "everyone" : audience.hide ? "except" : "only";
52
+ const set = (next: Audience | undefined) => {
53
+ const { audience: _old, ...rest } = node;
54
+ const clean = next ? tidy(next) : undefined;
55
+ onChange((clean ? { ...rest, audience: clean } : rest) as LayoutNode);
56
+ };
57
+ const base: Audience = audience ?? {};
58
+ const id = `emvb-aud-${node.id}`;
59
+ return (
60
+ <section className="emvb-bind" data-emvb-audience-editor="" aria-labelledby={`${id}-title`}>
61
+ <h3 className="emvb-bind-title" id={`${id}-title`}>
62
+ Visitors
63
+ </h3>
64
+ <label className="emvb-bind-row">
65
+ <span className="emvb-bind-label">Show to</span>
66
+ <select
67
+ className="emvb-native-select"
68
+ value={mode}
69
+ data-emvb-audience-mode=""
70
+ onChange={(event) => {
71
+ const value = event.currentTarget.value as Mode;
72
+ if (value === "everyone") set(undefined);
73
+ else set({ ...base, hide: value === "except" });
74
+ }}
75
+ >
76
+ <option value="everyone">Everyone</option>
77
+ <option value="only">Only visitors who match</option>
78
+ <option value="except">Everyone except visitors who match</option>
79
+ </select>
80
+ </label>
81
+ {audience && (
82
+ <>
83
+ <label className="emvb-bind-row">
84
+ <span className="emvb-bind-label">Countries (two-letter codes)</span>
85
+ <input
86
+ className="emvb-native-input"
87
+ value={countryText}
88
+ placeholder="CA, US"
89
+ data-emvb-audience-countries=""
90
+ onChange={(event) => setCountryText(event.currentTarget.value)}
91
+ onBlur={() => {
92
+ const countries = parseCountries(countryText);
93
+ setCountryText(countries.join(", "));
94
+ set({ ...base, countries });
95
+ }}
96
+ />
97
+ </label>
98
+ <fieldset className="emvb-aud-checks">
99
+ <legend className="emvb-bind-label">Devices</legend>
100
+ {AUDIENCE_DEVICES.map((device) => (
101
+ <label key={device}>
102
+ <input
103
+ type="checkbox"
104
+ checked={base.devices?.includes(device) ?? false}
105
+ data-emvb-audience-device={device}
106
+ onChange={(event) => {
107
+ const now = new Set(base.devices ?? []);
108
+ if (event.currentTarget.checked) now.add(device);
109
+ else now.delete(device);
110
+ set({ ...base, devices: AUDIENCE_DEVICES.filter((d) => now.has(d)) });
111
+ }}
112
+ />{" "}
113
+ {device[0]?.toUpperCase()}
114
+ {device.slice(1)}
115
+ </label>
116
+ ))}
117
+ </fieldset>
118
+ <label className="emvb-bind-row">
119
+ <span className="emvb-bind-label">Visit</span>
120
+ <select
121
+ className="emvb-native-select"
122
+ value={base.visitor ?? "any"}
123
+ data-emvb-audience-visitor=""
124
+ onChange={(event) => {
125
+ const value = event.currentTarget.value;
126
+ const { visitor: _v, ...rest } = base;
127
+ set(value === "new" || value === "returning" ? { ...rest, visitor: value } : rest);
128
+ }}
129
+ >
130
+ <option value="any">New or returning</option>
131
+ <option value="new">First visit</option>
132
+ <option value="returning">Returning visitor</option>
133
+ </select>
134
+ </label>
135
+ <div className="emvb-bind-row">
136
+ <span className="emvb-bind-label">Hours (24 h, empty = all day)</span>
137
+ <input
138
+ className="emvb-native-input"
139
+ type="number"
140
+ min={0}
141
+ max={23}
142
+ aria-label="From hour"
143
+ data-emvb-audience-from=""
144
+ value={base.hours?.from ?? ""}
145
+ onChange={(event) => {
146
+ const raw = event.currentTarget.value;
147
+ const { hours: _h, ...rest } = base;
148
+ if (raw === "") return set(rest);
149
+ const from = Math.min(23, Math.max(0, Math.round(Number(raw))));
150
+ set({ ...rest, hours: { from, to: base.hours?.to ?? 24 } });
151
+ }}
152
+ />
153
+ <input
154
+ className="emvb-native-input"
155
+ type="number"
156
+ min={0}
157
+ max={24}
158
+ aria-label="To hour"
159
+ data-emvb-audience-to=""
160
+ value={base.hours?.to ?? ""}
161
+ onChange={(event) => {
162
+ const raw = event.currentTarget.value;
163
+ const { hours: _h, ...rest } = base;
164
+ if (raw === "") return set(rest);
165
+ const to = Math.min(24, Math.max(0, Math.round(Number(raw))));
166
+ set({ ...rest, hours: { from: base.hours?.from ?? 0, to } });
167
+ }}
168
+ />
169
+ </div>
170
+ <fieldset className="emvb-aud-checks">
171
+ <legend className="emvb-bind-label">Days (none = every day)</legend>
172
+ {DAYS.map((day, index) => (
173
+ <label key={day}>
174
+ <input
175
+ type="checkbox"
176
+ checked={base.days?.includes(index) ?? false}
177
+ data-emvb-audience-day={index}
178
+ onChange={(event) => {
179
+ const now = new Set(base.days ?? []);
180
+ if (event.currentTarget.checked) now.add(index);
181
+ else now.delete(index);
182
+ set({ ...base, days: DAYS.map((_d, i) => i).filter((i) => now.has(i)) });
183
+ }}
184
+ />{" "}
185
+ {day}
186
+ </label>
187
+ ))}
188
+ </fieldset>
189
+ {(base.hours || base.days) && (
190
+ <label className="emvb-bind-row">
191
+ <span className="emvb-bind-label">Time zone</span>
192
+ <input
193
+ className="emvb-native-input"
194
+ value={base.timeZone ?? ""}
195
+ placeholder="UTC"
196
+ data-emvb-audience-zone=""
197
+ onChange={(event) => {
198
+ const value = event.currentTarget.value.trim();
199
+ if (value && !/^[A-Za-z][A-Za-z0-9_+-]*(\/[A-Za-z0-9_+-]+){0,2}$/.test(value))
200
+ return;
201
+ set({ ...base, timeZone: value });
202
+ }}
203
+ />
204
+ </label>
205
+ )}
206
+ <p className="emvb-helper" data-emvb-audience-help="">
207
+ {ruleCount(base) === 0
208
+ ? "Add a rule: with none, every visitor matches."
209
+ : "The server checks these on each visit, with no script. A rule it can't check (no country from the host) doesn't match. The canvas shows this element to you either way."}
210
+ </p>
211
+ </>
212
+ )}
213
+ </section>
214
+ );
215
+ }