-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathBrushes.cs
More file actions
721 lines (625 loc) · 28 KB
/
Brushes.cs
File metadata and controls
721 lines (625 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Windows.Media;
using Humanizer;
namespace MaterialDesignToolkit.ResourceGeneration;
public static partial class Brushes
{
[GeneratedRegex(@"^\s*<!-- INSERT HERE -->", RegexOptions.Multiline)]
private static partial Regex TemplateReplaceRegex();
private const string AutoGeneratedHeader = """
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by MaterialDesignToolkit.ResourceGeneration.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
""";
private const string IgnoredBrushName = "MaterialDesign.Brush.Ignored";
private const string ColorReferencePrefix = "ColorReference.";
private const int CSharpIndentSize = 4;
private const int XamlIndentSize = 2;
public static async Task GenerateBrushesAsync()
{
await using var inputFile = File.OpenRead("ThemeColors.json");
Brush[] brushes = await JsonSerializer.DeserializeAsync<Brush[]>(inputFile)
?? throw new InvalidOperationException("Did not find brushes from source file");
brushes = brushes.OrderBy(x => x.Name).ToArray();
var filteredBrushes = brushes.Where(x => x.Name != IgnoredBrushName).ToList();
TreeItem<Brush> brushTree = BuildBrushTree(filteredBrushes);
TreeItem<Brush> alternateBrushTree = BuildBrushTree(GetAllAlternateBrushesFlattened(filteredBrushes));
DirectoryInfo repoRoot = GetRepoRoot() ?? throw new InvalidOperationException("Failed to find the repo root");
GenerateBuiltInThemingDictionaries(brushes, repoRoot);
GenerateObsoleteBrushesDictionary(filteredBrushes, repoRoot);
GenerateThemeClass(alternateBrushTree, repoRoot);
GenerateThemeExtensionsClass(alternateBrushTree, repoRoot);
GenerateResourceDictionaryExtensions(alternateBrushTree, repoRoot);
GenerateThemeBrushTests(alternateBrushTree, repoRoot);
GenerateMigrationScript(filteredBrushes, repoRoot);
}
private static void GenerateBuiltInThemingDictionaries(IEnumerable<Brush> brushes, DirectoryInfo repoRoot)
{
WriteFile("Light");
WriteFile("Dark");
void WriteFile(string theme)
{
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "src", "MaterialDesignThemes.Wpf", "Themes", $"MaterialDesignTheme.{theme}.xaml"));
writer.WriteLine($"""
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:colors="clr-namespace:MaterialDesignColors;assembly=MaterialDesignColors"
xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="./Internal/MaterialDesignTheme.BaseThemeColors.xaml" />
</ResourceDictionary.MergedDictionaries>
""");
foreach (Brush brush in brushes)
{
string value = brush.ThemeValues[theme];
WriteBrush(brush.Name!, value, writer);
foreach (string alternate in brush.AlternateKeys ?? Enumerable.Empty<string>())
{
WriteBrush(alternate, value, writer);
}
static void WriteBrush(string name, string value, StreamWriter writer)
{
if (value.StartsWith('#'))
{
writer.WriteLine($$"""
<SolidColorBrush x:Key="{{name}}" Color="{{value}}" po:Freeze="True" />
""");
}
else if (value.StartsWith(ColorReferencePrefix))
{
string resourceKey = value[ColorReferencePrefix.Length..] switch
{
"SecondaryLight" => "MaterialDesign.Brush.Secondary.Light",
"SecondaryMid" => "MaterialDesign.Brush.Secondary",
"SecondaryDark" => "MaterialDesign.Brush.Secondary.Dark",
"PrimaryLight" => "MaterialDesign.Brush.Primary.Light",
"PrimaryMid" => "MaterialDesign.Brush.Primary",
"PrimaryDark" => "MaterialDesign.Brush.Primary.Dark",
_ => throw new InvalidOperationException($"Unknown color reference: {value}")
};
writer.WriteLine($$"""
<colors:StaticResource x:Key="{{name}}" ResourceKey="{{resourceKey}}" />
""");
}
else
{
writer.WriteLine($$"""
<colors:StaticResource x:Key="{{name}}" ResourceKey="{{value}}" />
""");
}
}
}
writer.WriteLine();
writer.WriteLine("</ResourceDictionary>");
}
}
private static void GenerateObsoleteBrushesDictionary(IEnumerable<Brush> brushes, DirectoryInfo repoRoot)
{
StringBuilder output = new();
foreach (Brush brush in brushes)
{
foreach (string obsoleteKey in brush.ObsoleteKeys ?? Enumerable.Empty<string>())
{
output.AppendLine($$"""
<colors:StaticResource x:Key="{{obsoleteKey}}" ResourceKey="{{brush.Name}}" />
""");
}
}
using var reader = new StreamReader("MaterialDesignTheme.ObsoleteBrushes.xaml");
string existingDictionary = reader.ReadToEnd();
string dictionaryContents = TemplateReplaceRegex().Replace(existingDictionary, output.ToString());
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "src", "MaterialDesignThemes.Wpf", "Themes", "MaterialDesignTheme.ObsoleteBrushes.xaml"));
writer.Write(dictionaryContents);
}
private static void GenerateThemeClass(TreeItem<Brush> brushes, DirectoryInfo repoRoot)
{
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "src", "MaterialDesignThemes.Wpf", "Theme.g.cs"));
writer.WriteLine(AutoGeneratedHeader);
writer.WriteLine("""
namespace MaterialDesignThemes.Wpf;
""");
WriteTreeItem(brushes, writer, 0);
static void WriteTreeItem(TreeItem<Brush> treeItem, StreamWriter writer, int indentLevel)
{
bool isTopLevel = string.IsNullOrWhiteSpace(treeItem.Name);
string indent = new(' ', indentLevel * CSharpIndentSize);
if (isTopLevel)
{
writer.WriteLine($"partial class Theme");
}
else
{
writer.WriteLine($"{indent}public class {treeItem.Name}");
}
writer.WriteLine($"{indent}{{");
if (isTopLevel)
{
writer.WriteLine($"{indent} public Theme()");
writer.WriteLine($"{indent} {{");
}
else
{
writer.WriteLine($"{indent} private readonly Theme _theme;");
writer.WriteLine($"{indent} public {treeItem.Name}(Theme theme)");
writer.WriteLine($"{indent} {{");
writer.WriteLine($"{indent} _theme = theme ?? throw new ArgumentNullException(nameof(theme));");
}
string themeValue = isTopLevel ? "this" : "theme";
foreach (TreeItem<Brush> child in treeItem.Children)
{
writer.WriteLine($"{indent} {child.Name.Pluralize()} = new({themeValue});");
}
writer.WriteLine($"{indent} }}");
writer.WriteLine();
foreach (Brush brush in treeItem.Values)
{
writer.WriteLine($"{indent} private ColorReference {brush.FieldName};");
writer.WriteLine($"{indent} public ColorReference {brush.PropertyName}");
writer.WriteLine($"{indent} {{");
if (string.IsNullOrWhiteSpace(treeItem.Name))
{
writer.WriteLine($"{indent} get => Resolve({brush.FieldName});");
}
else
{
writer.WriteLine($"{indent} get => _theme.Resolve({brush.FieldName});");
}
writer.WriteLine($"{indent} set => {brush.FieldName} = value;");
writer.WriteLine($"{indent} }}");
writer.WriteLine();
}
foreach (TreeItem<Brush> child in treeItem.Children)
{
writer.WriteLine($"{indent} public {child.Name} {child.Name.Pluralize()} {{ get; set; }}");
writer.WriteLine();
}
foreach (TreeItem<Brush> child in treeItem.Children)
{
WriteTreeItem(child, writer, indentLevel + 1);
}
writer.WriteLine($"{indent}}}");
writer.WriteLine();
}
}
private static void GenerateThemeExtensionsClass(TreeItem<Brush> brushes, DirectoryInfo repoRoot)
{
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "src", "MaterialDesignThemes.Wpf", "ThemeExtensions.g.cs"));
writer.WriteLine(AutoGeneratedHeader);
writer.WriteLine("""
using System.Windows.Media;
using MaterialDesignThemes.Wpf.Themes.Internal;
namespace MaterialDesignThemes.Wpf;
static partial class ThemeExtensions
{
""");
WriteSetTheme(brushes, writer, "Light");
writer.WriteLine();
WriteSetTheme(brushes, writer, "Dark");
writer.WriteLine("}");
static void WriteSetTheme(TreeItem<Brush> treeItem, StreamWriter writer, string theme)
{
string indent = new(' ', CSharpIndentSize);
writer.WriteLine($$"""
{{indent}}public static partial void Set{{theme}}Theme(this Theme theme)
{{indent}}{
""");
WriteTreeItem(treeItem, writer, theme.ToLowerInvariant(), "theme.");
writer.WriteLine($"{indent}}}");
}
static void WriteTreeItem(TreeItem<Brush> treeItem, StreamWriter writer, string theme, string propertyPrefix)
{
string indent = new(' ', CSharpIndentSize);
foreach (Brush brush in treeItem.Values)
{
string value = brush.ThemeValues[theme];
if (value.StartsWith("#", StringComparison.Ordinal))
{
Color color = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(value)!;
writer.WriteLine($$"""
{{indent}}{{indent}}{{propertyPrefix}}{{brush.PropertyName}} = Color.FromArgb(0x{{color.A:X2}}, 0x{{color.R:X2}}, 0x{{color.G:X2}}, 0x{{color.B:X2}});
"""
);
}
else if (value.StartsWith(ColorReferencePrefix))
{
writer.WriteLine($$"""
{{indent}}{{indent}}{{propertyPrefix}}{{brush.PropertyName}} = {{value}};
""");
}
else
{
writer.WriteLine($$"""
{{indent}}{{indent}}{{propertyPrefix}}{{brush.PropertyName}} = BaseThemeColors.{{value}};
""");
}
}
foreach (TreeItem<Brush> child in treeItem.Children)
{
WriteTreeItem(child, writer, theme, $"{propertyPrefix}{child.Name.Pluralize()}.");
}
}
}
private static void GenerateResourceDictionaryExtensions(TreeItem<Brush> brushes, DirectoryInfo repoRoot)
{
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "src", "MaterialDesignThemes.Wpf", "ResourceDictionaryExtensions.g.cs"));
string indent = new(' ', CSharpIndentSize);
writer.WriteLine(AutoGeneratedHeader);
writer.WriteLine($$"""
namespace MaterialDesignThemes.Wpf;
static partial class ResourceDictionaryExtensions
{
""");
writer.WriteLine($$"""
{{indent}}private static partial void LoadThemeColors(ResourceDictionary resourceDictionary, Theme theme)
{{indent}}{
""");
LoadThemeColors(brushes, writer, 2, "theme.");
writer.WriteLine($"{indent}}}");
writer.WriteLine();
writer.WriteLine($$"""
{{indent}}private static partial void ApplyThemeColors(ResourceDictionary resourceDictionary, Theme theme)
{{indent}}{
""");
ApplyThemeColors(brushes, writer, 2, "theme.");
writer.WriteLine($"{indent}}}");
writer.WriteLine("}");
static void LoadThemeColors(TreeItem<Brush> treeItem, StreamWriter writer, int indentLevel, string propertyPrefix)
{
string indent = new(' ', indentLevel * CSharpIndentSize);
foreach (Brush brush in treeItem.Values)
{
string keys = string.Join("\", \"", GetResourceKeys());
writer.WriteLine($"{indent}{propertyPrefix}{brush.PropertyName} = GetColor(resourceDictionary, \"{keys}\");");
IEnumerable<string> GetResourceKeys()
{
if (!string.IsNullOrWhiteSpace(brush.Name))
{
yield return brush.Name;
}
foreach (string key in brush.AlternateKeys ?? Enumerable.Empty<string>())
{
yield return key;
}
foreach (string key in brush.ObsoleteKeys ?? Enumerable.Empty<string>())
{
yield return key;
}
}
}
foreach (TreeItem<Brush> child in treeItem.Children)
{
LoadThemeColors(child, writer, indentLevel, $"{propertyPrefix}{child.Name.Pluralize()}.");
}
}
static void ApplyThemeColors(TreeItem<Brush> treeItem, StreamWriter writer, int indentLevel, string propertyPrefix)
{
string indent = new(' ', indentLevel * CSharpIndentSize);
foreach (Brush brush in treeItem.Values)
{
foreach (var key in GetResourceKeys())
{
writer.WriteLine($"{indent}SetSolidColorBrush(resourceDictionary, \"{key}\", {propertyPrefix}{brush.PropertyName});");
}
IEnumerable<string> GetResourceKeys()
{
if (!string.IsNullOrWhiteSpace(brush.Name))
{
yield return brush.Name;
}
foreach (string key in brush.AlternateKeys ?? Enumerable.Empty<string>())
{
yield return key;
}
//TODO: Conditionally include this
foreach (string key in brush.ObsoleteKeys ?? Enumerable.Empty<string>())
{
yield return key;
}
}
}
foreach (TreeItem<Brush> child in treeItem.Children)
{
ApplyThemeColors(child, writer, indentLevel, $"{propertyPrefix}{child.Name.Pluralize()}.");
}
}
}
private static void GenerateThemeBrushTests(IEnumerable<Brush> brushes, DirectoryInfo repoRoot)
{
string indent = new(' ', CSharpIndentSize);
string xamlIndent = new(' ', XamlIndentSize);
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "tests", "MaterialDesignThemes.UITests", "WPF", "Theme", "ThemeTests.g.cs"));
writer.WriteLine($$"""
{{AutoGeneratedHeader}}
using System.Windows.Media;
namespace MaterialDesignThemes.UITests.WPF.Theme;
partial class ThemeTests
{
""");
WriteGetXamlWrapPanel();
WriteAssertAllThemeBrushesSet();
WriteBrushNames();
writer.WriteLine("}");
void WriteGetXamlWrapPanel()
{
writer.WriteLine($$""""
{{indent}}private partial string GetXamlWrapPanel()
{{indent}}{
{{indent}}{{indent}}return """
{{indent}}{{indent}}<WrapPanel>
{{indent}}{{indent}}{{xamlIndent}}<WrapPanel.Resources>
{{indent}}{{indent}}{{xamlIndent}}{{xamlIndent}}<Style TargetType="TextBlock">
{{indent}}{{indent}}{{xamlIndent}}{{xamlIndent}}{{xamlIndent}}<Setter Property="Height" Value="50"/>
{{indent}}{{indent}}{{xamlIndent}}{{xamlIndent}}{{xamlIndent}}<Setter Property="Width" Value="50"/>
{{indent}}{{indent}}{{xamlIndent}}{{xamlIndent}}</Style>
{{indent}}{{indent}}{{xamlIndent}}</WrapPanel.Resources>
"""");
foreach (Brush brush in brushes)
{
WriteBrush(brush.Name!, brush.NameWithoutPrefix);
}
foreach (Brush brush in GetAllObsoleteBrushes(brushes))
{
WriteBrush(brush.Name!, brush.Name!);
}
foreach (string primaryColor in PrimaryColorBrushNames())
{
WriteBrush(primaryColor, primaryColor);
}
foreach (string secondaryColor in SecondaryColorBrushNames())
{
WriteBrush(secondaryColor, secondaryColor);
}
writer.WriteLine($$""""
{{indent}}{{indent}}</WrapPanel>
{{indent}}{{indent}}""";
{{indent}}}
"""");
void WriteBrush(string brushName, string displayName)
{
writer.WriteLine($$"""
{{indent}}{{indent}}{{xamlIndent}}<TextBlock Text="{{displayName}}" Background="{StaticResource {{brushName}}}" />
""");
}
}
void WriteAssertAllThemeBrushesSet()
{
writer.WriteLine($$"""
{{indent}}private partial async Task AssertAllThemeBrushesSet(IVisualElement<WrapPanel> panel)
{{indent}}{
""");
foreach (Brush brush in brushes)
{
WriteBrush(brush, brush.NameWithoutPrefix);
}
foreach (Brush brush in GetAllObsoleteBrushes(brushes))
{
WriteBrush(brush, brush.Name!);
}
writer.WriteLine($$"""
{{indent}}}
""");
void WriteBrush(Brush brush, string name)
{
writer.WriteLine($$"""
{{indent}}{{indent}}{
{{indent}}{{indent}}{{indent}}IVisualElement<TextBlock> textBlock = await panel.GetElement<TextBlock>("[Text=\"{{name}}\"]");
{{indent}}{{indent}}{{indent}}Color? textBlockBackground = await textBlock.GetBackgroundColor();
{{indent}}{{indent}}{{indent}}await Assert.That(textBlockBackground).IsEqualTo(await GetResourceColor("{{brush.Name}}"));
{{indent}}{{indent}}}
""");
}
}
void WriteBrushNames()
{
writer.WriteLine($$"""
{{indent}}private static IEnumerable<string> GetBrushResourceNames()
{{indent}}{
""");
foreach (Brush brush in brushes)
{
writer.WriteLine($$"""
{{indent}}{{indent}}yield return "{{brush.Name}}";
""");
}
writer.WriteLine($$"""
{{indent}}}
""");
writer.WriteLine($$"""
{{indent}}private static IEnumerable<string> GetObsoleteBrushResourceNames()
{{indent}}{
""");
foreach (Brush brush in GetAllObsoleteBrushes(brushes))
{
writer.WriteLine($$"""
{{indent}}{{indent}}yield return "{{brush.Name}}";
""");
}
writer.WriteLine($$"""
{{indent}}}
""");
}
}
private static void GenerateMigrationScript(IEnumerable<Brush> brushes, DirectoryInfo repoRoot)
{
StringBuilder output = new();
output.AppendLine("""
param(
[System.IO.DirectoryInfo]$RootDirectory
)
#NB: This script requires PowerShell 7.1 or later
""");
List<(string ObsoleteBrush, string? Brush)> brushMapping = new()
{
("PrimaryHueLightBrush", "MaterialDesign.Brush.Primary.Light"),
("PrimaryHueLightForegroundBrush", "MaterialDesign.Brush.Primary.Light.Foreground"),
("PrimaryHueMidBrush", "MaterialDesign.Brush.Primary"),
("PrimaryHueMidForegroundBrush", "MaterialDesign.Brush.Primary.Foreground"),
("PrimaryHueDarkBrush", "MaterialDesign.Brush.Primary.Dark"),
("PrimaryHueDarkForegroundBrush", "MaterialDesign.Brush.Primary.Dark.Foreground"),
("SecondaryHueLightBrush", "MaterialDesign.Brush.Secondary.Light"),
("SecondaryHueLightForegroundBrush", "MaterialDesign.Brush.Secondary.Light.Foreground"),
("SecondaryHueMidBrush", "MaterialDesign.Brush.Secondary"),
("SecondaryHueMidForegroundBrush", "MaterialDesign.Brush.Secondary.Foreground"),
("SecondaryHueDarkBrush", "MaterialDesign.Brush.Secondary.Dark"),
("SecondaryHueDarkForegroundBrush", "MaterialDesign.Brush.Secondary.Dark.Foreground"),
};
foreach (Brush brush in brushes)
{
foreach (string obsoleteKey in brush.ObsoleteKeys ?? Enumerable.Empty<string>())
{
brushMapping.Add((obsoleteKey, brush.Name));
}
}
//ReplaceBrushes("*.xaml", "{DynamicResource {BrushName}}");
ReplaceBrushes("*.xaml", "{StaticResource {BrushName}}");
//ReplaceBrushes("*.cs", "SetResourceReference(*, `\"{BrushName}`\")");
//ReplaceBrushes("*.cs", "[`\"{BrushName}`\"]");
using var writer = new StreamWriter(Path.Combine(repoRoot.FullName, "build", "MigrateBrushes.ps1"));
writer.Write(output);
void ReplaceBrushes(string fileMatch, string replaceFormat)
{
output.AppendLine($$"""
$files = Get-ChildItem -Recurse -Path $RootDirectory -Include "{{fileMatch}}"
foreach ($file in $files) {
$fileContents = Get-Content $file -Encoding utf8BOM -Raw
$fileLength = $fileContents.Length
""");
foreach ((string obsoleteBrush, string? brush) in brushMapping)
{
output.AppendLine($$"""
$fileContents = $fileContents -replace "{{Regex.Escape(replaceFormat.Replace("{BrushName}", obsoleteBrush)).Replace(@"\*", "(.+)")}}", "{{replaceFormat.Replace("*", "`$1").Replace("{BrushName}", brush)}}"
""");
}
output.AppendLine("""
if ($fileContents.Length -ne $fileLength) {
Set-Content -Path $file -Value $fileContents -Encoding utf8BOM -NoNewline
}
}
""");
}
}
private static IEnumerable<string> PrimaryColorBrushNames()
{
yield return "MaterialDesign.Brush.Primary.Light";
yield return "MaterialDesign.Brush.Primary.Light.Foreground";
yield return "MaterialDesign.Brush.Primary";
yield return "MaterialDesign.Brush.Primary.Foreground";
yield return "MaterialDesign.Brush.Primary.Dark";
yield return "MaterialDesign.Brush.Primary.Dark.Foreground";
}
private static IEnumerable<string> SecondaryColorBrushNames()
{
yield return "MaterialDesign.Brush.Secondary.Light";
yield return "MaterialDesign.Brush.Secondary.Light.Foreground";
yield return "MaterialDesign.Brush.Secondary";
yield return "MaterialDesign.Brush.Secondary.Foreground";
yield return "MaterialDesign.Brush.Secondary.Dark";
yield return "MaterialDesign.Brush.Secondary.Dark.Foreground";
}
private static DirectoryInfo? GetRepoRoot()
{
DirectoryInfo? currentDirectory = new(Environment.CurrentDirectory);
while (currentDirectory is not null && !currentDirectory.EnumerateDirectories(".git").Any())
{
currentDirectory = currentDirectory.Parent;
}
return currentDirectory;
}
private static TreeItem<Brush> BuildBrushTree(IEnumerable<Brush> brushes)
{
TreeItem<Brush> root = new("");
foreach (Brush brush in brushes)
{
TreeItem<Brush> current = root;
foreach (string part in brush.ContainerParts)
{
TreeItem<Brush>? child = current.Children.FirstOrDefault(x => x.Name == part);
if (child is null)
{
child = new(part);
current.Children.Add(child);
}
current = child;
}
current.Values.Add(brush);
}
return root;
}
private static IEnumerable<Brush> GetAllAlternateBrushesFlattened(IEnumerable<Brush> brushes)
{
return brushes.SelectMany(GetAllAlternateBrushes);
static IEnumerable<Brush> GetAllAlternateBrushes(Brush x)
{
yield return x with
{
AlternateKeys = null
};
foreach (string key in x.AlternateKeys ?? Enumerable.Empty<string>())
{
yield return x with
{
Name = key,
AlternateKeys = null,
};
}
}
}
private static IEnumerable<Brush> GetAllObsoleteBrushes(IEnumerable<Brush> brushes)
{
return brushes.SelectMany(GetAllObsoleteBrushes);
static IEnumerable<Brush> GetAllObsoleteBrushes(Brush x)
{
foreach (string key in x.ObsoleteKeys ?? Enumerable.Empty<string>())
{
yield return x with
{
Name = key,
AlternateKeys = null,
ObsoleteKeys = null,
};
}
}
}
}
public record class Brush(
[property:JsonPropertyName("name")]
string? Name,
[property:JsonPropertyName("themeValues")]
ThemeValues ThemeValues,
[property:JsonPropertyName("alternateKeys")]
string[]? AlternateKeys,
[property:JsonPropertyName("obsoleteKeys")]
string[]? ObsoleteKeys)
{
public const string BrushPrefix = "MaterialDesign.Brush.";
public string PropertyName => Name!.Split(".")[^1];
public string FieldName => $"_{char.ToLowerInvariant(PropertyName[0])}{PropertyName[1..]}";
public string NameWithoutPrefix => Name![BrushPrefix.Length..];
public string[] ContainerParts => Name!.Split('.')[2..^1];
public string ContainerTypeName => string.Join('.', ContainerParts);
}
public record class ThemeValues(
[property:JsonPropertyName("light")]
string Light,
[property:JsonPropertyName("dark")]
string Dark)
{
public string this[string theme]
{
get
{
return theme.ToLowerInvariant() switch
{
"light" => Light,
"dark" => Dark,
_ => throw new InvalidOperationException($"Unknown theme: {theme}")
};
}
}
}