|
| 1 | +using System.Diagnostics; |
| 2 | +using Motus.Abstractions; |
| 3 | + |
| 4 | +namespace Motus; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Walks the accessibility tree and invokes all registered rules on each node. |
| 8 | +/// </summary> |
| 9 | +internal sealed class AccessibilityRuleEngine |
| 10 | +{ |
| 11 | + private readonly IReadOnlyList<IAccessibilityRule> _rules; |
| 12 | + |
| 13 | + internal AccessibilityRuleEngine(IReadOnlyList<IAccessibilityRule> rules) |
| 14 | + { |
| 15 | + _rules = rules; |
| 16 | + } |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Executes the rule engine against the provided node list and context. |
| 20 | + /// </summary> |
| 21 | + internal AccessibilityAuditResult Run( |
| 22 | + IReadOnlyList<AccessibilityNode> nodes, |
| 23 | + AccessibilityAuditContext context, |
| 24 | + string? diagnosticMessage = null) |
| 25 | + { |
| 26 | + var sw = Stopwatch.StartNew(); |
| 27 | + |
| 28 | + if (nodes.Count == 0 || _rules.Count == 0) |
| 29 | + { |
| 30 | + return new AccessibilityAuditResult( |
| 31 | + Violations: [], |
| 32 | + PassCount: 0, |
| 33 | + ViolationCount: 0, |
| 34 | + Duration: sw.Elapsed, |
| 35 | + DiagnosticMessage: diagnosticMessage); |
| 36 | + } |
| 37 | + |
| 38 | + // Deduplication keyed on (RuleId, dedupeKey) where dedupeKey prefers |
| 39 | + // BackendDOMNodeId for stability, falling back to NodeId for virtual nodes. |
| 40 | + var seen = new HashSet<(string ruleId, string dedupeKey)>(); |
| 41 | + var violations = new List<AccessibilityViolation>(); |
| 42 | + int passCount = 0; |
| 43 | + |
| 44 | + foreach (var node in nodes) |
| 45 | + { |
| 46 | + foreach (var rule in _rules) |
| 47 | + { |
| 48 | + var violation = rule.Evaluate(node, context); |
| 49 | + if (violation is null) |
| 50 | + { |
| 51 | + passCount++; |
| 52 | + continue; |
| 53 | + } |
| 54 | + |
| 55 | + var dedupeKey = node.BackendDOMNodeId.HasValue |
| 56 | + ? node.BackendDOMNodeId.Value.ToString() |
| 57 | + : node.NodeId; |
| 58 | + |
| 59 | + if (seen.Add((violation.RuleId, dedupeKey))) |
| 60 | + violations.Add(violation); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return new AccessibilityAuditResult( |
| 65 | + Violations: violations, |
| 66 | + PassCount: passCount, |
| 67 | + ViolationCount: violations.Count, |
| 68 | + Duration: sw.Elapsed, |
| 69 | + DiagnosticMessage: diagnosticMessage); |
| 70 | + } |
| 71 | +} |
0 commit comments