using System.Globalization; using System.Text.RegularExpressions; using Xunit; namespace Mimante.Tests; /// /// I colori dell'interfaccia (ADR 0016): stanno tutti in wwwroot/css/tokens.css, ogni token usato esiste, e /// le coppie testo/fondo si leggono nei due temi (WCAG AA: 4,5:1 per il testo, 3:1 per i segni senza testo). /// public sealed partial class ContrastTests { private static readonly string Root = FindRoot(); private static readonly string WebRoot = Path.Combine(Root, "src", "Mimante", "wwwroot"); private static readonly Dictionary Tokens = ReadTokens(); /// Testo sul suo fondo: il testo di ogni livello su ogni superficie e ogni stato sul suo fondo tenue. public static TheoryData TextPairs() => new() { { "text", "bg" }, { "text", "surface" }, { "text", "surface-2" }, { "text", "surface-3" }, { "text", "hover" }, { "text", "accent-soft" }, { "muted", "bg" }, { "muted", "surface" }, { "muted", "surface-2" }, { "muted", "surface-3" }, { "muted", "hover" }, { "muted", "muted-soft" }, { "muted", "accent-soft" }, { "faint", "bg" }, { "faint", "surface" }, { "faint", "surface-2" }, { "faint", "surface-3" }, { "faint", "muted-soft" }, { "accent-ink", "accent" }, { "bad-ink", "bad" }, { "accent-text", "surface" }, { "accent-text", "accent-soft" }, { "accent-text", "surface-3" }, { "ok-text", "surface" }, { "ok-text", "ok-soft" }, { "warn-text", "surface" }, { "warn-text", "warn-soft" }, { "bad-text", "surface" }, { "bad-text", "bad-soft" }, { "gold-text", "surface" }, { "gold-text", "gold-soft" } }; /// Segni senza testo che portano significato: la stella accesa, i punti, le barre, il bordo attivo. public static TheoryData MarkPairs() => new() { { "accent", "surface" }, { "ok", "surface" }, { "bad", "surface" }, { "gold", "surface" } }; [Theory] [MemberData(nameof(TextPairs))] public void TextIsReadableInBothThemes(string fore, string back) { AssertContrast(fore, back, 4.5); } [Theory] [MemberData(nameof(MarkPairs))] public void MarksAreVisibleInBothThemes(string fore, string back) { AssertContrast(fore, back, 3.0); } [Fact] public void ThemeFollowsTheSystemUnlessChosen() { var css = File.ReadAllText(Path.Combine(WebRoot, "css", "tokens.css")); Assert.Matches(@":root\[data-theme=""auto""\]\s*\{\s*color-scheme:\s*light dark;", css); Assert.Matches(@":root\[data-theme=""light""\]\s*\{\s*color-scheme:\s*light;", css); Assert.Matches(@":root\[data-theme=""dark""\]\s*\{\s*color-scheme:\s*dark;", css); Assert.Contains("data-theme=\"auto\"", File.ReadAllText(Path.Combine(WebRoot, "index.html"))); } [Fact] public void NoColourOutsideTheTokens() { var offenders = new List(); foreach (var file in Directory.EnumerateFiles(Path.Combine(WebRoot, "css"), "*.css")) { if (Path.GetFileName(file) == "tokens.css") continue; var lines = File.ReadAllLines(file); for (var i = 0; i < lines.Length; i++) { var code = CommentRegex().Replace(lines[i], ""); if (ColourRegex().IsMatch(code)) offenders.Add($"{Path.GetFileName(file)}:{i + 1}: {lines[i].Trim()}"); } } Assert.True(offenders.Count == 0, "Colori scritti fuori da tokens.css:\n" + string.Join('\n', offenders)); } [Fact] public void EveryTokenUsedExists() { var defined = new HashSet(StringComparer.Ordinal); var css = File.ReadAllText(Path.Combine(WebRoot, "css", "tokens.css")); foreach (Match m in DefinitionRegex().Matches(css)) defined.Add(m.Groups[1].Value); defined.Add("panel-w"); // la larghezza del pannello, scritta da split.js var missing = new SortedSet(StringComparer.Ordinal); foreach (var file in Directory.EnumerateFiles(WebRoot, "*.*", SearchOption.AllDirectories) .Where(f => f.EndsWith(".css", StringComparison.Ordinal) || f.EndsWith(".js", StringComparison.Ordinal))) { foreach (Match m in UseRegex().Matches(File.ReadAllText(file))) if (!defined.Contains(m.Groups[1].Value)) missing.Add($"--{m.Groups[1].Value} ({Path.GetFileName(file)})"); } Assert.True(missing.Count == 0, "Token usati ma non definiti in tokens.css:\n" + string.Join('\n', missing)); } [Fact] public void FontsAreLocal() { var css = File.ReadAllText(Path.Combine(WebRoot, "css", "tokens.css")); foreach (Match m in Regex.Matches(css, @"url\(([^)]+)\)")) { var rel = m.Groups[1].Value.Trim('"', '\''); Assert.DoesNotContain("://", rel); Assert.True(File.Exists(Path.GetFullPath(Path.Combine(WebRoot, "css", rel))), "Carattere mancante: " + rel); } Assert.True(File.Exists(Path.Combine(WebRoot, "fonts", "Archivo-OFL.txt")), "Manca la licenza del carattere"); } private static void AssertContrast(string fore, string back, double min) { Assert.True(Tokens.ContainsKey(fore), "Token mancante: --" + fore); Assert.True(Tokens.ContainsKey(back), "Token mancante: --" + back); var light = Ratio(Tokens[fore].Light, Tokens[back].Light); var dark = Ratio(Tokens[fore].Dark, Tokens[back].Dark); Assert.True(light >= min, $"--{fore} su --{back}, tema chiaro: {light:F2}:1 (serve {min}:1)"); Assert.True(dark >= min, $"--{fore} su --{back}, tema scuro: {dark:F2}:1 (serve {min}:1)"); } internal static double Ratio(Rgb a, Rgb b) { var la = a.Luminance; var lb = b.Luminance; return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); } [Fact] public void RatioMatchesTheWcagExamples() { Assert.Equal(21.0, Ratio(Rgb.Parse("#000000"), Rgb.Parse("#FFFFFF")), 2); Assert.Equal(1.0, Ratio(Rgb.Parse("#777777"), Rgb.Parse("#777777")), 2); Assert.Equal(4.48, Ratio(Rgb.Parse("#777777"), Rgb.Parse("#FFFFFF")), 2); } private static Dictionary ReadTokens() { var css = File.ReadAllText(Path.Combine(WebRoot, "css", "tokens.css")); var map = new Dictionary(StringComparer.Ordinal); foreach (Match m in PairRegex().Matches(css)) map[m.Groups[1].Value] = (Rgb.Parse(m.Groups[2].Value), Rgb.Parse(m.Groups[3].Value)); foreach (Match m in SingleRegex().Matches(css)) map.TryAdd(m.Groups[1].Value, (Rgb.Parse(m.Groups[2].Value), Rgb.Parse(m.Groups[2].Value))); return map; } private static string FindRoot() { for (var d = new DirectoryInfo(AppContext.BaseDirectory); d != null; d = d.Parent) if (File.Exists(Path.Combine(d.FullName, "Mimante.slnx"))) return d.FullName; throw new InvalidOperationException("Mimante.slnx not found above " + AppContext.BaseDirectory); } internal readonly record struct Rgb(double R, double G, double B) { public static Rgb Parse(string hex) { var h = hex.TrimStart('#'); double C(int i) => int.Parse(h.AsSpan(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) / 255.0; return new Rgb(C(0), C(2), C(4)); } public double Luminance => 0.2126 * Lin(R) + 0.7152 * Lin(G) + 0.0722 * Lin(B); private static double Lin(double c) => c <= 0.04045 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4); } [GeneratedRegex(@"--([a-z0-9-]+):\s*light-dark\(\s*(#[0-9A-Fa-f]{6})\s*,\s*(#[0-9A-Fa-f]{6})\s*\)")] private static partial Regex PairRegex(); [GeneratedRegex(@"--([a-z0-9-]+):\s*(#[0-9A-Fa-f]{6})\s*;")] private static partial Regex SingleRegex(); [GeneratedRegex(@"(?