using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Media; using System.Xml.Linq; using Everything2Everything.App.Theming; using Xunit; namespace Everything2Everything.Tests; /// /// Windows 11 정통 네이티브 디자인 계약 (design.md §2026-10 리디자인). /// 근거: learn.microsoft.com/windows/apps/design/signature-experiences — typography(최소 12px Regular, /// Segoe UI Variable), geometry(컨트롤 4px · 컨테이너 8px), layering(Mica 베이스 + 콘텐츠 레이어). /// public class Win11NativeDesignTests { private static readonly XNamespace X = "http://schemas.microsoft.com/winfx/2006/xaml"; private static readonly string SolutionRoot = FindSolutionRoot(); private static readonly string ViewsDir = Path.Combine(SolutionRoot, "src", "Everything2Everything.App", "Views"); private static readonly string ThemesDir = Path.Combine(ViewsDir, "Themes"); private static readonly string DarkPalette = Path.Combine(ThemesDir, "FsPalette.Dark.xaml"); private static readonly string LightPalette = Path.Combine(ThemesDir, "FsPalette.Light.xaml"); // Mica 베이스의 대표 불투명 근사값 (WinUI SolidBackgroundFillColorBase) private static readonly Color DarkMica = Color.FromRgb(0x20, 0x20, 0x20); private static readonly Color LightMica = Color.FromRgb(0xF3, 0xF3, 0xF3); private static string FindSolutionRoot() { var dir = Directory.GetCurrentDirectory(); while (dir != null && !File.Exists(Path.Combine(dir, "Everything2Everything.slnx"))) dir = Directory.GetParent(dir)?.FullName; return dir ?? throw new DirectoryNotFoundException("솔루션 루트를 찾을 수 없습니다."); } private static IEnumerable ViewXamlFiles() => Directory.GetFiles(ViewsDir, "*.xaml", SearchOption.TopDirectoryOnly); private static Dictionary LoadPalette(string path) { var doc = XDocument.Load(path); var map = new Dictionary(); foreach (var e in doc.Root!.Elements()) { var key = e.Attribute(X + "Key")?.Value; if (key == null) continue; var raw = e.Name.LocalName == "Color" ? e.Value.Trim() : e.Attribute("Color")?.Value; if (raw == null || !raw.StartsWith('#')) continue; map[key] = (Color)ColorConverter.ConvertFromString(raw); } return map; } // ───────────────────────── 1. 강조색 파생 (시스템 강조색 → 대비 보장) ───────────────────────── [Theory] [InlineData("#0078D4", FsThemeMode.Dark)] [InlineData("#0078D4", FsThemeMode.Light)] [InlineData("#FFB900", FsThemeMode.Dark)] [InlineData("#FFB900", FsThemeMode.Light)] [InlineData("#00CC6A", FsThemeMode.Light)] [InlineData("#881798", FsThemeMode.Dark)] [InlineData("#E81123", FsThemeMode.Light)] [InlineData("#2D2D30", FsThemeMode.Dark)] [InlineData("#FFFFFF", FsThemeMode.Light)] public void AccentPalette_FromAnySystemAccent_KeepsWcagAaContrast(string accentHex, FsThemeMode mode) { var accent = (Color)ColorConverter.ConvertFromString(accentHex); var palette = LoadPalette(mode == FsThemeMode.Dark ? DarkPalette : LightPalette); var mica = mode == FsThemeMode.Dark ? DarkMica : LightMica; var layer = FsContrast.Composite(palette["FsBgLayerColor"], mica); var card = FsContrast.Composite(palette["FsBgCardColor"], layer); var a = FsAccentPalette.From(accent, mode); Assert.True(FsContrast.Ratio(a.Text, layer) >= 4.5, $"강조 텍스트 대비 부족(레이어): {FsContrast.Ratio(a.Text, layer):F2}"); Assert.True(FsContrast.Ratio(a.Text, card) >= 4.5, $"강조 텍스트 대비 부족(카드): {FsContrast.Ratio(a.Text, card):F2}"); Assert.True(FsContrast.Ratio(a.OnFill, a.Fill) >= 4.5, $"강조 버튼 글자 대비 부족: {FsContrast.Ratio(a.OnFill, a.Fill):F2}"); Assert.True(FsContrast.Ratio(a.OnFill, a.FillHover) >= 4.5, $"강조 버튼(호버) 글자 대비 부족: {FsContrast.Ratio(a.OnFill, a.FillHover):F2}"); Assert.NotEqual(a.Fill, a.FillHover); Assert.True(a.Subtle.A < 0x60, "선택 배경 틴트는 반투명이어야 레이어 재질이 비친다."); } [Fact] public void Contrast_KnownPairs_MatchWcagFormula() { Assert.Equal(21.0, FsContrast.Ratio(Colors.Black, Colors.White), 1); Assert.Equal(1.0, FsContrast.Ratio(Colors.White, Colors.White), 2); var half = FsContrast.Composite(Color.FromArgb(0x80, 0, 0, 0), Colors.White); Assert.InRange(half.R, 0x7E, 0x80); } // ───────────────────────── 2. 라이트/다크 팔레트 ───────────────────────── [Fact] public void Palettes_LightAndDark_DefineIdenticalKeySets_WithRequiredRoles() { Assert.True(File.Exists(DarkPalette), "Themes/FsPalette.Dark.xaml 이 필요합니다."); Assert.True(File.Exists(LightPalette), "Themes/FsPalette.Light.xaml 이 필요합니다."); static HashSet Keys(string p) => XDocument.Load(p).Root!.Elements() .Select(e => e.Attribute(X + "Key")?.Value).Where(k => k != null).Select(k => k!).ToHashSet(); var dark = Keys(DarkPalette); var light = Keys(LightPalette); Assert.Empty(dark.Except(light)); Assert.Empty(light.Except(dark)); string[] required = [ "FsBgBase", "FsBgLayer", "FsBgCard", "FsBgCardHover", "FsBgControl", "FsBgControlHover", "FsBgSubtleHover", "FsBgSolid", "FsBgSmoke", "FsBorderSubtle", "FsBorderControl", "FsBorderStrong", "FsDivider", "FsTextPrimary", "FsTextSecondary", "FsTextTertiary", "FsTextDisabled", "FsAccent", "FsAccentHover", "FsAccentText", "FsAccentSubtle", "FsTextOnAccent", "FsStatusSuccess", "FsStatusSuccessText", "FsStatusWarn", "FsStatusWarnText", "FsStatusDanger", "FsStatusDangerText", "FsStatusInfo", "FsStatusInfoText", "FsCaptionCloseHover", ]; foreach (var k in required) Assert.Contains(k, dark); } [Theory] [InlineData(FsThemeMode.Dark)] [InlineData(FsThemeMode.Light)] public void Palette_TextRoles_MeetWcagAa_OnLayerAndCard(FsThemeMode mode) { var p = LoadPalette(mode == FsThemeMode.Dark ? DarkPalette : LightPalette); var mica = mode == FsThemeMode.Dark ? DarkMica : LightMica; var layer = FsContrast.Composite(p["FsBgLayerColor"], mica); var card = FsContrast.Composite(p["FsBgCardColor"], layer); var sidebarCard = FsContrast.Composite(p["FsBgCardColor"], mica); foreach (var role in new[] { "FsTextPrimaryColor", "FsTextSecondaryColor", "FsTextTertiaryColor", "FsStatusSuccessTextColor", "FsStatusWarnTextColor", "FsStatusDangerTextColor", "FsStatusInfoTextColor" }) { foreach (var (name, bg) in new[] { ("레이어", layer), ("카드", card), ("사이드바 카드", sidebarCard), ("Mica", mica) }) { var fg = FsContrast.Composite(p[role], bg); var ratio = FsContrast.Ratio(fg, bg); Assert.True(ratio >= 4.5, $"{mode} {role} on {name}: {ratio:F2} < 4.5"); } } } // ───────────────────────── 3. 실시간 테마 전환 가능성 ───────────────────────── [Fact] public void ThemeColorTokens_MustBeReferencedDynamically_ForLiveThemeSwitch() { var paletteKeys = XDocument.Load(DarkPalette).Root!.Elements() .Select(e => e.Attribute(X + "Key")?.Value).Where(k => k != null).ToHashSet(); var offenders = new List(); foreach (var file in ViewXamlFiles()) { foreach (Match m in Regex.Matches(File.ReadAllText(file), @"\{StaticResource\s+(Fs\w+)\}")) if (paletteKeys.Contains(m.Groups[1].Value)) offenders.Add($"{Path.GetFileName(file)}: {m.Value}"); } Assert.True(offenders.Count == 0, "팔레트 색은 DynamicResource로 참조해야 시스템 테마 전환을 따른다:\n" + string.Join("\n", offenders.Distinct().Take(20))); } [Fact] public void Views_MustNotHardcodeHexColors_OutsidePalettes() { var offenders = new List(); foreach (var file in ViewXamlFiles()) { var doc = XDocument.Load(file); foreach (var attr in doc.Descendants().Attributes()) if (Regex.IsMatch(attr.Value, @"^#[0-9A-Fa-f]{3,8}$") || attr.Value is "White" or "Black") offenders.Add($"{Path.GetFileName(file)}: {attr.Parent!.Name.LocalName}.{attr.Name.LocalName}={attr.Value}"); } Assert.True(offenders.Count == 0, "색은 Themes/FsPalette.*.xaml 토큰으로만 지정한다:\n" + string.Join("\n", offenders.Take(30))); } [Fact] public void LegacyNeonGlassVocabulary_MustBeRetired() { string[] retired = ["FsDoubleBezel", "FsIsland", "FsGlassBorder", "FsAccentCyan", "FsAccentBlue", "FsAccentGreen", "FsAccentAmber", "FsInstrumentCard", "FsPrimaryButtonStyle"]; var appDir = Path.Combine(SolutionRoot, "src", "Everything2Everything.App"); var files = Directory.GetFiles(appDir, "*.*", SearchOption.AllDirectories) .Where(f => (f.EndsWith(".xaml") || f.EndsWith(".cs")) && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}") && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}")); var hits = files.SelectMany(f => retired.Where(r => File.ReadAllText(f).Contains(r)).Select(r => $"{Path.GetFileName(f)}: {r}")).ToList(); Assert.True(hits.Count == 0, "네온 글래스 시대 토큰이 남아 있습니다:\n" + string.Join("\n", hits)); } // ───────────────────────── 4. 타이포그래피 · 기하 ───────────────────────── [Fact] public void Typography_MustUseSegoeUIVariable_NotInter() { var theme = XDocument.Load(Path.Combine(ViewsDir, "FormatShiftTheme.xaml")); var sans = theme.Descendants().First(e => e.Attribute(X + "Key")?.Value == "FsFontSans").Value; Assert.StartsWith("Segoe UI Variable", sans.Trim()); foreach (var file in ViewXamlFiles()) Assert.DoesNotMatch(@"FontFamily=""[^""]*\bInter\b", File.ReadAllText(file)); Assert.DoesNotContain("Inter,", sans); } [Fact] public void Typography_MinimumFontSize_Is12px() { var offenders = new List(); foreach (var file in ViewXamlFiles()) { var doc = XDocument.Load(file); foreach (var e in doc.Descendants()) { var v = e.Attribute("FontSize")?.Value ?? (e.Name.LocalName == "Setter" && e.Attribute("Property")?.Value == "FontSize" ? e.Attribute("Value")?.Value : null); if (v != null && double.TryParse(v, out var size) && size < 12 && !IsIconGlyph(e)) offenders.Add($"{Path.GetFileName(file)}: {e.Name.LocalName} FontSize={v}"); } } Assert.True(offenders.Count == 0, "Windows 11 최소 글자 크기(12px)를 지켜야 한다:\n" + string.Join("\n", offenders.Take(30))); } private static bool IsIconGlyph(XElement e) => e.Name.LocalName is "SymbolIcon"; [Fact] public void Geometry_CornerRadius_FollowsWin11Levels() { var allowed = new HashSet { "0", "2", "4", "8" }; var offenders = new List(); foreach (var file in ViewXamlFiles().Append(DarkPalette)) { var doc = XDocument.Load(file); foreach (var e in doc.Descendants()) { var v = e.Attribute("CornerRadius")?.Value ?? (e.Name.LocalName == "Setter" && e.Attribute("Property")?.Value == "CornerRadius" ? e.Attribute("Value")?.Value : null); if (v == null || v.StartsWith('{')) continue; if (v.Split(',').Select(s => s.Trim()).Any(part => !allowed.Contains(part))) offenders.Add($"{Path.GetFileName(file)}: {e.Name.LocalName} CornerRadius={v}"); } } Assert.True(offenders.Count == 0, "CornerRadius는 0·2·4·8만 쓴다(컨트롤 4, 컨테이너 8):\n" + string.Join("\n", offenders.Take(30))); } // ───────────────────────── 5. 레이어 구조 · 창 재질 ───────────────────────── [Theory] [InlineData("MainWindow.xaml")] [InlineData("SettingsWindow.xaml")] [InlineData("ToolSetupWindow.xaml")] [InlineData("DiagnoseWindow.xaml")] [InlineData("QuickOptionsWindow.xaml")] [InlineData("QuickProgressWindow.xaml")] public void AllWindows_MustUseMicaBackdrop(string xamlName) { var root = XDocument.Load(Path.Combine(ViewsDir, xamlName)).Root!; Assert.Equal("Mica", root.Attribute("WindowBackdropType")?.Value); } [Fact] public void MainWindow_MustHave_RoundedContentLayer_OnMicaBase() { var doc = XDocument.Load(Path.Combine(ViewsDir, "MainWindow.xaml")); var layer = doc.Descendants().FirstOrDefault(e => e.Attribute(X + "Name")?.Value == "ContentLayer"); Assert.NotNull(layer); Assert.Equal("{DynamicResource FsBgLayer}", layer!.Attribute("Background")?.Value); Assert.Equal("8,0,0,0", layer.Attribute("CornerRadius")?.Value); Assert.True(layer.Descendants().Any(d => d.Attribute(X + "Name")?.Value == "ActiveQueueView"), "대기열은 콘텐츠 레이어 위에 있어야 한다."); Assert.True(layer.Descendants().Any(d => d.Attribute(X + "Name")?.Value == "PreviewImageArea"), "미리보기는 콘텐츠 레이어 위에 있어야 한다."); var rootGrid = doc.Root!.Elements().First(e => e.Name.LocalName == "Grid"); Assert.Equal("{DynamicResource FsBgBase}", rootGrid.Attribute("Background")?.Value); } [Fact] public void Cards_MustNotNestInsideCards() { foreach (var file in ViewXamlFiles()) { var doc = XDocument.Load(file); var cards = doc.Descendants().Where(e => e.Attribute("Style")?.Value == "{StaticResource FsCardStyle}"); foreach (var c in cards) Assert.False(c.Ancestors().Any(a => a.Attribute("Style")?.Value == "{StaticResource FsCardStyle}"), $"{Path.GetFileName(file)}: 카드 안에 카드를 중첩하지 않는다."); } } [Fact] public void CheckBoxes_WithLongLabels_MustWrap_InsteadOfClipping() { var offenders = new List(); foreach (var file in new[] { "MainWindow.xaml", "SettingsWindow.xaml", "QuickOptionsWindow.xaml" }) { var doc = XDocument.Load(Path.Combine(ViewsDir, file)); foreach (var cb in doc.Descendants().Where(e => e.Name.LocalName == "CheckBox")) { var content = cb.Attribute("Content")?.Value; if (content != null && content.Length > 8) offenders.Add($"{file}: '{content}'"); } } Assert.True(offenders.Count == 0, "긴 체크박스 라벨은 TextWrapping=Wrap TextBlock으로 감싼다(사이드바 잘림 결함):\n" + string.Join("\n", offenders)); } [Fact] public void TitleBarButtons_MustNotHostSymbolIconDirectly() { // 실측 결함(2026-10): 제목 표시줄(DWM 확장 영역) 안에서 SymbolIcon이 Button의 직접 콘텐츠면 // Foreground가 흰색이어도 글리프가 검게 합성된다. 패널로 한 번 감싸면 정상 렌더된다. var doc = XDocument.Load(Path.Combine(ViewsDir, "MainWindow.xaml")); var titleBar = doc.Descendants().First(e => e.Attribute(X + "Name")?.Value == "AppTitleBar"); var offenders = titleBar.Descendants() .Where(e => e.Name.LocalName == "Button") .Where(b => b.Elements().Any(c => c.Name.LocalName == "SymbolIcon")) .Select(b => b.Attribute("ToolTip")?.Value ?? "?") .ToList(); Assert.True(offenders.Count == 0, "제목 표시줄 버튼의 아이콘을 패널로 감싸야 한다: " + string.Join(", ", offenders)); } [Fact] public void ContentlessCheckBoxes_MustResetMinWidth_ToAvoidClipping() { // 실측 결함(2026-10): Wpf.Ui CheckBox의 기본 MinWidth 때문에 32px 열의 행 선택 체크박스가 반쯤 잘렸다. var offenders = new List(); foreach (var file in ViewXamlFiles()) { foreach (var cb in XDocument.Load(file).Descendants().Where(e => e.Name.LocalName == "CheckBox")) { var hasContent = cb.Attribute("Content") != null || cb.Elements().Any(c => !c.Name.LocalName.Contains('.')); if (!hasContent && cb.Attribute("MinWidth")?.Value != "0") offenders.Add($"{Path.GetFileName(file)}: {cb.Attribute("IsChecked")?.Value}"); } } Assert.True(offenders.Count == 0, "내용 없는 체크박스는 MinWidth=\"0\"이어야 한다:\n" + string.Join("\n", offenders)); } [Theory] [InlineData("FsPathInputStyle")] [InlineData("FsPasswordInputStyle")] public void InputTemplates_MustNotPadOuterBorder_TextBoxBaseAlreadyPadsContentHost(string styleKey) { // 실측 결함(2026-10): TextBoxBase가 Padding을 PART_ContentHost에 넘기는데 바깥 Border에도 Padding을 걸어 // 글자가 22px(10+10+2) 들여 씌어졌다. 여백은 한 곳(콘텐츠 호스트)에서만 준다. var doc = XDocument.Load(Path.Combine(ViewsDir, "FormatShiftTheme.xaml")); var style = doc.Descendants().First(e => e.Attribute(X + "Key")?.Value == styleKey); var outer = style.Descendants().First(e => e.Attribute(X + "Name")?.Value == "PART_Bd"); Assert.Null(outer.Attribute("Padding")); } [Fact] public void CodeBehindCopy_MustSay대기열_NotQueueJargon() { // 화면 어휘는 탭 이름과 같은 '대기열'로 통일한다(같은 대상을 두 이름으로 부르지 않는다). var code = File.ReadAllText(Path.Combine(ViewsDir, "MainWindow.xaml.cs")); var literals = Regex.Matches(code, "\\$?\"([^\"\\\\]|\\\\.)*\"").Select(m => m.Value).Where(v => v.Contains('큐')).ToList(); Assert.True(literals.Count == 0, "사용자 문구에 '큐'가 남아 있습니다:\n" + string.Join("\n", literals)); } [Theory] [InlineData("ImageProgressiveCheck")] [InlineData("ImageStripMetadataCheck")] public void SidebarCheckLabels_MustFitOneLine_WithoutMidWordBreak(string checkName) { // 사이드바 카드 안쪽 폭(약 230px, 14px 본문)에서 한 줄에 들어가야 한글이 낱자로 끊기지 않는다. var doc = XDocument.Load(Path.Combine(ViewsDir, "MainWindow.xaml")); var cb = doc.Descendants().First(e => e.Attribute(X + "Name")?.Value == checkName); var text = cb.Descendants().First(e => e.Name.LocalName == "TextBlock").Attribute("Text")!.Value; Assert.True(text.Length <= 16, $"{checkName} 라벨이 너무 깁니다({text.Length}자): {text}"); } // ───────────────────────── 6. 시스템 테마 추종 ───────────────────────── [Fact] public void ThemeService_ResolvesPaletteUri_PerMode() { Assert.EndsWith("Themes/FsPalette.Dark.xaml", FsThemeService.PaletteUri(FsThemeMode.Dark).OriginalString); Assert.EndsWith("Themes/FsPalette.Light.xaml", FsThemeService.PaletteUri(FsThemeMode.Light).OriginalString); } [Fact] public void App_MustFollowSystemTheme_AtStartup() { var appCs = File.ReadAllText(Path.Combine(SolutionRoot, "src", "Everything2Everything.App", "App.xaml.cs")); Assert.Contains("FsThemeService.FollowSystem", appCs); var appXaml = File.ReadAllText(Path.Combine(SolutionRoot, "src", "Everything2Everything.App", "App.xaml")); Assert.Contains("Themes/FsPalette.Dark.xaml", appXaml); } }