accessibility_rs/engine/audit/
auditor.rs

1use super::tree::parse_accessibility_tree;
2use super::tree::parse_accessibility_tree_bounded;
3use accessibility_scraper::ElementRef;
4use accessibility_scraper::Html;
5use accessibility_tree::style::StyleSet;
6use markup5ever::local_name;
7use taffy::TaffyTree;
8
9/// The configuration for auditing
10#[derive(Clone, Debug)]
11pub struct Auditor<'a> {
12    /// the html document
13    pub document: &'a Html,
14    /// the tree to map to nodes
15    pub tree: std::collections::BTreeMap<&'a str, Vec<(ElementRef<'a>, Option<taffy::NodeId>)>>,
16    /// styles for the audit
17    pub author: StyleSet,
18    /// language to get results in
19    pub locale: &'a str,
20}
21
22impl<'a> Auditor<'a> {
23    /// Create a new auditor that can be used to validate accessibility
24    pub fn new(
25        document: &'a Html,
26        css_rules: &str,
27        bounds: bool,
28        locale: &'a str,
29    ) -> (Auditor<'a>, Option<TaffyTree>) {
30        // TODO: make stylesheet building optional and only on first requirement
31        let author = {
32            let mut author = accessibility_tree::style::StyleSetBuilder::new();
33            if !css_rules.is_empty() {
34                author.add_stylesheet(css_rules);
35            } else {
36                let selector =
37                    unsafe { accessibility_scraper::Selector::parse("style").unwrap_unchecked() };
38                let mut s = document.select(&selector);
39
40                while let Some(node) = s.next() {
41                    if let Some(type_attr) = node.attr(&local_name!("type")) {
42                        if !type_attr.eq_ignore_ascii_case("text/css") {
43                            continue;
44                        }
45                        author.add_stylesheet(&node.inner_html())
46                    }
47                }
48            }
49            author.finish()
50        };
51
52        let (tree, taffy) = if bounds {
53            parse_accessibility_tree_bounded(&document, &author)
54        } else {
55            parse_accessibility_tree(&document, &author)
56        };
57
58        (
59            Auditor {
60                document,
61                tree,
62                author,
63                locale,
64            },
65            taffy,
66        )
67    }
68}