@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,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
|
+
}
|
package/src/constants.ts
CHANGED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import type { DesignSystem } from "../schema/design.ts";
|
|
2
|
+
import { isParentNode, type Layout, type LayoutNode } from "../schema/layout.ts";
|
|
3
|
+
import { updateNode } from "../tree-ops.ts";
|
|
4
|
+
|
|
5
|
+
export type A11yFix =
|
|
6
|
+
| { kind: "heading-level"; level: number }
|
|
7
|
+
| { kind: "decorative" }
|
|
8
|
+
| { kind: "text-color"; color: string }
|
|
9
|
+
| { kind: "drop-aria-hidden" };
|
|
10
|
+
|
|
11
|
+
export type A11yIssue = {
|
|
12
|
+
/** Stable per node and rule, for React keys and tests. */
|
|
13
|
+
id: string;
|
|
14
|
+
nodeId: string;
|
|
15
|
+
rule:
|
|
16
|
+
| "image-alt"
|
|
17
|
+
| "heading-order"
|
|
18
|
+
| "multiple-h1"
|
|
19
|
+
| "no-h1"
|
|
20
|
+
| "link-name"
|
|
21
|
+
| "vague-link"
|
|
22
|
+
| "contrast"
|
|
23
|
+
| "hidden-focusable"
|
|
24
|
+
| "new-tab";
|
|
25
|
+
severity: "error" | "warning";
|
|
26
|
+
message: string;
|
|
27
|
+
/** The one-click fix, when there is a safe one. */
|
|
28
|
+
fix?: A11yFix;
|
|
29
|
+
fixLabel?: string;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type A11yReport = { score: number; issues: A11yIssue[] };
|
|
33
|
+
|
|
34
|
+
const WEIGHT = { error: 12, warning: 4 } as const;
|
|
35
|
+
|
|
36
|
+
/** Alt text that names a file or says nothing a screen reader user can use. */
|
|
37
|
+
const USELESS_ALT =
|
|
38
|
+
/^(?:image|img|photo|picture|graphic|logo|icon|untitled|\s*)$|\.(?:jpe?g|png|gif|webp|avif|svg)$|^(?:img|dsc|pxl|screenshot)[_-]?\d+/i;
|
|
39
|
+
/** Link text that makes no sense out of context. */
|
|
40
|
+
const VAGUE = /^(?:click here|here|read more|more|learn more|link|this|go)\.?$/i;
|
|
41
|
+
const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
42
|
+
|
|
43
|
+
/** A style colour as hex: literal, or a site colour variable; undefined when unknown. */
|
|
44
|
+
function hexOf(value: unknown, design: DesignSystem): string | undefined {
|
|
45
|
+
if (typeof value === "string" && HEX.test(value)) return value;
|
|
46
|
+
if (value && typeof value === "object" && "var" in value) {
|
|
47
|
+
const id = (value as { var: unknown }).var;
|
|
48
|
+
return design.variables.colors.find((c) => c.id === id)?.value;
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function rgb(hex: string): [number, number, number] {
|
|
54
|
+
let h = hex.slice(1);
|
|
55
|
+
if (h.length <= 4) h = [...h].map((c) => c + c).join("");
|
|
56
|
+
return [0, 2, 4].map((i) => Number.parseInt(h.slice(i, i + 2), 16)) as [number, number, number];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const channel = (c: number) => {
|
|
60
|
+
const s = c / 255;
|
|
61
|
+
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const lum = (hex: string) => {
|
|
65
|
+
const [r, g, bl] = rgb(hex).map(channel) as [number, number, number];
|
|
66
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** WCAG contrast ratio between two hex colours, 1–21. */
|
|
70
|
+
export function contrastRatio(a: string, b: string): number {
|
|
71
|
+
const [hi, lo] = [lum(a), lum(b)].toSorted((x, y) => y - x) as [number, number];
|
|
72
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const TEXT_TYPES = new Set([
|
|
76
|
+
"heading",
|
|
77
|
+
"text",
|
|
78
|
+
"link",
|
|
79
|
+
"label",
|
|
80
|
+
"list",
|
|
81
|
+
"post-title",
|
|
82
|
+
"post-excerpt",
|
|
83
|
+
]);
|
|
84
|
+
const LINKISH = new Set(["link", "button", "menu-item"]);
|
|
85
|
+
|
|
86
|
+
function px(value: unknown): number | undefined {
|
|
87
|
+
if (!value || typeof value !== "object" || !("unit" in value)) return undefined;
|
|
88
|
+
const v = value as { value: number; unit: string };
|
|
89
|
+
if (v.unit === "px") return v.value;
|
|
90
|
+
if (v.unit === "rem" || v.unit === "em") return v.value * 16;
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Large text (24 px, or 18.66 px bold) needs 3:1; other text 4.5:1. */
|
|
95
|
+
function largeText(node: LayoutNode): boolean {
|
|
96
|
+
const style = node.style as { fontSize?: unknown; fontWeight?: unknown } | undefined;
|
|
97
|
+
const size = px(style?.fontSize) ?? (node.type === "heading" ? 24 : 16);
|
|
98
|
+
const weight =
|
|
99
|
+
typeof style?.fontWeight === "number" ? style.fontWeight : node.type === "heading" ? 700 : 400;
|
|
100
|
+
return size >= 24 || (size >= 18.66 && weight >= 700);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Checks a page for common accessibility problems (W-317): image alt text, heading order and
|
|
105
|
+
* the single H1, link names, vague link text, text contrast against its background, focusable
|
|
106
|
+
* elements hidden with aria-hidden, and unannounced new tabs. Each issue points at an element; most have a safe fix.
|
|
107
|
+
*/
|
|
108
|
+
export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
|
|
109
|
+
const issues: A11yIssue[] = [];
|
|
110
|
+
const add = (issue: Omit<A11yIssue, "id">) =>
|
|
111
|
+
issues.push({ ...issue, id: `${issue.rule}:${issue.nodeId}` });
|
|
112
|
+
let lastLevel = 0;
|
|
113
|
+
let h1s = 0;
|
|
114
|
+
// W-312 variants are alternatives: B is judged as if it stood where A does, so a page whose
|
|
115
|
+
// A/B pair each have an H1 doesn't count two.
|
|
116
|
+
const beforeA = new Map<string, [number, number]>();
|
|
117
|
+
const afterA = new Map<string, [number, number]>();
|
|
118
|
+
const walk = (node: LayoutNode, bg: string | undefined, color: string | undefined): void => {
|
|
119
|
+
const variant = node.variant;
|
|
120
|
+
if (variant?.arm === "a") beforeA.set(variant.test, [h1s, lastLevel]);
|
|
121
|
+
const before = variant?.arm === "b" ? beforeA.get(variant.test) : undefined;
|
|
122
|
+
if (before) [h1s, lastLevel] = before;
|
|
123
|
+
visitNode(node, bg, color);
|
|
124
|
+
if (variant?.arm === "a") afterA.set(variant.test, [h1s, lastLevel]);
|
|
125
|
+
const after = variant?.arm === "b" ? afterA.get(variant.test) : undefined;
|
|
126
|
+
if (after) [h1s, lastLevel] = after;
|
|
127
|
+
};
|
|
128
|
+
const visitNode = (node: LayoutNode, bg: string | undefined, color: string | undefined): void => {
|
|
129
|
+
const props = node.props as Record<string, unknown>;
|
|
130
|
+
const style = node.style as
|
|
131
|
+
| { backgroundColor?: unknown; color?: unknown; backgroundImage?: unknown }
|
|
132
|
+
| undefined;
|
|
133
|
+
// A background image hides the colour behind the text: contrast can't be judged below it.
|
|
134
|
+
const ownBg = style?.backgroundImage ? "unknown" : hexOf(style?.backgroundColor, design);
|
|
135
|
+
const nextBg = ownBg ?? bg;
|
|
136
|
+
const nextColor = hexOf(style?.color, design) ?? color;
|
|
137
|
+
if (node.type === "image" && props["decorative"] !== true) {
|
|
138
|
+
const alt = typeof props["alt"] === "string" ? props["alt"].trim() : "";
|
|
139
|
+
if (USELESS_ALT.test(alt)) {
|
|
140
|
+
add({
|
|
141
|
+
nodeId: node.id,
|
|
142
|
+
rule: "image-alt",
|
|
143
|
+
severity: "error",
|
|
144
|
+
message: alt
|
|
145
|
+
? `The alt text "${alt.slice(0, 40)}" doesn't describe the image.`
|
|
146
|
+
: "This image has no alt text.",
|
|
147
|
+
fix: { kind: "decorative" },
|
|
148
|
+
fixLabel: "Mark as decorative",
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (node.type === "heading") {
|
|
153
|
+
const level = typeof props["level"] === "number" ? props["level"] : 2;
|
|
154
|
+
if (level === 1) {
|
|
155
|
+
h1s += 1;
|
|
156
|
+
if (h1s > 1) {
|
|
157
|
+
add({
|
|
158
|
+
nodeId: node.id,
|
|
159
|
+
rule: "multiple-h1",
|
|
160
|
+
severity: "warning",
|
|
161
|
+
message: "The page already has an H1; screen readers use it as the page title.",
|
|
162
|
+
fix: { kind: "heading-level", level: 2 },
|
|
163
|
+
fixLabel: "Make it H2",
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
} else if (level > Math.max(lastLevel, 1) + 1) {
|
|
167
|
+
// The site layout may give the page its H1, so an H2 may come first.
|
|
168
|
+
const to = Math.max(2, lastLevel + 1);
|
|
169
|
+
add({
|
|
170
|
+
nodeId: node.id,
|
|
171
|
+
rule: "heading-order",
|
|
172
|
+
severity: "warning",
|
|
173
|
+
message: `This H${level} skips a level after ${lastLevel ? `an H${lastLevel}` : "the page start"}.`,
|
|
174
|
+
fix: { kind: "heading-level", level: to },
|
|
175
|
+
fixLabel: `Make it H${to}`,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
lastLevel = level;
|
|
179
|
+
}
|
|
180
|
+
if (LINKISH.has(node.type) || (node.type === "icon" && props["href"])) {
|
|
181
|
+
const text = String(props["text"] ?? props["title"] ?? "").trim();
|
|
182
|
+
const hasHref = typeof props["href"] === "string" && props["href"].trim() !== "";
|
|
183
|
+
if (!text && !node.bind) {
|
|
184
|
+
add({
|
|
185
|
+
nodeId: node.id,
|
|
186
|
+
rule: "link-name",
|
|
187
|
+
severity: "error",
|
|
188
|
+
message:
|
|
189
|
+
node.type === "icon"
|
|
190
|
+
? "This icon link has no title, so it has no name."
|
|
191
|
+
: "This link has no text.",
|
|
192
|
+
});
|
|
193
|
+
} else if (hasHref && VAGUE.test(text)) {
|
|
194
|
+
add({
|
|
195
|
+
nodeId: node.id,
|
|
196
|
+
rule: "vague-link",
|
|
197
|
+
severity: "warning",
|
|
198
|
+
message: `"${text}" doesn't say where the link goes; screen reader users often list links alone.`,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
if (hasHref && props["newTab"] === true && !/new (tab|window)/i.test(text)) {
|
|
202
|
+
add({
|
|
203
|
+
nodeId: node.id,
|
|
204
|
+
rule: "new-tab",
|
|
205
|
+
severity: "warning",
|
|
206
|
+
message: "This link opens a new tab without saying so; add “(opens in a new tab)”.",
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (TEXT_TYPES.has(node.type) && nextColor && nextBg && nextBg !== "unknown") {
|
|
211
|
+
const ratio = contrastRatio(nextColor, nextBg);
|
|
212
|
+
const needed = largeText(node) ? 3 : 4.5;
|
|
213
|
+
if (ratio < needed) {
|
|
214
|
+
const black = contrastRatio("#000000", nextBg);
|
|
215
|
+
const white = contrastRatio("#ffffff", nextBg);
|
|
216
|
+
const better = black >= white ? "#111111" : "#ffffff";
|
|
217
|
+
add({
|
|
218
|
+
nodeId: node.id,
|
|
219
|
+
rule: "contrast",
|
|
220
|
+
severity: "error",
|
|
221
|
+
message: `Text contrast is ${ratio.toFixed(1)}:1; it needs ${needed}:1.`,
|
|
222
|
+
fix: { kind: "text-color", color: better },
|
|
223
|
+
fixLabel: better === "#ffffff" ? "Use white text" : "Use dark text",
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const focusable =
|
|
228
|
+
LINKISH.has(node.type) || node.type === "text-input" || Boolean(props["href"]);
|
|
229
|
+
if (
|
|
230
|
+
focusable &&
|
|
231
|
+
(node.attributes ?? []).some((a) => a.name === "aria-hidden" && a.value === "true")
|
|
232
|
+
) {
|
|
233
|
+
add({
|
|
234
|
+
nodeId: node.id,
|
|
235
|
+
rule: "hidden-focusable",
|
|
236
|
+
severity: "error",
|
|
237
|
+
message: "aria-hidden hides this from screen readers, but the keyboard still reaches it.",
|
|
238
|
+
fix: { kind: "drop-aria-hidden" },
|
|
239
|
+
fixLabel: "Remove aria-hidden",
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
if (isParentNode(node)) for (const child of node.children) walk(child, nextBg, nextColor);
|
|
243
|
+
};
|
|
244
|
+
walk(layout.root, undefined, undefined);
|
|
245
|
+
if (h1s === 0 && layout.root.children.length > 0) {
|
|
246
|
+
issues.unshift({
|
|
247
|
+
id: `no-h1:${layout.root.id}`,
|
|
248
|
+
nodeId: layout.root.id,
|
|
249
|
+
rule: "no-h1",
|
|
250
|
+
severity: "warning",
|
|
251
|
+
message: "The page has no H1. Pages that use the site layout may get one from it.",
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const penalty = issues.reduce((sum, issue) => sum + WEIGHT[issue.severity], 0);
|
|
255
|
+
return { score: Math.max(0, 100 - penalty), issues };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Applies one issue's fix (W-317). Unchanged when the issue has none. */
|
|
259
|
+
export function applyA11yFix(layout: Layout, issue: A11yIssue): Layout {
|
|
260
|
+
const fix = issue.fix;
|
|
261
|
+
if (!fix) return layout;
|
|
262
|
+
return updateNode(layout, issue.nodeId, (node) => {
|
|
263
|
+
switch (fix.kind) {
|
|
264
|
+
case "heading-level":
|
|
265
|
+
return { ...node, props: { ...node.props, level: fix.level } } as LayoutNode;
|
|
266
|
+
case "decorative":
|
|
267
|
+
return { ...node, props: { ...node.props, decorative: true } } as LayoutNode;
|
|
268
|
+
case "text-color":
|
|
269
|
+
return { ...node, style: { ...node.style, color: fix.color } } as LayoutNode;
|
|
270
|
+
case "drop-aria-hidden": {
|
|
271
|
+
const attributes = (node.attributes ?? []).filter((a) => a.name !== "aria-hidden");
|
|
272
|
+
const { attributes: _a, ...rest } = node;
|
|
273
|
+
return (attributes.length > 0 ? { ...rest, attributes } : rest) as LayoutNode;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Applies every issue's fix at once (W-317). */
|
|
280
|
+
export function applyAllA11yFixes(layout: Layout, issues: A11yIssue[]): Layout {
|
|
281
|
+
return issues.reduce((next, issue) => applyA11yFix(next, issue), layout);
|
|
282
|
+
}
|
package/src/core/arrange.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
nodeChildren,
|
|
20
20
|
removeNode,
|
|
21
21
|
starterLayout,
|
|
22
|
+
updateNode,
|
|
22
23
|
} from "./tree-ops.ts";
|
|
23
24
|
|
|
24
25
|
/** A refused operation, with the reason shown or announced to the user (R-003). */
|
|
@@ -63,6 +64,7 @@ export const REASONS = {
|
|
|
63
64
|
onlyAccordionItems: "An accordion can only hold accordion items.",
|
|
64
65
|
itemOutsideMenu: "Menu items can only go inside a Menu.",
|
|
65
66
|
onlyMenuItems: "A menu can only hold menu items.",
|
|
67
|
+
emptyOutsideLoop: "An Empty state can only go inside a Loop.",
|
|
66
68
|
} as const;
|
|
67
69
|
|
|
68
70
|
const refuse = (reason: string): Refusal => ({ ok: false, reason });
|
|
@@ -120,6 +122,10 @@ type Drop = { layout: Layout; node: LayoutNode; into: Located; isNew: boolean };
|
|
|
120
122
|
|
|
121
123
|
/** Placement rules in the order their reasons take precedence (R-003, W-034, W-074). */
|
|
122
124
|
const DROP_RULES: [breaks: (drop: Drop) => boolean, reason: string][] = [
|
|
125
|
+
[
|
|
126
|
+
({ node, into }) => node.type === "loop-empty" && into.node.type !== "loop",
|
|
127
|
+
REASONS.emptyOutsideLoop,
|
|
128
|
+
],
|
|
123
129
|
[
|
|
124
130
|
({ node, into }) => node.type === "tab-panel" && into.node.type !== "tabs",
|
|
125
131
|
REASONS.tabOutsideTabs,
|
|
@@ -349,6 +355,29 @@ export function addNodeNear(
|
|
|
349
355
|
return tried;
|
|
350
356
|
}
|
|
351
357
|
|
|
358
|
+
/**
|
|
359
|
+
* Adds a whole section (a W-320 recipe): right after the outermost Section the selection is in,
|
|
360
|
+
* so it never lands inside another Section; with no Section around the selection, like `addNodeNear`.
|
|
361
|
+
*/
|
|
362
|
+
export function addSectionNear(
|
|
363
|
+
layout: Layout,
|
|
364
|
+
node: LayoutNode,
|
|
365
|
+
selectedId: string | null,
|
|
366
|
+
): Added | Refusal {
|
|
367
|
+
let outer: Located | undefined;
|
|
368
|
+
for (let at = selectedId ? locate(layout, selectedId) : undefined; at;) {
|
|
369
|
+
if (at.node.type === "layout-section") outer = at;
|
|
370
|
+
at = at.parent ? locate(layout, at.parent.id) : undefined;
|
|
371
|
+
}
|
|
372
|
+
const at = outer;
|
|
373
|
+
if (at?.parent) {
|
|
374
|
+
const place = { parentId: at.parent.id, index: at.index + 1 };
|
|
375
|
+
const added = addNode(layout, node, place);
|
|
376
|
+
if (added.ok) return { ...added, parentId: place.parentId };
|
|
377
|
+
}
|
|
378
|
+
return addNodeNear(layout, node, selectedId);
|
|
379
|
+
}
|
|
380
|
+
|
|
352
381
|
type Child = Located & { parent: NonNullable<Located["parent"]> };
|
|
353
382
|
|
|
354
383
|
/** Moves a non-root element to where `place` says, or returns the first refusal. */
|
|
@@ -446,3 +475,65 @@ export function subtreeSize(layout: Layout, id: string): number {
|
|
|
446
475
|
const node = findNode(layout, id);
|
|
447
476
|
return node ? size(node) : 0;
|
|
448
477
|
}
|
|
478
|
+
|
|
479
|
+
/** The default A/B test name for an element (W-312): `test-` and its id, lowercased. */
|
|
480
|
+
export const defaultTestName = (id: string): string =>
|
|
481
|
+
`test-${
|
|
482
|
+
id
|
|
483
|
+
.toLowerCase()
|
|
484
|
+
.replace(/[^a-z0-9]/g, "")
|
|
485
|
+
.slice(0, 12) || "1"
|
|
486
|
+
}`;
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Edge A/B testing (W-312): the element becomes arm A of a new test and a copy right after it
|
|
490
|
+
* becomes arm B (selected, ready to edit). Visitors see one or the other, picked on the server.
|
|
491
|
+
*/
|
|
492
|
+
export function createVariantB(
|
|
493
|
+
layout: Layout,
|
|
494
|
+
id: string,
|
|
495
|
+
random: () => number = Math.random,
|
|
496
|
+
): Arranged {
|
|
497
|
+
const found = locate(layout, id);
|
|
498
|
+
if (!found) return refuse(REASONS.missing);
|
|
499
|
+
if (found.node.variant) return refuse("This element is already in an A/B test.");
|
|
500
|
+
if (found.node.type === "loop-empty" || !found.parent) return refuse(REASONS.rootCopy);
|
|
501
|
+
const variant = { test: defaultTestName(found.node.id), arm: "a" as const };
|
|
502
|
+
const marked = updateNode(layout, id, (node) => ({ ...node, variant }) as LayoutNode);
|
|
503
|
+
const copied = duplicateNode(marked, id, random);
|
|
504
|
+
if (!copied.ok) return copied;
|
|
505
|
+
return {
|
|
506
|
+
...copied,
|
|
507
|
+
layout: updateNode(
|
|
508
|
+
copied.layout,
|
|
509
|
+
copied.selected,
|
|
510
|
+
(node) =>
|
|
511
|
+
({
|
|
512
|
+
...node,
|
|
513
|
+
variant: { ...variant, arm: "b" },
|
|
514
|
+
}) as LayoutNode,
|
|
515
|
+
),
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Ends an A/B test (W-312): `keepId` stays, without its variant mark, and every other element of
|
|
521
|
+
* that test is removed.
|
|
522
|
+
*/
|
|
523
|
+
export function endAbTest(layout: Layout, keepId: string): Arranged {
|
|
524
|
+
const kept = locate(layout, keepId);
|
|
525
|
+
const test = kept?.node.variant?.test;
|
|
526
|
+
if (!kept || !test) return refuse(REASONS.missing);
|
|
527
|
+
const others: string[] = [];
|
|
528
|
+
const walk = (node: LayoutNode): void => {
|
|
529
|
+
if (node.id !== keepId && node.variant?.test === test) others.push(node.id);
|
|
530
|
+
else for (const child of nodeChildren(node)) walk(child);
|
|
531
|
+
};
|
|
532
|
+
walk(layout.root);
|
|
533
|
+
let next = updateNode(layout, keepId, (node) => {
|
|
534
|
+
const { variant: _variant, ...rest } = node;
|
|
535
|
+
return rest as LayoutNode;
|
|
536
|
+
});
|
|
537
|
+
for (const id of others) next = removeNode(next, id).layout;
|
|
538
|
+
return { ok: true, layout: next, selected: keepId };
|
|
539
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isParentNode, type Audience, type Layout, type LayoutNode } from "../schema/layout.ts";
|
|
2
|
+
|
|
3
|
+
/** What the host knows about this visitor (W-313). Anything unknown is left out. */
|
|
4
|
+
export type VisitorInfo = {
|
|
5
|
+
/** ISO 3166 two-letter code, uppercase. */
|
|
6
|
+
country?: string;
|
|
7
|
+
device?: "mobile" | "tablet" | "desktop";
|
|
8
|
+
returning?: boolean;
|
|
9
|
+
/** The request time, epoch ms. */
|
|
10
|
+
now?: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
14
|
+
|
|
15
|
+
/** Hour (0–23) and weekday (0 = Sunday) at `now` in a time zone; UTC when the zone is unknown. */
|
|
16
|
+
export function clockIn(now: number, timeZone: string | undefined): { hour: number; day: number } {
|
|
17
|
+
const read = (zone: string) => {
|
|
18
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
19
|
+
timeZone: zone,
|
|
20
|
+
hour: "numeric",
|
|
21
|
+
hourCycle: "h23",
|
|
22
|
+
weekday: "short",
|
|
23
|
+
}).formatToParts(new Date(now));
|
|
24
|
+
const hour = Number(parts.find((p) => p.type === "hour")?.value ?? "0") % 24;
|
|
25
|
+
const day = WEEKDAYS.indexOf(parts.find((p) => p.type === "weekday")?.value ?? "Sun");
|
|
26
|
+
return { hour, day: Math.max(0, day) };
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
return read(timeZone ?? "UTC");
|
|
30
|
+
} catch {
|
|
31
|
+
return read("UTC");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function inHours(hour: number, from: number, to: number): boolean {
|
|
36
|
+
if (from === to) return true;
|
|
37
|
+
return from < to ? hour >= from && hour < to : hour >= from || hour < to;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Whether a visitor matches every rule in the audience (W-313); unknown facts don't match. */
|
|
41
|
+
function matches(audience: Audience, visitor: VisitorInfo): boolean {
|
|
42
|
+
if (audience.countries && !(visitor.country && audience.countries.includes(visitor.country))) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
if (audience.devices && !(visitor.device && audience.devices.includes(visitor.device))) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
if (audience.visitor) {
|
|
49
|
+
if (visitor.returning === undefined) return false;
|
|
50
|
+
if ((audience.visitor === "returning") !== visitor.returning) return false;
|
|
51
|
+
}
|
|
52
|
+
if (audience.hours || audience.days) {
|
|
53
|
+
if (visitor.now === undefined) return false;
|
|
54
|
+
const { hour, day } = clockIn(visitor.now, audience.timeZone);
|
|
55
|
+
if (audience.hours && !inHours(hour, audience.hours.from, audience.hours.to)) return false;
|
|
56
|
+
if (audience.days && !audience.days.includes(day)) return false;
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Whether a node shows for this visitor (W-313). No audience = everyone. */
|
|
62
|
+
export function audienceShows(node: LayoutNode, visitor: VisitorInfo | undefined): boolean {
|
|
63
|
+
const audience = node.audience;
|
|
64
|
+
if (!audience) return true;
|
|
65
|
+
const match = matches(audience, visitor ?? {});
|
|
66
|
+
return audience.hide ? !match : match;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Does any element in the layout have an audience? Hosts then read the visitor (W-313). */
|
|
70
|
+
export function layoutUsesAudience(layout: Layout): boolean {
|
|
71
|
+
return hasAudience(layout.root);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const hasAudience = (node: LayoutNode): boolean =>
|
|
75
|
+
Boolean(node.audience) || (isParentNode(node) && node.children.some(hasAudience));
|
|
76
|
+
|
|
77
|
+
/** A device from a User-Agent and the Sec-CH-UA-Mobile hint (W-313). */
|
|
78
|
+
export function deviceFromUserAgent(
|
|
79
|
+
ua: string | null | undefined,
|
|
80
|
+
mobileHint?: string | null,
|
|
81
|
+
): VisitorInfo["device"] {
|
|
82
|
+
if (mobileHint === "?1") return "mobile";
|
|
83
|
+
if (!ua) return mobileHint === "?0" ? "desktop" : undefined;
|
|
84
|
+
if (/iPad|Tablet|PlayBook|Silk|Kindle|(Android(?!.*Mobile))/i.test(ua)) return "tablet";
|
|
85
|
+
if (/Mobi|iPhone|iPod|Android|Windows Phone|Opera Mini/i.test(ua)) return "mobile";
|
|
86
|
+
return "desktop";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const DEVICE_LABELS = { mobile: "mobile", tablet: "tablet", desktop: "desktop" } as const;
|
|
90
|
+
|
|
91
|
+
/** A short summary for the canvas and Layers, e.g. "CA, US · mobile · returning" (W-313). */
|
|
92
|
+
export function audienceSummary(audience: Audience): string {
|
|
93
|
+
const parts: string[] = [];
|
|
94
|
+
if (audience.countries)
|
|
95
|
+
parts.push(
|
|
96
|
+
audience.countries.slice(0, 3).join(", ") + (audience.countries.length > 3 ? "…" : ""),
|
|
97
|
+
);
|
|
98
|
+
if (audience.devices) parts.push(audience.devices.map((d) => DEVICE_LABELS[d]).join("/"));
|
|
99
|
+
if (audience.visitor) parts.push(audience.visitor === "new" ? "new visitors" : "returning");
|
|
100
|
+
if (audience.hours) parts.push(`${audience.hours.from}:00–${audience.hours.to}:00`);
|
|
101
|
+
if (audience.days) parts.push(audience.days.map((d) => WEEKDAYS[d]).join(" "));
|
|
102
|
+
const who = parts.join(" · ") || "everyone";
|
|
103
|
+
return audience.hide ? `Hidden for ${who}` : `Only ${who}`;
|
|
104
|
+
}
|