Skip to main content

rustango_cms/
a11y.rs

1//! Server-side accessibility heuristics.
2//!
3//! Walks the canonical [`Page`] row + the page's rendered extension
4//! HTML and flags common accessibility issues. Output is rendered
5//! as a side panel on the page editor.
6//!
7//! Contrast / ARIA checks run client-side instead: the admin serves a
8//! bundled axe-core against the preview pane.
9//!
10//! ## Checks
11//!
12//! | Code | Severity | What it catches |
13//! |---|---|---|
14//! | `empty_title` | Error | Page title blank |
15//! | `seo_title_too_long` | Warning | SEO title > 70 chars (truncated in SERPs) |
16//! | `seo_description_too_long` | Warning | SEO description > 200 chars |
17//! | `noindex` | Info | Page is excluded from indexing |
18//! | `img_missing_alt` | Error | `<img>` tag with no `alt=` attribute |
19//! | `empty_link` | Warning | `<a>...</a>` with no text or only `click here` / `read more` |
20//! | `skipped_heading` | Warning | Heading levels jump (h1 → h3) |
21//!
22//! Heuristics are deliberately forgiving — false negatives are
23//! preferable to noisy false positives that train editors to ignore
24//! the panel.
25
26use crate::page::Page;
27
28/// One accessibility issue surfaced to the editor.
29#[derive(Debug, Clone, serde::Serialize)]
30pub struct Violation {
31    pub code: &'static str,
32    pub severity: Severity,
33    pub message: String,
34    /// Optional canonical field hint — drives a scroll-to-field link
35    /// in the side panel.
36    pub field: Option<&'static str>,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
40#[serde(rename_all = "lowercase")]
41pub enum Severity {
42    Error,
43    Warning,
44    Info,
45}
46
47impl Severity {
48    #[must_use]
49    pub fn icon(self) -> &'static str {
50        match self {
51            Self::Error => "error",
52            Self::Warning => "warning",
53            Self::Info => "info",
54        }
55    }
56}
57
58/// Run every check against `page` + the optional rendered HTML body
59/// the page-type handler exposed. Returns a stable-sorted list with
60/// errors first, warnings second, info last.
61#[must_use]
62pub fn check_page(page: &Page, body_html: Option<&str>) -> Vec<Violation> {
63    let mut out = Vec::new();
64    check_canonical(page, &mut out);
65    if let Some(html) = body_html {
66        check_html(html, &mut out);
67    }
68    out.sort_by_key(|v| match v.severity {
69        Severity::Error => 0,
70        Severity::Warning => 1,
71        Severity::Info => 2,
72    });
73    out
74}
75
76/// Counts grouped by severity. Drives the side-panel tab badge.
77#[must_use]
78pub fn count_by_severity(violations: &[Violation]) -> (usize, usize, usize) {
79    let mut errors = 0;
80    let mut warnings = 0;
81    let mut infos = 0;
82    for v in violations {
83        match v.severity {
84            Severity::Error => errors += 1,
85            Severity::Warning => warnings += 1,
86            Severity::Info => infos += 1,
87        }
88    }
89    (errors, warnings, infos)
90}
91
92fn check_canonical(page: &Page, out: &mut Vec<Violation>) {
93    if page.title.trim().is_empty() {
94        out.push(Violation {
95            code: "empty_title",
96            severity: Severity::Error,
97            message: "Page title is empty — screen readers + browser tabs need a title.".to_owned(),
98            field: Some("title"),
99        });
100    }
101    if page.seo_title.chars().count() > 70 {
102        out.push(Violation {
103            code: "seo_title_too_long",
104            severity: Severity::Warning,
105            message: format!(
106                "SEO title is {} chars — search engines truncate around 70.",
107                page.seo_title.chars().count()
108            ),
109            field: Some("seo_title"),
110        });
111    }
112    if page.seo_description.chars().count() > 200 {
113        out.push(Violation {
114            code: "seo_description_too_long",
115            severity: Severity::Warning,
116            message: format!(
117                "SEO description is {} chars — search engines truncate around 200.",
118                page.seo_description.chars().count()
119            ),
120            field: Some("seo_description"),
121        });
122    }
123    if !page.robots_index {
124        out.push(Violation {
125            code: "noindex",
126            severity: Severity::Info,
127            message: "This page is set to noindex — search engines are asked to skip it."
128                .to_owned(),
129            field: Some("robots_index"),
130        });
131    }
132}
133
134fn check_html(html: &str, out: &mut Vec<Violation>) {
135    scan_images(html, out);
136    scan_links(html, out);
137    scan_heading_order(html, out);
138}
139
140/// Find every `<img …>` tag and report ones without an `alt=…`
141/// attribute. Empty `alt=""` counts as decorative + is allowed.
142fn scan_images(html: &str, out: &mut Vec<Violation>) {
143    let mut missing = 0;
144    for tag in iter_tags(html, "img") {
145        if !has_attr(tag, "alt") {
146            missing += 1;
147        }
148    }
149    if missing > 0 {
150        out.push(Violation {
151            code: "img_missing_alt",
152            severity: Severity::Error,
153            message: format!(
154                "{missing} image{plural} missing `alt` attribute. Use `alt=\"\"` for purely decorative images.",
155                plural = if missing == 1 { " is" } else { "s are" }
156            ),
157            field: None,
158        });
159    }
160}
161
162/// Find `<a>` tags whose visible text is empty or a known-bad
163/// placeholder. Match is intentionally narrow — we don't want to
164/// flag every "Learn more" link.
165fn scan_links(html: &str, out: &mut Vec<Violation>) {
166    let mut bad = 0;
167    let lower = html.to_ascii_lowercase();
168    let mut cursor = 0;
169    while let Some(open) = lower[cursor..].find("<a ") {
170        let abs_open = cursor + open;
171        let Some(close_lt) = lower[abs_open..].find('>') else {
172            break;
173        };
174        let abs_close_lt = abs_open + close_lt + 1;
175        let Some(close_a) = lower[abs_close_lt..].find("</a>") else {
176            break;
177        };
178        let abs_close_a = abs_close_lt + close_a;
179        let inner = &html[abs_close_lt..abs_close_a];
180        let stripped = strip_tags(inner).trim().to_ascii_lowercase();
181        if stripped.is_empty()
182            || stripped == "click here"
183            || stripped == "here"
184            || stripped == "read more"
185            || stripped == "learn more"
186        {
187            bad += 1;
188        }
189        cursor = abs_close_a + 4;
190    }
191    if bad > 0 {
192        out.push(Violation {
193            code: "empty_link",
194            severity: Severity::Warning,
195            message: format!(
196                "{bad} link{plural} have empty or generic text (e.g. \"click here\"). Use descriptive link text instead.",
197                plural = if bad == 1 { "" } else { "s" }
198            ),
199            field: None,
200        });
201    }
202}
203
204/// Detect heading-order jumps. The rule: any heading that's more
205/// than one level deeper than the previous one is suspicious.
206/// (h1 → h2 OK; h2 → h4 NOT OK; h2 → h2 OK; descending always OK.)
207fn scan_heading_order(html: &str, out: &mut Vec<Violation>) {
208    let mut last_level: Option<u8> = None;
209    let mut jumps = 0;
210    let lower = html.to_ascii_lowercase();
211    let mut cursor = 0;
212    while cursor < lower.len() {
213        let Some(rel) = lower[cursor..].find("<h") else {
214            break;
215        };
216        let abs = cursor + rel;
217        // Need at least one digit after `<h`.
218        let after = &lower[abs + 2..];
219        let level_char = after.chars().next().unwrap_or(' ');
220        if !('1'..='6').contains(&level_char) {
221            cursor = abs + 2;
222            continue;
223        }
224        // Confirm next char is `>` or space (a real heading tag).
225        let next = after.chars().nth(1).unwrap_or(' ');
226        if next != '>' && !next.is_whitespace() {
227            cursor = abs + 2;
228            continue;
229        }
230        let level = (level_char as u8) - b'0';
231        if let Some(prev) = last_level {
232            if level > prev + 1 {
233                jumps += 1;
234            }
235        }
236        last_level = Some(level);
237        cursor = abs + 2;
238    }
239    if jumps > 0 {
240        out.push(Violation {
241            code: "skipped_heading",
242            severity: Severity::Warning,
243            message: format!(
244                "{jumps} heading level jump{plural} detected (e.g. h1 → h3). Use consecutive levels so screen readers can build the outline.",
245                plural = if jumps == 1 { "" } else { "s" }
246            ),
247            field: None,
248        });
249    }
250}
251
252// ---------------------------------------------------------------
253// tiny tag iterators (no html5ever dep)
254// ---------------------------------------------------------------
255
256/// Iterate over every opening tag in `html` whose name matches
257/// `tag_lower` (case-insensitive). Yields the raw text of the
258/// opening tag (e.g. `<img src="x" alt="y">`).
259fn iter_tags<'a>(html: &'a str, tag_lower: &'a str) -> impl Iterator<Item = &'a str> {
260    TagIter {
261        html,
262        tag_lower,
263        cursor: 0,
264    }
265}
266
267struct TagIter<'a> {
268    html: &'a str,
269    tag_lower: &'a str,
270    cursor: usize,
271}
272
273impl<'a> Iterator for TagIter<'a> {
274    type Item = &'a str;
275    fn next(&mut self) -> Option<&'a str> {
276        let lower = self.html.to_ascii_lowercase();
277        let needle_lower = format!("<{}", self.tag_lower);
278        while self.cursor < lower.len() {
279            let rel = lower[self.cursor..].find(&needle_lower)?;
280            let abs = self.cursor + rel;
281            let after = abs + needle_lower.len();
282            // Validate the byte after the tag name is a space or `>`,
283            // so `<imgs` doesn't match `<img`.
284            let next = lower.as_bytes().get(after).copied().unwrap_or(b' ');
285            if next != b'>' && next != b' ' && next != b'/' && next != b'\t' && next != b'\n' {
286                self.cursor = after;
287                continue;
288            }
289            let Some(gt) = lower[after..].find('>') else {
290                return None;
291            };
292            let end = after + gt + 1;
293            let slice = &self.html[abs..end];
294            self.cursor = end;
295            return Some(slice);
296        }
297        None
298    }
299}
300
301fn has_attr(tag: &str, name: &str) -> bool {
302    let lower = tag.to_ascii_lowercase();
303    let needle = format!("{name}=");
304    let bare = name.to_owned();
305    lower.contains(&needle) || lower.split_whitespace().any(|tok| tok == bare)
306}
307
308/// Strip every `<…>` from `inner`. Cheap one-pass scanner.
309fn strip_tags(inner: &str) -> String {
310    let mut out = String::with_capacity(inner.len());
311    let mut depth = 0;
312    for c in inner.chars() {
313        if c == '<' {
314            depth += 1;
315        } else if c == '>' && depth > 0 {
316            depth -= 1;
317        } else if depth == 0 {
318            out.push(c);
319        }
320    }
321    out
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::page::PageStatus;
328    use rustango::sql::Auto;
329
330    fn sample_page() -> Page {
331        Page {
332            id: Auto::Set(1),
333            page_type_id: 1,
334            title: "Hello world".to_owned(),
335            slug: "hello".to_owned(),
336            path: "0001/".to_owned(),
337            url_path: "/hello".to_owned(),
338            preview_path: String::new(),
339            template_override: String::new(),
340            depth: 1,
341            parent_id: None,
342            locale_variant_of: None,
343            alias_of: None,
344            theme_id: None,
345            sort_order: 0,
346            status: PageStatus::Published.as_str().to_owned(),
347            published_at: None,
348            last_published_at: None,
349            go_live_at: None,
350            expire_at: None,
351            seo_title: String::new(),
352            seo_description: String::new(),
353            robots_index: true,
354            sitemap_priority: 0.5,
355            show_in_menus: false,
356            og_title: String::new(),
357            og_description: String::new(),
358            og_image_media_id: None,
359            twitter_card: "summary_large_image".to_owned(),
360            notification_pre_published_sent: false,
361            created_at: Auto::Unset,
362            updated_at: Auto::Unset,
363        }
364    }
365
366    #[test]
367    fn flags_empty_title() {
368        let mut p = sample_page();
369        p.title = String::new();
370        let v = check_page(&p, None);
371        assert!(v.iter().any(|x| x.code == "empty_title"));
372    }
373
374    #[test]
375    fn passes_normal_page() {
376        let p = sample_page();
377        let v = check_page(&p, None);
378        assert!(v.iter().all(|x| x.severity != Severity::Error));
379    }
380
381    #[test]
382    fn flags_long_seo_title() {
383        let mut p = sample_page();
384        p.seo_title = "x".repeat(80);
385        let v = check_page(&p, None);
386        assert!(v.iter().any(|x| x.code == "seo_title_too_long"));
387    }
388
389    #[test]
390    fn flags_noindex_as_info() {
391        let mut p = sample_page();
392        p.robots_index = false;
393        let v = check_page(&p, None);
394        let row = v.iter().find(|x| x.code == "noindex").expect("noindex");
395        assert_eq!(row.severity, Severity::Info);
396    }
397
398    #[test]
399    fn flags_img_without_alt() {
400        let p = sample_page();
401        let html = r#"<p><img src="foo.png"></p>"#;
402        let v = check_page(&p, Some(html));
403        assert!(v.iter().any(|x| x.code == "img_missing_alt"));
404    }
405
406    #[test]
407    fn passes_img_with_empty_alt() {
408        let p = sample_page();
409        let html = r#"<img src="x.png" alt="">"#;
410        let v = check_page(&p, Some(html));
411        assert!(v.iter().all(|x| x.code != "img_missing_alt"));
412    }
413
414    #[test]
415    fn flags_click_here_link() {
416        let p = sample_page();
417        let html = r#"<a href="/x">click here</a>"#;
418        let v = check_page(&p, Some(html));
419        assert!(v.iter().any(|x| x.code == "empty_link"));
420    }
421
422    #[test]
423    fn flags_skipped_heading_h1_to_h3() {
424        let p = sample_page();
425        let html = "<h1>Title</h1><h3>Sub</h3>";
426        let v = check_page(&p, Some(html));
427        assert!(v.iter().any(|x| x.code == "skipped_heading"));
428    }
429
430    #[test]
431    fn passes_consecutive_headings() {
432        let p = sample_page();
433        let html = "<h1>A</h1><h2>B</h2><h3>C</h3>";
434        let v = check_page(&p, Some(html));
435        assert!(v.iter().all(|x| x.code != "skipped_heading"));
436    }
437
438    #[test]
439    fn errors_come_first_in_sort_order() {
440        let mut p = sample_page();
441        p.title = String::new();
442        p.seo_title = "x".repeat(80);
443        let v = check_page(&p, None);
444        assert_eq!(v.first().unwrap().severity, Severity::Error);
445    }
446
447    #[test]
448    fn count_by_severity_buckets() {
449        let mut p = sample_page();
450        p.title = String::new();
451        p.seo_title = "x".repeat(80);
452        p.robots_index = false;
453        let v = check_page(&p, None);
454        let (errors, warnings, infos) = count_by_severity(&v);
455        assert_eq!(errors, 1);
456        assert_eq!(warnings, 1);
457        assert_eq!(infos, 1);
458    }
459}