auditmysite 1.7.2

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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! WCAG 2.4.4 Link Purpose (In Context)
//!
//! Ensures the purpose of each link can be determined from the link text alone
//! or from the link text together with its context.
//! Level A

use crate::accessibility::{AXNode, AXTree};
use crate::cli::WcagLevel;
use crate::wcag::types::{RuleMetadata, Severity, Violation, WcagResults};

/// Rule metadata for 2.4.4
pub(super) const LINK_PURPOSE_RULE: RuleMetadata = RuleMetadata {
    id: "2.4.4",
    name: "Link Purpose (In Context)",
    level: WcagLevel::A,
    severity: Severity::Medium,
    description: "The purpose of each link can be determined from the link text or context",
    help_url: "https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html",
    axe_id: "link-name",
    tags: &["wcag2a", "wcag244", "cat.links"],
};

/// Rule metadata for the "generic link text with detected context" sub-case.
/// Same WCAG criterion as `LINK_PURPOSE_RULE` but a distinct `axe_id` — this
/// lets `output::explanations::get_explanation` resolve a customer-facing
/// explanation that acknowledges WCAG 2.4.4's context allowance ("verify
/// manually") instead of falling back to `LINK_PURPOSE_RULE`'s generic text,
/// which is written for the no-context case and reads as an unconditional
/// rewrite instruction (#571).
pub(super) const LINK_PURPOSE_CONTEXT_RULE: RuleMetadata = RuleMetadata {
    id: "2.4.4",
    name: "Link Purpose (In Context)",
    level: WcagLevel::A,
    severity: Severity::Medium,
    description: "The purpose of each link can be determined from the link text or context",
    help_url: "https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html",
    axe_id: "link-name-context",
    tags: &["wcag2a", "wcag244", "cat.links"],
};

/// Check for link purpose issues
pub fn check_link_purpose(tree: &AXTree) -> WcagResults {
    let mut results = WcagResults::new();

    for node in tree.iter() {
        if node.ignored || node.role.as_deref() != Some("link") {
            continue;
        }

        results.nodes_checked += 1;
        let link_text = node.name.as_deref().unwrap_or("").trim();

        // Empty links (no accessible text at all) are already covered by
        // a11y.name_role.missing (WCAG 4.1.2). Reporting them here too would
        // cause the same element to appear in two separate findings and inflate
        // severity_counts. Skip empty links in this rule.
        if link_text.is_empty() {
            continue;
        }

        // Check for generic/ambiguous link text.
        // Issue #569: WCAG 2.4.4 explicitly allows link purpose to be determined
        // from context (surrounding text), not just the link text alone. A
        // generic phrase with descriptive context nearby (e.g. "Weiter" right
        // after "Zum Blogartikel") may still satisfy 2.4.4, so it's demoted to a
        // Warning — a review hint, not a confirmed violation. With no detectable
        // context, the automated match remains a confident Violation.
        if is_generic_link_text(link_text) {
            let has_context = has_link_context(node, tree);
            let axe_id = if has_context {
                LINK_PURPOSE_CONTEXT_RULE.axe_id
            } else {
                LINK_PURPOSE_RULE.axe_id
            };
            let violation = Violation::new(
                LINK_PURPOSE_RULE.id,
                LINK_PURPOSE_RULE.name,
                LINK_PURPOSE_RULE.level,
                LINK_PURPOSE_RULE.severity,
                format!("Link has generic text: '{}'", link_text),
                &node.node_id,
            )
            .with_role(node.role.clone())
            .with_name(node.name.clone())
            .with_fix("Use descriptive link text that explains where the link goes")
            .with_help_url(LINK_PURPOSE_RULE.help_url)
            .with_rule_id(axe_id);

            if has_context {
                results.add_violation(violation.as_warning());
            } else {
                results.add_violation(violation);
            }
        } else if looks_like_url(link_text) && !has_link_context(node, tree) {
            // Check for URL-only link text
            let violation = Violation::new(
                LINK_PURPOSE_RULE.id,
                LINK_PURPOSE_RULE.name,
                LINK_PURPOSE_RULE.level,
                Severity::Low,
                "Link text appears to be a raw URL",
                &node.node_id,
            )
            .with_role(node.role.clone())
            .with_name(node.name.clone())
            .with_fix("Replace URL with descriptive text")
            .with_help_url(LINK_PURPOSE_RULE.help_url)
            .with_rule_id(LINK_PURPOSE_RULE.axe_id);

            results.add_violation(violation.as_warning());
        } else if link_text.len() == 1
            && !link_text
                .chars()
                .next()
                .map(|c| c.is_ascii_digit())
                .unwrap_or(false)
        {
            // Check for single character links
            let violation = Violation::new(
                LINK_PURPOSE_RULE.id,
                LINK_PURPOSE_RULE.name,
                LINK_PURPOSE_RULE.level,
                LINK_PURPOSE_RULE.severity,
                format!("Link has single character text: '{}'", link_text),
                &node.node_id,
            )
            .with_role(node.role.clone())
            .with_name(node.name.clone())
            .with_fix("Expand single character links to be more descriptive")
            .with_help_url(LINK_PURPOSE_RULE.help_url)
            .with_rule_id(LINK_PURPOSE_RULE.axe_id);

            results.add_violation(violation);
        } else {
            results.passes += 1;
        }

        // Check for links that open in new window without warning
        if opens_new_window(node) && !indicates_new_window(link_text) {
            let violation = Violation::new(
                LINK_PURPOSE_RULE.id,
                LINK_PURPOSE_RULE.name,
                LINK_PURPOSE_RULE.level,
                Severity::Low,
                "Link opens in new window without indication",
                &node.node_id,
            )
            .with_role(node.role.clone())
            .with_name(node.name.clone())
            .with_fix("Add '(opens in new window)' to link text")
            .with_help_url(LINK_PURPOSE_RULE.help_url)
            .with_rule_id(LINK_PURPOSE_RULE.axe_id);

            results.add_violation(violation);
        }
    }

    results
}

/// Check if the link has a descriptive context
fn has_link_context(node: &AXNode, tree: &AXTree) -> bool {
    if let Some(desc) = &node.description {
        if !desc.trim().is_empty() {
            return true;
        }
    }

    if let Some(parent_id) = &node.parent_id {
        if let Some(parent) = tree.get_node(parent_id) {
            for child_id in &parent.child_ids {
                if child_id == &node.node_id {
                    continue;
                }
                if let Some(sibling) = tree.get_node(child_id) {
                    if !sibling.ignored {
                        let text = sibling.name.as_deref().unwrap_or("").trim();
                        if !text.is_empty()
                            && matches!(
                                sibling.role.as_deref(),
                                Some("StaticText" | "text" | "paragraph")
                            )
                        {
                            return true;
                        }
                    }
                }
            }
        }
    }

    false
}

/// Check if link text is generic/ambiguous
fn is_generic_link_text(text: &str) -> bool {
    let generic_phrases = [
        // English
        "click here",
        "click",
        "here",
        "read more",
        "more",
        "learn more",
        "info",
        "information",
        "details",
        "link",
        "this link",
        "go",
        "continue",
        "download",
        "view",
        "see more",
        "see all",
        "read",
        "start",
        "begin",
        "submit",
        "next",
        "previous",
        // German
        "weiterlesen",
        "mehr erfahren",
        "mehr",
        "hier klicken",
        "klicken sie hier",
        "hier",
        "weiter",
        "alle anzeigen",
        "ansehen",
        "jetzt lesen",
        "öffnen",
        // French
        "cliquez ici",
        "ici",
        "en savoir plus",
        "lire la suite",
        "lire plus",
        "plus",
        "voir plus",
        "voir tout",
        "continuer",
        "télécharger",
        "suivant",
        "précédent",
        "commencer",
        // Spanish
        "haz clic aquí",
        "aquí",
        "leer más",
        "más",
        "saber más",
        "ver más",
        "ver todo",
        "continuar",
        "descargar",
        "siguiente",
        "anterior",
        "empezar",
        // Italian
        "clicca qui",
        "qui",
        "leggi di più",
        "scopri di più",
        "più",
        "vedi di più",
        "vedi tutto",
        "continua",
        "scarica",
        "successivo",
        "precedente",
        "inizia",
        // Portuguese
        "clique aqui",
        "aqui",
        "leia mais",
        "saiba mais",
        "mais",
        "ver mais",
        "ver tudo",
        "baixar",
        "próximo",
        "começar",
        // Dutch
        "klik hier",
        "meer lezen",
        "lees meer",
        "meer",
        "bekijk meer",
        "volgende",
        "vorige",
        "downloaden",
        "beginnen",
        // Swedish
        "klicka här",
        "här",
        "läs mer",
        "mer",
        "nästa",
        "föregående",
        "ladda ner",
        "börja",
        // Norwegian
        "klikk her",
        "her",
        "les mer",
        "neste",
        "forrige",
        "last ned",
        // Danish
        "klik her",
        "læs mere",
        "mere",
        "næste",
        // Finnish
        "klikkaa tästä",
        "lue lisää",
        "lisää",
        "seuraava",
        "edellinen",
        "lataa",
        // Polish
        "kliknij tutaj",
        "tutaj",
        "czytaj więcej",
        "więcej",
        "następny",
        "poprzedni",
        "pobierz",
        // Turkish
        "buraya tıklayın",
        "devamını oku",
        "daha fazla",
        "sonraki",
        "önceki",
        "indir",
        // Czech / Slovak
        "klikněte zde",
        "zde",
        "číst více",
        "více",
        "další",
        "předchozí",
        "stáhnout",
        // Romanian
        "citește mai mult",
        "mai mult",
        "următor",
        "descărcați",
        // Hungarian
        "tovább olvas",
        "több",
        "következő",
        "előző",
        "letöltés",
        // Symbols
        "...",
        ">",
        ">>",
        "→",
    ];

    let text_lower = text.to_lowercase();
    generic_phrases.iter().any(|&phrase| text_lower == phrase)
}

/// Check if text looks like a URL
fn looks_like_url(text: &str) -> bool {
    text.starts_with("http://")
        || text.starts_with("https://")
        || text.starts_with("www.")
        || (text.contains(".com") && !text.contains(' '))
        || (text.contains(".org") && !text.contains(' '))
        || (text.contains(".net") && !text.contains(' '))
}

/// Check if link opens in new window
fn opens_new_window(node: &AXNode) -> bool {
    node.properties
        .iter()
        .any(|p| p.name.to_lowercase() == "haspopup" && p.value.as_bool().unwrap_or(false))
}

/// Check if link text indicates it opens in new window
fn indicates_new_window(text: &str) -> bool {
    let indicators = [
        "new window",
        "new tab",
        "opens in",
        "(external)",
        "external link",
        "[external]",
    ];
    let text_lower = text.to_lowercase();
    indicators.iter().any(|&ind| text_lower.contains(ind))
}

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

    fn create_link(id: &str, name: Option<&str>) -> AXNode {
        AXNode {
            node_id: id.to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("link".to_string()),
            name: name.map(String::from),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: None,
            backend_dom_node_id: None,
        }
    }

    #[test]
    fn test_link_purpose_rule_metadata() {
        assert_eq!(LINK_PURPOSE_RULE.id, "2.4.4");
        assert_eq!(LINK_PURPOSE_RULE.level, WcagLevel::A);
    }

    #[test]
    fn test_generic_link_text() {
        assert!(is_generic_link_text("click here"));
        assert!(is_generic_link_text("Read more"));
        assert!(is_generic_link_text("HERE"));
        assert!(is_generic_link_text("Weiterlesen"));
        assert!(is_generic_link_text("Mehr erfahren"));
        assert!(is_generic_link_text("weiter"));
        assert!(!is_generic_link_text("View product specifications"));
        assert!(!is_generic_link_text("Artikel über HBOT lesen"));
    }

    #[test]
    fn test_looks_like_url() {
        assert!(looks_like_url("https://example.com"));
        assert!(looks_like_url("www.example.com"));
        assert!(!looks_like_url("Visit our website"));
    }

    #[test]
    fn test_empty_link() {
        // Empty links are handled by a11y.name_role.missing (4.1.2).
        // This rule (2.4.4) skips them to avoid double-reporting.
        let tree = AXTree::from_nodes(vec![create_link("1", None)]);
        let results = check_link_purpose(&tree);
        assert!(
            results.violations.is_empty(),
            "Empty links must not be reported by link_purpose — covered by name_role.missing"
        );
    }

    #[test]
    fn test_generic_link() {
        let tree = AXTree::from_nodes(vec![create_link("1", Some("click here"))]);
        let results = check_link_purpose(&tree);
        assert!(results
            .violations
            .iter()
            .any(|v| v.message.contains("generic text")));
    }

    #[test]
    fn test_good_link_text() {
        let tree = AXTree::from_nodes(vec![create_link(
            "1",
            Some("View our accessibility statement"),
        )]);
        let results = check_link_purpose(&tree);
        assert!(results.violations.is_empty());
    }

    #[test]
    fn test_url_as_link_text() {
        let tree = AXTree::from_nodes(vec![create_link("1", Some("https://example.com/page"))]);
        let results = check_link_purpose(&tree);
        assert!(results
            .warnings
            .iter()
            .any(|v| v.message.contains("raw URL")));
    }

    #[test]
    fn test_generic_link_with_context_is_warning() {
        // Issue #569: "Weiter" next to descriptive sibling text may satisfy
        // 2.4.4 via context (WCAG explicitly allows this) — automated check
        // can't confirm that, so it must be a Warning, not a Violation.
        let parent = AXNode {
            node_id: "parent".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("paragraph".to_string()),
            name: None,
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec!["text1".to_string(), "link1".to_string()],
            parent_id: None,
            backend_dom_node_id: None,
        };
        let text_node = AXNode {
            node_id: "text1".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("StaticText".to_string()),
            name: Some("Zum Blogartikel über Barrierefreiheit".to_string()),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: Some("parent".to_string()),
            backend_dom_node_id: None,
        };
        let link_node = AXNode {
            node_id: "link1".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("link".to_string()),
            name: Some("weiter".to_string()),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: Some("parent".to_string()),
            backend_dom_node_id: None,
        };
        let tree = AXTree::from_nodes(vec![parent, text_node, link_node]);
        let results = check_link_purpose(&tree);
        let warning = results
            .warnings
            .iter()
            .find(|v| v.message.contains("generic text"))
            .expect("expected a warning-kind finding for generic text with context");
        // Regression for #571: this finding must carry the distinct
        // "link-name-context" rule_id, not the shared "link-name" id, so
        // `output::explanations::get_explanation` resolves the context-
        // verification explanation instead of LINK_PURPOSE_RULE's generic
        // unconditional-rewrite text.
        assert_eq!(
            warning.rule_id.as_deref(),
            Some(LINK_PURPOSE_CONTEXT_RULE.axe_id)
        );
        assert!(
            !results
                .violations
                .iter()
                .any(|v| v.message.contains("generic text")),
            "generic text with context must not be a confirmed violation"
        );
    }

    #[test]
    fn test_url_as_link_text_with_context() {
        let parent = AXNode {
            node_id: "parent".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("paragraph".to_string()),
            name: None,
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec!["text1".to_string(), "link1".to_string()],
            parent_id: None,
            backend_dom_node_id: None,
        };
        let text_node = AXNode {
            node_id: "text1".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("StaticText".to_string()),
            name: Some("Go to ".to_string()),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: Some("parent".to_string()),
            backend_dom_node_id: None,
        };
        let link_node = AXNode {
            node_id: "link1".to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some("link".to_string()),
            name: Some("https://example.com".to_string()),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: Some("parent".to_string()),
            backend_dom_node_id: None,
        };
        let tree = AXTree::from_nodes(vec![parent, text_node, link_node]);
        let results = check_link_purpose(&tree);
        assert!(results.warnings.is_empty());
        assert!(results.violations.is_empty());
    }
}