@perkyzz/emvb 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/package.json +3 -1
- package/src/admin/access/role.ts +9 -3
- package/src/admin/api.ts +17 -7
- package/src/admin/content-api.ts +7 -51
- package/src/admin/content-item.ts +22 -0
- package/src/admin/design-api.ts +30 -0
- package/src/admin/editor/A11yCopilot.tsx +126 -0
- package/src/admin/editor/CommandPalette.tsx +118 -0
- package/src/admin/editor/Editor.tsx +188 -152
- package/src/admin/editor/EditorOverlay.tsx +9 -1
- package/src/admin/editor/PerfMeter.tsx +121 -0
- package/src/admin/editor/ShareLink.tsx +164 -0
- package/src/admin/editor/ShortcutsDialog.tsx +4 -1
- package/src/admin/editor/Timeline.tsx +287 -0
- package/src/admin/editor/TopBar.tsx +4 -0
- package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
- package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
- package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
- package/src/admin/editor/canvas/canvas-scale.ts +20 -0
- package/src/admin/editor/canvas/drop-line.ts +24 -0
- package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
- package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
- package/src/admin/editor/collection-previews.ts +114 -0
- package/src/admin/editor/editor-chrome.tsx +346 -0
- package/src/admin/editor/editor-commands.ts +360 -0
- package/src/admin/editor/editor-css.ts +5 -3
- package/src/admin/editor/element-chrome.ts +89 -0
- package/src/admin/editor/feature-css.ts +105 -0
- package/src/admin/editor/host.ts +35 -0
- package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
- package/src/admin/editor/icons/library.ts +29 -19
- package/src/admin/editor/icons/use-icon-library.ts +315 -0
- package/src/admin/editor/live-data.tsx +71 -0
- package/src/admin/editor/palette-items.ts +136 -0
- package/src/admin/editor/palette.ts +68 -0
- package/src/admin/editor/panels/AddPanel.tsx +48 -68
- package/src/admin/editor/panels/ClassesSection.tsx +5 -1
- package/src/admin/editor/panels/ColorControl.tsx +2 -10
- package/src/admin/editor/panels/ElementPanel.tsx +74 -102
- package/src/admin/editor/panels/LayersPanel.tsx +72 -63
- package/src/admin/editor/panels/LeftPanel.tsx +4 -1
- package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
- package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
- package/src/admin/editor/panels/TokenScales.tsx +168 -0
- package/src/admin/editor/panels/VariableSection.tsx +10 -14
- package/src/admin/editor/panels/inline-error.tsx +11 -0
- package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
- package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -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/DraftTextField.tsx +4 -0
- package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
- package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
- package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
- 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 +26 -2
- 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/form-names.ts +7 -11
- package/src/admin/editor/panels/settings/length-units.ts +16 -5
- package/src/admin/editor/panels/settings/style-sections.ts +7 -2
- package/src/admin/editor/panels/style-target.ts +105 -0
- package/src/admin/editor/section-templates.ts +43 -21
- package/src/admin/editor/shortcuts.ts +6 -1
- package/src/admin/editor/store.ts +10 -1
- package/src/admin/editor/useClipboardActions.ts +1 -1
- package/src/admin/editor/useEditorCommands.ts +61 -13
- package/src/admin/editor/useEditorData.ts +7 -1
- package/src/admin/editor/useEditorShortcuts.ts +30 -14
- package/src/admin/editor/useNodeActions.ts +44 -16
- package/src/admin/forms-api.ts +17 -6
- package/src/admin/icon-uploads-api.ts +18 -0
- package/src/admin/theme-api.ts +5 -18
- package/src/admin/ui.ts +4 -4
- package/src/astro/content-port.ts +24 -0
- package/src/astro/forms/EmVBFormsClient.astro +11 -0
- package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
- package/src/astro/forms/client.ts +1 -0
- package/src/astro/forms-definitions.ts +24 -11
- package/src/astro/index.ts +1 -0
- package/src/astro/render-session.ts +85 -0
- package/src/astro/request-data.ts +109 -0
- package/src/astro/resolve-theme.ts +184 -64
- package/src/astro/resolve.ts +63 -16
- package/src/astro/theme-posts.ts +48 -5
- package/src/astro/visitor.ts +204 -0
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +282 -0
- package/src/core/arrange.ts +150 -34
- package/src/core/audience/rules.ts +124 -0
- package/src/core/audience/variants.ts +51 -0
- package/src/core/canvas-styles.ts +24 -0
- package/src/core/clipboard.ts +11 -32
- package/src/core/css/generate.ts +29 -2
- package/src/core/css/print.ts +12 -0
- package/src/core/css/scope.ts +3 -3
- package/src/core/css/trace.ts +169 -0
- package/src/core/css-keywords.ts +83 -0
- package/src/core/data/bindings.ts +255 -0
- package/src/core/design/classes.ts +13 -15
- package/src/core/design/diff.ts +55 -0
- package/src/core/design/merge.ts +127 -0
- package/src/core/design/tokens.ts +127 -0
- package/src/core/design/variables.ts +25 -21
- package/src/core/elements/dynamic-elements.ts +117 -2
- package/src/core/elements/form-elements.ts +1 -0
- package/src/core/elements/index.ts +185 -7
- package/src/core/forms/binding.ts +4 -13
- package/src/core/history/diff.ts +152 -0
- package/src/core/index.ts +121 -0
- package/src/core/local-style.ts +27 -0
- package/src/core/migrate/index.ts +12 -4
- package/src/core/nesting.ts +4 -22
- package/src/core/perf/meter.ts +160 -0
- package/src/core/perf/scripts.ts +61 -0
- package/src/core/recipes/index.ts +433 -0
- package/src/core/record.ts +3 -0
- package/src/core/render/context.ts +2 -0
- package/src/core/render/dynamic-post.ts +1 -2
- package/src/core/render/form.ts +133 -10
- package/src/core/render/index.ts +206 -17
- package/src/core/render/loop.ts +54 -7
- package/src/core/render/pagination.ts +9 -1
- package/src/core/render/vnode.ts +12 -2
- package/src/core/sanitize/css.ts +129 -80
- package/src/core/sanitize/motion.ts +129 -0
- package/src/core/sanitize/svg.ts +8 -3
- package/src/core/sanitize/url.ts +10 -1
- package/src/core/schema/design.ts +29 -8
- package/src/core/schema/layout.ts +291 -169
- package/src/core/schema/motion.ts +14 -0
- package/src/core/schema/style.ts +101 -66
- package/src/core/share/link.ts +187 -0
- package/src/core/tabs/presence.ts +7 -17
- package/src/core/theme/dynamic.ts +242 -32
- package/src/core/theme/float.ts +1 -1
- package/src/core/theme/pagination.ts +56 -0
- package/src/core/tree-ops.ts +57 -0
- package/src/index.ts +14 -2
- package/src/server/design-routes.ts +4 -1
- package/src/server/icon-routes.ts +68 -16
- package/src/server/plugin.ts +8 -2
- package/src/admin/editor/icons/sets/fontawesome.json +0 -1
- package/src/admin/editor/icons/sets/lucide.json +0 -1
- package/src/admin/editor/icons/sets/remix.json +0 -1
- package/src/admin/editor/icons/sets/tabler.json +0 -1
package/src/astro/theme-posts.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { loopPermalink, type ThemePostFields } from "../core/index.ts";
|
|
2
2
|
|
|
3
3
|
type MediaLike = {
|
|
4
4
|
src?: unknown;
|
|
@@ -42,7 +42,15 @@ export function entryTimestamp(value: unknown): string | undefined {
|
|
|
42
42
|
*/
|
|
43
43
|
export function themePostFromEntry(
|
|
44
44
|
entry: { id?: string; data?: Record<string, unknown> } | Record<string, unknown>,
|
|
45
|
-
options: {
|
|
45
|
+
options: {
|
|
46
|
+
permalinkPrefix?: string;
|
|
47
|
+
/** W-330: a Loop's link pattern, e.g. `/team/{slug}`. */
|
|
48
|
+
permalinkPattern?: string;
|
|
49
|
+
/** W-330: the field with the entry's image, instead of `featured_image`. */
|
|
50
|
+
imageField?: string;
|
|
51
|
+
/** W-330: the field with the entry's excerpt, instead of `excerpt`. */
|
|
52
|
+
excerptField?: string;
|
|
53
|
+
} = {},
|
|
46
54
|
): ThemePostFields | null {
|
|
47
55
|
const data =
|
|
48
56
|
"data" in entry && entry.data && typeof entry.data === "object"
|
|
@@ -52,16 +60,20 @@ export function themePostFromEntry(
|
|
|
52
60
|
const slug = typeof data["slug"] === "string" ? data["slug"] : id;
|
|
53
61
|
if (!slug && !id) return null;
|
|
54
62
|
const title = typeof data["title"] === "string" ? data["title"] : "";
|
|
55
|
-
const
|
|
63
|
+
const excerptValue = data[options.excerptField ?? "excerpt"];
|
|
64
|
+
const excerpt = typeof excerptValue === "string" ? excerptValue : "";
|
|
56
65
|
const content = data["content"] ?? "";
|
|
57
66
|
const prefix = options.permalinkPrefix ?? "/posts";
|
|
58
|
-
const permalink =
|
|
59
|
-
|
|
67
|
+
const permalink = options.permalinkPattern
|
|
68
|
+
? loopPermalink(options.permalinkPattern, { slug: slug || id, id: id || slug })
|
|
69
|
+
: `${prefix.replace(/\/$/, "")}/${slug || id}`;
|
|
70
|
+
const media = mediaFieldsFrom(data[options.imageField ?? "featured_image"]);
|
|
60
71
|
// W-303: EmDash's own publish date is `data.publishedAt`, a `Date`; a custom field may be text.
|
|
61
72
|
const publishedAt = ["published_at", "publishedAt", "date"]
|
|
62
73
|
.map((key) => entryTimestamp(data[key]))
|
|
63
74
|
.find(Boolean);
|
|
64
75
|
const authorName = authorFrom(data);
|
|
76
|
+
const fields = plainFieldsOf(data);
|
|
65
77
|
return {
|
|
66
78
|
id: id || slug,
|
|
67
79
|
slug: slug || id,
|
|
@@ -72,9 +84,40 @@ export function themePostFromEntry(
|
|
|
72
84
|
...(publishedAt ? { publishedAt } : {}),
|
|
73
85
|
...(authorName ? { authorName } : {}),
|
|
74
86
|
...media,
|
|
87
|
+
...(Object.keys(fields).length > 0 ? { fields } : {}),
|
|
75
88
|
};
|
|
76
89
|
}
|
|
77
90
|
|
|
91
|
+
/** Field names a binding may read; EmDash's internal fields are left out. */
|
|
92
|
+
const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;
|
|
93
|
+
/** Already on ThemePostFields under their own names. */
|
|
94
|
+
const MAPPED = new Set(["id", "slug", "title", "excerpt", "content"]);
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The entry's plain fields for data bindings (W-307): text, numbers, true/false, and an image
|
|
98
|
+
* field's URL. Rich text and other objects are left out; at most 100 fields, text cut at 2000.
|
|
99
|
+
*/
|
|
100
|
+
export function plainFieldsOf(
|
|
101
|
+
data: Record<string, unknown>,
|
|
102
|
+
): Record<string, string | number | boolean> {
|
|
103
|
+
const fields: Record<string, string | number | boolean> = {};
|
|
104
|
+
for (const [key, value] of Object.entries(data)) {
|
|
105
|
+
if (Object.keys(fields).length >= 100) break;
|
|
106
|
+
if (!FIELD_NAME.test(key) || MAPPED.has(key)) continue;
|
|
107
|
+
if (typeof value === "string") fields[key] = value.slice(0, 2000);
|
|
108
|
+
else if (typeof value === "number" && Number.isFinite(value)) fields[key] = value;
|
|
109
|
+
else if (typeof value === "boolean") fields[key] = value;
|
|
110
|
+
else if (value instanceof Date) {
|
|
111
|
+
const iso = entryTimestamp(value);
|
|
112
|
+
if (iso) fields[key] = iso;
|
|
113
|
+
} else if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
114
|
+
const url = mediaFieldsFrom(value).featuredImageUrl;
|
|
115
|
+
if (url) fields[key] = url;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return fields;
|
|
119
|
+
}
|
|
120
|
+
|
|
78
121
|
function firstString(data: Record<string, unknown>, keys: string[]): string | undefined {
|
|
79
122
|
for (const key of keys) {
|
|
80
123
|
const value = data[key];
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AUDIENCE_SEGMENT,
|
|
3
|
+
abCookieName,
|
|
4
|
+
collectAbTests,
|
|
5
|
+
deviceFromUserAgent,
|
|
6
|
+
layoutUsesAudience,
|
|
7
|
+
layoutUsesVisitorRule,
|
|
8
|
+
pickArm,
|
|
9
|
+
type AbArm,
|
|
10
|
+
type Layout,
|
|
11
|
+
type VisitorInfo,
|
|
12
|
+
} from "../core/index.ts";
|
|
13
|
+
|
|
14
|
+
/** What EmVB reads from Astro to decide per-visitor content on the server (W-312, W-313). */
|
|
15
|
+
export type VisitorAstro = {
|
|
16
|
+
url: URL;
|
|
17
|
+
request?: Request;
|
|
18
|
+
cookies?: {
|
|
19
|
+
get(name: string): { value: string } | undefined;
|
|
20
|
+
set(name: string, value: string, options?: Record<string, unknown>): void;
|
|
21
|
+
};
|
|
22
|
+
response?: { headers: Headers };
|
|
23
|
+
locals?: unknown;
|
|
24
|
+
/** Astro's route cache, when the host configured a provider. */
|
|
25
|
+
cache?: { enabled: boolean; set(input: false): void };
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const AB_COOKIE_DAYS = 30;
|
|
29
|
+
|
|
30
|
+
const random = (): number => {
|
|
31
|
+
const bytes = new Uint32Array(1);
|
|
32
|
+
crypto.getRandomValues(bytes);
|
|
33
|
+
return (bytes[0] ?? 0) / 2 ** 32;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The response varies per visitor: keep shared caches from serving one visitor's arm or
|
|
38
|
+
* audience to another (W-312), including Astro's route cache. A host that sets cache hints
|
|
39
|
+
* after this should skip them when `Cache-Control` is private (the demos' Base layout does).
|
|
40
|
+
*/
|
|
41
|
+
function markPersonalized(astro: VisitorAstro): void {
|
|
42
|
+
if (astro.cache?.enabled) astro.cache.set(false);
|
|
43
|
+
const headers = astro.response?.headers;
|
|
44
|
+
if (!headers) return;
|
|
45
|
+
headers.set("Cache-Control", "private, no-store");
|
|
46
|
+
const vary = headers.get("Vary");
|
|
47
|
+
if (!vary?.toLowerCase().includes("cookie"))
|
|
48
|
+
headers.set("Vary", vary ? `${vary}, Cookie` : "Cookie");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Picks each A/B test's arm for this visitor (W-312): the arm in their cookie, or a fresh pick
|
|
53
|
+
* that the cookie then keeps for 30 days. Without cookie access the visitor sees arm A.
|
|
54
|
+
*/
|
|
55
|
+
export function abArmsFor(
|
|
56
|
+
layout: Layout | null,
|
|
57
|
+
astro: VisitorAstro,
|
|
58
|
+
): Record<string, AbArm> | undefined {
|
|
59
|
+
if (!layout) return undefined;
|
|
60
|
+
const tests = collectAbTests(layout);
|
|
61
|
+
if (tests.length === 0) return undefined;
|
|
62
|
+
const cookies = astro.cookies;
|
|
63
|
+
if (!cookies) return undefined;
|
|
64
|
+
const arms: Record<string, AbArm> = {};
|
|
65
|
+
for (const test of tests) {
|
|
66
|
+
const name = abCookieName(test.test);
|
|
67
|
+
const { arm, fresh } = pickArm(test, cookies.get(name)?.value, random());
|
|
68
|
+
arms[test.test] = arm;
|
|
69
|
+
if (fresh) {
|
|
70
|
+
try {
|
|
71
|
+
cookies.set(name, arm, {
|
|
72
|
+
path: "/",
|
|
73
|
+
maxAge: AB_COOKIE_DAYS * 86_400,
|
|
74
|
+
sameSite: "lax",
|
|
75
|
+
httpOnly: true,
|
|
76
|
+
secure: astro.url.protocol === "https:",
|
|
77
|
+
});
|
|
78
|
+
} catch {
|
|
79
|
+
// Headers already sent (a streamed layout): the pick holds for this response only.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
markPersonalized(astro);
|
|
84
|
+
return arms;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Marks a visitor as seen, so their next visit counts as returning (W-313). */
|
|
88
|
+
const SEEN_COOKIE = "emvb_seen";
|
|
89
|
+
const SEEN_DAYS = 365;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One cookie as the browser sent it, decoded as `Astro.cookies.get` would. Unlike that getter, it
|
|
93
|
+
* ignores a cookie set earlier in this request, so the page and its theme parts agree on a first
|
|
94
|
+
* visit.
|
|
95
|
+
*/
|
|
96
|
+
function requestCookie(astro: VisitorAstro, name: string): string | undefined {
|
|
97
|
+
for (const pair of astro.request?.headers.get("cookie")?.split(";") ?? []) {
|
|
98
|
+
const at = pair.indexOf("=");
|
|
99
|
+
if (at < 0 || pair.slice(0, at).trim() !== name) continue;
|
|
100
|
+
const raw = pair.slice(at + 1).trim();
|
|
101
|
+
try {
|
|
102
|
+
return decodeURIComponent(raw);
|
|
103
|
+
} catch {
|
|
104
|
+
return raw;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const COUNTRY = /^[A-Z]{2}$/;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The visitor's country from the edge: Cloudflare's header or `request.cf`, or Vercel's header.
|
|
114
|
+
* Not `Astro.locals.runtime.cf`: since Astro 6 the Cloudflare adapter throws when it is read.
|
|
115
|
+
*/
|
|
116
|
+
function countryOf(astro: VisitorAstro): string | undefined {
|
|
117
|
+
const headers = astro.request?.headers;
|
|
118
|
+
const cf = (astro.request as { cf?: { country?: unknown } } | undefined)?.cf;
|
|
119
|
+
const candidates = [
|
|
120
|
+
headers?.get("cf-ipcountry"),
|
|
121
|
+
headers?.get("x-vercel-ip-country"),
|
|
122
|
+
cf?.country,
|
|
123
|
+
];
|
|
124
|
+
for (const value of candidates) {
|
|
125
|
+
const code = typeof value === "string" ? value.trim().toUpperCase() : "";
|
|
126
|
+
// XX is Cloudflare's "unknown" and T1 is Tor: neither is a country.
|
|
127
|
+
if (COUNTRY.test(code) && code !== "XX" && code !== "T1") return code;
|
|
128
|
+
}
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* What the host site knows about this visitor (W-329), passed as
|
|
134
|
+
* `resolveEmVBPage(Astro, { visitor })` or `resolveThemeParts(Astro, ctx, { visitor })`:
|
|
135
|
+
* segments (`member`, `pro`) that Visitors rules match, and facts that replace what EmVB detects.
|
|
136
|
+
*/
|
|
137
|
+
export type HostVisitor = {
|
|
138
|
+
segments?: readonly string[];
|
|
139
|
+
country?: string;
|
|
140
|
+
device?: VisitorInfo["device"];
|
|
141
|
+
returning?: boolean;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const MAX_SEGMENTS = 50;
|
|
145
|
+
|
|
146
|
+
/** The host's visitor facts EmVB can use; bad values are left out (W-329). */
|
|
147
|
+
export function hostVisitorFacts(host: HostVisitor | undefined): Partial<VisitorInfo> {
|
|
148
|
+
if (!host || typeof host !== "object") return {};
|
|
149
|
+
const facts: Partial<VisitorInfo> = {};
|
|
150
|
+
if (Array.isArray(host.segments)) {
|
|
151
|
+
const segments = [
|
|
152
|
+
...new Set(
|
|
153
|
+
host.segments
|
|
154
|
+
.filter((s): s is string => typeof s === "string")
|
|
155
|
+
.map((s) => s.trim().toLowerCase())
|
|
156
|
+
.filter((s) => AUDIENCE_SEGMENT.test(s)),
|
|
157
|
+
),
|
|
158
|
+
].slice(0, MAX_SEGMENTS);
|
|
159
|
+
facts.segments = segments;
|
|
160
|
+
}
|
|
161
|
+
const country = typeof host.country === "string" ? host.country.trim().toUpperCase() : "";
|
|
162
|
+
if (COUNTRY.test(country)) facts.country = country;
|
|
163
|
+
if (host.device === "mobile" || host.device === "tablet" || host.device === "desktop")
|
|
164
|
+
facts.device = host.device;
|
|
165
|
+
if (typeof host.returning === "boolean") facts.returning = host.returning;
|
|
166
|
+
return facts;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* What the server knows about this visitor, for visitor-aware elements (W-313): country from
|
|
171
|
+
* the edge, device from the User-Agent, new or returning from a first-party cookie, and the time.
|
|
172
|
+
* Facts the host passes (W-329) win over detected ones. Only read when the layout has a rule.
|
|
173
|
+
*/
|
|
174
|
+
export function visitorFor(
|
|
175
|
+
layout: Layout | null,
|
|
176
|
+
astro: VisitorAstro,
|
|
177
|
+
host?: HostVisitor,
|
|
178
|
+
): VisitorInfo | undefined {
|
|
179
|
+
if (!layout || !layoutUsesAudience(layout)) return undefined;
|
|
180
|
+
const headers = astro.request?.headers;
|
|
181
|
+
const visitor: VisitorInfo = { now: Date.now() };
|
|
182
|
+
const country = countryOf(astro);
|
|
183
|
+
if (country) visitor.country = country;
|
|
184
|
+
const device = deviceFromUserAgent(headers?.get("user-agent"), headers?.get("sec-ch-ua-mobile"));
|
|
185
|
+
if (device) visitor.device = device;
|
|
186
|
+
if (astro.cookies && layoutUsesVisitorRule(layout)) {
|
|
187
|
+
visitor.returning = requestCookie(astro, SEEN_COOKIE) === "1";
|
|
188
|
+
if (!visitor.returning) {
|
|
189
|
+
try {
|
|
190
|
+
astro.cookies.set(SEEN_COOKIE, "1", {
|
|
191
|
+
path: "/",
|
|
192
|
+
maxAge: SEEN_DAYS * 86_400,
|
|
193
|
+
sameSite: "lax",
|
|
194
|
+
httpOnly: true,
|
|
195
|
+
secure: astro.url.protocol === "https:",
|
|
196
|
+
});
|
|
197
|
+
} catch {
|
|
198
|
+
// Headers already sent: they count as new again next time.
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
markPersonalized(astro);
|
|
203
|
+
return { ...visitor, ...hostVisitorFacts(host) };
|
|
204
|
+
}
|
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
|
+
}
|