0.2.0-dev Download ZIP
220 lines ·7.2 KB Raw
| 1 | using System.Reflection; |
| 2 | |
| 3 | namespace EvilEngine.Tailwind; |
| 4 | |
| 5 | public sealed class DesignSystem |
| 6 | { |
| 7 | public const string TailwindVersion = "4.3.3"; |
| 8 | private readonly Dictionary<CompileAstFlags, Dictionary<Candidate, List<CompiledRule>>> compiledAstNodes = []; |
| 9 | private readonly Dictionary<string, List<Candidate>> parsedCandidates = []; |
| 10 | |
| 11 | private readonly Dictionary<string, Variant?> parsedVariants = []; |
| 12 | |
| 13 | public DesignSystem(Theme theme) |
| 14 | { |
| 15 | Theme = theme; |
| 16 | Utilities = UtilityBuilder.Create(theme); |
| 17 | Variants = Variants.Create(theme); |
| 18 | } |
| 19 | |
| 20 | public Theme Theme { get; } |
| 21 | public Utilities Utilities { get; } |
| 22 | public Variants Variants { get; } |
| 23 | public HashSet<string> InvalidCandidates { get; } = []; |
| 24 | public bool Important { get; set; } |
| 25 | |
| 26 | public static DesignSystem Default() |
| 27 | { |
| 28 | return new DesignSystem(LoadTheme(ReadResource("theme.css"))); |
| 29 | } |
| 30 | |
| 31 | public static string ReadResource(string name) |
| 32 | { |
| 33 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"EvilEngine.Tailwind.{name}") |
| 34 | ?? throw new InvalidOperationException($"Missing resource {name}"); |
| 35 | using var reader = new StreamReader(stream); |
| 36 | return reader.ReadToEnd(); |
| 37 | } |
| 38 | |
| 39 | public static Theme LoadTheme(string css) |
| 40 | { |
| 41 | var theme = new Theme(); |
| 42 | foreach (var node in CssParser.Parse(css)) |
| 43 | { |
| 44 | if (node is not AtRule { Name: "@theme" } themeRule) |
| 45 | continue; |
| 46 | |
| 47 | var (options, prefix) = ParseThemeOptions(themeRule.Params); |
| 48 | if (prefix != null) |
| 49 | theme.Prefix = prefix; |
| 50 | |
| 51 | Walker.Walk(themeRule.Nodes, child => |
| 52 | { |
| 53 | if (child is AtRule { Name: "@keyframes" } keyframes) |
| 54 | { |
| 55 | theme.AddKeyframes(keyframes); |
| 56 | return WalkAction.Skip; |
| 57 | } |
| 58 | |
| 59 | if (child is Comment) |
| 60 | return WalkAction.Continue; |
| 61 | |
| 62 | if (child is Declaration declaration && declaration.Property.StartsWith("--")) |
| 63 | { |
| 64 | theme.Add(Strings.Unescape(declaration.Property), declaration.Value ?? "", options); |
| 65 | return WalkAction.Continue; |
| 66 | } |
| 67 | |
| 68 | throw new InvalidOperationException( |
| 69 | "`@theme` blocks must only contain custom properties or `@keyframes`."); |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | return theme; |
| 74 | } |
| 75 | |
| 76 | private static (ThemeOptions Options, string? Prefix) ParseThemeOptions(string @params) |
| 77 | { |
| 78 | var options = ThemeOptions.None; |
| 79 | string? prefix = null; |
| 80 | |
| 81 | foreach (var option in Strings.Segment(@params, ' ')) |
| 82 | if (option == "reference") |
| 83 | options |= ThemeOptions.Reference; |
| 84 | else if (option == "inline") |
| 85 | options |= ThemeOptions.Inline; |
| 86 | else if (option == "default") |
| 87 | options |= ThemeOptions.Default; |
| 88 | else if (option == "static") |
| 89 | options |= ThemeOptions.Static; |
| 90 | else if (option.StartsWith("prefix(") && option.EndsWith(')')) |
| 91 | prefix = option[7..^1]; |
| 92 | |
| 93 | return (options, prefix); |
| 94 | } |
| 95 | |
| 96 | public Variant? ParseVariant(string variant) |
| 97 | { |
| 98 | if (!parsedVariants.TryGetValue(variant, out var parsed)) |
| 99 | parsedVariants[variant] = parsed = Candidates.ParseVariant(variant, this); |
| 100 | return parsed; |
| 101 | } |
| 102 | |
| 103 | public List<Candidate> ParseCandidate(string candidate) |
| 104 | { |
| 105 | if (!parsedCandidates.TryGetValue(candidate, out var parsed)) |
| 106 | parsedCandidates[candidate] = parsed = Candidates.Parse(candidate, this).ToList(); |
| 107 | return parsed; |
| 108 | } |
| 109 | |
| 110 | public List<CompiledRule> CompileAstNodes(Candidate candidate, |
| 111 | CompileAstFlags flags = CompileAstFlags.RespectImportant) |
| 112 | { |
| 113 | if (!compiledAstNodes.TryGetValue(flags, out var cache)) |
| 114 | compiledAstNodes[flags] = |
| 115 | cache = new Dictionary<Candidate, List<CompiledRule>>(ReferenceEqualityComparer.Instance); |
| 116 | |
| 117 | if (cache.TryGetValue(candidate, out var rules)) |
| 118 | return rules; |
| 119 | |
| 120 | rules = Compiler.CompileAstNodes(candidate, this, flags); |
| 121 | try |
| 122 | { |
| 123 | var nodes = rules.Select(rule => rule.Node).ToList(); |
| 124 | CssFunctions.SubstituteFunctions(nodes, this); |
| 125 | } |
| 126 | catch (InvalidOperationException) |
| 127 | { |
| 128 | rules = []; |
| 129 | } |
| 130 | |
| 131 | cache[candidate] = rules; |
| 132 | return rules; |
| 133 | } |
| 134 | |
| 135 | public Dictionary<Variant, int> GetVariantOrder() |
| 136 | { |
| 137 | var variants = Js.Sort(parsedVariants.Values, Variants.Compare); |
| 138 | |
| 139 | var order = new Dictionary<Variant, int>(ReferenceEqualityComparer.Instance); |
| 140 | Variant? prevVariant = null; |
| 141 | var hasPrev = false; |
| 142 | var index = 0; |
| 143 | |
| 144 | foreach (var variant in variants) |
| 145 | { |
| 146 | if (variant == null) |
| 147 | continue; |
| 148 | |
| 149 | if (hasPrev && Variants.Compare(prevVariant, variant) != 0) |
| 150 | index++; |
| 151 | |
| 152 | order[variant] = index; |
| 153 | prevVariant = variant; |
| 154 | hasPrev = true; |
| 155 | } |
| 156 | |
| 157 | return order; |
| 158 | } |
| 159 | |
| 160 | public string? ResolveThemeValue(string path, bool forceInline = true) |
| 161 | { |
| 162 | var lastSlash = path.LastIndexOf('/'); |
| 163 | string? modifier = null; |
| 164 | if (lastSlash != -1) |
| 165 | { |
| 166 | modifier = path[(lastSlash + 1)..].Trim(); |
| 167 | path = path[..lastSlash].Trim(); |
| 168 | } |
| 169 | |
| 170 | var themeValue = Theme.Resolve(null, [path], forceInline ? ThemeOptions.Inline : ThemeOptions.None); |
| 171 | |
| 172 | if (!string.IsNullOrEmpty(modifier) && !string.IsNullOrEmpty(themeValue)) |
| 173 | return UtilityHelpers.WithAlpha(themeValue, modifier); |
| 174 | |
| 175 | return themeValue; |
| 176 | } |
| 177 | |
| 178 | public void TrackUsedVariables(string raw) |
| 179 | { |
| 180 | foreach (var variable in Strings.ExtractUsedVariables(raw)) |
| 181 | Theme.MarkUsedVariable(variable); |
| 182 | } |
| 183 | |
| 184 | public List<List<AstNode>> CandidatesToAst(IEnumerable<string> classes) |
| 185 | { |
| 186 | var result = new List<List<AstNode>>(); |
| 187 | foreach (var className in classes) |
| 188 | { |
| 189 | var wasValid = true; |
| 190 | var (astNodes, _) = Compiler.CompileCandidates([className], this, _ => wasValid = false); |
| 191 | astNodes = AstPrinter.OptimizeAst(astNodes, this, Polyfills.None); |
| 192 | result.Add(wasValid ? astNodes : []); |
| 193 | } |
| 194 | |
| 195 | return result; |
| 196 | } |
| 197 | |
| 198 | public List<string?> CandidatesToCss(IEnumerable<string> classes) |
| 199 | { |
| 200 | return CandidatesToAst(classes).Select(nodes => nodes.Count > 0 ? AstPrinter.ToCss(nodes) : null).ToList(); |
| 201 | } |
| 202 | |
| 203 | public List<(string ClassName, long? Order)> GetClassOrder(IReadOnlyList<string> classes) |
| 204 | { |
| 205 | var (astNodes, nodeSorting) = Compiler.CompileCandidates(classes, this); |
| 206 | var sorted = new Dictionary<string, long?>(); |
| 207 | foreach (var className in classes) |
| 208 | sorted.TryAdd(className, null); |
| 209 | |
| 210 | long idx = 0; |
| 211 | foreach (var node in astNodes) |
| 212 | { |
| 213 | if (!nodeSorting.TryGetValue(node, out var sorting)) |
| 214 | continue; |
| 215 | sorted[sorting.Candidate] = sorted.GetValueOrDefault(sorting.Candidate) ?? idx++; |
| 216 | } |
| 217 | |
| 218 | return classes.Select(className => (className, sorted.GetValueOrDefault(className))).ToList(); |
| 219 | } |
| 220 | } |