Skip to main content

rustango_cms/
content_checks.rs

1//! Extensible content-checks framework.
2//!
3//! The accessibility panel ([`crate::a11y`]) runs a fixed set of
4//! server-side heuristics. This module generalises that idea into a
5//! *registerable* check framework:
6//! a host implements [`ContentCheck`], registers it with
7//! [`register_content_check!`](crate::register_content_check!), and its findings show up in the editor's
8//! "Content & SEO" panel alongside the built-ins.
9//!
10//! Ships built-in SEO checks — most notably the
11//! **empty meta-description** check — plus a thin /
12//! missing social-image heuristic.
13//!
14//! Checks are synchronous and run against the saved [`Page`] (the panel
15//! is server-rendered on editor open, same as the a11y heuristics). The
16//! [`Severity`] levels are shared with the a11y
17//! panel so the two read consistently.
18
19use crate::a11y::Severity;
20use crate::page::Page;
21
22/// One content/SEO finding surfaced to the editor. Mirrors
23/// [`crate::a11y::Violation`] but carries a `category` so the panel can
24/// group SEO / content / custom checks.
25#[derive(Debug, Clone, serde::Serialize)]
26pub struct Finding {
27    /// Stable identifier, e.g. `"empty_seo_description"`.
28    pub code: &'static str,
29    /// Display bucket, e.g. `"SEO"` or `"Content"`.
30    pub category: &'static str,
31    pub severity: Severity,
32    pub message: String,
33    /// Optional canonical field hint — drives a scroll-to-field link.
34    pub field: Option<&'static str>,
35}
36
37/// A registerable content check. Implementors are zero-field structs
38/// registered with [`register_content_check!`](crate::register_content_check!).
39pub trait ContentCheck: Send + Sync + 'static {
40    /// Stable code prefix / identifier for the check.
41    fn code(&self) -> &'static str;
42    /// Run against the page; return zero or more findings.
43    fn run(&self, page: &Page) -> Vec<Finding>;
44}
45
46/// Inventory registration — mirrors [`crate::admin::report`] /
47/// [`crate::admin::model_admin`].
48pub struct ContentCheckRegistration {
49    pub factory: fn() -> Box<dyn ContentCheck>,
50}
51
52inventory::collect!(ContentCheckRegistration);
53
54/// Register a [`ContentCheck`] implementation.
55///
56/// ```ignore
57/// #[derive(Default)]
58/// struct MyCheck;
59/// impl rustango_cms::content_checks::ContentCheck for MyCheck { /* … */ }
60/// rustango_cms::register_content_check!(MyCheck);
61/// ```
62#[macro_export]
63macro_rules! register_content_check {
64    ($ty:ty) => {
65        $crate::inventory::submit! {
66            $crate::content_checks::ContentCheckRegistration {
67                factory: || ::std::boxed::Box::new(<$ty>::default()),
68            }
69        }
70    };
71}
72
73/// Every registered content check, sorted by `code` for a stable order.
74#[must_use]
75pub fn registered_checks() -> Vec<Box<dyn ContentCheck>> {
76    let mut v: Vec<Box<dyn ContentCheck>> = inventory::iter::<ContentCheckRegistration>
77        .into_iter()
78        .map(|r| (r.factory)())
79        .collect();
80    v.sort_by_key(|c| c.code());
81    v
82}
83
84/// Run every registered check against `page`, returning a stable-sorted
85/// list (errors first, then warnings, then info; ties keep registry
86/// order). Drives the editor's "Content & SEO" panel.
87#[must_use]
88pub fn run_all(page: &Page) -> Vec<Finding> {
89    let mut out = Vec::new();
90    for check in registered_checks() {
91        out.extend(check.run(page));
92    }
93    out.sort_by_key(|f| match f.severity {
94        Severity::Error => 0,
95        Severity::Warning => 1,
96        Severity::Info => 2,
97    });
98    out
99}
100
101/// Counts grouped by severity — drives the panel badge.
102#[must_use]
103pub fn count_by_severity(findings: &[Finding]) -> (usize, usize, usize) {
104    let mut errors = 0;
105    let mut warnings = 0;
106    let mut infos = 0;
107    for f in findings {
108        match f.severity {
109            Severity::Error => errors += 1,
110            Severity::Warning => warnings += 1,
111            Severity::Info => infos += 1,
112        }
113    }
114    (errors, warnings, infos)
115}
116
117// ============================================================ built-in SEO checks
118
119/// Recommended meta-description length floor — shorter than this and
120/// search engines have little to work with.
121const MIN_SEO_DESCRIPTION_CHARS: usize = 50;
122
123/// **Empty meta description** (SEO check). A page with no
124/// `seo_description` lets the search engine synthesise a snippet from
125/// the body — usually worse than an authored one. Warning (it's
126/// recommended, not required).
127#[derive(Default)]
128pub struct EmptySeoDescriptionCheck;
129
130impl ContentCheck for EmptySeoDescriptionCheck {
131    fn code(&self) -> &'static str {
132        "empty_seo_description"
133    }
134    fn run(&self, page: &Page) -> Vec<Finding> {
135        if page.seo_description.trim().is_empty() {
136            vec![Finding {
137                code: "empty_seo_description",
138                category: "SEO",
139                severity: Severity::Warning,
140                message: "No meta description — search engines will synthesise a snippet \
141                          from the page body, which is usually worse than an authored one."
142                    .to_owned(),
143                field: Some("seo_description"),
144            }]
145        } else {
146            Vec::new()
147        }
148    }
149}
150
151/// **Thin meta description** — present but very short, so it under-uses
152/// the SERP snippet. Info (a nudge, not a problem). Skipped when the
153/// description is empty (the empty check already fired).
154#[derive(Default)]
155pub struct ThinSeoDescriptionCheck;
156
157impl ContentCheck for ThinSeoDescriptionCheck {
158    fn code(&self) -> &'static str {
159        "thin_seo_description"
160    }
161    fn run(&self, page: &Page) -> Vec<Finding> {
162        let len = page.seo_description.trim().chars().count();
163        if len > 0 && len < MIN_SEO_DESCRIPTION_CHARS {
164            vec![Finding {
165                code: "thin_seo_description",
166                category: "SEO",
167                severity: Severity::Info,
168                message: format!(
169                    "Meta description is only {len} characters — aim for ~50–160 to fill \
170                     the search snippet."
171                ),
172                field: Some("seo_description"),
173            }]
174        } else {
175            Vec::new()
176        }
177    }
178}
179
180/// **Missing social share image** — no `og:image`, so link unfurls on
181/// social / chat have no preview image. Info.
182#[derive(Default)]
183pub struct MissingOgImageCheck;
184
185impl ContentCheck for MissingOgImageCheck {
186    fn code(&self) -> &'static str {
187        "missing_og_image"
188    }
189    fn run(&self, page: &Page) -> Vec<Finding> {
190        if page.og_image_media_id.is_none() {
191            vec![Finding {
192                code: "missing_og_image",
193                category: "SEO",
194                severity: Severity::Info,
195                message: "No social share image (og:image) — links to this page won't show \
196                          a preview image when shared."
197                    .to_owned(),
198                field: Some("og_image_media_id"),
199            }]
200        } else {
201            Vec::new()
202        }
203    }
204}
205
206register_content_check!(EmptySeoDescriptionCheck);
207register_content_check!(ThinSeoDescriptionCheck);
208register_content_check!(MissingOgImageCheck);
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::page::PageStatus;
214    use rustango::sql::Auto;
215
216    /// Minimal valid page for check fixtures — every field a check
217    /// reads is set; the rest get sensible zero values.
218    fn sample_page() -> Page {
219        Page {
220            id: Auto::Unset,
221            page_type_id: 1,
222            title: "Hello".to_owned(),
223            slug: "hello".to_owned(),
224            path: "0001".to_owned(),
225            url_path: "/hello".to_owned(),
226            preview_path: String::new(),
227            template_override: String::new(),
228            depth: 1,
229            parent_id: None,
230            locale_variant_of: None,
231            alias_of: None,
232            theme_id: None,
233            sort_order: 0,
234            status: PageStatus::Draft.as_str().to_owned(),
235            published_at: None,
236            last_published_at: None,
237            go_live_at: None,
238            expire_at: None,
239            seo_title: String::new(),
240            seo_description: "A good, sufficiently long meta description for this page.".to_owned(),
241            robots_index: true,
242            sitemap_priority: 0.5,
243            show_in_menus: true,
244            og_title: String::new(),
245            og_description: String::new(),
246            og_image_media_id: Some(7),
247            twitter_card: "summary".to_owned(),
248            notification_pre_published_sent: false,
249            created_at: Auto::Unset,
250            updated_at: Auto::Unset,
251        }
252    }
253
254    #[test]
255    fn three_builtin_checks_register() {
256        let codes: Vec<&str> = registered_checks().iter().map(|c| c.code()).collect();
257        for code in [
258            "empty_seo_description",
259            "thin_seo_description",
260            "missing_og_image",
261        ] {
262            assert!(codes.contains(&code), "check `{code}` should register");
263        }
264    }
265
266    #[test]
267    fn clean_page_has_no_seo_findings() {
268        let findings = run_all(&sample_page());
269        assert!(
270            findings.is_empty(),
271            "a page with a good description + og image is clean: {findings:?}"
272        );
273    }
274
275    #[test]
276    fn empty_description_flags_warning() {
277        let mut p = sample_page();
278        p.seo_description = String::new();
279        let findings = run_all(&p);
280        let f = findings
281            .iter()
282            .find(|f| f.code == "empty_seo_description")
283            .expect("empty description flagged");
284        assert_eq!(f.severity, Severity::Warning);
285        assert_eq!(f.category, "SEO");
286        // Empty (not thin) — the thin check must not double-fire.
287        assert!(!findings.iter().any(|f| f.code == "thin_seo_description"));
288    }
289
290    #[test]
291    fn thin_description_flags_info() {
292        let mut p = sample_page();
293        p.seo_description = "Too short.".to_owned();
294        let findings = run_all(&p);
295        assert!(findings
296            .iter()
297            .any(|f| f.code == "thin_seo_description" && f.severity == Severity::Info));
298    }
299
300    #[test]
301    fn missing_og_image_flags_info() {
302        let mut p = sample_page();
303        p.og_image_media_id = None;
304        let findings = run_all(&p);
305        assert!(findings.iter().any(|f| f.code == "missing_og_image"));
306    }
307
308    #[test]
309    fn findings_sorted_errors_then_warnings_then_info() {
310        let mut p = sample_page();
311        p.seo_description = String::new(); // warning
312        p.og_image_media_id = None; // info
313        let findings = run_all(&p);
314        let sevs: Vec<Severity> = findings.iter().map(|f| f.severity).collect();
315        let mut sorted = sevs.clone();
316        sorted.sort_by_key(|s| match s {
317            Severity::Error => 0,
318            Severity::Warning => 1,
319            Severity::Info => 2,
320        });
321        assert_eq!(sevs, sorted);
322        let (e, w, i) = count_by_severity(&findings);
323        assert_eq!((e, w, i), (0, 1, 1));
324    }
325}