@perkyzz/emvb 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +22 -4
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +5 -2
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/agents-api.ts +39 -0
  6. package/src/admin/api.ts +17 -7
  7. package/src/admin/content-api.ts +7 -51
  8. package/src/admin/content-item.ts +22 -0
  9. package/src/admin/design-api.ts +30 -0
  10. package/src/admin/editor/A11yCopilot.tsx +1 -1
  11. package/src/admin/editor/CommandPalette.tsx +43 -2
  12. package/src/admin/editor/Editor.tsx +133 -332
  13. package/src/admin/editor/EditorOverlay.tsx +3 -1
  14. package/src/admin/editor/PerfMeter.tsx +1 -1
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +124 -9
  17. package/src/admin/editor/canvas/CanvasFrame.tsx +51 -368
  18. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  19. package/src/admin/editor/canvas/SelectionOverlay.tsx +86 -46
  20. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  21. package/src/admin/editor/canvas/drop-line.ts +24 -0
  22. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  23. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  24. package/src/admin/editor/collection-previews.ts +28 -5
  25. package/src/admin/editor/editor-chrome.tsx +346 -0
  26. package/src/admin/editor/editor-commands.ts +360 -0
  27. package/src/admin/editor/editor-css.ts +4 -0
  28. package/src/admin/editor/element-chrome.ts +89 -0
  29. package/src/admin/editor/feature-css.ts +37 -18
  30. package/src/admin/editor/host.ts +33 -0
  31. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  32. package/src/admin/editor/icons/library.ts +29 -19
  33. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  34. package/src/admin/editor/palette-items.ts +36 -5
  35. package/src/admin/editor/palette.ts +9 -4
  36. package/src/admin/editor/panels/AddPanel.tsx +2 -67
  37. package/src/admin/editor/panels/ColorControl.tsx +21 -18
  38. package/src/admin/editor/panels/ElementPanel.tsx +40 -99
  39. package/src/admin/editor/panels/LayersPanel.tsx +34 -62
  40. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  41. package/src/admin/editor/panels/SiteStylesDrawer.tsx +16 -10
  42. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  43. package/src/admin/editor/panels/VariableSection.tsx +1 -10
  44. package/src/admin/editor/panels/color-space.ts +12 -1
  45. package/src/admin/editor/panels/inline-error.tsx +11 -0
  46. package/src/admin/editor/panels/settings/AdvancedFields.tsx +143 -1
  47. package/src/admin/editor/panels/settings/AudienceEditor.tsx +115 -7
  48. package/src/admin/editor/panels/settings/DraftTextField.tsx +42 -9
  49. package/src/admin/editor/panels/settings/FieldControl.tsx +6 -0
  50. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  51. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  52. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  53. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  54. package/src/admin/editor/panels/settings/MediaPicker.tsx +2 -3
  55. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  56. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -2
  57. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  58. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  59. package/src/admin/editor/panels/settings/length-units.ts +15 -4
  60. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  61. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  62. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  63. package/src/admin/editor/panels/settings/style-sections.ts +5 -1
  64. package/src/admin/editor/panels/style-target.ts +105 -0
  65. package/src/admin/editor/panels/variable-values.ts +4 -2
  66. package/src/admin/editor/remote-change.ts +67 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +4 -0
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +23 -15
  74. package/src/admin/editor/useNodeActions.ts +6 -1
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/index.tsx +3 -1
  78. package/src/admin/media-api.ts +20 -0
  79. package/src/admin/pages/AgentsPage.tsx +274 -0
  80. package/src/admin/theme-api.ts +5 -18
  81. package/src/admin/ui.ts +28 -0
  82. package/src/astro/content-port.ts +24 -0
  83. package/src/astro/floats/runtime.ts +10 -0
  84. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  85. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  86. package/src/astro/forms/client.ts +1 -0
  87. package/src/astro/forms-definitions.ts +24 -11
  88. package/src/astro/index.ts +1 -0
  89. package/src/astro/popups/runtime.ts +15 -0
  90. package/src/astro/render-session.ts +85 -0
  91. package/src/astro/request-data.ts +20 -8
  92. package/src/astro/resolve-theme.ts +166 -76
  93. package/src/astro/resolve.ts +57 -16
  94. package/src/astro/tabs/runtime.ts +60 -1
  95. package/src/astro/theme-posts.ts +16 -5
  96. package/src/astro/visitor.ts +67 -5
  97. package/src/constants.ts +1 -1
  98. package/src/core/a11y/audit.ts +202 -26
  99. package/src/core/arrange.ts +71 -38
  100. package/src/core/audience/rules.ts +22 -2
  101. package/src/core/canvas-styles.ts +24 -0
  102. package/src/core/clipboard.ts +11 -32
  103. package/src/core/css/generate.ts +18 -1
  104. package/src/core/css/print.ts +12 -0
  105. package/src/core/css/scope.ts +3 -3
  106. package/src/core/css-keywords.ts +83 -0
  107. package/src/core/data/bindings.ts +4 -6
  108. package/src/core/design/classes.ts +13 -15
  109. package/src/core/design/diff.ts +55 -0
  110. package/src/core/design/merge.ts +127 -0
  111. package/src/core/design/variables.ts +25 -21
  112. package/src/core/elements/dynamic-elements.ts +30 -0
  113. package/src/core/elements/form-elements.ts +20 -3
  114. package/src/core/elements/index.ts +211 -7
  115. package/src/core/forms/binding.ts +4 -13
  116. package/src/core/index.ts +10 -0
  117. package/src/core/local-style.ts +27 -0
  118. package/src/core/migrate/index.ts +9 -4
  119. package/src/core/nesting.ts +4 -23
  120. package/src/core/perf/scripts.ts +9 -6
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +22 -7
  124. package/src/core/render/form.ts +145 -15
  125. package/src/core/render/index.ts +195 -14
  126. package/src/core/render/pagination.ts +21 -2
  127. package/src/core/render/vnode.ts +12 -2
  128. package/src/core/sanitize/css.ts +90 -77
  129. package/src/core/sanitize/embed-url.ts +7 -1
  130. package/src/core/sanitize/href.ts +13 -1
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/descriptors.ts +4 -1
  134. package/src/core/schema/design.ts +5 -7
  135. package/src/core/schema/layout.ts +160 -181
  136. package/src/core/schema/style.ts +53 -63
  137. package/src/core/share/link.ts +72 -29
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +205 -39
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/tree-ops.ts +57 -0
  142. package/src/index.ts +14 -2
  143. package/src/mcp/errors.ts +44 -0
  144. package/src/mcp/index.ts +4 -0
  145. package/src/mcp/ports.ts +78 -0
  146. package/src/mcp/prompts.ts +76 -0
  147. package/src/mcp/publish.ts +60 -0
  148. package/src/mcp/queue.ts +19 -0
  149. package/src/mcp/rate-limit.ts +80 -0
  150. package/src/mcp/read.ts +419 -0
  151. package/src/mcp/refs.ts +84 -0
  152. package/src/mcp/settings.ts +18 -0
  153. package/src/mcp/tools.ts +265 -0
  154. package/src/mcp/write.ts +582 -0
  155. package/src/server/agent-settings.ts +134 -0
  156. package/src/server/design-routes.ts +75 -18
  157. package/src/server/icon-routes.ts +72 -16
  158. package/src/server/mcp-routes.ts +265 -0
  159. package/src/server/plugin.ts +40 -4
  160. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  161. package/src/admin/editor/icons/sets/lucide.json +0 -1
  162. package/src/admin/editor/icons/sets/remix.json +0 -1
  163. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -90,7 +90,15 @@ function enhance(root: HTMLElement): void {
90
90
  activate(root, selectedIndex(root));
91
91
 
92
92
  list.addEventListener("keydown", (event) => {
93
- const target = KEY_TARGETS[event.key];
93
+ // W-405: in right-to-left text the first tab is on the right, so the arrows swap.
94
+ const rtl = list.closest("[dir]")?.getAttribute("dir")?.toLowerCase() === "rtl";
95
+ const key =
96
+ rtl && event.key === "ArrowRight"
97
+ ? "ArrowLeft"
98
+ : rtl && event.key === "ArrowLeft"
99
+ ? "ArrowRight"
100
+ : event.key;
101
+ const target = KEY_TARGETS[key];
94
102
  if (!target) return;
95
103
  event.preventDefault();
96
104
  if (labels.length === 0) return;
@@ -105,9 +113,60 @@ function enhance(root: HTMLElement): void {
105
113
  });
106
114
  }
107
115
 
116
+ /**
117
+ * W-414: opens every closed tab around `target` (outermost first) so a link to something inside a
118
+ * tab, a table of contents entry most often, lands on it. True when a tab was opened.
119
+ */
120
+ function revealInTabs(target: Element): boolean {
121
+ const steps: { root: HTMLElement; index: number }[] = [];
122
+ let panel = target.closest<HTMLElement>(".emvb-tab-panel");
123
+ while (panel) {
124
+ const root = panel.parentElement?.parentElement;
125
+ if (root?.classList.contains("emvb-tabs")) {
126
+ const index = parts(root).panels.indexOf(panel);
127
+ if (index >= 0) steps.unshift({ root, index });
128
+ }
129
+ panel = root?.parentElement?.closest<HTMLElement>(".emvb-tab-panel") ?? null;
130
+ }
131
+ let opened = false;
132
+ for (const { root, index } of steps) {
133
+ if (selectedIndex(root) === index) continue;
134
+ activate(root, index);
135
+ opened = true;
136
+ }
137
+ return opened;
138
+ }
139
+
140
+ function targetOf(hash: string): Element | null {
141
+ if (!hash || hash === "#") return null;
142
+ try {
143
+ return document.getElementById(decodeURIComponent(hash.slice(1)));
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /** After opening a tab, the browser's own jump already happened, so scroll again. */
150
+ function revealHash(hash: string): void {
151
+ const target = targetOf(hash);
152
+ if (!target || !revealInTabs(target)) return;
153
+ target.scrollIntoView?.({ block: "start" });
154
+ }
155
+
156
+ let hashWatch = false;
157
+
108
158
  export function initTabs(root: ParentNode = document): void {
109
159
  const nodes = root.querySelectorAll<HTMLElement>(".emvb-tabs");
110
160
  for (const node of nodes) enhance(node);
161
+ if (hashWatch || typeof window === "undefined") return;
162
+ hashWatch = true;
163
+ // A link to the page's own anchors, then the URL's hash on load and on back/forward.
164
+ document.addEventListener("click", (event) => {
165
+ const link = (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href^="#"]');
166
+ if (link) revealHash(link.getAttribute("href") ?? "");
167
+ });
168
+ window.addEventListener("hashchange", () => revealHash(window.location.hash));
169
+ revealHash(window.location.hash);
111
170
  }
112
171
 
113
172
  /** Test helper: select tab by index after enhance. */
@@ -1,4 +1,4 @@
1
- import type { ThemePostFields } from "../core/index.ts";
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: { permalinkPrefix?: string } = {},
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,11 +60,14 @@ 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 excerpt = typeof data["excerpt"] === "string" ? data["excerpt"] : "";
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 = `${prefix.replace(/\/$/, "")}/${slug || id}`;
59
- const media = mediaFieldsFrom(data["featured_image"]);
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]))
@@ -1,8 +1,10 @@
1
1
  import {
2
+ AUDIENCE_SEGMENT,
2
3
  abCookieName,
3
4
  collectAbTests,
4
5
  deviceFromUserAgent,
5
6
  layoutUsesAudience,
7
+ layoutUsesVisitorRule,
6
8
  pickArm,
7
9
  type AbArm,
8
10
  type Layout,
@@ -86,6 +88,25 @@ export function abArmsFor(
86
88
  const SEEN_COOKIE = "emvb_seen";
87
89
  const SEEN_DAYS = 365;
88
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
+
89
110
  const COUNTRY = /^[A-Z]{2}$/;
90
111
 
91
112
  /**
@@ -108,12 +129,53 @@ function countryOf(astro: VisitorAstro): string | undefined {
108
129
  return undefined;
109
130
  }
110
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
+
111
169
  /**
112
170
  * What the server knows about this visitor, for visitor-aware elements (W-313): country from
113
171
  * 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.
172
+ * Facts the host passes (W-329) win over detected ones. Only read when the layout has a rule.
115
173
  */
116
- export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorInfo | undefined {
174
+ export function visitorFor(
175
+ layout: Layout | null,
176
+ astro: VisitorAstro,
177
+ host?: HostVisitor,
178
+ ): VisitorInfo | undefined {
117
179
  if (!layout || !layoutUsesAudience(layout)) return undefined;
118
180
  const headers = astro.request?.headers;
119
181
  const visitor: VisitorInfo = { now: Date.now() };
@@ -121,8 +183,8 @@ export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorI
121
183
  if (country) visitor.country = country;
122
184
  const device = deviceFromUserAgent(headers?.get("user-agent"), headers?.get("sec-ch-ua-mobile"));
123
185
  if (device) visitor.device = device;
124
- if (astro.cookies) {
125
- visitor.returning = astro.cookies.get(SEEN_COOKIE)?.value === "1";
186
+ if (astro.cookies && layoutUsesVisitorRule(layout)) {
187
+ visitor.returning = requestCookie(astro, SEEN_COOKIE) === "1";
126
188
  if (!visitor.returning) {
127
189
  try {
128
190
  astro.cookies.set(SEEN_COOKIE, "1", {
@@ -138,5 +200,5 @@ export function visitorFor(layout: Layout | null, astro: VisitorAstro): VisitorI
138
200
  }
139
201
  }
140
202
  markPersonalized(astro);
141
- return visitor;
203
+ return { ...visitor, ...hostVisitorFacts(host) };
142
204
  }
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const PLUGIN_ID = "emvb";
2
- export const PLUGIN_VERSION = "0.3.0";
2
+ export const PLUGIN_VERSION = "0.5.0";
3
3
  export const PACKAGE_NAME = "@perkyzz/emvb";
4
4
  export const ADMIN_ENTRY = `${PACKAGE_NAME}/admin`;
5
5
  export const PAGES_COLLECTION = "emvb_pages";
@@ -21,7 +21,11 @@ export type A11yIssue = {
21
21
  | "vague-link"
22
22
  | "contrast"
23
23
  | "hidden-focusable"
24
- | "new-tab";
24
+ | "new-tab"
25
+ | "image-sizes"
26
+ | "control-name"
27
+ | "empty-heading"
28
+ | "landmark-name";
25
29
  severity: "error" | "warning";
26
30
  message: string;
27
31
  /** The one-click fix, when there is a safe one. */
@@ -34,10 +38,15 @@ export type A11yReport = { score: number; issues: A11yIssue[] };
34
38
  const WEIGHT = { error: 12, warning: 4 } as const;
35
39
 
36
40
  /** Alt text that names a file or says nothing a screen reader user can use. */
41
+ // W-431: camera and screenshot file names as people get them, spaces included
42
+ // ("Screenshot 2026-10-01 at 10.00.00", "WhatsApp Image 2024-…"), not only with _ or -.
37
43
  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;
44
+ /^(?:image|img|photo|picture|graphic|logo|icon|untitled|\s*)$|\.(?:jpe?g|png|gif|webp|avif|svg)$|^(?:img|dsc|pxl|screen ?shot|whatsapp image)[\s_-]?\d+/i;
39
45
  /** Link text that makes no sense out of context. */
40
- const VAGUE = /^(?:click here|here|read more|more|learn more|link|this|go)\.?$/i;
46
+ /** W-411: trailing punctuation and arrows ("Read more…", "Learn more →", "Click here!") too. */
47
+ // W-432: the other common "more" phrasings ("See more", "More info", "Continue reading"…).
48
+ const VAGUE =
49
+ /^(?:click here|here|read more|more|learn more|link|this|go|see more|view more|more info(?:rmation)?|details|find out more|continue reading|read more here|click here to (?:read|learn) more)\s*[.!…:»›→>\u2192\u203a\u00bb-]*$/i;
41
50
  const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
42
51
 
43
52
  /** A style colour as hex: literal, or a site colour variable; undefined when unknown. */
@@ -66,6 +75,24 @@ const lum = (hex: string) => {
66
75
  return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
67
76
  };
68
77
 
78
+ /**
79
+ * W-412: `top` painted over opaque `bottom`, as 6-digit hex. A colour's alpha (#rgba,
80
+ * #rrggbbaa) used to be dropped, so faint text counted as full strength.
81
+ */
82
+ function over(top: string, bottom: string, fade = 1): string {
83
+ let h = top.slice(1);
84
+ if (h.length <= 4) h = [...h].map((c) => c + c).join("");
85
+ // W-415: `fade` is the element's opacity times its ancestors'.
86
+ const alpha = (h.length === 8 ? Number.parseInt(h.slice(6, 8), 16) / 255 : 1) * fade;
87
+ if (alpha >= 1) return `#${h.slice(0, 6)}`;
88
+ const a = rgb(`#${h.slice(0, 6)}`);
89
+ const b = rgb(bottom);
90
+ return `#${a
91
+ .map((c, i) => Math.round(c * alpha + (b[i] ?? 0) * (1 - alpha)))
92
+ .map((c) => c.toString(16).padStart(2, "0"))
93
+ .join("")}`;
94
+ }
95
+
69
96
  /** WCAG contrast ratio between two hex colours, 1–21. */
70
97
  export function contrastRatio(a: string, b: string): number {
71
98
  const [hi, lo] = [lum(a), lum(b)].toSorted((x, y) => y - x) as [number, number];
@@ -81,6 +108,7 @@ const TEXT_TYPES = new Set([
81
108
  "post-title",
82
109
  "post-excerpt",
83
110
  ]);
111
+ const FIELD_TYPES = new Set(["text-input", "textarea", "select", "checkbox", "radio"]);
84
112
  const LINKISH = new Set(["link", "button", "menu-item"]);
85
113
 
86
114
  function px(value: unknown): number | undefined {
@@ -110,20 +138,42 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
110
138
  const add = (issue: Omit<A11yIssue, "id">) =>
111
139
  issues.push({ ...issue, id: `${issue.rule}:${issue.nodeId}` });
112
140
  let lastLevel = 0;
113
- let h1s = 0;
141
+ // W-444: H1s counted per device, so a desktop H1 and a mobile H1 that swap places aren't two.
142
+ const DEVICES = ["desktop", "tablet", "mobile"] as const;
143
+ let h1s = [0, 0, 0];
144
+ let shownOn = [true, true, true];
145
+ // W-446: aria-hidden on a box hides everything inside it from screen readers, links included.
146
+ let ariaHiddenAbove = false;
114
147
  // W-312 variants are alternatives: B is judged as if it stood where A does, so a page whose
115
148
  // 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]>();
149
+ const beforeA = new Map<string, [number[], number]>();
150
+ const afterA = new Map<string, [number[], number]>();
151
+ let fade = 1;
152
+ // W-445: per device, like H1s, so a desktop menu and a mobile menu may share a name.
153
+ const menuNames = [new Set<string>(), new Set<string>(), new Set<string>()];
118
154
  const walk = (node: LayoutNode, bg: string | undefined, color: string | undefined): void => {
155
+ // W-413: an element hidden on every device (and what's inside it) is never shown or read.
156
+ if (
157
+ node !== layout.root &&
158
+ (["desktop", "tablet", "mobile"] as const).every((d) => node.hiddenOn?.includes(d))
159
+ ) {
160
+ return;
161
+ }
119
162
  const variant = node.variant;
120
- if (variant?.arm === "a") beforeA.set(variant.test, [h1s, lastLevel]);
163
+ if (variant?.arm === "a") beforeA.set(variant.test, [[...h1s], lastLevel]);
121
164
  const before = variant?.arm === "b" ? beforeA.get(variant.test) : undefined;
122
- if (before) [h1s, lastLevel] = before;
165
+ if (before) [h1s, lastLevel] = [[...before[0]], before[1]];
166
+ const outerFade = fade;
167
+ const opacity = (node.style as { opacity?: unknown } | undefined)?.opacity;
168
+ if (typeof opacity === "number" && opacity >= 0 && opacity < 1) fade *= opacity;
169
+ const outerShown = shownOn;
170
+ shownOn = shownOn.map((shown, i) => shown && !node.hiddenOn?.includes(DEVICES[i] ?? "desktop"));
123
171
  visitNode(node, bg, color);
124
- if (variant?.arm === "a") afterA.set(variant.test, [h1s, lastLevel]);
172
+ fade = outerFade;
173
+ shownOn = outerShown;
174
+ if (variant?.arm === "a") afterA.set(variant.test, [[...h1s], lastLevel]);
125
175
  const after = variant?.arm === "b" ? afterA.get(variant.test) : undefined;
126
- if (after) [h1s, lastLevel] = after;
176
+ if (after) [h1s, lastLevel] = [[...after[0]], after[1]];
127
177
  };
128
178
  const visitNode = (node: LayoutNode, bg: string | undefined, color: string | undefined): void => {
129
179
  const props = node.props as Record<string, unknown>;
@@ -132,9 +182,20 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
132
182
  | undefined;
133
183
  // A background image hides the colour behind the text: contrast can't be judged below it.
134
184
  const ownBg = style?.backgroundImage ? "unknown" : hexOf(style?.backgroundColor, design);
135
- const nextBg = ownBg ?? bg;
185
+ const nextBg =
186
+ ownBg && ownBg !== "unknown" && bg && bg !== "unknown" ? over(ownBg, bg) : (ownBg ?? bg);
136
187
  const nextColor = hexOf(style?.color, design) ?? color;
137
- if (node.type === "image" && props["decorative"] !== true) {
188
+ // W-386: a linked image's alt text is the link's name, so it can't be decorative.
189
+ const imageLinked =
190
+ node.type === "image" && typeof props["href"] === "string" && props["href"].trim() !== "";
191
+ if (node.type === "image" && imageLinked && props["decorative"] === true) {
192
+ add({
193
+ nodeId: node.id,
194
+ rule: "link-name",
195
+ severity: "error",
196
+ message: "This image is a link but is marked decorative, so the link has no name.",
197
+ });
198
+ } else if (node.type === "image" && props["decorative"] !== true) {
138
199
  const alt = typeof props["alt"] === "string" ? props["alt"].trim() : "";
139
200
  if (USELESS_ALT.test(alt)) {
140
201
  add({
@@ -144,16 +205,106 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
144
205
  message: alt
145
206
  ? `The alt text "${alt.slice(0, 40)}" doesn't describe the image.`
146
207
  : "This image has no alt text.",
147
- fix: { kind: "decorative" },
148
- fixLabel: "Mark as decorative",
208
+ ...(imageLinked
209
+ ? {}
210
+ : { fix: { kind: "decorative" as const }, fixLabel: "Mark as decorative" }),
211
+ });
212
+ }
213
+ }
214
+ // W-403: with extra sizes but no Width, the main image is left out of srcset, so wide screens
215
+ // can only get the listed copies.
216
+ if (node.type === "image" && Array.isArray(props["sources"]) && props["sources"].length > 0) {
217
+ const width = props["width"];
218
+ const widthSet = typeof width === "number" && Number.isInteger(width) && width >= 1;
219
+ const mainListed = (props["sources"] as { src?: unknown }[]).some(
220
+ (s) => typeof s?.src === "string" && s.src === props["src"],
221
+ );
222
+ if (!widthSet && !mainListed) {
223
+ add({
224
+ nodeId: node.id,
225
+ rule: "image-sizes",
226
+ severity: "warning",
227
+ message:
228
+ "This image has extra sizes but no Width (px), so the main image is left out of the list the browser picks from.",
149
229
  });
150
230
  }
151
231
  }
232
+ if (
233
+ imageLinked &&
234
+ props["newTab"] === true &&
235
+ !/new (tab|window)/i.test(String(props["alt"] ?? ""))
236
+ ) {
237
+ add({
238
+ nodeId: node.id,
239
+ rule: "new-tab",
240
+ severity: "warning",
241
+ message: "This image link opens a new tab without saying so; say so in the alt text.",
242
+ });
243
+ }
244
+ // W-408: a blank tab label or accordion title renders a tab or summary with no name.
245
+ // W-416: a form field with no label (a placeholder is not one: it goes once you type).
246
+ if (FIELD_TYPES.has(node.type) && !String(props["label"] ?? "").trim() && !node.bind) {
247
+ add({
248
+ nodeId: node.id,
249
+ rule: "control-name",
250
+ severity: "error",
251
+ message: String(props["placeholder"] ?? "").trim()
252
+ ? "This field has only a placeholder, which disappears once you type; give it a label."
253
+ : "This field has no label, so screen readers can't say what it's for.",
254
+ });
255
+ }
256
+ const NAME_PROP = {
257
+ "tab-panel": "label",
258
+ "accordion-item": "summary",
259
+ video: "title",
260
+ } as const;
261
+ if (node.type === "tab-panel" || node.type === "accordion-item" || node.type === "video") {
262
+ const name = String(props[NAME_PROP[node.type]] ?? "").trim();
263
+ if (!name && !node.bind) {
264
+ add({
265
+ nodeId: node.id,
266
+ rule: "control-name",
267
+ severity: "error",
268
+ message:
269
+ node.type === "tab-panel"
270
+ ? "This tab's label is blank, so the tab has no name."
271
+ : node.type === "video"
272
+ ? // W-410: the title names the player for screen readers.
273
+ "This video's title is blank, so the player has no name."
274
+ : "This accordion item's title is blank, so it has no name.",
275
+ });
276
+ }
277
+ }
278
+ // W-424: two menus with the same name are two "Menu navigation" landmarks nobody can tell apart.
279
+ if (node.type === "menu" && (node.children?.length ?? 0) > 0) {
280
+ const name = String(props["label"] ?? "").trim() || "Menu";
281
+ const key = name.toLowerCase();
282
+ if (menuNames.some((names, i) => shownOn[i] && names.has(key))) {
283
+ add({
284
+ nodeId: node.id,
285
+ rule: "landmark-name",
286
+ severity: "warning",
287
+ message: `Another menu on this page is also named "${name}"; give each menu its own label.`,
288
+ });
289
+ }
290
+ menuNames.forEach((names, i) => {
291
+ if (shownOn[i]) names.add(key);
292
+ });
293
+ }
294
+ // W-419: an empty heading still shows up in screen readers' heading list, with nothing to say.
295
+ if (node.type === "heading" && !String(props["text"] ?? "").trim() && !node.bind) {
296
+ add({
297
+ nodeId: node.id,
298
+ rule: "empty-heading",
299
+ severity: "warning",
300
+ message: "This heading is empty; screen readers list it as a heading with no words.",
301
+ });
302
+ }
152
303
  if (node.type === "heading") {
153
304
  const level = typeof props["level"] === "number" ? props["level"] : 2;
154
305
  if (level === 1) {
155
- h1s += 1;
156
- if (h1s > 1) {
306
+ h1s = h1s.map((count, i) => count + (shownOn[i] ? 1 : 0));
307
+ if (h1s.some((count, i) => shownOn[i] && count > 1)) {
157
308
  add({
158
309
  nodeId: node.id,
159
310
  rule: "multiple-h1",
@@ -188,7 +339,12 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
188
339
  message:
189
340
  node.type === "icon"
190
341
  ? "This icon link has no title, so it has no name."
191
- : "This link has no text.",
342
+ : node.type === "button" && !hasHref
343
+ ? // W-400: without a URL this is a <button>, not a link.
344
+ props["iconId"]
345
+ ? "This icon-only button has no text or title, so it has no name."
346
+ : "This button has no text."
347
+ : "This link has no text.",
192
348
  });
193
349
  } else if (hasHref && VAGUE.test(text)) {
194
350
  add({
@@ -208,28 +364,37 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
208
364
  }
209
365
  }
210
366
  if (TEXT_TYPES.has(node.type) && nextColor && nextBg && nextBg !== "unknown") {
211
- const ratio = contrastRatio(nextColor, nextBg);
367
+ const ratio = contrastRatio(over(nextColor, nextBg, fade), nextBg);
212
368
  const needed = largeText(node) ? 3 : 4.5;
213
369
  if (ratio < needed) {
214
370
  const black = contrastRatio("#000000", nextBg);
215
371
  const white = contrastRatio("#ffffff", nextBg);
216
372
  const better = black >= white ? "#111111" : "#ffffff";
373
+ // W-421: when opacity is what fades the text, a new colour can't fix it; say so instead
374
+ // of offering a fix that leaves the issue in place.
375
+ const fixable = contrastRatio(over(better, nextBg, fade), nextBg) >= needed;
217
376
  add({
218
377
  nodeId: node.id,
219
378
  rule: "contrast",
220
379
  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",
380
+ message: fixable
381
+ ? `Text contrast is ${ratio.toFixed(1)}:1; it needs ${needed}:1.`
382
+ : `Text contrast is ${ratio.toFixed(1)}:1; it needs ${needed}:1. Opacity on this element or a parent fades it; raise the opacity.`,
383
+ ...(fixable
384
+ ? {
385
+ fix: { kind: "text-color" as const, color: better },
386
+ fixLabel: better === "#ffffff" ? "Use white text" : "Use dark text",
387
+ }
388
+ : {}),
224
389
  });
225
390
  }
226
391
  }
227
392
  const focusable =
228
393
  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
- ) {
394
+ const ownAriaHidden = (node.attributes ?? []).some(
395
+ (a) => a.name === "aria-hidden" && a.value === "true",
396
+ );
397
+ if (focusable && ownAriaHidden) {
233
398
  add({
234
399
  nodeId: node.id,
235
400
  rule: "hidden-focusable",
@@ -238,11 +403,22 @@ export function auditPage(layout: Layout, design: DesignSystem): A11yReport {
238
403
  fix: { kind: "drop-aria-hidden" },
239
404
  fixLabel: "Remove aria-hidden",
240
405
  });
406
+ } else if (focusable && ariaHiddenAbove) {
407
+ add({
408
+ nodeId: node.id,
409
+ rule: "hidden-focusable",
410
+ severity: "error",
411
+ message:
412
+ "This sits inside an element with aria-hidden, so screen readers skip it, but the keyboard still reaches it.",
413
+ });
241
414
  }
415
+ const outerHidden = ariaHiddenAbove;
416
+ if (ownAriaHidden) ariaHiddenAbove = true;
242
417
  if (isParentNode(node)) for (const child of node.children) walk(child, nextBg, nextColor);
418
+ ariaHiddenAbove = outerHidden;
243
419
  };
244
420
  walk(layout.root, undefined, undefined);
245
- if (h1s === 0 && layout.root.children.length > 0) {
421
+ if (h1s.every((count) => count === 0) && layout.root.children.length > 0) {
246
422
  issues.unshift({
247
423
  id: `no-h1:${layout.root.id}`,
248
424
  nodeId: layout.root.id,