using System.Xml.Linq;
namespace Chronos.Tools.Commands;
///
/// BRIEF §20.3 / DESIGN §4: every actionable control carries a tooltip and no visible text is a literal.
/// Elements inside ControlTemplates are template parts and exempt from the tooltip rule.
///
internal sealed class XamlLintCommand : ICommand
{
private static readonly HashSet Actionable = new(StringComparer.Ordinal)
{
"Button", "ToggleButton", "RepeatButton", "Slider", "ComboBox", "CheckBox", "RadioButton", "MenuItem",
"AutoSlider", "IconButton", "SplitButton", "PreviewViewport",
};
private static readonly string[] TextAttributes = ["Content", "Text", "Header", "ToolTip", "Title", "Tag"];
public string Name => "xaml-lint";
public string Summary => "Check tooltips and literal text in all XAML under src/";
public Task RunAsync(string[] args)
{
var root = Args.RepoRoot();
var problems = new List();
var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.xaml", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
&& !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
.ToList();
var documents = files.Select(f => (File: f, Doc: XDocument.Load(f, LoadOptions.SetLineInfo))).ToList();
var valueTypes = ValueResourceTypes(documents.Select(d => d.Doc));
foreach (var (file, doc) in documents)
{
foreach (var el in doc.Descendants())
{
var line = ((System.Xml.IXmlLineInfo)el).LineNumber;
var where = $"{Path.GetRelativePath(root, file)}:{line}";
var name = el.Name.LocalName;
var inTemplate = el.Ancestors().Any(a => a.Name.LocalName is "ControlTemplate" or "Setter" or "Style");
if (Actionable.Contains(name) && !inTemplate && !HasToolTip(el) && !IsExempt(el))
problems.Add($"{where}: <{name}> has no ToolTip");
foreach (var attrName in TextAttributes)
{
var attr = el.Attribute(attrName);
if (attr is null) continue;
var v = attr.Value;
if (v.Length == 0 || v.StartsWith('{')) continue;
if (attrName == "Tag" || (attrName == "Content" && inTemplate)) continue;
if (v.Any(char.IsLetter))
problems.Add($"{where}: literal {attrName}=\"{v}\" on <{name}> (use {{l:Loc …}})");
}
foreach (var attr in el.Attributes())
{
if (ExpectedValueType(name, attr.Name.LocalName) is not { } expected || ResourceKey(attr.Value) is not { } key) continue;
if (valueTypes.TryGetValue(key, out var actual) && actual != expected)
problems.Add($"{where}: {name}.{attr.Name.LocalName} needs a {expected} but resource {key} is a {actual}");
}
// Literal element content such as Hello or Hi.
if (name is "TextBlock" or "Run" or "Label" or "Button" && !el.HasElements && el.Value.Any(char.IsLetter))
problems.Add($"{where}: literal text in <{name}>");
}
}
foreach (var p in problems) Console.Error.WriteLine(p);
Console.WriteLine($"xaml-lint: {files.Count} file(s), {problems.Count} problem(s)");
return Task.FromResult(problems.Count == 0 ? 0 : 1);
}
/// Keyed resources of the value types WPF cannot convert into each other at run time (parsing succeeds, loading fails).
private static Dictionary ValueResourceTypes(IEnumerable documents)
{
var types = new Dictionary(StringComparer.Ordinal);
foreach (var el in documents.SelectMany(d => d.Descendants()))
{
if (el.Name.LocalName is not ("Double" or "GridLength" or "Thickness" or "CornerRadius")) continue;
if (el.Attributes().FirstOrDefault(a => a.Name.LocalName == "Key") is { } key) types[key.Value] = el.Name.LocalName;
}
return types;
}
private static string? ExpectedValueType(string element, string attribute) => attribute switch
{
"Width" when element == "ColumnDefinition" => "GridLength",
"Height" when element == "RowDefinition" => "GridLength",
"Margin" or "Padding" or "BorderThickness" => "Thickness",
"CornerRadius" => "CornerRadius",
"Width" or "Height" or "MinWidth" or "MaxWidth" or "MinHeight" or "MaxHeight" or "FontSize" => "Double",
_ => null,
};
private static string? ResourceKey(string value)
{
var match = System.Text.RegularExpressions.Regex.Match(value, @"^\{(?:Static|Dynamic)Resource\s+(?:ResourceKey=)?([^\s}]+)\s*\}$");
return match.Success ? match.Groups[1].Value : null;
}
private static bool HasToolTip(XElement el) =>
el.Attribute("ToolTip") is not null
|| el.Elements().Any(c => c.Name.LocalName.EndsWith(".ToolTip", StringComparison.Ordinal))
|| el.Attributes().Any(a => a.Name.LocalName == "TipKey");
/// Opt-out for controls whose tooltip is applied by a style (marked explicitly in XAML).
private static bool IsExempt(XElement el) =>
el.Attributes().Any(a => a.Name.LocalName == "ToolTipFromStyle" && a.Value == "True");
}