added a source generator that maps MudIcons to their svg strings.

This commit is contained in:
krut_ni 2026-03-10 00:04:22 +01:00
parent 9dba7f415e
commit b221d083d2
No known key found for this signature in database
GPG Key ID: A5C0151B4DDB172C
6 changed files with 186 additions and 1 deletions

View File

@ -8,6 +8,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build Script", "Build\Build
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedTools", "SharedTools\SharedTools.csproj", "{969C74DF-7678-4CD5-B269-D03E1ECA3D2A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceGeneratedMappings", "SourceGeneratedMappings\SourceGeneratedMappings.csproj", "{4D7141D5-9C22-4D85-B748-290D15FF484C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -30,6 +32,10 @@ Global
{969C74DF-7678-4CD5-B269-D03E1ECA3D2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{969C74DF-7678-4CD5-B269-D03E1ECA3D2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{969C74DF-7678-4CD5-B269-D03E1ECA3D2A}.Release|Any CPU.Build.0 = Release|Any CPU
{4D7141D5-9C22-4D85-B748-290D15FF484C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4D7141D5-9C22-4D85-B748-290D15FF484C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4D7141D5-9C22-4D85-B748-290D15FF484C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4D7141D5-9C22-4D85-B748-290D15FF484C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
EndGlobalSection

View File

@ -23,7 +23,7 @@
MaxLength="@textArea.MaxLength"
Immediate="@textArea.IsImmediate"
Adornment="@textArea.GetAdornmentPos()"
AdornmentIcon="@textArea.AdornmentIcon"
AdornmentIcon="@textArea.GetIconSvg()"
AdornmentText="@textArea.AdornmentText"
AdornmentColor="@textArea.GetAdornmentColor()"
Variant="Variant.Outlined"

View File

@ -62,6 +62,19 @@
<ProjectReference Include="..\SourceCodeRules\SourceCodeRules\SourceCodeRules.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"/>
</ItemGroup>
<PropertyGroup>
<SourceGeneratedMappingsProject>..\SourceGeneratedMappings\SourceGeneratedMappings.csproj</SourceGeneratedMappingsProject>
<SourceGeneratedMappingsAssembly>..\SourceGeneratedMappings\bin\$(Configuration)\net9.0\SourceGeneratedMappings.dll</SourceGeneratedMappingsAssembly>
</PropertyGroup>
<Target Name="BuildSourceGeneratedMappings" BeforeTargets="CoreCompile">
<MSBuild Projects="$(SourceGeneratedMappingsProject)" Targets="Restore;Build" Properties="Configuration=$(Configuration);RestoreIgnoreFailedSources=true" />
<ItemGroup>
<Analyzer Include="$(SourceGeneratedMappingsAssembly)" Condition="Exists('$(SourceGeneratedMappingsAssembly)')" />
</ItemGroup>
</Target>
<ItemGroup>
<Folder Include="Plugins\assistants\assets\" />
</ItemGroup>

View File

@ -1,3 +1,5 @@
using AIStudio.Tools.PluginSystem.Assistants.Icons;
namespace AIStudio.Tools.PluginSystem.Assistants.DataModel;
internal sealed class AssistantTextArea : AssistantComponentBase
@ -111,4 +113,6 @@ internal sealed class AssistantTextArea : AssistantComponentBase
public Adornment GetAdornmentPos() => Enum.TryParse<MudBlazor.Adornment>(this.Adornment, out var position) ? position : MudBlazor.Adornment.Start;
public Color GetAdornmentColor() => Enum.TryParse<Color>(this.AdornmentColor, out var color) ? color : Color.Default;
public string GetIconSvg() => MudBlazorIconRegistry.TryGetSvg(this.AdornmentIcon, out var svg) ? svg : string.Empty;
}

View File

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace SourceGeneratedMappings;
[Generator]
public sealed class MappingRegistryGenerator : IIncrementalGenerator
{
private const string GENERATED_NAMESPACE = "AIStudio.Tools.PluginSystem.Assistants.Icons";
private const string ROOT_TYPE_NAME = "MudBlazor.Icons";
private static readonly string[] ALLOWED_GROUP_PATHS = ["Material.Filled", "Material.Outlined"];
private static readonly DiagnosticDescriptor ROOT_TYPE_MISSING = new(
id: "MBI001",
title: "MudBlazor icon root type was not found",
messageFormat: "The generator could not find '{0}' in the current compilation references. No icon registry was generated.",
category: "SourceGeneration",
DiagnosticSeverity.Info,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor NO_ICONS_FOUND = new(
id: "MBI002",
title: "No MudBlazor icons were discovered",
messageFormat: "The generator found '{0}', but no nested icon constants were discovered below it.",
category: "SourceGeneration",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterSourceOutput(context.CompilationProvider, static (spc, compilation) =>
{
Generate(spc, compilation);
});
}
private static void Generate(SourceProductionContext context, Compilation compilation)
{
var rootType = compilation.GetTypeByMetadataName(ROOT_TYPE_NAME);
if (rootType is null)
{
context.ReportDiagnostic(Diagnostic.Create(ROOT_TYPE_MISSING, Location.None, ROOT_TYPE_NAME));
return;
}
var icons = new List<IconDefinition>();
CollectIcons(rootType, new List<string>(), icons);
if (icons.Count == 0)
{
context.ReportDiagnostic(Diagnostic.Create(NO_ICONS_FOUND, Location.None, ROOT_TYPE_NAME));
return;
}
var source = RenderSource(icons);
context.AddSource("MudBlazorIconRegistry.g.cs", SourceText.From(source, Encoding.UTF8));
}
private static void CollectIcons(INamedTypeSymbol currentType, List<string> path, List<IconDefinition> icons)
{
foreach (var nestedType in currentType.GetTypeMembers().OrderBy(static t => t.Name, StringComparer.Ordinal))
{
path.Add(nestedType.Name);
CollectIcons(nestedType, path, icons);
path.RemoveAt(path.Count - 1);
}
foreach (var field in currentType.GetMembers().OfType<IFieldSymbol>().OrderBy(static f => f.Name, StringComparer.Ordinal))
{
if (!field.IsConst || field.Type.SpecialType != SpecialType.System_String || field.ConstantValue is not string svg)
continue;
if (path.Count == 0)
continue;
var groupPath = string.Join(".", path);
if (!ALLOWED_GROUP_PATHS.Contains(groupPath, StringComparer.Ordinal))
continue;
icons.Add(new IconDefinition(
QualifiedName: $"Icons.{groupPath}.{field.Name}",
Svg: svg));
}
}
private static string RenderSource(IReadOnlyList<IconDefinition> icons)
{
var builder = new StringBuilder();
builder.AppendLine("// <auto-generated />");
builder.AppendLine("#nullable enable");
builder.AppendLine("using System;");
builder.AppendLine("using System.Collections.Generic;");
builder.AppendLine();
builder.Append("namespace ").Append(GENERATED_NAMESPACE).AppendLine(";");
builder.AppendLine();
builder.AppendLine("public static class MudBlazorIconRegistry");
builder.AppendLine("{");
builder.AppendLine(" public static readonly IReadOnlyDictionary<string, string> SvgByIdentifier = new Dictionary<string, string>(StringComparer.Ordinal)");
builder.AppendLine(" {");
foreach (var icon in icons)
{
builder.Append(" [")
.Append(ToLiteral(icon.QualifiedName))
.Append("] = ")
.Append(ToLiteral(icon.Svg))
.AppendLine(",");
}
builder.AppendLine(" };");
builder.AppendLine();
builder.AppendLine(" public static bool TryGetSvg(string identifier, out string svg)");
builder.AppendLine(" {");
builder.AppendLine(" return SvgByIdentifier.TryGetValue(identifier, out svg!);");
builder.AppendLine(" }");
builder.AppendLine("}");
return builder.ToString();
}
private static string ToLiteral(string value)
{
return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(value, quote: true);
}
private sealed record IconDefinition(string QualifiedName, string Svg);
}

View File

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
<RootNamespace>SourceGeneratedMappings</RootNamespace>
<AssemblyName>SourceGeneratedMappings</AssemblyName>
<Version>1.0.0</Version>
<PackageId>SourceGeneratedMappings</PackageId>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CodeAnalysis">
<HintPath>$(MSBuildSDKsPath)\..\Roslyn\bincore\Microsoft.CodeAnalysis.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp">
<HintPath>$(MSBuildSDKsPath)\..\Roslyn\bincore\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>