@perkyzz/emvb 0.2.1 → 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.
- package/package.json +1 -1
- package/src/admin/editor/A11yCopilot.tsx +126 -0
- package/src/admin/editor/CommandPalette.tsx +118 -0
- package/src/admin/editor/Editor.tsx +274 -12
- package/src/admin/editor/EditorOverlay.tsx +6 -0
- package/src/admin/editor/PerfMeter.tsx +121 -0
- package/src/admin/editor/ShareLink.tsx +164 -0
- package/src/admin/editor/Timeline.tsx +274 -0
- package/src/admin/editor/TopBar.tsx +4 -0
- package/src/admin/editor/canvas/CanvasFrame.tsx +12 -3
- package/src/admin/editor/canvas/SelectionOverlay.tsx +1 -1
- package/src/admin/editor/collection-previews.ts +91 -0
- package/src/admin/editor/editor-css.ts +5 -3
- package/src/admin/editor/feature-css.ts +105 -0
- package/src/admin/editor/host.ts +2 -0
- package/src/admin/editor/live-data.tsx +71 -0
- package/src/admin/editor/palette-items.ts +105 -0
- package/src/admin/editor/palette.ts +67 -0
- package/src/admin/editor/panels/AddPanel.tsx +47 -2
- package/src/admin/editor/panels/ClassesSection.tsx +5 -1
- package/src/admin/editor/panels/ElementPanel.tsx +34 -3
- package/src/admin/editor/panels/LayersPanel.tsx +38 -1
- package/src/admin/editor/panels/LeftPanel.tsx +4 -1
- package/src/admin/editor/panels/SettingsPanel.tsx +12 -0
- package/src/admin/editor/panels/SiteStylesDrawer.tsx +2 -0
- package/src/admin/editor/panels/TokenScales.tsx +168 -0
- package/src/admin/editor/panels/VariableSection.tsx +9 -4
- package/src/admin/editor/panels/settings/AudienceEditor.tsx +215 -0
- package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
- package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
- package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
- package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
- package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
- package/src/admin/editor/panels/settings/StyleRow.tsx +12 -0
- package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
- package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
- package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
- package/src/admin/editor/panels/settings/length-units.ts +1 -1
- package/src/admin/editor/panels/settings/style-sections.ts +2 -1
- package/src/admin/editor/shortcuts.ts +2 -1
- package/src/admin/editor/useEditorShortcuts.ts +8 -0
- package/src/admin/editor/useNodeActions.ts +38 -15
- package/src/admin/ui.ts +4 -4
- package/src/astro/request-data.ts +97 -0
- package/src/astro/resolve-theme.ts +35 -5
- package/src/astro/resolve.ts +8 -2
- package/src/astro/theme-posts.ts +32 -0
- package/src/astro/visitor.ts +142 -0
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +282 -0
- package/src/core/arrange.ts +91 -0
- package/src/core/audience/rules.ts +104 -0
- package/src/core/audience/variants.ts +51 -0
- package/src/core/css/generate.ts +20 -2
- package/src/core/css/trace.ts +169 -0
- package/src/core/data/bindings.ts +257 -0
- package/src/core/design/tokens.ts +127 -0
- package/src/core/elements/dynamic-elements.ts +87 -2
- package/src/core/elements/index.ts +2 -0
- package/src/core/history/diff.ts +152 -0
- package/src/core/index.ts +111 -0
- package/src/core/migrate/index.ts +4 -1
- package/src/core/nesting.ts +1 -0
- package/src/core/perf/meter.ts +160 -0
- package/src/core/perf/scripts.ts +58 -0
- package/src/core/recipes/index.ts +433 -0
- package/src/core/render/index.ts +51 -4
- package/src/core/render/loop.ts +54 -7
- package/src/core/render/pagination.ts +9 -1
- package/src/core/sanitize/css.ts +39 -3
- package/src/core/sanitize/motion.ts +129 -0
- package/src/core/schema/design.ts +25 -2
- package/src/core/schema/layout.ts +168 -18
- package/src/core/schema/motion.ts +14 -0
- package/src/core/schema/style.ts +48 -3
- package/src/core/share/link.ts +147 -0
- package/src/core/theme/dynamic.ts +49 -0
- package/src/core/theme/pagination.ts +56 -0
|
@@ -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
|
+
}
|
|
@@ -8,7 +8,7 @@ export type LengthLiteral = { value: number; unit: LengthUnit };
|
|
|
8
8
|
const BOX: readonly UnitChoice[] = ["px", "%", "rem", "em", "vw", "vh"];
|
|
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,
|
|
@@ -207,7 +207,7 @@ const SECTION_KEYS: Record<StyleSectionId, StyleKey[]> = {
|
|
|
207
207
|
"borderBottomRightRadius",
|
|
208
208
|
"borderBottomLeftRadius",
|
|
209
209
|
],
|
|
210
|
-
effects: ["opacity", "boxShadow", "filter", "cursor", "entrance", "transition"],
|
|
210
|
+
effects: ["opacity", "boxShadow", "filter", "cursor", "entrance", "scrollMotion", "transition"],
|
|
211
211
|
icon: ["iconRotate", "iconFlip", "iconScale", "iconStrokeWidth", "iconShadow", "iconAnimation"],
|
|
212
212
|
advanced: [],
|
|
213
213
|
};
|
|
@@ -381,6 +381,7 @@ export const STYLE_LABELS: Record<StyleKey, string> = {
|
|
|
381
381
|
filter: "Filters",
|
|
382
382
|
cursor: "Cursor",
|
|
383
383
|
entrance: "Entrance",
|
|
384
|
+
scrollMotion: "Scroll motion",
|
|
384
385
|
iconRotate: "Rotate",
|
|
385
386
|
iconFlip: "Flip",
|
|
386
387
|
iconScale: "Scale",
|
|
@@ -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" },
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
previousInOrder,
|
|
13
13
|
} from "../../core/index.ts";
|
|
14
14
|
import type { EditorState, HistoryAction } from "./store.ts";
|
|
15
|
+
import { isPaletteShortcut } from "./shortcuts.ts";
|
|
15
16
|
|
|
16
17
|
const isTextField = (target: EventTarget | null) => {
|
|
17
18
|
const element = target as HTMLElement | null;
|
|
@@ -92,6 +93,8 @@ export type ShortcutHandlers = {
|
|
|
92
93
|
copy: (id: string) => void;
|
|
93
94
|
paste: (id: string | null) => void;
|
|
94
95
|
pasteStyle: (id: string | null) => void;
|
|
96
|
+
/** Ctrl/Cmd+K from the canvas frame, whose keys don't reach the window (W-314). */
|
|
97
|
+
palette?: () => void;
|
|
95
98
|
};
|
|
96
99
|
|
|
97
100
|
/**
|
|
@@ -110,6 +113,11 @@ export function useEditorShortcuts({
|
|
|
110
113
|
handlers: React.RefObject<ShortcutHandlers>;
|
|
111
114
|
}): (event: KeyboardEvent) => void {
|
|
112
115
|
const onKeyDown = React.useCallback((event: KeyboardEvent) => {
|
|
116
|
+
if (isPaletteShortcut(event)) {
|
|
117
|
+
event.preventDefault();
|
|
118
|
+
handlers.current.palette?.();
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
113
121
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
|
114
122
|
event.preventDefault();
|
|
115
123
|
void handlers.current.save();
|
|
@@ -3,15 +3,19 @@ import type { createKumoToastManager } from "@cloudflare/kumo";
|
|
|
3
3
|
import {
|
|
4
4
|
addNode,
|
|
5
5
|
addNodeNear,
|
|
6
|
+
addSectionNear,
|
|
6
7
|
duplicateNode,
|
|
7
8
|
ELEMENT_DESCRIPTORS,
|
|
8
9
|
findNode,
|
|
9
10
|
moveDown,
|
|
10
11
|
moveUp,
|
|
12
|
+
recipeNode,
|
|
13
|
+
withFreshIds,
|
|
11
14
|
subtreeSize,
|
|
12
15
|
type Arranged,
|
|
13
16
|
type ElementType,
|
|
14
17
|
type Layout,
|
|
18
|
+
type LayoutNode,
|
|
15
19
|
} from "../../core/index.ts";
|
|
16
20
|
import { newElement } from "./dnd/new-element.ts";
|
|
17
21
|
import { ELEMENT_NAMES } from "./panels/ElementPanel.tsx";
|
|
@@ -139,27 +143,25 @@ export function useNodeActions({
|
|
|
139
143
|
},
|
|
140
144
|
};
|
|
141
145
|
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const result = addNodeNear(layout, node, latest.current.selectedId);
|
|
146
|
+
const notice = (message: string) => {
|
|
147
|
+
announce(message);
|
|
148
|
+
if (lastToast.current) toasts.close(lastToast.current);
|
|
149
|
+
lastToast.current = toasts.add({ title: message, timeout: NOTICE_TIMEOUT_MS });
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/** Puts a new element (or a recipe's section) where the selection says (W-175). */
|
|
153
|
+
const place = (layout: Layout, node: LayoutNode, label: string, section = false) => {
|
|
154
|
+
const result = (section ? addSectionNear : addNodeNear)(
|
|
155
|
+
layout,
|
|
156
|
+
node,
|
|
157
|
+
latest.current.selectedId,
|
|
158
|
+
);
|
|
156
159
|
if (!result.ok) {
|
|
157
160
|
notice(result.reason);
|
|
158
161
|
return;
|
|
159
162
|
}
|
|
160
163
|
dispatch({ type: "apply-arranged", layout: result.layout, selected: result.selected });
|
|
161
164
|
const nameOf = (id: string) => ELEMENT_NAMES[findNode(layout, id)?.type ?? "container"];
|
|
162
|
-
const label = ELEMENT_DESCRIPTORS.find((d) => d.type === type)?.name ?? type;
|
|
163
165
|
if (result.fallback) {
|
|
164
166
|
// Added next to the nearest ancestor that takes it, rather than refused (W-175).
|
|
165
167
|
const after = nameOf(result.fallback.after) ?? "the selection";
|
|
@@ -169,6 +171,26 @@ export function useNodeActions({
|
|
|
169
171
|
announce(`${label} added inside ${nameOf(result.parentId) ?? "Container"}`);
|
|
170
172
|
};
|
|
171
173
|
|
|
174
|
+
const addFromPanel = (type: ElementType) => {
|
|
175
|
+
const layout = latest.current.page.layout;
|
|
176
|
+
if (!layout) {
|
|
177
|
+
if (type === "container") dispatch({ type: "add-root-container" });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const node = newElement(type);
|
|
181
|
+
if (!node) return;
|
|
182
|
+
place(layout, node, ELEMENT_DESCRIPTORS.find((d) => d.type === type)?.name ?? type);
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/** A section recipe built from the site's styles (W-320). */
|
|
186
|
+
const addRecipe = (id: string) => {
|
|
187
|
+
const layout = latest.current.page.layout;
|
|
188
|
+
if (!layout) return;
|
|
189
|
+
const node = recipeNode(id, latest.current.design, layout);
|
|
190
|
+
if (!node) return;
|
|
191
|
+
place(layout, withFreshIds(layout, node), `${node.label ?? "Section"} section`, true);
|
|
192
|
+
};
|
|
193
|
+
|
|
172
194
|
return {
|
|
173
195
|
deleteAsk,
|
|
174
196
|
setDeleteAsk,
|
|
@@ -179,6 +201,7 @@ export function useNodeActions({
|
|
|
179
201
|
arrange,
|
|
180
202
|
duplicate,
|
|
181
203
|
addFromPanel,
|
|
204
|
+
addRecipe,
|
|
182
205
|
items,
|
|
183
206
|
};
|
|
184
207
|
}
|
package/src/admin/ui.ts
CHANGED
|
@@ -9,19 +9,19 @@ const solid = (color: string) =>
|
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Kumo paints emphasis buttons with a light gradient that leaves white text below AA. EmVB
|
|
12
|
-
* flattens it to the solid fill (contrast override). Kumo lets `style` win.
|
|
12
|
+
* flattens it to the solid fill (DESIGN.md, contrast override). Kumo lets `style` win.
|
|
13
13
|
*/
|
|
14
14
|
export const SOLID_PRIMARY = solid("var(--color-kumo-brand)");
|
|
15
15
|
export const SOLID_DESTRUCTIVE = solid("var(--text-color-kumo-danger)");
|
|
16
16
|
|
|
17
|
-
/** EmVB's compact control size: 28 px and a 6 px radius. Doubled to beat utilities. */
|
|
17
|
+
/** EmVB's compact control size: 28 px and a 6 px radius (DESIGN.md). Doubled to beat utilities. */
|
|
18
18
|
export const BUTTON = "emvb-btn";
|
|
19
19
|
export const FIELD = "emvb-field";
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* Shared EmVB admin chrome (list pages, dialogs, setup states, conditions) plus compact
|
|
23
|
-
* control sizing used inside the editor. Glass / elevation tokens match the
|
|
24
|
-
* editor's denser elevated look.
|
|
23
|
+
* control sizing used inside the editor. Glass / elevation tokens match DESIGN.md and the
|
|
24
|
+
* editor's mockup1 denser elevated look.
|
|
25
25
|
*/
|
|
26
26
|
export const UI_CSS = `
|
|
27
27
|
[data-emvb-page],
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { getEmDashCollection, getSiteSettings } from "emdash";
|
|
2
|
+
import {
|
|
3
|
+
collectCollectionLoops,
|
|
4
|
+
layoutUsesSource,
|
|
5
|
+
paramsFromSearch,
|
|
6
|
+
siteBindingValues,
|
|
7
|
+
type CollectionLoop,
|
|
8
|
+
type Layout,
|
|
9
|
+
type ThemePostFields,
|
|
10
|
+
type VisitorInfo,
|
|
11
|
+
} from "../core/index.ts";
|
|
12
|
+
import { themePostFromEntry } from "./theme-posts.ts";
|
|
13
|
+
import { abArmsFor, visitorFor, type VisitorAstro } from "./visitor.ts";
|
|
14
|
+
|
|
15
|
+
type RequestData = {
|
|
16
|
+
site?: Record<string, string>;
|
|
17
|
+
params?: Record<string, string>;
|
|
18
|
+
origin?: string;
|
|
19
|
+
collections?: Record<string, ThemePostFields[]>;
|
|
20
|
+
abArms?: Record<string, "a" | "b">;
|
|
21
|
+
visitor?: VisitorInfo;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// D1/SQLite columns are snake_case, so orderBy names the columns as stored.
|
|
25
|
+
const ORDER_BY: Record<CollectionLoop["order"], Record<string, "asc" | "desc">> = {
|
|
26
|
+
newest: { published_at: "desc" },
|
|
27
|
+
oldest: { published_at: "asc" },
|
|
28
|
+
title: { title: "asc" },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Published entries for one collection Loop (W-308); a failing query lists nothing. */
|
|
32
|
+
async function loopEntries(loop: CollectionLoop): Promise<ThemePostFields[]> {
|
|
33
|
+
try {
|
|
34
|
+
const result = await getEmDashCollection(loop.collection, {
|
|
35
|
+
status: "published",
|
|
36
|
+
limit: loop.limit,
|
|
37
|
+
orderBy: ORDER_BY[loop.order],
|
|
38
|
+
} as never);
|
|
39
|
+
return (result.entries ?? [])
|
|
40
|
+
.map((entry) =>
|
|
41
|
+
themePostFromEntry(entry as never, { permalinkPrefix: `/${loop.collection}` }),
|
|
42
|
+
)
|
|
43
|
+
.filter((post): post is ThemePostFields => post !== null);
|
|
44
|
+
} catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The layout plus the synced sections and Loop items it pulls in. Their elements render with the
|
|
51
|
+
* same request data, so A/B tests, visitor rules, bindings and Loops inside them count too.
|
|
52
|
+
*/
|
|
53
|
+
function withTemplates(layout: Layout, templates: readonly Layout[]): Layout {
|
|
54
|
+
if (templates.length === 0) return layout;
|
|
55
|
+
const children = [...layout.root.children, ...templates.flatMap((t) => t.root.children)];
|
|
56
|
+
return { ...layout, root: { ...layout.root, children } };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Live values a layout needs on this request: site settings and URL parameters for bindings
|
|
61
|
+
* (W-307), entries for collection Loops (W-308), A/B arms (W-312) and the visitor (W-313).
|
|
62
|
+
* `templates` are the synced sections and Loop items the layout renders.
|
|
63
|
+
*/
|
|
64
|
+
export async function bindingDataFor(
|
|
65
|
+
page: Layout | null,
|
|
66
|
+
url: URL,
|
|
67
|
+
astro?: VisitorAstro,
|
|
68
|
+
templates: readonly Layout[] = [],
|
|
69
|
+
): Promise<RequestData> {
|
|
70
|
+
if (!page) return {};
|
|
71
|
+
const layout = withTemplates(page, templates);
|
|
72
|
+
const data: RequestData = {};
|
|
73
|
+
// W-312: the visitor's arm of each A/B test, picked here on the server.
|
|
74
|
+
const abArms = astro ? abArmsFor(layout, astro) : undefined;
|
|
75
|
+
if (abArms) data.abArms = abArms;
|
|
76
|
+
// W-313: what the server knows about the visitor, for visitor-aware elements.
|
|
77
|
+
const visitor = astro ? visitorFor(layout, astro) : undefined;
|
|
78
|
+
if (visitor) data.visitor = visitor;
|
|
79
|
+
const loops = collectCollectionLoops(layout);
|
|
80
|
+
if (loops.length > 0) {
|
|
81
|
+
const lists = await Promise.all(loops.map(loopEntries));
|
|
82
|
+
data.collections = Object.fromEntries(loops.map((loop, i) => [loop.nodeId, lists[i] ?? []]));
|
|
83
|
+
}
|
|
84
|
+
if (layoutUsesSource(layout.root, "param")) {
|
|
85
|
+
data.params = paramsFromSearch(url.searchParams);
|
|
86
|
+
// W-307: URL-parameter links and images stay on this origin unless allowed outside.
|
|
87
|
+
data.origin = url.origin;
|
|
88
|
+
}
|
|
89
|
+
if (layoutUsesSource(layout.root, "site")) {
|
|
90
|
+
try {
|
|
91
|
+
data.site = siteBindingValues(await getSiteSettings());
|
|
92
|
+
} catch {
|
|
93
|
+
data.site = {};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return data;
|
|
97
|
+
}
|
|
@@ -32,6 +32,8 @@ import {
|
|
|
32
32
|
} from "../core/index.ts";
|
|
33
33
|
import { THEME_PARTS_COLLECTION } from "../constants.ts";
|
|
34
34
|
import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
|
|
35
|
+
import type { VisitorAstro } from "./visitor.ts";
|
|
36
|
+
import { bindingDataFor } from "./request-data.ts";
|
|
35
37
|
import { decodePathSegment, themeContextFrom } from "./theme-context.ts";
|
|
36
38
|
import { entryTimestamp, themePostFromEntry } from "./theme-posts.ts";
|
|
37
39
|
|
|
@@ -108,7 +110,7 @@ export type ResolvedThemeParts = {
|
|
|
108
110
|
dir?: "ltr" | "rtl" | "auto";
|
|
109
111
|
};
|
|
110
112
|
|
|
111
|
-
type AstroLike = {
|
|
113
|
+
type AstroLike = VisitorAstro & {
|
|
112
114
|
url: URL;
|
|
113
115
|
locals: unknown;
|
|
114
116
|
props?: Record<string, unknown>;
|
|
@@ -390,7 +392,19 @@ export async function resolveThemeParts(
|
|
|
390
392
|
|
|
391
393
|
const byId = new Map(parts.map((part) => [part.id, part]));
|
|
392
394
|
const rendered: RenderedPage[] = [];
|
|
393
|
-
|
|
395
|
+
// W-307: bound fields in a part read site settings and URL parameters too.
|
|
396
|
+
// W-312/W-313: synced sections and Loop items the part uses count too.
|
|
397
|
+
const boundFor = (stored: StoredPart, referenced: ThemeDynamicData | undefined) =>
|
|
398
|
+
bindingDataFor(readLayout(stored.layout), astro.url, astro, [
|
|
399
|
+
...Object.values(referenced?.sectionTemplates ?? {}),
|
|
400
|
+
...Object.values(referenced?.loopTemplates ?? {}),
|
|
401
|
+
]);
|
|
402
|
+
const renderOne = (
|
|
403
|
+
stored: StoredPart,
|
|
404
|
+
partDynamic: ThemeDynamicData | undefined,
|
|
405
|
+
bound: Awaited<ReturnType<typeof bindingDataFor>>,
|
|
406
|
+
) => {
|
|
407
|
+
const dynamic = Object.keys(bound).length > 0 ? { ...partDynamic, ...bound } : partDynamic;
|
|
394
408
|
const page = renderStored(stored.layout, design, stored.id, undefined, dynamic);
|
|
395
409
|
rendered.push(page);
|
|
396
410
|
// W-216: a header or footer part is the page's banner or contentinfo landmark (hosts put it
|
|
@@ -438,7 +452,7 @@ export async function resolveThemeParts(
|
|
|
438
452
|
if (winner === contentWinner && (dynamic?.pagination?.page ?? 1) > 1) {
|
|
439
453
|
pastLastPage = (dynamic?.posts ?? []).length === 0;
|
|
440
454
|
}
|
|
441
|
-
const { html, css } = renderOne(stored, dynamic);
|
|
455
|
+
const { html, css } = renderOne(stored, dynamic, await boundFor(stored, referenced));
|
|
442
456
|
return { id: stored.id, title: stored.title, partType: stored.partType, html, css };
|
|
443
457
|
};
|
|
444
458
|
|
|
@@ -454,12 +468,24 @@ export async function resolveThemeParts(
|
|
|
454
468
|
extraParts.map(async (stored) => [stored.id, await templatesFor(stored)] as const),
|
|
455
469
|
),
|
|
456
470
|
);
|
|
471
|
+
const extraBound = new Map(
|
|
472
|
+
await Promise.all(
|
|
473
|
+
extraParts.map(
|
|
474
|
+
async (stored) =>
|
|
475
|
+
[stored.id, await boundFor(stored, extraTemplates.get(stored.id))] as const,
|
|
476
|
+
),
|
|
477
|
+
),
|
|
478
|
+
);
|
|
457
479
|
|
|
458
480
|
const popups: RenderedPopup[] = [];
|
|
459
481
|
for (const match of popupMatches) {
|
|
460
482
|
const stored = byId.get(match.id);
|
|
461
483
|
if (!stored) continue;
|
|
462
|
-
const { html, css } = renderOne(
|
|
484
|
+
const { html, css } = renderOne(
|
|
485
|
+
stored,
|
|
486
|
+
extraTemplates.get(stored.id),
|
|
487
|
+
extraBound.get(stored.id) ?? {},
|
|
488
|
+
);
|
|
463
489
|
popups.push({
|
|
464
490
|
id: stored.id,
|
|
465
491
|
title: stored.title,
|
|
@@ -473,7 +499,11 @@ export async function resolveThemeParts(
|
|
|
473
499
|
for (const match of floatMatches) {
|
|
474
500
|
const stored = byId.get(match.id);
|
|
475
501
|
if (!stored) continue;
|
|
476
|
-
const { html, css } = renderOne(
|
|
502
|
+
const { html, css } = renderOne(
|
|
503
|
+
stored,
|
|
504
|
+
extraTemplates.get(stored.id),
|
|
505
|
+
extraBound.get(stored.id) ?? {},
|
|
506
|
+
);
|
|
477
507
|
const layout = readLayout(stored.layout);
|
|
478
508
|
const surface = !layout || !floatHasOwnSurface(layout, design);
|
|
479
509
|
floats.push({
|
package/src/astro/resolve.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
|
|
|
3
3
|
import { PAGES_COLLECTION } from "../constants.ts";
|
|
4
4
|
import { formIdsInLayout, loadFormDefinitions } from "./forms-definitions.ts";
|
|
5
5
|
import { loadDesign, readLayout, renderStored, type RenderedPage } from "./render.ts";
|
|
6
|
+
import { bindingDataFor } from "./request-data.ts";
|
|
7
|
+
import type { VisitorAstro } from "./visitor.ts";
|
|
6
8
|
import { sectionTemplatesFor } from "./resolve-theme.ts";
|
|
7
9
|
|
|
8
10
|
type EmDashEntry = NonNullable<Awaited<ReturnType<typeof getEmDashEntry>>["entry"]>;
|
|
@@ -16,7 +18,7 @@ export type ResolvedEmVBPage = RenderedPage & {
|
|
|
16
18
|
isPreview: boolean;
|
|
17
19
|
};
|
|
18
20
|
|
|
19
|
-
type AstroLike = {
|
|
21
|
+
type AstroLike = VisitorAstro & {
|
|
20
22
|
params: Record<string, string | undefined>;
|
|
21
23
|
url: URL;
|
|
22
24
|
locals: unknown;
|
|
@@ -49,13 +51,17 @@ export async function resolveEmVBPage(
|
|
|
49
51
|
? await loadFormDefinitions(handler, astro.url, formIdsInLayout(layout))
|
|
50
52
|
: undefined;
|
|
51
53
|
const sectionTemplates = layout ? await sectionTemplatesFor(layout) : {};
|
|
54
|
+
const dynamic = {
|
|
55
|
+
...(Object.keys(sectionTemplates).length > 0 ? { sectionTemplates } : {}),
|
|
56
|
+
...(await bindingDataFor(layout, astro.url, astro, Object.values(sectionTemplates))),
|
|
57
|
+
};
|
|
52
58
|
return {
|
|
53
59
|
...renderStored(
|
|
54
60
|
data["layout"],
|
|
55
61
|
design,
|
|
56
62
|
String(data["id"] ?? slug),
|
|
57
63
|
formDefinitions,
|
|
58
|
-
Object.keys(
|
|
64
|
+
Object.keys(dynamic).length > 0 ? dynamic : undefined,
|
|
59
65
|
),
|
|
60
66
|
entry,
|
|
61
67
|
title: typeof data["title"] === "string" ? data["title"] : "",
|
package/src/astro/theme-posts.ts
CHANGED
|
@@ -62,6 +62,7 @@ export function themePostFromEntry(
|
|
|
62
62
|
.map((key) => entryTimestamp(data[key]))
|
|
63
63
|
.find(Boolean);
|
|
64
64
|
const authorName = authorFrom(data);
|
|
65
|
+
const fields = plainFieldsOf(data);
|
|
65
66
|
return {
|
|
66
67
|
id: id || slug,
|
|
67
68
|
slug: slug || id,
|
|
@@ -72,9 +73,40 @@ export function themePostFromEntry(
|
|
|
72
73
|
...(publishedAt ? { publishedAt } : {}),
|
|
73
74
|
...(authorName ? { authorName } : {}),
|
|
74
75
|
...media,
|
|
76
|
+
...(Object.keys(fields).length > 0 ? { fields } : {}),
|
|
75
77
|
};
|
|
76
78
|
}
|
|
77
79
|
|
|
80
|
+
/** Field names a binding may read; EmDash's internal fields are left out. */
|
|
81
|
+
const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;
|
|
82
|
+
/** Already on ThemePostFields under their own names. */
|
|
83
|
+
const MAPPED = new Set(["id", "slug", "title", "excerpt", "content"]);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The entry's plain fields for data bindings (W-307): text, numbers, true/false, and an image
|
|
87
|
+
* field's URL. Rich text and other objects are left out; at most 100 fields, text cut at 2000.
|
|
88
|
+
*/
|
|
89
|
+
export function plainFieldsOf(
|
|
90
|
+
data: Record<string, unknown>,
|
|
91
|
+
): Record<string, string | number | boolean> {
|
|
92
|
+
const fields: Record<string, string | number | boolean> = {};
|
|
93
|
+
for (const [key, value] of Object.entries(data)) {
|
|
94
|
+
if (Object.keys(fields).length >= 100) break;
|
|
95
|
+
if (!FIELD_NAME.test(key) || MAPPED.has(key)) continue;
|
|
96
|
+
if (typeof value === "string") fields[key] = value.slice(0, 2000);
|
|
97
|
+
else if (typeof value === "number" && Number.isFinite(value)) fields[key] = value;
|
|
98
|
+
else if (typeof value === "boolean") fields[key] = value;
|
|
99
|
+
else if (value instanceof Date) {
|
|
100
|
+
const iso = entryTimestamp(value);
|
|
101
|
+
if (iso) fields[key] = iso;
|
|
102
|
+
} else if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
103
|
+
const url = mediaFieldsFrom(value).featuredImageUrl;
|
|
104
|
+
if (url) fields[key] = url;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return fields;
|
|
108
|
+
}
|
|
109
|
+
|
|
78
110
|
function firstString(data: Record<string, unknown>, keys: string[]): string | undefined {
|
|
79
111
|
for (const key of keys) {
|
|
80
112
|
const value = data[key];
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import {
|
|
2
|
+
abCookieName,
|
|
3
|
+
collectAbTests,
|
|
4
|
+
deviceFromUserAgent,
|
|
5
|
+
layoutUsesAudience,
|
|
6
|
+
pickArm,
|
|
7
|
+
type AbArm,
|
|
8
|
+
type Layout,
|
|
9
|
+
type VisitorInfo,
|
|
10
|
+
} from "../core/index.ts";
|
|
11
|
+
|
|
12
|
+
/** What EmVB reads from Astro to decide per-visitor content on the server (W-312, W-313). */
|
|
13
|
+
export type VisitorAstro = {
|
|
14
|
+
url: URL;
|
|
15
|
+
request?: Request;
|
|
16
|
+
cookies?: {
|
|
17
|
+
get(name: string): { value: string } | undefined;
|
|
18
|
+
set(name: string, value: string, options?: Record<string, unknown>): void;
|
|
19
|
+
};
|
|
20
|
+
response?: { headers: Headers };
|
|
21
|
+
locals?: unknown;
|
|
22
|
+
/** Astro's route cache, when the host configured a provider. */
|
|
23
|
+
cache?: { enabled: boolean; set(input: false): void };
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const AB_COOKIE_DAYS = 30;
|
|
27
|
+
|
|
28
|
+
const random = (): number => {
|
|
29
|
+
const bytes = new Uint32Array(1);
|
|
30
|
+
crypto.getRandomValues(bytes);
|
|
31
|
+
return (bytes[0] ?? 0) / 2 ** 32;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The response varies per visitor: keep shared caches from serving one visitor's arm or
|
|
36
|
+
* audience to another (W-312), including Astro's route cache. A host that sets cache hints
|
|
37
|
+
* after this should skip them when `Cache-Control` is private (the demos' Base layout does).
|
|
38
|
+
*/
|
|
39
|
+
function markPersonalized(astro: VisitorAstro): void {
|
|
40
|
+
if (astro.cache?.enabled) astro.cache.set(false);
|
|
41
|
+
const headers = astro.response?.headers;
|
|
42
|
+
if (!headers) return;
|
|
43
|
+
headers.set("Cache-Control", "private, no-store");
|
|
44
|
+
const vary = headers.get("Vary");
|
|
45
|
+
if (!vary?.toLowerCase().includes("cookie"))
|
|
46
|
+
headers.set("Vary", vary ? `${vary}, Cookie` : "Cookie");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Picks each A/B test's arm for this visitor (W-312): the arm in their cookie, or a fresh pick
|
|
51
|
+
* that the cookie then keeps for 30 days. Without cookie access the visitor sees arm A.
|
|
52
|
+
*/
|
|
53
|
+
export function abArmsFor(
|
|
54
|
+
layout: Layout | null,
|
|
55
|
+
astro: VisitorAstro,
|
|
56
|
+
): Record<string, AbArm> | undefined {
|
|
57
|
+
if (!layout) return undefined;
|
|
58
|
+
const tests = collectAbTests(layout);
|
|
59
|
+
if (tests.length === 0) return undefined;
|
|
60
|
+
const cookies = astro.cookies;
|
|
61
|
+
if (!cookies) return undefined;
|
|
62
|
+
const arms: Record<string, AbArm> = {};
|
|
63
|
+
for (const test of tests) {
|
|
64
|
+
const name = abCookieName(test.test);
|
|
65
|
+
const { arm, fresh } = pickArm(test, cookies.get(name)?.value, random());
|
|
66
|
+
arms[test.test] = arm;
|
|
67
|
+
if (fresh) {
|
|
68
|
+
try {
|
|
69
|
+
cookies.set(name, arm, {
|
|
70
|
+
path: "/",
|
|
71
|
+
maxAge: AB_COOKIE_DAYS * 86_400,
|
|
72
|
+
sameSite: "lax",
|
|
73
|
+
httpOnly: true,
|
|
74
|
+
secure: astro.url.protocol === "https:",
|
|
75
|
+
});
|
|
76
|
+
} catch {
|
|
77
|
+
// Headers already sent (a streamed layout): the pick holds for this response only.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
markPersonalized(astro);
|
|
82
|
+
return arms;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Marks a visitor as seen, so their next visit counts as returning (W-313). */
|
|
86
|
+
const SEEN_COOKIE = "emvb_seen";
|
|
87
|
+
const SEEN_DAYS = 365;
|
|
88
|
+
|
|
89
|
+
const COUNTRY = /^[A-Z]{2}$/;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The visitor's country from the edge: Cloudflare's header or `request.cf`, or Vercel's header.
|
|
93
|
+
* Not `Astro.locals.runtime.cf`: since Astro 6 the Cloudflare adapter throws when it is read.
|
|
94
|
+
*/
|
|
95
|
+
function countryOf(astro: VisitorAstro): string | undefined {
|
|
96
|
+
const headers = astro.request?.headers;
|
|
97
|
+
const cf = (astro.request as { cf?: { country?: unknown } } | undefined)?.cf;
|
|
98
|
+
const candidates = [
|
|
99
|
+
headers?.get("cf-ipcountry"),
|
|
100
|
+
headers?.get("x-vercel-ip-country"),
|
|
101
|
+
cf?.country,
|
|
102
|
+
];
|
|
103
|
+
for (const value of candidates) {
|
|
104
|
+
const code = typeof value === "string" ? value.trim().toUpperCase() : "";
|
|
105
|
+
// XX is Cloudflare's "unknown" and T1 is Tor: neither is a country.
|
|
106
|
+
if (COUNTRY.test(code) && code !== "XX" && code !== "T1") return code;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* What the server knows about this visitor, for visitor-aware elements (W-313): country from
|
|
113
|
+
* the edge, device from the User-Agent, new or returning from a first-party cookie, and the time.
|
|
114
|
+
* Only read when the layout has a visitor rule.
|
|
115
|
+
*/
|
|
116
|
+
export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorInfo | undefined {
|
|
117
|
+
if (!layout || !layoutUsesAudience(layout)) return undefined;
|
|
118
|
+
const headers = astro.request?.headers;
|
|
119
|
+
const visitor: VisitorInfo = { now: Date.now() };
|
|
120
|
+
const country = countryOf(astro);
|
|
121
|
+
if (country) visitor.country = country;
|
|
122
|
+
const device = deviceFromUserAgent(headers?.get("user-agent"), headers?.get("sec-ch-ua-mobile"));
|
|
123
|
+
if (device) visitor.device = device;
|
|
124
|
+
if (astro.cookies) {
|
|
125
|
+
visitor.returning = astro.cookies.get(SEEN_COOKIE)?.value === "1";
|
|
126
|
+
if (!visitor.returning) {
|
|
127
|
+
try {
|
|
128
|
+
astro.cookies.set(SEEN_COOKIE, "1", {
|
|
129
|
+
path: "/",
|
|
130
|
+
maxAge: SEEN_DAYS * 86_400,
|
|
131
|
+
sameSite: "lax",
|
|
132
|
+
httpOnly: true,
|
|
133
|
+
secure: astro.url.protocol === "https:",
|
|
134
|
+
});
|
|
135
|
+
} catch {
|
|
136
|
+
// Headers already sent: they count as new again next time.
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
markPersonalized(astro);
|
|
141
|
+
return visitor;
|
|
142
|
+
}
|