auditmysite 1.3.0

Resource-efficient WCAG 2.1 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Turns recorded journey traces + focus snapshots into
//! `InteractiveFinding`s.
//!
//! Each evaluator function takes the *evidence* from a journey runner
//! and produces findings without itself touching the browser. That keeps
//! the runtime side effects (CDP, JS evaluate, …) and the evaluation
//! logic in separate, testable units.
//!
//! Currently covers:
//! - hidden focusables (aria-hidden, inert, hidden-by-style)
//! - missing focus indicator (no outline / box-shadow / border on :focus)
//! - tab order vs. DOM order (`tab_walk_order`, separate evaluator)

use crate::accessibility::{FocusIndicatorStatus, FocusSnapshot};
use crate::audit::normalized::{
    InteractiveFinding, InteractiveFindingKind, InteractiveFindingValues, JourneyTrace,
};
use crate::taxonomy::Severity;

/// Evaluate a tab-walk trace and its per-step focus snapshots.
///
/// Pure function: deterministic given the inputs. No browser calls.
pub fn tab_walk(trace: &JourneyTrace, snapshots: &[FocusSnapshot]) -> Vec<InteractiveFinding> {
    let mut findings = Vec::new();

    // Walk steps + snapshots in lockstep. `trace.steps[i]` corresponds to
    // `snapshots[i]` by construction in `tab_walk::record`.
    for (step, snap) in trace.steps.iter().zip(snapshots.iter()) {
        // Hidden focusables are only meaningful for tab-press steps. The
        // "start" step records the initial state and isn't an interaction.
        if step.action != "tab" {
            continue;
        }
        let Some(selector) = &step.focus else {
            continue;
        };

        if snap.aria_hidden_chain {
            findings.push(InteractiveFinding::new(
                "HiddenFocusable",
                InteractiveFindingKind::HiddenFocusableAriaHidden,
                Some("a11y.aria_hidden_focus.invalid".to_string()),
                Severity::High,
                trace.journey.clone(),
                None,
                step.snapshot_label.clone(),
                InteractiveFindingValues {
                    selector: Some(selector.clone()),
                    ..Default::default()
                },
            ));
        } else if snap.inert_chain {
            findings.push(InteractiveFinding::new(
                "HiddenFocusable",
                InteractiveFindingKind::HiddenFocusableInert,
                Some("a11y.aria_hidden_focus.invalid".to_string()),
                Severity::High,
                trace.journey.clone(),
                None,
                step.snapshot_label.clone(),
                InteractiveFindingValues {
                    selector: Some(selector.clone()),
                    ..Default::default()
                },
            ));
        } else if snap.hidden_by_style {
            findings.push(InteractiveFinding::new(
                "HiddenFocusable",
                InteractiveFindingKind::HiddenFocusableStyle,
                // CSS-hidden elements (display:none / visibility:hidden / opacity:0) are a
                // different failure type from aria-hidden-focus — no existing static rule covers
                // this exact case, so there is nothing to reference.
                None,
                Severity::Medium,
                trace.journey.clone(),
                None,
                step.snapshot_label.clone(),
                InteractiveFindingValues {
                    selector: Some(selector.clone()),
                    ..Default::default()
                },
            ));
        } else if matches!(
            snap.focus_indicator,
            Some(FocusIndicatorStatus::NotDetected)
        ) {
            findings.push(InteractiveFinding::new(
                "FocusIndicator",
                InteractiveFindingKind::FocusIndicatorNotDetected,
                None,
                Severity::Medium,
                trace.journey.clone(),
                None,
                step.snapshot_label.clone(),
                InteractiveFindingValues {
                    selector: Some(selector.clone()),
                    ..Default::default()
                },
            ));
        } else if snap.media_control_missing_name {
            findings.push(InteractiveFinding::new(
                "MediaControls",
                InteractiveFindingKind::MediaControlsMissingName,
                None,
                Severity::Medium,
                trace.journey.clone(),
                None,
                step.snapshot_label.clone(),
                InteractiveFindingValues {
                    selector: Some(selector.clone()),
                    ..Default::default()
                },
            ));
        }
    }

    findings
}

/// Returns `true` when a DOM-order selector string denotes a native
/// `<video>` element — matches `__amsCssSelector`'s tag-first segment format
/// (e.g. `"video#hero"` or `"main > video:nth-of-type(1)"`).
fn is_video_selector(selector: &str) -> bool {
    selector
        .rsplit(" > ")
        .next()
        .is_some_and(|seg| seg.starts_with("video"))
}

/// Evaluate whether every native `<video controls>` element found in the
/// pre-walk DOM order was actually reached by the tab walk.
///
/// Only trusted when the walk stopped because it detected a natural repeat
/// (`focus_stuck`, see `tab_walk::record`) rather than simply running out of
/// its step budget — otherwise a video positioned late in a long page could
/// be falsely flagged as unreachable merely because the walk never got that
/// far. Pure function — takes the evidence from the tab-walk runner.
pub fn video_controls_reachability(
    trace: &JourneyTrace,
    dom_order: &[String],
) -> Vec<InteractiveFinding> {
    let stopped_naturally =
        trace.steps.last().and_then(|s| s.result.as_deref()) == Some("focus_stuck");
    if !stopped_naturally {
        return Vec::new();
    }

    let focused: std::collections::HashSet<&str> = trace
        .steps
        .iter()
        .filter_map(|s| s.focus.as_deref())
        .collect();

    let unreachable: Vec<String> = dom_order
        .iter()
        .filter(|sel| is_video_selector(sel) && !focused.contains(sel.as_str()))
        .cloned()
        .collect();

    if unreachable.is_empty() {
        return Vec::new();
    }

    let count = unreachable.len();
    let examples = unreachable
        .iter()
        .take(3)
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");

    vec![InteractiveFinding::new(
        "MediaControls",
        InteractiveFindingKind::MediaControlsNotReachable,
        None,
        Severity::High,
        trace.journey.clone(),
        None,
        None,
        InteractiveFindingValues {
            count: Some(count as u32),
            examples: Some(examples),
            truncated: Some(count > 3),
            ..Default::default()
        },
    )]
}

/// Evaluate tab order against the DOM order of focusable elements.
///
/// Emits a single Warning-severity finding when the tab sequence jumps
/// **backwards** relative to the DOM — that is, the focus moves to an
/// element that comes earlier in the DOM than the previously focused one.
/// Forward gaps (skipping elements) are ignored: Grid/Flex/Sticky layouts
/// make them too ambiguous to call.
///
/// Pure function — takes the evidence from the tab-walk runner.
pub fn tab_walk_order(trace: &JourneyTrace, dom_order: &[String]) -> Vec<InteractiveFinding> {
    if dom_order.is_empty() {
        return Vec::new();
    }

    // Build selector → DOM index lookup.
    let dom_index =
        |selector: &str| -> Option<usize> { dom_order.iter().position(|s| s == selector) };

    let mut last_dom_index: Option<usize> = None;
    let mut reverse_jumps: Vec<String> = Vec::new();

    for step in &trace.steps {
        if step.action != "tab" {
            continue;
        }
        let Some(selector) = &step.focus else {
            continue;
        };
        let Some(idx) = dom_index(selector) else {
            // Element not in our pre-walk focusable list — could be a
            // dynamically inserted control. Skip rather than flag.
            continue;
        };
        if let Some(prev) = last_dom_index {
            if idx < prev {
                reverse_jumps.push(selector.clone());
            }
        }
        last_dom_index = Some(idx);
    }

    if reverse_jumps.is_empty() {
        return Vec::new();
    }

    // Aggregate one finding per page, not per jump — avoids spam on pages
    // with several legitimate-but-noisy layouts.
    let preview = reverse_jumps
        .iter()
        .take(3)
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");
    let count = reverse_jumps.len();

    vec![InteractiveFinding::new(
        "TabOrder",
        InteractiveFindingKind::TabOrderBackwardJumps,
        None,
        Severity::Medium,
        trace.journey.clone(),
        None,
        None,
        InteractiveFindingValues {
            count: Some(count as u32),
            examples: Some(preview),
            truncated: Some(count > 3),
            ..Default::default()
        },
    )]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::normalized::JourneyStep;

    fn step_tab(selector: &str, label: &str) -> JourneyStep {
        JourneyStep {
            action: "tab".to_string(),
            target: None,
            focus: Some(selector.to_string()),
            result: None,
            snapshot_label: Some(label.to_string()),
        }
    }

    fn snap_with(aria: bool, inert: bool, hidden: bool) -> FocusSnapshot {
        snap_full(aria, inert, hidden, None)
    }

    fn snap_full(
        aria: bool,
        inert: bool,
        hidden: bool,
        indicator: Option<FocusIndicatorStatus>,
    ) -> FocusSnapshot {
        FocusSnapshot {
            selector: Some("a".to_string()),
            aria_hidden_chain: aria,
            inert_chain: inert,
            hidden_by_style: hidden,
            focus_indicator: indicator,
            ..Default::default()
        }
    }

    fn trace_with(steps: Vec<JourneyStep>) -> JourneyTrace {
        JourneyTrace {
            journey: "tab_walk".to_string(),
            steps,
        }
    }

    #[test]
    fn clean_walk_produces_no_findings() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_with(false, false, false)];
        assert!(tab_walk(&trace, &snaps).is_empty());
    }

    #[test]
    fn aria_hidden_chain_emits_high_finding() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_with(true, false, false)];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].category, "HiddenFocusable");
        assert_eq!(findings[0].severity, Severity::High);
        assert!(findings[0].message.contains("aria-hidden"));
    }

    #[test]
    fn inert_chain_emits_high_finding() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_with(false, true, false)];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert!(findings[0].message.contains("inert"));
    }

    #[test]
    fn hidden_by_style_emits_medium_finding() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_with(false, false, true)];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::Medium);
    }

    #[test]
    fn aria_hidden_takes_precedence_over_inert() {
        // Both flags set — only the highest-priority finding is emitted.
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_with(true, true, true)];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert!(findings[0].message.contains("aria-hidden"));
    }

    #[test]
    fn start_step_is_ignored() {
        let mut trace = trace_with(vec![]);
        trace.steps.push(JourneyStep {
            action: "start".to_string(),
            target: None,
            focus: Some("body".to_string()),
            result: None,
            snapshot_label: Some("initial".to_string()),
        });
        let snaps = vec![snap_with(true, false, false)];
        assert!(tab_walk(&trace, &snaps).is_empty());
    }

    #[test]
    fn focus_indicator_not_detected_emits_finding() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_full(
            false,
            false,
            false,
            Some(FocusIndicatorStatus::NotDetected),
        )];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].category, "FocusIndicator");
        assert_eq!(findings[0].severity, Severity::Medium);
        assert!(findings[0].message.contains("focus indicator"));
    }

    #[test]
    fn focus_indicator_detected_emits_no_finding() {
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_full(
            false,
            false,
            false,
            Some(FocusIndicatorStatus::Detected),
        )];
        assert!(tab_walk(&trace, &snaps).is_empty());
    }

    #[test]
    fn focus_indicator_ambiguous_emits_no_finding() {
        // Ambiguous is suppressed in evaluation — too noisy to surface as a
        // finding. Phase 3 may aggregate it.
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_full(
            false,
            false,
            false,
            Some(FocusIndicatorStatus::Ambiguous),
        )];
        assert!(tab_walk(&trace, &snaps).is_empty());
    }

    #[test]
    fn hidden_focusable_takes_precedence_over_indicator() {
        // If aria-hidden / inert / hidden-by-style fires, we don't also flag
        // missing indicator on the same element.
        let trace = trace_with(vec![step_tab("a#one", "after_tab_1")]);
        let snaps = vec![snap_full(
            true,
            false,
            false,
            Some(FocusIndicatorStatus::NotDetected),
        )];
        let findings = tab_walk(&trace, &snaps);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].category, "HiddenFocusable");
        assert_eq!(
            findings[0].maps_to_finding.as_deref(),
            Some("a11y.aria_hidden_focus.invalid")
        );
    }

    // ── tab_walk_order tests ─────────────────────────────────────────────

    #[test]
    fn forward_walk_produces_no_order_finding() {
        let trace = trace_with(vec![
            step_tab("a", "after_tab_1"),
            step_tab("b", "after_tab_2"),
            step_tab("c", "after_tab_3"),
        ]);
        let dom = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert!(tab_walk_order(&trace, &dom).is_empty());
    }

    #[test]
    fn reverse_jump_emits_warning() {
        // Tab goes a → c → b (b is before c in DOM) → reverse jump on step 3.
        let trace = trace_with(vec![
            step_tab("a", "after_tab_1"),
            step_tab("c", "after_tab_2"),
            step_tab("b", "after_tab_3"),
        ]);
        let dom = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let findings = tab_walk_order(&trace, &dom);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].category, "TabOrder");
        assert_eq!(findings[0].severity, Severity::Medium);
        assert!(findings[0].message.contains("b"));
    }

    #[test]
    fn forward_gap_is_not_a_finding() {
        // Skipping "b" forward is allowed — Grid/Flex layouts.
        let trace = trace_with(vec![
            step_tab("a", "after_tab_1"),
            step_tab("c", "after_tab_2"),
        ]);
        let dom = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert!(tab_walk_order(&trace, &dom).is_empty());
    }

    #[test]
    fn empty_dom_order_produces_no_finding() {
        let trace = trace_with(vec![step_tab("a", "after_tab_1")]);
        assert!(tab_walk_order(&trace, &[]).is_empty());
    }

    #[test]
    fn unknown_selector_does_not_panic() {
        // Selector that's not in the DOM list — dynamic content. Skip rather
        // than flag.
        let trace = trace_with(vec![
            step_tab("a", "after_tab_1"),
            step_tab("z", "after_tab_2"),
        ]);
        let dom = vec!["a".to_string(), "b".to_string()];
        assert!(tab_walk_order(&trace, &dom).is_empty());
    }
}