auditmysite 1.7.3

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! WCAG 2.4.11 Focus Not Obscured (Minimum) (Level AA, WCAG 2.2)
//!
//! "When a user interface component receives keyboard focus, the component
//! is not entirely hidden due to author-created content."
//!
//! In practice: sticky/fixed headers, footers, cookie banners, or chat
//! widgets can sit on top of page content, so a keyboard user tabbing to a
//! control underneath one of these can land on something the CDP/DOM still
//! considers "focused" but that is no longer visible at all.
//!
//! **What this checks.** This is a static-layout, single-page-load
//! geometric heuristic, not a real focus-walk: it does *not* press Tab and
//! inspect `document.activeElement` for every control (that would require a
//! CDP round-trip per focusable element and does not by itself simulate the
//! post-scroll layout that triggers the classic version of this bug). One
//! `evaluate()` call collects (a) all `position: fixed`/`sticky` elements
//! large enough to plausibly be a header/footer/banner/widget, and (b) all
//! natively-focusable elements, both in their *current* bounding-box
//! position. The pure Rust half then checks whether any overlay's rect
//! covers essentially the *entire* area of a focusable element's rect.
//!
//! This narrower, static-snapshot version does catch real, permanent
//! instances of the bug (an overlay that structurally always sits on top of
//! some focusable control regardless of scroll position — e.g. a
//! badly-positioned fixed newsletter/chat widget, or a fixed bottom banner
//! overlapping the last footer links), but it will **not** catch the
//! textbook variant where an element is only obscured *after* the user
//! scrolls it under a sticky header, since that requires actually walking
//! focus and observing the resulting scroll position, which is out of scope
//! here.
//!
//! Deliberately excluded to avoid false positives:
//! - An overlay that is an *ancestor* of the focusable element itself (a
//!   link inside a sticky header is not "obscured by its own header").
//! - Fixed/sticky elements that are hidden (`display: none`,
//!   `visibility: hidden`, `opacity: 0`) or too small to plausibly be an
//!   overlay (`< 20px` in either dimension).
//! - Overlap ratios below "entirely hidden" (see [`ENTIRELY_HIDDEN_RATIO`])
//!   — a merely partially-covered element still satisfies this (Minimum)
//!   criterion; see `focus_not_obscured_enhanced` (2.4.12, AAA) for the
//!   stricter "no part hidden at all" version.
//!
//! **Not checked:** paint/stacking order (`z-index`). A geometric rect
//! overlap does not guarantee the overlay actually paints on top of the
//! focusable element — a `position: fixed` element with a lower stacking
//! context could sit fully behind it. Combined with the static-snapshot
//! limitation above, findings are reported as
//! [`crate::wcag::types::Outcome::Review`] (heuristic, manual-review
//! candidate), matching the precedent set by `redundant_entry.rs` and
//! `meaningful_sequence.rs` for this kind of geometry-based judgment call.

use chromiumoxide::Page;

use crate::cli::WcagLevel;
use crate::wcag::types::{RuleMetadata, Severity, Violation};

pub(super) const FOCUS_NOT_OBSCURED_MINIMUM_RULE: RuleMetadata = RuleMetadata {
    id: "2.4.11",
    name: "Focus Not Obscured (Minimum)",
    level: WcagLevel::AA,
    severity: Severity::Medium,
    description:
        "Focusable elements are not entirely hidden behind fixed or sticky-positioned content",
    help_url: "https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html",
    axe_id: "focus-not-obscured-minimum",
    tags: &["wcag22aa", "wcag2411", "cat.keyboard"],
};

/// Fraction of a focusable element's bounding-box area that a fixed/sticky
/// overlay must cover for the element to be considered "entirely hidden"
/// per 2.4.11. Slightly below 1.0 to tolerate the sub-pixel rounding
/// `getBoundingClientRect()` commonly produces between visually-flush edges.
const ENTIRELY_HIDDEN_RATIO: f64 = 0.98;

/// A CSS-pixel bounding box, as returned by `getBoundingClientRect()`.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Rect {
    x: f64,
    y: f64,
    w: f64,
    h: f64,
}

/// Fraction of `focusable`'s area covered by `overlay`'s rect (0.0 when they
/// don't overlap at all).
fn overlap_ratio(focusable: Rect, overlay: Rect) -> f64 {
    let x_overlap =
        (focusable.x + focusable.w).min(overlay.x + overlay.w) - focusable.x.max(overlay.x);
    let y_overlap =
        (focusable.y + focusable.h).min(overlay.y + overlay.h) - focusable.y.max(overlay.y);
    if x_overlap <= 0.0 || y_overlap <= 0.0 {
        return 0.0;
    }
    let focusable_area = focusable.w * focusable.h;
    if focusable_area <= 0.0 {
        return 0.0;
    }
    (x_overlap * y_overlap) / focusable_area
}

/// True if any overlay rect covers at least [`ENTIRELY_HIDDEN_RATIO`] of the
/// focusable element's area.
fn is_entirely_hidden(focusable: Rect, overlays: &[Rect]) -> bool {
    overlays
        .iter()
        .any(|overlay| overlap_ratio(focusable, *overlay) >= ENTIRELY_HIDDEN_RATIO)
}

/// Collects, in one evaluation: (a) sizeable `position: fixed`/`sticky`
/// elements ("overlays"), and (b) natively-focusable elements with, for
/// each, the indices of overlays that are *not* one of its own DOM
/// ancestors (candidates that could actually obscure it).
const FOCUS_OBSCURED_JS: &str = r#"
(function() {
  /*CSS_SELECTOR*/

  var overlays = [];
  var overlayEls = [];
  var all = document.querySelectorAll('*');
  for (var i = 0; i < all.length && overlays.length < 30; i++) {
    var el = all[i];
    var cs = getComputedStyle(el);
    if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;
    if (cs.visibility === 'hidden' || cs.display === 'none' || parseFloat(cs.opacity) === 0) continue;
    var rect = el.getBoundingClientRect();
    if (rect.width < 20 || rect.height < 20) continue;
    overlays.push({ selector: __amsCssSelector(el), x: rect.x, y: rect.y, w: rect.width, h: rect.height });
    overlayEls.push(el);
  }
  if (overlays.length === 0) return { overlays: [], focusables: [] };

  var sel = 'a[href], button, input:not([type="hidden"]), select, textarea, ' +
            '[tabindex], [contenteditable=""], [contenteditable="true"]';
  var els = document.querySelectorAll(sel);
  var focusables = [];
  for (var j = 0; j < els.length && __amsReal(focusables) < 200; j++) {
    var fel = els[j];
    if (fel.disabled) continue;
    if (typeof fel.tabIndex === 'number' && fel.tabIndex < 0) continue;
    var fcs = getComputedStyle(fel);
    if (fcs.display === 'none' || fcs.visibility === 'hidden') continue;
    var frect = fel.getBoundingClientRect();
    if (frect.width <= 0 || frect.height <= 0) continue;

    var candidates = [];
    for (var k = 0; k < overlayEls.length; k++) {
      if (overlayEls[k] === fel || overlayEls[k].contains(fel)) continue;
      candidates.push(k);
    }
    if (candidates.length === 0) continue;

    __amsPush(focusables, fel, {
      selector: __amsCssSelector(fel),
      x: frect.x, y: frect.y, w: frect.width, h: frect.height,
      overlayIndices: candidates
    }, 200);
  }

  return { overlays: overlays, focusables: focusables };
})()
"#;

pub async fn check_focus_not_obscured_minimum_with_page(page: &Page) -> Vec<Violation> {
    if let Some(findings) = focus_walk_findings(page).await {
        return findings;
    }
    let val = match crate::wcag::types::evaluate_or_fail(
        page,
        &FOCUS_NOT_OBSCURED_MINIMUM_RULE,
        &FOCUS_OBSCURED_JS.replace(
            "/*CSS_SELECTOR*/",
            crate::accessibility::js_helpers::CSS_SELECTOR_JS,
        ),
    )
    .await
    {
        Ok(v) => v,
        Err(violations) => return violations,
    };

    let overlays_json = match val.get("overlays").and_then(|v| v.as_array()) {
        Some(a) => a,
        None => {
            return vec![crate::wcag::technical_rule_failure(
                &FOCUS_NOT_OBSCURED_MINIMUM_RULE,
                "invalid_evaluation_shape",
            )]
        }
    };
    if overlays_json.is_empty() {
        return vec![];
    }
    let overlays: Vec<Rect> = overlays_json
        .iter()
        .filter_map(|o| {
            Some(Rect {
                x: o.get("x")?.as_f64()?,
                y: o.get("y")?.as_f64()?,
                w: o.get("w")?.as_f64()?,
                h: o.get("h")?.as_f64()?,
            })
        })
        .collect();

    let focusables_json = match val.get("focusables").and_then(|v| v.as_array()) {
        Some(a) => a.clone(),
        None => {
            return vec![crate::wcag::technical_rule_failure(
                &FOCUS_NOT_OBSCURED_MINIMUM_RULE,
                "invalid_evaluation_shape",
            )]
        }
    };

    let mut violations = Vec::new();
    for f in &focusables_json {
        let Some(selector) = f.get("selector").and_then(|v| v.as_str()) else {
            continue;
        };
        let (Some(x), Some(y), Some(w), Some(h)) = (
            f.get("x").and_then(|v| v.as_f64()),
            f.get("y").and_then(|v| v.as_f64()),
            f.get("w").and_then(|v| v.as_f64()),
            f.get("h").and_then(|v| v.as_f64()),
        ) else {
            continue;
        };
        let rect = Rect { x, y, w, h };

        let indices: Vec<usize> = f
            .get("overlayIndices")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|i| i.as_u64().map(|n| n as usize))
                    .collect()
            })
            .unwrap_or_default();
        let candidate_overlays: Vec<Rect> = indices
            .iter()
            .filter_map(|i| overlays.get(*i).copied())
            .collect();
        if candidate_overlays.is_empty() {
            continue;
        }

        if is_entirely_hidden(rect, &candidate_overlays) {
            violations.push(
                Violation::new(
                    FOCUS_NOT_OBSCURED_MINIMUM_RULE.id,
                    FOCUS_NOT_OBSCURED_MINIMUM_RULE.name,
                    FOCUS_NOT_OBSCURED_MINIMUM_RULE.level,
                    Severity::Medium,
                    format!(
                        "Focusable element '{}' is entirely covered by a fixed or sticky-positioned \
                         element at its current layout position, so a keyboard user tabbing to it \
                         would not be able to see it.",
                        selector
                    ),
                    selector,
                )
                .with_selector(selector)
                .with_fix(
                    "Make sure focused elements stay visible: add `scroll-margin-top`/`scroll-padding-top` \
                     so sticky headers don't cover the target after it scrolls into view, or reposition/resize \
                     the fixed or sticky element so it never fully covers interactive content.",
                )
                .with_rule_id(FOCUS_NOT_OBSCURED_MINIMUM_RULE.axe_id)
                .with_help_url(FOCUS_NOT_OBSCURED_MINIMUM_RULE.help_url)
                .as_warning(),
            );
            if violations.len() >= 5 {
                break;
            }
        }
    }
    violations
}

/// Bounded focus/scroll walk. `elementsFromPoint` supplies the browser's paint
/// order, avoiding geometric false positives from overlays that are behind the
/// focused control. The previous static geometry path remains a fallback when
/// this live probe cannot execute.
async fn focus_walk_findings(page: &Page) -> Option<Vec<Violation>> {
    let value = page
        .evaluate(
            r#"
            (() => {
              const originalX = scrollX, originalY = scrollY, original = document.activeElement;
              /*CSS_SELECTOR*/
              const selector = 'a[href],button,input:not([type="hidden"]),select,textarea,[tabindex]:not([tabindex="-1"]),[contenteditable="true"]';
              const controls = [];
              for (const element of document.querySelectorAll(selector)) {
                const style = getComputedStyle(element);
                const rect = element.getBoundingClientRect();
                if (element.disabled || style.display === 'none' || style.visibility === 'hidden' || rect.width <= 3 || rect.height <= 3) continue;
                __amsPush(controls, element, element, 60);
                if (__amsReal(controls) >= 60) break;
              }
              const findings = [];
              for (const control of controls) {
                control.focus({preventScroll: true});
                control.scrollIntoView({block: 'nearest', inline: 'nearest'});
                const rect = control.getBoundingClientRect();
                const points = [
                  [rect.left + 1, rect.top + 1], [rect.right - 1, rect.top + 1],
                  [rect.left + 1, rect.bottom - 1], [rect.right - 1, rect.bottom - 1],
                  [rect.left + rect.width / 2, rect.top + rect.height / 2]
                ].filter(([x,y]) => x >= 0 && y >= 0 && x < innerWidth && y < innerHeight);
                if (!points.length) continue;
                const blockers = points.map(([x,y]) => {
                  const painted = document.elementsFromPoint(x, y);
                  const controlIndex = painted.findIndex(element => element === control || control.contains(element));
                  if (controlIndex <= 0) return null;
                  return painted.slice(0, controlIndex).find(element => {
                    if (element.contains(control) || control.contains(element)) return false;
                    const style = getComputedStyle(element);
                    return style.position === 'fixed' || style.position === 'sticky';
                  }) || null;
                });
                if (blockers.every(Boolean)) {
                  __amsPush(findings, control, {control: __amsCssSelector(control), blocker: __amsCssSelector(blockers[0])}, 5);
                  if (__amsReal(findings) >= 5) break;
                }
              }
              scrollTo(originalX, originalY);
              if (original && original.focus) original.focus({preventScroll:true});
              return { findings };
            })()
            "#
            .replace(
                "/*CSS_SELECTOR*/",
                crate::accessibility::js_helpers::CSS_SELECTOR_JS,
            ),
        )
        .await
        .ok()?
        .value()
        .cloned()?;
    let findings = value.get("findings")?.as_array()?;
    Some(
        findings
            .iter()
            .filter_map(|finding| {
                let selector = finding.get("control")?.as_str()?;
                let blocker = finding.get("blocker")?.as_str()?;
                Some(
                    Violation::new(
                        FOCUS_NOT_OBSCURED_MINIMUM_RULE.id,
                        FOCUS_NOT_OBSCURED_MINIMUM_RULE.name,
                        FOCUS_NOT_OBSCURED_MINIMUM_RULE.level,
                        FOCUS_NOT_OBSCURED_MINIMUM_RULE.severity,
                        format!(
                            "Keyboard focus on {selector} is entirely hidden in paint order by fixed or sticky element {blocker} after scrolling it into view."
                        ),
                        selector,
                    )
                    .with_selector(selector)
                    .with_rule_id(FOCUS_NOT_OBSCURED_MINIMUM_RULE.axe_id)
                    .with_kind(crate::wcag::types::Outcome::Review)
                    .with_fix(
                        "Reserve space for sticky content or add scroll-padding/scroll-margin so focused controls remain visible",
                    )
                    .with_help_url(FOCUS_NOT_OBSCURED_MINIMUM_RULE.help_url),
                )
            })
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rect(x: f64, y: f64, w: f64, h: f64) -> Rect {
        Rect { x, y, w, h }
    }

    #[test]
    fn fires_when_focusable_entirely_covered_by_sticky_header() {
        // A form field scrolled to sit right under a full-width sticky
        // header — the classic real-world 2.4.11 scenario.
        let focusable = rect(100.0, 10.0, 200.0, 30.0);
        let header = rect(0.0, 0.0, 1200.0, 60.0);
        assert!(is_entirely_hidden(focusable, &[header]));
    }

    #[test]
    fn does_not_fire_when_no_overlap() {
        let focusable = rect(100.0, 500.0, 200.0, 30.0);
        let header = rect(0.0, 0.0, 1200.0, 60.0);
        assert!(!is_entirely_hidden(focusable, &[header]));
    }

    #[test]
    fn does_not_fire_for_partial_edge_touch_overlap() {
        // Sticky header only clips the top 2px of a 30px-tall field — well
        // below the "entirely hidden" bar, and exactly the kind of
        // near-miss this rule must not flag.
        let focusable = rect(100.0, 58.0, 200.0, 30.0);
        let header = rect(0.0, 0.0, 1200.0, 60.0);
        assert!(!is_entirely_hidden(focusable, &[header]));
    }

    #[test]
    fn does_not_fire_when_own_container_excluded_leaves_no_candidates() {
        // Models the effect of the JS-side ancestor exclusion: a link
        // inside a sticky header has no candidate overlays left once its
        // own header is filtered out, so the geometric check never runs
        // against it (an empty overlay list can never look "hidden").
        let focusable = rect(20.0, 15.0, 80.0, 20.0);
        assert!(!is_entirely_hidden(focusable, &[]));
    }

    #[test]
    fn rule_metadata_is_level_aa() {
        assert_eq!(FOCUS_NOT_OBSCURED_MINIMUM_RULE.id, "2.4.11");
        assert_eq!(FOCUS_NOT_OBSCURED_MINIMUM_RULE.level, WcagLevel::AA);
    }
}