0.2.0-dev Download ZIP
63 lines ·2.2 KB Raw
| 1 | using System.Text.RegularExpressions; |
| 2 | using EvilEngine.Tailwind; |
| 3 | |
| 4 | namespace EvilEngine.Html; |
| 5 | |
| 6 | public sealed record ThemeFace(string Family, string Source, int Weight, bool Italic); |
| 7 | |
| 8 | public sealed partial class EngineTheme |
| 9 | { |
| 10 | private EngineTheme(string css) |
| 11 | { |
| 12 | Css = css; |
| 13 | Faces = ReadFaces(css); |
| 14 | System = new Lazy<DesignSystem>(() => css.Length == 0 |
| 15 | ? DesignSystem.Default() |
| 16 | : new DesignSystem(DesignSystem.LoadTheme(DesignSystem.ReadResource("theme.css") + "\n" + css))); |
| 17 | } |
| 18 | |
| 19 | public static EngineTheme Stock { get; } = new(""); |
| 20 | public static EngineTheme Current { get; private set; } = Stock; |
| 21 | |
| 22 | public string Css { get; } |
| 23 | public IReadOnlyList<ThemeFace> Faces { get; } |
| 24 | internal Lazy<DesignSystem> System { get; } |
| 25 | internal Dictionary<string, string?> Signatures { get; } = []; |
| 26 | |
| 27 | public static EngineTheme Of(string css) |
| 28 | { |
| 29 | return css.Length == 0 ? Stock : new EngineTheme(css); |
| 30 | } |
| 31 | |
| 32 | public static void Use(string css) |
| 33 | { |
| 34 | Current = Of(css); |
| 35 | } |
| 36 | |
| 37 | private static List<ThemeFace> ReadFaces(string css) |
| 38 | { |
| 39 | var faces = new List<ThemeFace>(); |
| 40 | if (css.Length == 0) |
| 41 | return faces; |
| 42 | foreach (var node in CssParser.Parse(css)) |
| 43 | { |
| 44 | if (node is not AtRule { Name: "@font-face" } rule) |
| 45 | continue; |
| 46 | var values = rule.Nodes.OfType<Declaration>() |
| 47 | .ToDictionary(d => d.Property, d => d.Value ?? "", StringComparer.OrdinalIgnoreCase); |
| 48 | if (!values.TryGetValue("font-family", out var family) || !values.TryGetValue("src", out var src) || |
| 49 | Url().Match(src) is not { Success: true } url) |
| 50 | continue; |
| 51 | var weight = values.TryGetValue("font-weight", out var w) && int.TryParse(w.Trim(), out var parsed) |
| 52 | ? parsed |
| 53 | : w?.Trim() == "bold" ? 700 : 400; |
| 54 | var italic = values.TryGetValue("font-style", out var s) && s.Trim() is "italic" or "oblique"; |
| 55 | faces.Add(new ThemeFace(family.Trim().Trim('"', '\''), url.Groups[1].Value, weight, italic)); |
| 56 | } |
| 57 | |
| 58 | return faces; |
| 59 | } |
| 60 | |
| 61 | [GeneratedRegex("""url\(\s*["']?([^"')]+)["']?\s*\)""")] |
| 62 | private static partial Regex Url(); |
| 63 | } |