@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.
- package/README.md +2 -2
- package/package.json +2 -2
- 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 +4 -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 +39 -9
- package/src/astro/resolve.ts +8 -2
- package/src/astro/theme-context.ts +14 -2
- package/src/astro/theme-posts.ts +51 -1
- 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,51 @@
|
|
|
1
|
+
import { AB_TEST_NAME, isParentNode, type Layout, type LayoutNode } from "../schema/layout.ts";
|
|
2
|
+
|
|
3
|
+
export type AbArm = "a" | "b";
|
|
4
|
+
|
|
5
|
+
/** An A/B test in a layout (W-312): its name and the share of visitors who see B. */
|
|
6
|
+
export type AbTest = { test: string; split: number };
|
|
7
|
+
|
|
8
|
+
/** The cookie that keeps a visitor on one arm of a test (W-312). */
|
|
9
|
+
export const abCookieName = (test: string) => `emvb_ab_${test.replaceAll("-", "_")}`;
|
|
10
|
+
|
|
11
|
+
/** Every A/B test in the layout, at most 10, with B's split (default 50 %). */
|
|
12
|
+
export function collectAbTests(layout: Layout): AbTest[] {
|
|
13
|
+
const tests = new Map<string, number>();
|
|
14
|
+
const walk = (node: LayoutNode): void => {
|
|
15
|
+
const v = node.variant;
|
|
16
|
+
if (v && AB_TEST_NAME.test(v.test) && (tests.has(v.test) || tests.size < 10)) {
|
|
17
|
+
const known = tests.get(v.test);
|
|
18
|
+
if (v.arm === "b" && v.split !== undefined) tests.set(v.test, v.split);
|
|
19
|
+
else if (known === undefined) tests.set(v.test, 50);
|
|
20
|
+
}
|
|
21
|
+
if (isParentNode(node)) for (const child of node.children) walk(child);
|
|
22
|
+
};
|
|
23
|
+
walk(layout.root);
|
|
24
|
+
return [...tests].map(([test, split]) => ({ test, split }));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The arm for one visitor (W-312): their cookie when it holds a valid arm, else a fresh pick.
|
|
29
|
+
* `random` is a number in [0, 1); B wins when it falls under the split.
|
|
30
|
+
*/
|
|
31
|
+
export function pickArm(
|
|
32
|
+
test: AbTest,
|
|
33
|
+
cookie: string | undefined,
|
|
34
|
+
random: number,
|
|
35
|
+
): { arm: AbArm; fresh: boolean } {
|
|
36
|
+
if (cookie === "a" || cookie === "b") return { arm: cookie, fresh: false };
|
|
37
|
+
return { arm: random * 100 < test.split ? "b" : "a", fresh: true };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Whether a node shows for these arms (W-312). Without a decision for its test (a host that
|
|
42
|
+
* doesn't run tests, or the editor), arm A shows and B stays hidden, so pages never show both.
|
|
43
|
+
*/
|
|
44
|
+
export function variantShows(
|
|
45
|
+
node: LayoutNode,
|
|
46
|
+
arms: Readonly<Record<string, AbArm>> | undefined,
|
|
47
|
+
): boolean {
|
|
48
|
+
const v = node.variant;
|
|
49
|
+
if (!v) return true;
|
|
50
|
+
return (arms?.[v.test] ?? "a") === v.arm;
|
|
51
|
+
}
|
package/src/core/css/generate.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { DEFAULT_FLUID_RANGE, fluidClamp } from "../design/tokens.ts";
|
|
2
|
+
import type { FluidRange, LengthVariable } from "../schema/design.ts";
|
|
1
3
|
import type { DesignSystem } from "../schema/design.ts";
|
|
2
4
|
import { DEFAULT_STYLE_TAGS } from "../schema/design.ts";
|
|
3
5
|
import {
|
|
@@ -16,6 +18,7 @@ import {
|
|
|
16
18
|
} from "../sanitize/css.ts";
|
|
17
19
|
import { STYLE_STATES, type StyleStateName } from "../schema/state-names.ts";
|
|
18
20
|
import { DEVICE_MEDIA, type PopupDevice } from "../theme/popup-rules.ts";
|
|
21
|
+
import { MOTION_KEYFRAMES } from "../sanitize/motion.ts";
|
|
19
22
|
|
|
20
23
|
export type CssInput = {
|
|
21
24
|
design: DesignSystem;
|
|
@@ -87,6 +90,12 @@ const fontStack = (value: string) => (isSafeFontStack(value) ? value : undefined
|
|
|
87
90
|
const lengthCss = (length: { value: number; unit: string }) =>
|
|
88
91
|
safe(`${length.value}${length.unit}`);
|
|
89
92
|
|
|
93
|
+
/** A size token: its fixed length, or a fluid `clamp()` when it has one (W-316). */
|
|
94
|
+
const sizeCss = (variable: LengthVariable, range: FluidRange | undefined) =>
|
|
95
|
+
variable.fluid
|
|
96
|
+
? fluidClamp(variable.fluid.min, variable.fluid.max, range ?? DEFAULT_FLUID_RANGE)
|
|
97
|
+
: lengthCss(variable.value);
|
|
98
|
+
|
|
90
99
|
/** One custom property per variable whose id and value are both safe to emit. */
|
|
91
100
|
function declare<T extends { id: string }>(
|
|
92
101
|
variables: readonly T[] | undefined,
|
|
@@ -100,6 +109,10 @@ function declare<T extends { id: string }>(
|
|
|
100
109
|
});
|
|
101
110
|
}
|
|
102
111
|
|
|
112
|
+
/** W-319: declarations that play scroll motion. */
|
|
113
|
+
const usesMotion = (declarations: readonly Declaration[]) =>
|
|
114
|
+
declarations.some((d) => d.property === "animation" && /\bemvb-m[otsrb]\b/.test(d.value));
|
|
115
|
+
|
|
103
116
|
/**
|
|
104
117
|
* Cascade order (R-021 / W-030 / W-089): variables on `.emvb-root`, base CSS, shared
|
|
105
118
|
* `.emvb-k-<id>` class rules, then local `.emvb-e-<id>` (local wins). Each selector's `:hover`,
|
|
@@ -120,11 +133,13 @@ export function generateCss({
|
|
|
120
133
|
const variables = [
|
|
121
134
|
...declare(colors, colorVariableName, (color) => safe(color.value)),
|
|
122
135
|
...declare(fonts, fontVariableName, (font) => fontStack(font.value)),
|
|
123
|
-
...declare(fontSizes, fontSizeVariableName, (size) =>
|
|
124
|
-
...declare(spacings, spacingVariableName, (space) =>
|
|
136
|
+
...declare(fontSizes, fontSizeVariableName, (size) => sizeCss(size, design.fluidRange)),
|
|
137
|
+
...declare(spacings, spacingVariableName, (space) => sizeCss(space, design.fluidRange)),
|
|
125
138
|
];
|
|
126
139
|
const animated: string[] = [];
|
|
127
140
|
const entrances: string[] = [];
|
|
141
|
+
/** W-319: any scroll motion on the page, so its keyframes are sent. */
|
|
142
|
+
let motion = false;
|
|
128
143
|
const rules = (selector: string, declarations: Declaration[], states: StateDeclarations) => [
|
|
129
144
|
block(selector, declarations),
|
|
130
145
|
...STYLE_STATES.map((state) =>
|
|
@@ -139,6 +154,7 @@ export function generateCss({
|
|
|
139
154
|
const track = (selector: string, declarations: Declaration[]) => {
|
|
140
155
|
if (declarations.some((d) => d.property === "transition")) animated.push(selector);
|
|
141
156
|
if (declarations.some((d) => d.property === "animation")) entrances.push(selector);
|
|
157
|
+
if (usesMotion(declarations)) motion = true;
|
|
142
158
|
return declarations;
|
|
143
159
|
};
|
|
144
160
|
const classes = (design.classes ?? []).flatMap((cls) => {
|
|
@@ -202,6 +218,7 @@ export function generateCss({
|
|
|
202
218
|
);
|
|
203
219
|
};
|
|
204
220
|
for (const rule of responsive) {
|
|
221
|
+
if (usesMotion(rule.tablet) || usesMotion(rule.mobile)) motion = true;
|
|
205
222
|
if (
|
|
206
223
|
!entrances.includes(rule.selector) &&
|
|
207
224
|
[...rule.tablet, ...rule.mobile].some((d) => d.property === "animation")
|
|
@@ -213,6 +230,7 @@ export function generateCss({
|
|
|
213
230
|
entrances.length > 0
|
|
214
231
|
? "@keyframes emvb-fade{from{opacity:0}to{opacity:1}}@keyframes emvb-fade-up{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}@keyframes emvb-fade-down{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}@keyframes emvb-slide-up{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:none}}@keyframes emvb-slide-down{from{opacity:0;transform:translateY(-16px)}to{opacity:1;transform:none}}@keyframes emvb-scale{from{opacity:0;transform:scale(0.96)}to{opacity:1;transform:none}}"
|
|
215
232
|
: "",
|
|
233
|
+
entrances.length > 0 && motion ? MOTION_KEYFRAMES : "",
|
|
216
234
|
block(".emvb-root", variables),
|
|
217
235
|
tagDefaultCss(design),
|
|
218
236
|
backgroundVideo
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { DefaultStyleTag, DesignSystem } from "../schema/design.ts";
|
|
2
|
+
import type { LayoutNode } from "../schema/layout.ts";
|
|
3
|
+
import type { StyleStateName } from "../schema/state-names.ts";
|
|
4
|
+
import type { StyleProps } from "../schema/style.ts";
|
|
5
|
+
|
|
6
|
+
export type TraceDevice = "desktop" | "tablet" | "mobile";
|
|
7
|
+
|
|
8
|
+
/** Where one style value comes from (W-318). */
|
|
9
|
+
export type StyleSource = {
|
|
10
|
+
kind: "default" | "class" | "local";
|
|
11
|
+
/** "Site default (H2)", ".card", "This element". */
|
|
12
|
+
label: string;
|
|
13
|
+
/** Desktop, Tablet, Mobile, or a state such as Hover. */
|
|
14
|
+
layer: string;
|
|
15
|
+
classId?: string;
|
|
16
|
+
value: unknown;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** For one property: the value that applies and the ones it overrides, strongest first. */
|
|
20
|
+
export type StyleTrace = { winner: StyleSource; overridden: StyleSource[] };
|
|
21
|
+
|
|
22
|
+
/** The tag a node renders whose Site styles default applies (W-318). */
|
|
23
|
+
export function defaultTagFor(node: LayoutNode): DefaultStyleTag | undefined {
|
|
24
|
+
const props = node.props as Record<string, unknown>;
|
|
25
|
+
switch (node.type) {
|
|
26
|
+
case "heading": {
|
|
27
|
+
const level = typeof props["level"] === "number" ? props["level"] : 2;
|
|
28
|
+
return `h${Math.min(6, Math.max(1, level))}` as DefaultStyleTag;
|
|
29
|
+
}
|
|
30
|
+
case "text":
|
|
31
|
+
return props["tag"] === "div" ? undefined : "p";
|
|
32
|
+
case "link":
|
|
33
|
+
return "a";
|
|
34
|
+
case "button":
|
|
35
|
+
return typeof props["href"] === "string" && props["href"].trim() ? "a" : "button";
|
|
36
|
+
default:
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const LAYER = { desktop: "Desktop", tablet: "Tablet", mobile: "Mobile" } as const;
|
|
42
|
+
const STATE_LABEL: Record<StyleStateName, string> = {
|
|
43
|
+
hover: "Hover",
|
|
44
|
+
focus: "Focus",
|
|
45
|
+
active: "Active",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
type Owner = {
|
|
49
|
+
kind: "class" | "local";
|
|
50
|
+
label: string;
|
|
51
|
+
classId?: string;
|
|
52
|
+
style?: StyleProps;
|
|
53
|
+
devices?: { tablet?: StyleProps; mobile?: StyleProps };
|
|
54
|
+
states?: Partial<Record<StyleStateName, StyleProps>>;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Every style layer that applies to a node on a device and in a state, weakest first, in the
|
|
59
|
+
* cascade EmVB emits (W-318): the tag's Site styles default, each class in site order (later
|
|
60
|
+
* classes win), then the element's own styles; within each, Desktop then Tablet then Mobile;
|
|
61
|
+
* state styles last, classes before the element.
|
|
62
|
+
*/
|
|
63
|
+
export function styleLayers(
|
|
64
|
+
node: LayoutNode,
|
|
65
|
+
design: DesignSystem,
|
|
66
|
+
device: TraceDevice = "desktop",
|
|
67
|
+
state: StyleStateName | "normal" = "normal",
|
|
68
|
+
): { source: Omit<StyleSource, "value">; style: StyleProps }[] {
|
|
69
|
+
const layers: { source: Omit<StyleSource, "value">; style: StyleProps }[] = [];
|
|
70
|
+
const tag = defaultTagFor(node);
|
|
71
|
+
const tagStyle = tag ? design.defaults?.[tag] : undefined;
|
|
72
|
+
if (tag && tagStyle) {
|
|
73
|
+
layers.push({
|
|
74
|
+
source: { kind: "default", label: `Site default (${tag.toUpperCase()})`, layer: "Desktop" },
|
|
75
|
+
style: tagStyle,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const applied = new Set(node.classes ?? []);
|
|
79
|
+
const owners: Owner[] = [];
|
|
80
|
+
for (const cls of design.classes ?? []) {
|
|
81
|
+
if (!applied.has(cls.id)) continue;
|
|
82
|
+
const owner: Owner = {
|
|
83
|
+
kind: "class",
|
|
84
|
+
label: `.${cls.name}`,
|
|
85
|
+
classId: cls.id,
|
|
86
|
+
style: cls.style,
|
|
87
|
+
};
|
|
88
|
+
if (cls.devices) owner.devices = cls.devices;
|
|
89
|
+
if (cls.states) owner.states = cls.states;
|
|
90
|
+
owners.push(owner);
|
|
91
|
+
}
|
|
92
|
+
owners.push({
|
|
93
|
+
kind: "local",
|
|
94
|
+
label: "This element",
|
|
95
|
+
...(node.style ? { style: node.style } : {}),
|
|
96
|
+
...(node.devices ? { devices: node.devices } : {}),
|
|
97
|
+
...(node.states ? { states: node.states as Owner["states"] } : {}),
|
|
98
|
+
});
|
|
99
|
+
for (const owner of owners) {
|
|
100
|
+
const base = {
|
|
101
|
+
kind: owner.kind,
|
|
102
|
+
label: owner.label,
|
|
103
|
+
...(owner.classId ? { classId: owner.classId } : {}),
|
|
104
|
+
};
|
|
105
|
+
if (owner.style) layers.push({ source: { ...base, layer: LAYER.desktop }, style: owner.style });
|
|
106
|
+
if (device !== "desktop" && owner.devices?.tablet) {
|
|
107
|
+
layers.push({ source: { ...base, layer: LAYER.tablet }, style: owner.devices.tablet });
|
|
108
|
+
}
|
|
109
|
+
if (device === "mobile" && owner.devices?.mobile) {
|
|
110
|
+
layers.push({ source: { ...base, layer: LAYER.mobile }, style: owner.devices.mobile });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (state !== "normal") {
|
|
114
|
+
for (const owner of owners) {
|
|
115
|
+
const style = owner.states?.[state];
|
|
116
|
+
if (!style) continue;
|
|
117
|
+
layers.push({
|
|
118
|
+
source: {
|
|
119
|
+
kind: owner.kind,
|
|
120
|
+
label: owner.label,
|
|
121
|
+
...(owner.classId ? { classId: owner.classId } : {}),
|
|
122
|
+
layer: STATE_LABEL[state],
|
|
123
|
+
},
|
|
124
|
+
style,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return layers;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Where each set property of a node comes from (W-318), by property name. */
|
|
132
|
+
export function traceStyle(
|
|
133
|
+
node: LayoutNode,
|
|
134
|
+
design: DesignSystem,
|
|
135
|
+
device: TraceDevice = "desktop",
|
|
136
|
+
state: StyleStateName | "normal" = "normal",
|
|
137
|
+
): Record<string, StyleTrace> {
|
|
138
|
+
const all: Record<string, StyleSource[]> = {};
|
|
139
|
+
for (const { source, style } of styleLayers(node, design, device, state)) {
|
|
140
|
+
for (const [key, value] of Object.entries(style)) {
|
|
141
|
+
if (value === undefined) continue;
|
|
142
|
+
(all[key] ??= []).push({ ...source, value });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const out: Record<string, StyleTrace> = {};
|
|
146
|
+
for (const [key, sources] of Object.entries(all)) {
|
|
147
|
+
const strongest = sources.toReversed();
|
|
148
|
+
out[key] = { winner: strongest[0] as StyleSource, overridden: strongest.slice(1) };
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* What a node's own style edit sits on top of (W-318): every value from its tag default and its
|
|
155
|
+
* classes on this device (and, on Tablet/Mobile or in a state, from its own wider layers). The
|
|
156
|
+
* editor shows these as the controls' inherited values.
|
|
157
|
+
*/
|
|
158
|
+
export function inheritedStyle(
|
|
159
|
+
node: LayoutNode,
|
|
160
|
+
design: DesignSystem,
|
|
161
|
+
device: TraceDevice,
|
|
162
|
+
state: StyleStateName | "normal",
|
|
163
|
+
): StyleProps {
|
|
164
|
+
const layers = styleLayers(node, design, device, state);
|
|
165
|
+
// Drop the layer being edited: the element's own on this device and state.
|
|
166
|
+
const editing = state !== "normal" ? STATE_LABEL[state] : LAYER[device];
|
|
167
|
+
const below = layers.filter((l) => !(l.source.kind === "local" && l.source.layer === editing));
|
|
168
|
+
return Object.assign({}, ...below.map((l) => l.style)) as StyleProps;
|
|
169
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import type { Binding, BindSource, LayoutNode } from "../schema/layout.ts";
|
|
2
|
+
import { sanitizeHref } from "../sanitize/href.ts";
|
|
3
|
+
import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
|
|
4
|
+
import type { ThemePostFields } from "../theme/dynamic.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Live data bindings (W-307). A text, image or link field can read a post field, a site setting
|
|
8
|
+
* or a URL parameter instead of its typed value. The typed value stays as the fallback, so a page
|
|
9
|
+
* never shows an empty heading because a parameter is missing. Values are plain text: the element
|
|
10
|
+
* still escapes text and sanitizes links and image URLs, exactly as for a typed value.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** How a bound value is used, which decides how it's cleaned before the element sees it. */
|
|
14
|
+
export type BindKind = "text" | "url" | "image";
|
|
15
|
+
|
|
16
|
+
export type BindableField = { key: string; label: string; kind: BindKind };
|
|
17
|
+
|
|
18
|
+
const TEXT = (label = "Text"): BindableField => ({ key: "text", label, kind: "text" });
|
|
19
|
+
const HREF = (label = "Link"): BindableField => ({ key: "href", label, kind: "url" });
|
|
20
|
+
|
|
21
|
+
/** Which props of which elements can be bound. Anything else in `bind` is ignored on render. */
|
|
22
|
+
export const BINDABLE_FIELDS: Readonly<Record<string, readonly BindableField[]>> = {
|
|
23
|
+
heading: [TEXT(), HREF()],
|
|
24
|
+
text: [TEXT()],
|
|
25
|
+
label: [TEXT()],
|
|
26
|
+
link: [TEXT(), HREF("URL")],
|
|
27
|
+
button: [TEXT(), HREF()],
|
|
28
|
+
image: [
|
|
29
|
+
{ key: "src", label: "Image", kind: "image" },
|
|
30
|
+
{ key: "alt", label: "Alt text", kind: "text" },
|
|
31
|
+
],
|
|
32
|
+
icon: [HREF(), { key: "title", label: "Title", kind: "text" }],
|
|
33
|
+
"menu-item": [TEXT("Label"), HREF()],
|
|
34
|
+
container: [HREF()],
|
|
35
|
+
"div-block": [HREF()],
|
|
36
|
+
flexbox: [HREF()],
|
|
37
|
+
grid: [HREF()],
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const bindableFields = (type: string): readonly BindableField[] =>
|
|
41
|
+
Object.hasOwn(BINDABLE_FIELDS, type) ? (BINDABLE_FIELDS[type] ?? []) : [];
|
|
42
|
+
|
|
43
|
+
/** The post fields the editor offers by name; any other key reads the post's own data. */
|
|
44
|
+
export const POST_BIND_KEYS = [
|
|
45
|
+
{ key: "title", label: "Title" },
|
|
46
|
+
{ key: "excerpt", label: "Excerpt" },
|
|
47
|
+
{ key: "permalink", label: "Permalink" },
|
|
48
|
+
{ key: "slug", label: "Slug" },
|
|
49
|
+
{ key: "publishedAt", label: "Published date" },
|
|
50
|
+
{ key: "authorName", label: "Author" },
|
|
51
|
+
{ key: "featuredImageUrl", label: "Featured image" },
|
|
52
|
+
{ key: "featuredImageAlt", label: "Featured image alt" },
|
|
53
|
+
] as const;
|
|
54
|
+
|
|
55
|
+
/** Site settings hosts pass in by default (EmDash's `getSiteSettings`). */
|
|
56
|
+
export const SITE_BIND_KEYS = [
|
|
57
|
+
{ key: "title", label: "Site title" },
|
|
58
|
+
{ key: "tagline", label: "Tagline" },
|
|
59
|
+
{ key: "url", label: "Site URL" },
|
|
60
|
+
] as const;
|
|
61
|
+
|
|
62
|
+
export const BIND_SOURCE_LABELS: Readonly<Record<BindSource, string>> = {
|
|
63
|
+
post: "Post field",
|
|
64
|
+
site: "Site setting",
|
|
65
|
+
param: "URL parameter",
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Where bound values come from on this render. */
|
|
69
|
+
export type BindingData = {
|
|
70
|
+
post?: ThemePostFields;
|
|
71
|
+
site?: Readonly<Record<string, string>>;
|
|
72
|
+
params?: Readonly<Record<string, string>>;
|
|
73
|
+
/** The page's origin; a URL-parameter link or image must stay on it unless `outside` (W-307). */
|
|
74
|
+
origin?: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Longest bound value an element receives; longer values are cut (URL parameters are untrusted). */
|
|
78
|
+
export const MAX_BOUND_LENGTH = 500;
|
|
79
|
+
|
|
80
|
+
const POST_KEYS = new Set<string>(POST_BIND_KEYS.map((k) => k.key));
|
|
81
|
+
|
|
82
|
+
function scalar(value: unknown): string | undefined {
|
|
83
|
+
if (typeof value === "string") return value;
|
|
84
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
85
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function postValue(post: ThemePostFields | undefined, key: string): string | undefined {
|
|
90
|
+
if (!post) return undefined;
|
|
91
|
+
if (POST_KEYS.has(key)) return scalar((post as Record<string, unknown>)[key]);
|
|
92
|
+
const fields = post.fields;
|
|
93
|
+
if (!fields || !Object.hasOwn(fields, key)) return undefined;
|
|
94
|
+
return scalar(fields[key]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Text with control characters removed and its length capped. */
|
|
98
|
+
function clean(value: string): string {
|
|
99
|
+
let out = "";
|
|
100
|
+
for (const char of value) {
|
|
101
|
+
const code = char.codePointAt(0) ?? 0;
|
|
102
|
+
if (code === 10 || code === 9) out += char === "\t" ? " " : char;
|
|
103
|
+
else if (code >= 32 && code !== 127) out += char;
|
|
104
|
+
if (out.length >= MAX_BOUND_LENGTH) break;
|
|
105
|
+
}
|
|
106
|
+
return out.slice(0, MAX_BOUND_LENGTH).trim();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The live value of one binding, or undefined when its source has nothing for this key. */
|
|
110
|
+
export function resolveBinding(binding: Binding, data: BindingData): string | undefined {
|
|
111
|
+
let raw: string | undefined;
|
|
112
|
+
if (binding.source === "post") raw = postValue(data.post, binding.key);
|
|
113
|
+
else if (binding.source === "site") {
|
|
114
|
+
raw = data.site && Object.hasOwn(data.site, binding.key) ? data.site[binding.key] : undefined;
|
|
115
|
+
} else {
|
|
116
|
+
raw =
|
|
117
|
+
data.params && Object.hasOwn(data.params, binding.key) ? data.params[binding.key] : undefined;
|
|
118
|
+
}
|
|
119
|
+
if (raw === undefined) return undefined;
|
|
120
|
+
const value = clean(raw);
|
|
121
|
+
return value.length > 0 ? value : undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** True when the node has at least one binding render would use. */
|
|
125
|
+
export function hasBindings(node: LayoutNode): boolean {
|
|
126
|
+
const bind = node.bind;
|
|
127
|
+
if (!bind) return false;
|
|
128
|
+
return bindableFields(node.type).some((field) => Object.hasOwn(bind, field.key));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Whether a URL stays on this site: relative (`/path`, `?q`, `#top`, `page`), or absolute on
|
|
133
|
+
* `origin`. `//host` and other schemes are outside; without an origin, only relative URLs pass.
|
|
134
|
+
*/
|
|
135
|
+
function isSameSiteUrl(value: string, origin: string | undefined): boolean {
|
|
136
|
+
const url = value.trim();
|
|
137
|
+
if (/^[/\\]{2}/.test(url)) return false;
|
|
138
|
+
if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) return true;
|
|
139
|
+
if (!origin) return false;
|
|
140
|
+
try {
|
|
141
|
+
return new URL(url).origin === new URL(origin).origin;
|
|
142
|
+
} catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The value a bound field shows (W-307), after every check render applies, or undefined when
|
|
149
|
+
* the typed value shows instead: nothing to read, a link or image the sanitizer refuses, or a
|
|
150
|
+
* URL-parameter link or image to another site without "Allow outside sites".
|
|
151
|
+
*/
|
|
152
|
+
export function boundValue(
|
|
153
|
+
field: BindableField,
|
|
154
|
+
binding: Binding,
|
|
155
|
+
data: BindingData,
|
|
156
|
+
multiline = false,
|
|
157
|
+
): string | undefined {
|
|
158
|
+
let value = resolveBinding(binding, data);
|
|
159
|
+
if (value === undefined) return undefined;
|
|
160
|
+
if (!multiline) value = value.replace(/\s*\n\s*/g, " ");
|
|
161
|
+
if (field.kind === "url" && !sanitizeHref(value)) return undefined;
|
|
162
|
+
if (field.kind === "image" && !sanitizeMediaUrl(value)) return undefined;
|
|
163
|
+
if (
|
|
164
|
+
field.kind !== "text" &&
|
|
165
|
+
binding.source === "param" &&
|
|
166
|
+
!binding.outside &&
|
|
167
|
+
!isSameSiteUrl(value, data.origin)
|
|
168
|
+
) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The node with its bound props replaced by live values (W-307). Unbindable keys, empty values and
|
|
176
|
+
* links or images the sanitizer would refuse leave the typed prop as it is, so a bad URL parameter
|
|
177
|
+
* can't blank a button or an image. A URL parameter can't send a link or image off the site unless
|
|
178
|
+
* the binding allows outside sites (see `boundValue`). A bound text field that is single-line stays single-line.
|
|
179
|
+
*/
|
|
180
|
+
export function applyBindings(node: LayoutNode, data: BindingData): LayoutNode {
|
|
181
|
+
const bind = node.bind;
|
|
182
|
+
if (!bind) return node;
|
|
183
|
+
let props: Record<string, unknown> | undefined;
|
|
184
|
+
for (const field of bindableFields(node.type)) {
|
|
185
|
+
const binding = Object.hasOwn(bind, field.key) ? bind[field.key] : undefined;
|
|
186
|
+
if (!binding) continue;
|
|
187
|
+
const value = boundValue(field, binding, data, field.kind === "text" && node.type === "text");
|
|
188
|
+
if (value === undefined) continue;
|
|
189
|
+
props ??= { ...(node.props as Record<string, unknown>) };
|
|
190
|
+
props[field.key] = value;
|
|
191
|
+
// A bound image is no longer the media library item it was picked from.
|
|
192
|
+
if (field.kind === "image") delete props["mediaId"];
|
|
193
|
+
}
|
|
194
|
+
return props ? ({ ...node, props } as LayoutNode) : node;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Sets or clears one binding, dropping `bind` once it is empty. */
|
|
198
|
+
export function withBinding(
|
|
199
|
+
node: LayoutNode,
|
|
200
|
+
key: string,
|
|
201
|
+
binding: Binding | undefined,
|
|
202
|
+
): LayoutNode {
|
|
203
|
+
const next: Record<string, Binding> = { ...node.bind };
|
|
204
|
+
if (binding) next[key] = binding;
|
|
205
|
+
else delete next[key];
|
|
206
|
+
const { bind: _old, ...rest } = node;
|
|
207
|
+
return (Object.keys(next).length > 0 ? { ...rest, bind: next } : rest) as LayoutNode;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Search parameters as a plain record, first value per name, with names and values capped. */
|
|
211
|
+
export function paramsFromSearch(search: URLSearchParams): Record<string, string> {
|
|
212
|
+
const params: Record<string, string> = {};
|
|
213
|
+
let count = 0;
|
|
214
|
+
for (const [name, value] of search) {
|
|
215
|
+
if (count >= 50) break;
|
|
216
|
+
if (!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name) || Object.hasOwn(params, name)) continue;
|
|
217
|
+
params[name] = value.slice(0, MAX_BOUND_LENGTH * 4);
|
|
218
|
+
count += 1;
|
|
219
|
+
}
|
|
220
|
+
return params;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Site settings as flat text for bindings (W-307): `title`, `tagline`, `url`, `social.github`… */
|
|
224
|
+
export function siteBindingValues(settings: unknown): Record<string, string> {
|
|
225
|
+
const out: Record<string, string> = {};
|
|
226
|
+
if (!settings || typeof settings !== "object") return out;
|
|
227
|
+
const add = (key: string, value: unknown) => {
|
|
228
|
+
if (typeof value === "string" && value.trim()) out[key] = value.trim();
|
|
229
|
+
else if (typeof value === "number" && Number.isFinite(value)) out[key] = String(value);
|
|
230
|
+
};
|
|
231
|
+
for (const [key, value] of Object.entries(settings as Record<string, unknown>)) {
|
|
232
|
+
if (key === "seo") continue;
|
|
233
|
+
if (value && typeof value === "object") {
|
|
234
|
+
if (key === "logo" || key === "favicon") {
|
|
235
|
+
const media = value as { src?: unknown; url?: unknown };
|
|
236
|
+
add(key, media.src ?? media.url);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
for (const [inner, innerValue] of Object.entries(value as Record<string, unknown>)) {
|
|
240
|
+
add(`${key}.${inner}`, innerValue);
|
|
241
|
+
}
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
add(key, value);
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Whether any node in the tree reads a source (hosts fetch site settings only when needed). */
|
|
250
|
+
export function layoutUsesSource(root: LayoutNode, source: BindSource): boolean {
|
|
251
|
+
const walk = (node: LayoutNode): boolean => {
|
|
252
|
+
if (node.bind && Object.values(node.bind).some((b) => b.source === source)) return true;
|
|
253
|
+
const children: unknown = (node as { children?: unknown }).children;
|
|
254
|
+
return Array.isArray(children) && (children as LayoutNode[]).some(walk);
|
|
255
|
+
};
|
|
256
|
+
return walk(root);
|
|
257
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { DesignSystem, FluidRange, LengthVariable } from "../schema/design.ts";
|
|
2
|
+
|
|
3
|
+
/** Screen widths fluid sizes grow between when the site sets none (W-316). */
|
|
4
|
+
export const DEFAULT_FLUID_RANGE: FluidRange = { minWidth: 360, maxWidth: 1280 };
|
|
5
|
+
|
|
6
|
+
const round = (n: number, places = 4) => Number(n.toFixed(places));
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `clamp()` growing from `min` px at the range's small screen to `max` px at its large one
|
|
10
|
+
* (W-316), in rem so it follows the visitor's font size. Equal sizes give a plain rem value.
|
|
11
|
+
*/
|
|
12
|
+
export function fluidClamp(
|
|
13
|
+
min: number,
|
|
14
|
+
max: number,
|
|
15
|
+
range: FluidRange = DEFAULT_FLUID_RANGE,
|
|
16
|
+
): string {
|
|
17
|
+
const lo = Math.min(min, max);
|
|
18
|
+
const hi = Math.max(min, max);
|
|
19
|
+
if (lo === hi || range.maxWidth <= range.minWidth) return `${round(max / 16)}rem`;
|
|
20
|
+
const slope = (max - min) / (range.maxWidth - range.minWidth);
|
|
21
|
+
const intercept = min - slope * range.minWidth;
|
|
22
|
+
return `clamp(${round(lo / 16)}rem, ${round(intercept / 16)}rem + ${round(slope * 100)}vw, ${round(hi / 16)}rem)`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Musical ratios type scales use, with their names (W-316). */
|
|
26
|
+
export const SCALE_RATIOS = [
|
|
27
|
+
{ value: 1.125, label: "Major second · 1.125" },
|
|
28
|
+
{ value: 1.2, label: "Minor third · 1.2" },
|
|
29
|
+
{ value: 1.25, label: "Major third · 1.25" },
|
|
30
|
+
{ value: 1.333, label: "Perfect fourth · 1.333" },
|
|
31
|
+
{ value: 1.4, label: "Augmented fourth · 1.4" },
|
|
32
|
+
{ value: 1.5, label: "Perfect fifth · 1.5" },
|
|
33
|
+
{ value: 1.618, label: "Golden ratio · 1.618" },
|
|
34
|
+
] as const;
|
|
35
|
+
|
|
36
|
+
export type ScaleInput = {
|
|
37
|
+
/** Body size on large screens, px. */
|
|
38
|
+
base: number;
|
|
39
|
+
ratio: number;
|
|
40
|
+
/** Body size on small screens, px; unset = not fluid. */
|
|
41
|
+
minBase?: number;
|
|
42
|
+
/** Ratio on small screens (usually smaller); unset = `ratio`. */
|
|
43
|
+
minRatio?: number;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const TYPE_STEPS = [
|
|
47
|
+
{ id: "fs-xs", name: "Text XS", step: -2 },
|
|
48
|
+
{ id: "fs-s", name: "Text S", step: -1 },
|
|
49
|
+
{ id: "fs-m", name: "Text M", step: 0 },
|
|
50
|
+
{ id: "fs-l", name: "Text L", step: 1 },
|
|
51
|
+
{ id: "fs-xl", name: "Heading S", step: 2 },
|
|
52
|
+
{ id: "fs-2xl", name: "Heading M", step: 3 },
|
|
53
|
+
{ id: "fs-3xl", name: "Heading L", step: 4 },
|
|
54
|
+
{ id: "fs-4xl", name: "Display", step: 5 },
|
|
55
|
+
] as const;
|
|
56
|
+
|
|
57
|
+
const SPACE_STEPS = [
|
|
58
|
+
{ id: "space-3xs", name: "Space 3XS", times: 0.25 },
|
|
59
|
+
{ id: "space-2xs", name: "Space 2XS", times: 0.5 },
|
|
60
|
+
{ id: "space-xs", name: "Space XS", times: 0.75 },
|
|
61
|
+
{ id: "space-s", name: "Space S", times: 1 },
|
|
62
|
+
{ id: "space-m", name: "Space M", times: 1.5 },
|
|
63
|
+
{ id: "space-l", name: "Space L", times: 2 },
|
|
64
|
+
{ id: "space-xl", name: "Space XL", times: 3 },
|
|
65
|
+
{ id: "space-2xl", name: "Space 2XL", times: 4 },
|
|
66
|
+
{ id: "space-3xl", name: "Space 3XL", times: 6 },
|
|
67
|
+
] as const;
|
|
68
|
+
|
|
69
|
+
const valid = (n: number | undefined, lo: number, hi: number): n is number =>
|
|
70
|
+
typeof n === "number" && Number.isFinite(n) && n >= lo && n <= hi;
|
|
71
|
+
|
|
72
|
+
function token(id: string, name: string, max: number, min: number | undefined): LengthVariable {
|
|
73
|
+
const big = round(Math.min(1000, max), 2);
|
|
74
|
+
return {
|
|
75
|
+
id,
|
|
76
|
+
name,
|
|
77
|
+
value: { value: big, unit: "px" },
|
|
78
|
+
...(min !== undefined && round(min, 2) !== big
|
|
79
|
+
? { fluid: { min: round(Math.min(1000, min), 2), max: big } }
|
|
80
|
+
: {}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A type scale from a base size and a ratio (W-316): eight sizes from Text XS to Display. With a
|
|
86
|
+
* small-screen base (and ratio), each size is fluid between the two.
|
|
87
|
+
*/
|
|
88
|
+
export function typeScale(input: ScaleInput): LengthVariable[] {
|
|
89
|
+
if (!valid(input.base, 8, 64) || !valid(input.ratio, 1.01, 2)) return [];
|
|
90
|
+
const minBase = valid(input.minBase, 8, 64) ? input.minBase : undefined;
|
|
91
|
+
const minRatio = valid(input.minRatio, 1.01, 2) ? input.minRatio : input.ratio;
|
|
92
|
+
return TYPE_STEPS.map(({ id, name, step }) =>
|
|
93
|
+
token(
|
|
94
|
+
id,
|
|
95
|
+
name,
|
|
96
|
+
input.base * input.ratio ** step,
|
|
97
|
+
minBase === undefined ? undefined : minBase * minRatio ** step,
|
|
98
|
+
),
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A spacing scale from one base gap (W-316): nine steps from 3XS to 3XL; fluid like type. */
|
|
103
|
+
export function spaceScale(input: { base: number; minBase?: number }): LengthVariable[] {
|
|
104
|
+
if (!valid(input.base, 2, 64)) return [];
|
|
105
|
+
const minBase = valid(input.minBase, 2, 64) ? input.minBase : undefined;
|
|
106
|
+
return SPACE_STEPS.map(({ id, name, times }) =>
|
|
107
|
+
token(id, name, input.base * times, minBase === undefined ? undefined : minBase * times),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Adds generated tokens to the site's font sizes or spacing (W-316). A token whose id exists
|
|
113
|
+
* replaces it in place, so elements using it pick up the new size; others are appended.
|
|
114
|
+
*/
|
|
115
|
+
export function applyTokens(
|
|
116
|
+
design: DesignSystem,
|
|
117
|
+
list: "fontSizes" | "spacings",
|
|
118
|
+
tokens: LengthVariable[],
|
|
119
|
+
): DesignSystem {
|
|
120
|
+
const current = design.variables[list] ?? [];
|
|
121
|
+
const byId = new Map(tokens.map((t) => [t.id, t]));
|
|
122
|
+
const replaced = current.map((v) => byId.get(v.id) ?? v);
|
|
123
|
+
const have = new Set(current.map((v) => v.id));
|
|
124
|
+
const limit = list === "fontSizes" ? 50 : 100;
|
|
125
|
+
const added = tokens.filter((t) => !have.has(t.id)).slice(0, Math.max(0, limit - current.length));
|
|
126
|
+
return { ...design, variables: { ...design.variables, [list]: [...replaced, ...added] } };
|
|
127
|
+
}
|