XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI.Xaml.Automation.Provider;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Services;

namespace XFEWorkflow.Views;

public sealed partial class AppShellPage
{
    private static async Task WaitForAccountAsync(Func<bool> condition)
    {
        for (var i = 0; i < 80; i++) { if (condition()) return; await Task.Delay(50); }
        throw new InvalidOperationException("用户界面状态未按预期变化");
    }
    private static T AccountElement<T>(DependencyObject root, string name) where T : FrameworkElement
        => UiSmokeTest.Descendants(root).OfType<T>().FirstOrDefault(x => x.Name == name || AutomationProperties.GetAutomationId(x) == name)
            ?? throw new InvalidOperationException($"未找到账号控件 {name}:" + string.Join(", ", UiSmokeTest.Descendants(root).OfType<T>().Select(x => x.Name + "/" + (x as ContentControl)?.Content)));
    private static async Task ActivateAccountButtonAsync(Button button)
    {
        try { await WaitForAccountAsync(() => button.IsLoaded && button.IsEnabled && button.ActualWidth > 0); }
        catch (InvalidOperationException) { throw new InvalidOperationException($"账号按钮不可用:{button.Name}, loaded={button.IsLoaded}, enabled={button.IsEnabled}, visibility={button.Visibility}, size={button.ActualWidth}x{button.ActualHeight}, popup={Current!.accountMenuOpen}, foreground={UiSmokeTest.GetForegroundWindow()}"); }
        // Invoke WinUI's native automation peer, so this account-only suite
        // does not send keys to whichever application currently has focus.
        var peer = FrameworkElementAutomationPeer.FromElement(button) ?? new ButtonAutomationPeer(button);
        ((IInvokeProvider)peer.GetPattern(PatternInterface.Invoke)).Invoke(); await Task.Delay(100);
    }
    private async Task CaptureAccountPopupAsync(string path)
    {
        var panel = (Panel)UserAccountMenu.Content;
        var background = panel.Background;
        try
        {
            // RenderTargetBitmap cannot capture a system backdrop. Use the
            // matching theme's base color for the visual-tree snapshot.
            panel.Background = new SolidColorBrush(ActualTheme == ElementTheme.Dark ? Microsoft.UI.ColorHelper.FromArgb(255, 32, 32, 32) : Microsoft.UI.ColorHelper.FromArgb(255, 243, 243, 243));
            await UiSmokeTest.CaptureElementAsync(UserAccountMenu, path);
        }
        finally { panel.Background = background; }
    }
    private async Task OpenAccountPopupAsync()
    {
        App.MainWindow.Tray!.Show();
        await ActivateAccountButtonAsync(HeaderAccountButton);
        await WaitForAccountAsync(() => accountMenuOpen && UserAccountMenu.IsLoaded && UserAccountMenu.ActualWidth > 0);
    }
    internal async Task SmokeAccountMenuAsync(string output, string url)
    {
        var services = AppServices.Current; var previousAddress = services.State.SpaceAddress;
        var previousTheme = RequestedTheme;
        try
        {
            services.State.SpaceAddress = url + "space/v1/"; services.Space.Reconnect(); await services.Space.LogoutAsync();
            ViewModel.NavigationViewService.NavigateTo<MainPage>(); SetNavigationOpenForSmoke(false);
            RequestedTheme = ElementTheme.Dark; await Task.Delay(150);
            var page = navigationFrame.Content;
            await OpenAccountPopupAsync();
            if (navigationFrame.Content != page) throw new InvalidOperationException("标题栏用户点击直接跳转页面,没有显示弹窗");
            if (ViewModel.SignedOutVisibility != Visibility.Visible || AccountElement<Button>(UserAccountMenu, "SignInButton").Visibility != Visibility.Visible)
                throw new InvalidOperationException("未登录弹窗未显示登录入口");
            await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "SignInButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is not null && !accountMenuOpen);
            var dialog = AccountDialog.Current!;
            await WaitForAccountAsync(() => dialog.IsLoaded && dialog.ActualWidth > 100);
            var name = AccountElement<TextBox>(dialog, "SpaceLoginAccount"); var password = AccountElement<PasswordBox>(dialog, "SpaceLoginPassword");
            name.Text = "design-user"; password.Password = "incorrect";
            Button DialogButton(string buttonName) => UiSmokeTest.Descendants(dialog).OfType<Button>().FirstOrDefault(x => x.IsLoaded && x.Visibility == Visibility.Visible && x.ActualWidth > 0 && (x.Name == buttonName || x.Content?.ToString() == (buttonName switch { "PrimaryButton" => dialog.PrimaryButtonText, "SecondaryButton" => dialog.SecondaryButtonText, _ => dialog.CloseButtonText })))
                ?? throw new InvalidOperationException("登录对话框按钮未加载:" + buttonName);
            await ActivateAccountButtonAsync(DialogButton("PrimaryButton"));
            await WaitForAccountAsync(() => UiSmokeTest.Descendants(dialog).OfType<InfoBar>().Any(x => x.IsOpen));
            if (AccountDialog.Current != dialog || name.Text != "design-user" || services.Space.User is not null) throw new InvalidOperationException("登录错误关闭了对话框、丢失输入或错误更新账号");
            password.Password = AccountUiFixture.Password;
            await ActivateAccountButtonAsync(DialogButton("PrimaryButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is null && services.Space.User?.UserName == "design-user" && ViewModel.UserName == "界面验收作者");
            await OpenAccountPopupAsync();
            if (ViewModel.RoleLabel != "作者" || AccountElement<Button>(UserAccountMenu, "SignInButton").Visibility != Visibility.Collapsed)
                throw new InvalidOperationException("登录后的菜单未更新真实账号与登录入口");
            await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "SwitchButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is not null);
            dialog = AccountDialog.Current!;
            await WaitForAccountAsync(() => dialog.IsLoaded && dialog.ActualWidth > 100);
            await ActivateAccountButtonAsync(DialogButton("CloseButton")); await WaitForAccountAsync(() => AccountDialog.Current is null);
            if (services.Space.User?.UserName != "design-user") throw new InvalidOperationException("取消切换账号丢失原登录状态");
            await OpenAccountPopupAsync(); await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "SwitchButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is not null); dialog = AccountDialog.Current!;
            await WaitForAccountAsync(() => dialog.IsLoaded && dialog.ActualWidth > 100);
            AccountElement<TextBox>(dialog, "SpaceLoginAccount").Text = "design-admin";
            AccountElement<PasswordBox>(dialog, "SpaceLoginPassword").Password = AccountUiFixture.Password;
            await ActivateAccountButtonAsync(DialogButton("PrimaryButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is null && ViewModel.RoleLabel == "管理员");
            await OpenAccountPopupAsync(); await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "ProfileButton"));
            await WaitForAccountAsync(() => navigationFrame.Content is AccountPage && !accountMenuOpen);
            await OpenAccountPopupAsync(); await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "SignOutButton"));
            await WaitForAccountAsync(() => services.Space.User is null && ViewModel.UserName == "未登录");
            if (ViewModel.Avatar is not null || ViewModel.SignedInVisibility != Visibility.Collapsed) throw new InvalidOperationException("退出后头像或已登录操作未清除");
            await OpenAccountPopupAsync(); await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "SignInButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is not null); dialog = AccountDialog.Current!;
            await WaitForAccountAsync(() => dialog.IsLoaded && dialog.ActualWidth > 100);
            AccountElement<TextBox>(dialog, "SpaceLoginAccount").Text = "registered-user";
            AccountElement<PasswordBox>(dialog, "SpaceLoginPassword").Password = AccountUiFixture.Password;
            await ActivateAccountButtonAsync(DialogButton("SecondaryButton"));
            await WaitForAccountAsync(() => AccountDialog.Current is null && services.Space.User?.UserName == "registered-user");
            await OpenAccountPopupAsync(); await ActivateAccountButtonAsync(AccountElement<Button>(UserAccountMenu, "AccountMenuSpace"));
            await WaitForAccountAsync(() => navigationFrame.Content is SpacePage && !accountMenuOpen);
            // Snapshot popup content after the interactive scenarios: a
            // RenderTargetBitmap of an island-hosted popup can invalidate
            // its child layout until the next ShowAt.
            await services.Space.LogoutAsync(); await OpenAccountPopupAsync();
            await CaptureAccountPopupAsync(Path.Combine(output, "account-menu-signed-out.png"));
            HeaderAccountFlyout.Hide(); await WaitForAccountAsync(() => !accountMenuOpen);
            await services.Space.LoginAsync("design-user", AccountUiFixture.Password); await OpenAccountPopupAsync();
            await CaptureAccountPopupAsync(Path.Combine(output, "account-menu-signed-in.png"));
        }
        finally
        {
            AccountDialog.Current?.Hide(); HeaderAccountFlyout.Hide();
            await services.Space.LogoutAsync(); services.State.SpaceAddress = previousAddress; services.Space.Reconnect();
            RequestedTheme = previousTheme; ViewModel.NavigationViewService.NavigateTo<MainPage>();
        }
    }

    internal async Task SmokeAccountProfileAsync(string output, string url, AccountUiFixture fixture)
    {
        var services = AppServices.Current; var previousAddress = services.State.SpaceAddress;
        var theme = RequestedTheme; var size = App.MainWindow.AppWindow.Size;
        try
        {
            services.State.SpaceAddress = url + "space/v1/"; services.Space.Reconnect();
            await services.Space.LoginAsync("design-user", AccountUiFixture.Password);
            ViewModel.NavigationViewService.NavigateTo<AccountPage>(); SetNavigationOpenForSmoke(false); await Task.Delay(180);
            var page = (AccountPage)navigationFrame.Content;
            var name = AccountElement<TextBox>(page, "NicknameInput"); var avatar = AccountElement<TextBox>(page, "AvatarInput");
            var save = AccountElement<Button>(page, "SaveProfileButton"); var reset = AccountElement<Button>(page, "ResetProfileButton");
            var status = AccountElement<InfoBar>(page, "AccountStatus");
            if (save.IsEnabled || AccountElement<Border>(page, "ProfileCard").Visibility != Visibility.Visible) throw new InvalidOperationException("资料表单初始状态错误");
            name.Text = "更新后的昵称"; avatar.Text = url + "avatar.png"; await Task.Delay(80);
            if (!save.IsEnabled || AccountElement<PersonPicture>(page, "DraftAvatar").DisplayName != name.Text) throw new InvalidOperationException("编辑资料未更新保存状态或头像预览");
            fixture.RejectProfileUpdate = true;
            await ActivateAccountButtonAsync(save);
            await WaitForAccountAsync(() => status.IsOpen && status.Severity == InfoBarSeverity.Error);
            if (name.Text != "更新后的昵称" || ViewModel.UserName != "界面验收作者") throw new InvalidOperationException("保存失败丢失草稿或更新了真实账号");
            fixture.RejectProfileUpdate = false;
            await ActivateAccountButtonAsync(save);
            await WaitForAccountAsync(() => services.Space.User?.NickName == name.Text && status.Severity == InfoBarSeverity.Success && ViewModel.UserName == name.Text);
            AssertAccountPresentation("更新后的昵称", true);
            if (new Infrastructure.Space.SpaceClient(services.State, services.Credentials).User?.NickName != "更新后的昵称") throw new InvalidOperationException("用户资料未持久化");
            avatar.Text = "file:///invalid-avatar.png"; await WaitForAccountAsync(() => save.IsEnabled); await ActivateAccountButtonAsync(save);
            await WaitForAccountAsync(() => status.IsOpen && status.Severity == InfoBarSeverity.Error);
            await ActivateAccountButtonAsync(reset);
            if (avatar.Text != services.Space.User!.AvatarUrl || save.IsEnabled) throw new InvalidOperationException("重置未恢复已保存的用户资料");
            var scale = XamlRoot.RasterizationScale;
            App.MainWindow.AppWindow.Resize(new((int)(1420 * scale), (int)(960 * scale))); RequestedTheme = ElementTheme.Dark; await Task.Delay(700);
            var content = AccountElement<StackPanel>(page, "AccountContent"); var position = content.TransformToVisual(page).TransformPoint(new(0, 0)); var pagePosition = page.TransformToVisual(this).TransformPoint(new(0, 0));
            var scroll = AccountElement<ScrollViewer>(page, "AccountScroll");
            await Infrastructure.Storage.AtomicJson.WriteAsync(Path.Combine(output, "account-layout.json"), new { rootWidth = ActualWidth, rootHeight = ActualHeight, scale = XamlRoot.RasterizationScale, frameWidth = navigationFrame.ActualWidth, pageWidth = page.ActualWidth, scrollWidth = scroll.ActualWidth, scrollViewport = scroll.ViewportWidth, scrollExtent = scroll.ExtentWidth, scrollOffset = scroll.HorizontalOffset, contentWidth = content.ActualWidth, contentHeight = content.ActualHeight, slot = Microsoft.UI.Xaml.Controls.Primitives.LayoutInformation.GetLayoutSlot(content), position, pagePosition, appWidth = App.MainWindow.AppWindow.Size.Width });
            if (position.X < -1 || position.X + content.ActualWidth > page.ActualWidth + 1) throw new InvalidOperationException("个人中心内容超出可见页面宽度");
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "account-center-dark.png"));
            RequestedTheme = ElementTheme.Light; await Task.Delay(150);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "account-center-light.png"));
            await OpenAccountPopupAsync();
            RequestedTheme = ElementTheme.Dark; await WaitForAccountAsync(() => UserAccountMenu.ActualTheme == ElementTheme.Dark);
            RequestedTheme = ElementTheme.Light; await WaitForAccountAsync(() => UserAccountMenu.ActualTheme == ElementTheme.Light);
            await CaptureAccountPopupAsync(Path.Combine(output, "account-menu-light.png"));
            HeaderAccountFlyout.Hide(); await WaitForAccountAsync(() => !accountMenuOpen);
            App.MainWindow.AppWindow.Resize(new((int)(760 * scale), (int)(950 * scale))); await Task.Delay(180);
            if (Grid.GetRow(AccountElement<Border>(page, "SpaceCard")) != 1) throw new InvalidOperationException("窄窗口未切换纵向资料布局");
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "account-center-narrow.png"));
            await services.Space.LogoutAsync(); await WaitForAccountAsync(() => ViewModel.SignedOutVisibility == Visibility.Visible);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "account-center-signed-out.png"));
        }
        finally
        {
            fixture.RejectProfileUpdate = false; AccountDialog.Current?.Hide(); HeaderAccountFlyout.Hide();
            await services.Space.LogoutAsync(); services.State.SpaceAddress = previousAddress; services.Space.Reconnect();
            RequestedTheme = theme; App.MainWindow.AppWindow.Resize(size); ViewModel.NavigationViewService.NavigateTo<MainPage>();
        }
    }
}