auditmysite 0.9.27

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
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
//! UX Analysis — heuristic evaluation from AXTree data
//!
//! Extracts CTA clarity, visual hierarchy, content clarity,
//! trust signals, and cognitive load metrics from the Accessibility Tree.

use serde::{Deserialize, Serialize};
use tracing::info;

use crate::accessibility::AXTree;
use crate::ux::scoring::{dimension_score, saturating_penalty, weighted_average};

// ── CTA detection keywords ──────────────────────────────────────────
const CTA_KEYWORDS_DE: &[&str] = &[
    "kaufen",
    "bestellen",
    "kontakt",
    "anfrage",
    "starten",
    "registrieren",
    "anmelden",
    "buchen",
    "jetzt",
    "kostenlos",
    "testen",
    "demo",
    "termin",
    "beratung",
    "angebot",
    "download",
    "herunterladen",
    "newsletter",
    "abonnieren",
    "warenkorb",
    "kasse",
];

const CTA_KEYWORDS_EN: &[&str] = &[
    "buy",
    "order",
    "contact",
    "start",
    "register",
    "sign up",
    "book",
    "free",
    "trial",
    "demo",
    "schedule",
    "get started",
    "download",
    "subscribe",
    "cart",
    "checkout",
    "request",
    "apply",
];

const GENERIC_LABELS: &[&str] = &[
    "mehr",
    "hier",
    "klicken",
    "weiter",
    "link",
    "more",
    "click here",
    "read more",
    "learn more",
    "hier klicken",
    "mehr erfahren",
    "details",
    "weiterlesen",
    "info",
];

const TRUST_KEYWORDS: &[&str] = &[
    "kontakt",
    "impressum",
    "datenschutz",
    "agb",
    "über uns",
    "about",
    "partner",
    "referenz",
    "kunden",
    "zertifikat",
    "auszeichnung",
    "bewertung",
    "erfahrung",
    "garantie",
    "sicherheit",
    "ssl",
    "tüv",
    "iso",
    "dsgvo",
    "privacy",
    "terms",
    "imprint",
    "contact",
];

// ── Dimension weights ───────────────────────────────────────────────
const W_CTA: f64 = 0.30;
const W_HIERARCHY: f64 = 0.20;
const W_CONTENT: f64 = 0.20;
const W_TRUST: f64 = 0.15;
const W_COGNITIVE: f64 = 0.15;

// ── Public types ────────────────────────────────────────────────────

/// Complete UX analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UxAnalysis {
    /// Overall UX score (0–100)
    pub score: u32,
    /// Grade (A–F)
    pub grade: String,
    /// Per-dimension results
    pub cta_clarity: UxDimension,
    pub visual_hierarchy: UxDimension,
    pub content_clarity: UxDimension,
    pub trust_signals: UxDimension,
    pub cognitive_load: UxDimension,
    /// All issues found
    pub issues: Vec<UxIssue>,
}

/// A scored UX dimension
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UxDimension {
    pub name: String,
    pub score: u32,
    pub weight: f64,
    pub summary: String,
}

/// A single UX issue
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UxIssue {
    pub dimension: String,
    pub severity: String,
    pub problem: String,
    pub impact: String,
    pub recommendation: String,
}

// ── Analysis entry point ────────────────────────────────────────────

/// Analyze UX quality from the Accessibility Tree.
/// This runs purely on already-extracted AXTree data — no CDP calls needed.
pub fn analyze_ux(tree: &AXTree) -> UxAnalysis {
    info!("Analyzing UX heuristics...");

    let mut issues = Vec::new();

    // ── 1. CTA Clarity ──────────────────────────────────────────────
    let cta_clarity = analyze_cta_clarity(tree, &mut issues);

    // ── 2. Visual Hierarchy ─────────────────────────────────────────
    let visual_hierarchy = analyze_visual_hierarchy(tree, &mut issues);

    // ── 3. Content Clarity ──────────────────────────────────────────
    let content_clarity = analyze_content_clarity(tree, &mut issues);

    // ── 4. Trust Signals ────────────────────────────────────────────
    let trust_signals = analyze_trust_signals(tree, &mut issues);

    // ── 5. Cognitive Load ───────────────────────────────────────────
    let cognitive_load = analyze_cognitive_load(tree, &mut issues);

    // ── Overall score ───────────────────────────────────────────────
    let score = weighted_average(&[
        (cta_clarity.score, W_CTA),
        (visual_hierarchy.score, W_HIERARCHY),
        (content_clarity.score, W_CONTENT),
        (trust_signals.score, W_TRUST),
        (cognitive_load.score, W_COGNITIVE),
    ]);

    let grade = match score {
        90..=100 => "A",
        80..=89 => "B",
        70..=79 => "C",
        60..=69 => "D",
        _ => "F",
    }
    .to_string();

    info!("UX analysis: score={}, issues={}", score, issues.len());

    UxAnalysis {
        score,
        grade,
        cta_clarity,
        visual_hierarchy,
        content_clarity,
        trust_signals,
        cognitive_load,
        issues,
    }
}

// ── Dimension analyzers ─────────────────────────────────────────────

fn analyze_cta_clarity(tree: &AXTree, issues: &mut Vec<UxIssue>) -> UxDimension {
    let buttons = tree.nodes_with_role("button");
    let links = tree.links();

    // Find primary CTAs (buttons or links with CTA keywords)
    let mut cta_count = 0;
    let mut generic_count = 0;
    let mut primary_found = false;

    for node in buttons.iter().chain(links.iter()) {
        let name = node.name.as_deref().unwrap_or("").to_lowercase();
        if name.is_empty() {
            continue;
        }

        let is_cta = CTA_KEYWORDS_DE
            .iter()
            .chain(CTA_KEYWORDS_EN.iter())
            .any(|kw| name.contains(kw));
        let is_generic = GENERIC_LABELS
            .iter()
            .any(|g| name.trim() == *g || name.starts_with(g));

        if is_cta {
            cta_count += 1;
            primary_found = true;
        }
        if is_generic {
            generic_count += 1;
        }
    }

    let mut penalties = Vec::new();

    if !primary_found {
        penalties.push(45.0);
        issues.push(UxIssue {
            dimension: "CTA Clarity".into(),
            severity: "high".into(),
            problem: "Kein erkennbarer Call-to-Action gefunden".into(),
            impact: "Nutzer wissen nicht, was der nächste Schritt ist".into(),
            recommendation: "Primären CTA klar hervorheben und eindeutig benennen".into(),
        });
    } else if cta_count > 5 {
        let p = saturating_penalty((cta_count - 5) as f64, 15.0, 5.0);
        penalties.push(p);
        issues.push(UxIssue {
            dimension: "CTA Clarity".into(),
            severity: "medium".into(),
            problem: format!("{} konkurrierende Call-to-Actions gefunden", cta_count),
            impact: "Zu viele gleichwertige Handlungsaufforderungen verwirren Nutzer".into(),
            recommendation: "Einen primären CTA priorisieren, sekundäre visuell zurücknehmen"
                .into(),
        });
    }

    if generic_count > 0 {
        let p = saturating_penalty(generic_count as f64, 20.0, 5.0);
        penalties.push(p);
        if generic_count >= 3 {
            issues.push(UxIssue {
                dimension: "CTA Clarity".into(),
                severity: "medium".into(),
                problem: format!(
                    "{} generische Linktexte (\"mehr\", \"hier\", \"klicken\")",
                    generic_count
                ),
                impact: "Nutzer können Ziele nicht unterscheiden".into(),
                recommendation: "Links mit beschreibenden Texten versehen, die das Ziel benennen"
                    .into(),
            });
        }
    }

    let score = dimension_score(&penalties, 100.0);
    let summary = if score >= 85 {
        "Call-to-Actions sind klar und verständlich".into()
    } else if score >= 60 {
        "CTAs vorhanden, aber teilweise unklar oder konkurrierend".into()
    } else {
        "CTAs fehlen oder sind nicht erkennbar".into()
    };

    UxDimension {
        name: "CTA Clarity".into(),
        score,
        weight: W_CTA,
        summary,
    }
}

fn analyze_visual_hierarchy(tree: &AXTree, issues: &mut Vec<UxIssue>) -> UxDimension {
    let headings = tree.headings();
    let mut penalties = Vec::new();

    // Check H1
    let h1_count = headings
        .iter()
        .filter(|h| h.heading_level() == Some(1))
        .count();

    if h1_count == 0 {
        penalties.push(40.0);
        issues.push(UxIssue {
            dimension: "Visual Hierarchy".into(),
            severity: "high".into(),
            problem: "Keine H1-Überschrift vorhanden".into(),
            impact: "Seitenthema ist für Nutzer und Suchmaschinen nicht erkennbar".into(),
            recommendation: "Genau eine H1-Überschrift mit dem Hauptthema der Seite setzen".into(),
        });
    } else if h1_count > 1 {
        penalties.push(15.0);
        issues.push(UxIssue {
            dimension: "Visual Hierarchy".into(),
            severity: "medium".into(),
            problem: format!("{} H1-Überschriften gefunden", h1_count),
            impact: "Seite hat keinen klaren Hauptfokus".into(),
            recommendation: "Nur eine H1-Überschrift pro Seite verwenden".into(),
        });
    }

    // Check heading order
    let mut last_level: u8 = 0;
    let mut skip_count = 0;
    for h in &headings {
        if let Some(level) = h.heading_level() {
            if last_level > 0 && level > last_level + 1 {
                skip_count += 1;
            }
            last_level = level;
        }
    }
    if skip_count > 0 {
        let p = saturating_penalty(skip_count as f64, 30.0, 3.0);
        penalties.push(p);
        if skip_count >= 2 {
            issues.push(UxIssue {
                dimension: "Visual Hierarchy".into(),
                severity: "medium".into(),
                problem: format!(
                    "Heading-Hierarchie {} mal übersprungen (z. B. H2 → H4)",
                    skip_count
                ),
                impact: "Seitenstruktur ist für Screenreader und Nutzer unklar".into(),
                recommendation: "Heading-Ebenen lückenlos aufbauen (H1 → H2 → H3)".into(),
            });
        }
    }

    // Check DOM depth (very large trees = visual overload)
    let dom_size = tree.len();
    if dom_size > 2000 {
        let excess = (dom_size - 2000) as f64;
        let p = saturating_penalty(excess, 20.0, 2000.0);
        penalties.push(p);
        if dom_size > 4000 {
            issues.push(UxIssue {
                dimension: "Visual Hierarchy".into(),
                severity: "low".into(),
                problem: format!("Sehr großer DOM mit {} Knoten", dom_size),
                impact: "Hohe visuelle Komplexität kann Nutzer überfordern".into(),
                recommendation: "Seitenstruktur vereinfachen, weniger verschachtelte Elemente"
                    .into(),
            });
        }
    }

    let score = dimension_score(&penalties, 100.0);
    let summary = if score >= 85 {
        "Klare visuelle Hierarchie mit logischer Heading-Struktur".into()
    } else if score >= 60 {
        "Grundstruktur vorhanden, aber Heading-Hierarchie lückenhaft".into()
    } else {
        "Schwache visuelle Struktur — Seitenfokus nicht erkennbar".into()
    };

    UxDimension {
        name: "Visual Hierarchy".into(),
        score,
        weight: W_HIERARCHY,
        summary,
    }
}

fn analyze_content_clarity(tree: &AXTree, issues: &mut Vec<UxIssue>) -> UxDimension {
    let headings = tree.headings();
    let mut penalties = Vec::new();

    // Count text content (approximation from AXTree names)
    let mut total_text_len = 0usize;
    let mut _text_node_count = 0usize;
    for node in tree.iter() {
        if let Some(role) = node.role.as_deref() {
            if matches!(
                role,
                "StaticText" | "paragraph" | "listitem" | "cell" | "heading"
            ) {
                if let Some(name) = &node.name {
                    total_text_len += name.len();
                    _text_node_count += 1;
                }
            }
        }
    }

    // Approximate word count (German avg ~6 chars/word)
    let word_count = total_text_len / 6;

    if word_count < 50 {
        penalties.push(40.0);
        issues.push(UxIssue {
            dimension: "Content Clarity".into(),
            severity: "high".into(),
            problem: format!("Sehr wenig Textinhalt (~{} Wörter)", word_count),
            impact: "Nutzer erhalten nicht genügend Information für eine Entscheidung".into(),
            recommendation: "Relevanten Inhalt ergänzen, der den Seitenzweck klar vermittelt"
                .into(),
        });
    } else if word_count < 100 {
        penalties.push(20.0);
    }

    // Subheadings: content without structure
    if word_count > 200 && headings.len() < 3 {
        penalties.push(25.0);
        issues.push(UxIssue {
            dimension: "Content Clarity".into(),
            severity: "medium".into(),
            problem: "Viel Text ohne ausreichende Zwischenüberschriften".into(),
            impact: "Nutzer können Inhalte nicht scannen und finden relevante Stellen nicht".into(),
            recommendation: "Text mit Zwischenüberschriften (H2, H3) gliedern".into(),
        });
    }

    // Very long page without structure
    if word_count > 1000 && headings.len() < 5 {
        penalties.push(15.0);
    }

    let score = dimension_score(&penalties, 100.0);
    let summary = if score >= 85 {
        "Inhalte sind klar strukturiert und in angemessenem Umfang vorhanden".into()
    } else if score >= 60 {
        "Inhalte vorhanden, aber Struktur oder Umfang verbesserungswürdig".into()
    } else {
        "Unzureichende Inhalte oder fehlende Textstruktur".into()
    };

    UxDimension {
        name: "Content Clarity".into(),
        score,
        weight: W_CONTENT,
        summary,
    }
}

fn analyze_trust_signals(tree: &AXTree, issues: &mut Vec<UxIssue>) -> UxDimension {
    let links = tree.links();
    let mut penalties = Vec::new();

    // Scan links and text for trust keywords
    let mut contact_found = false;
    let mut impressum_found = false;
    let mut privacy_found = false;
    let mut trust_keyword_count = 0;

    for node in links.iter() {
        let name = node.name.as_deref().unwrap_or("").to_lowercase();
        if name.is_empty() {
            continue;
        }

        if name.contains("kontakt") || name.contains("contact") {
            contact_found = true;
        }
        if name.contains("impressum") || name.contains("imprint") {
            impressum_found = true;
        }
        if name.contains("datenschutz") || name.contains("privacy") {
            privacy_found = true;
        }
        if TRUST_KEYWORDS.iter().any(|kw| name.contains(kw)) {
            trust_keyword_count += 1;
        }
    }

    if !contact_found {
        penalties.push(30.0);
        issues.push(UxIssue {
            dimension: "Trust Signals".into(),
            severity: "high".into(),
            problem: "Kein Kontakt-Link erkennbar".into(),
            impact: "Kein Kontakt-Link auf dieser Seite erkennbar (heuristisch — Kontakt könnte bewusst ausgelagert sein).".into(),
            recommendation: "Kontaktseite oder Kontaktinformationen gut sichtbar verlinken".into(),
        });
    }

    if !impressum_found {
        penalties.push(20.0);
        issues.push(UxIssue {
            dimension: "Trust Signals".into(),
            severity: "medium".into(),
            problem: "Kein Impressum-Link erkennbar".into(),
            impact: "Rechtlich erforderlich in DACH — signalisiert mangelnde Seriosität".into(),
            recommendation: "Impressum im Footer verlinken".into(),
        });
    }

    if !privacy_found {
        penalties.push(15.0);
        issues.push(UxIssue {
            dimension: "Trust Signals".into(),
            severity: "medium".into(),
            problem: "Kein Datenschutz-Link erkennbar".into(),
            impact: "DSGVO-Pflicht, stärkt Nutzervertrauen".into(),
            recommendation: "Datenschutzerklärung im Footer verlinken".into(),
        });
    }

    // Overall trust signal density
    if trust_keyword_count < 3 {
        penalties.push(15.0);
    }

    let score = dimension_score(&penalties, 100.0);
    let summary = if score >= 85 {
        "Vertrauenssignale vorhanden (Kontakt, Impressum, Datenschutz)".into()
    } else if score >= 60 {
        "Grundlegende Vertrauenssignale teilweise vorhanden".into()
    } else {
        "Wichtige Vertrauenssignale fehlen".into()
    };

    UxDimension {
        name: "Trust Signals".into(),
        score,
        weight: W_TRUST,
        summary,
    }
}

fn analyze_cognitive_load(tree: &AXTree, issues: &mut Vec<UxIssue>) -> UxDimension {
    let link_count = tree.links().len();
    let interactive_count = tree.iter().filter(|n| n.is_interactive()).count();
    let dom_size = tree.len();

    let mut penalties = Vec::new();

    // Too many links
    if link_count > 40 {
        let excess = (link_count - 40) as f64;
        let p = saturating_penalty(excess, 30.0, 80.0);
        penalties.push(p);
        if link_count > 80 {
            issues.push(UxIssue {
                dimension: "Cognitive Load".into(),
                severity: "medium".into(),
                problem: format!("{} Links auf der Seite", link_count),
                impact: "Hohe Linkdichte überfordert Nutzer bei der Orientierung".into(),
                recommendation: "Navigation vereinfachen, Links priorisieren und gruppieren".into(),
            });
        }
    }

    // Too many interactive elements
    if interactive_count > 50 {
        let excess = (interactive_count - 50) as f64;
        let p = saturating_penalty(excess, 25.0, 50.0);
        penalties.push(p);
        if interactive_count > 100 {
            issues.push(UxIssue {
                dimension: "Cognitive Load".into(),
                severity: "medium".into(),
                problem: format!("{} interaktive Elemente auf der Seite", interactive_count),
                impact: "Zu viele Interaktionsmöglichkeiten erschweren die Orientierung".into(),
                recommendation: "Interaktive Elemente reduzieren oder in Abschnitte gruppieren"
                    .into(),
            });
        }
    }

    // Very large DOM
    if dom_size > 1500 {
        let excess = (dom_size - 1500) as f64;
        let p = saturating_penalty(excess, 20.0, 1000.0);
        penalties.push(p);
    }

    let score = dimension_score(&penalties, 100.0);
    let summary = if score >= 85 {
        "Angemessene Komplexität — Seite ist übersichtlich".into()
    } else if score >= 60 {
        "Leicht erhöhte Komplexität — Navigation noch handhabbar".into()
    } else {
        "Hohe Komplexität — Seite wirkt überladen".into()
    };

    UxDimension {
        name: "Cognitive Load".into(),
        score,
        weight: W_COGNITIVE,
        summary,
    }
}