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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;
using Microsoft.UI.Xaml.Automation;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Services;
using XFEWorkflow.Space.Contracts;

namespace XFEWorkflow.Views;

public sealed partial class SpacePage
{
    private Task ShowDetailAsync(SpaceCardModel card, IReadOnlyList<SpaceCardModel>? versions = null)
    {
        var revision = ++detailVersion; var section = mode; detail.Children.Clear();
        detail.Children.Add(new FontIcon { Glyph = card.Glyph, FontSize = 32, HorizontalAlignment = HorizontalAlignment.Left });
        detail.Children.Add(new TextBlock { Text = card.Name, FontSize = 22, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap });
        detail.Children.Add(Caption(card.VersionLabel + " · " + card.StateLabel)); detail.Children.Add(Label(card.Description)); detail.Children.Add(Caption(card.ResourceId));
        detail.Children.Add(Caption($"提交于 {card.SubmittedAt.ToLocalTime():yyyy-MM-dd HH:mm} · {card.PackageBytes / 1024d:0.#} KiB"));
        if (card.ReviewReason.Length > 0) detail.Children.Add(Label("审核说明:" + card.ReviewReason));
        if (versions is { Count: > 0 })
        {
            var selector = new ComboBox { Header = "发布版本", ItemsSource = versions, DisplayMemberPath = "Version", SelectedItem = versions.FirstOrDefault(x => x.Id == card.Id), HorizontalAlignment = HorizontalAlignment.Stretch };
            AutomationProperties.SetAutomationId(selector, "SpaceVersions");
            selector.SelectionChanged += async (_, _) => { if (selector.SelectedItem is SpaceCardModel choice && choice.Id != card.Id) await Guard(() => ShowDetailAsync(choice, versions)); };
            detail.Children.Add(selector);
        }
        else if (IsCatalog) detail.Children.Add(ActionButton("查看所有版本", async () =>
        {
            var result = await Services.Space.RequestAsync(card.IsWorkflow ? "workflows/detail" : "plugins/detail", new() { [card.IsWorkflow ? "workflowId" : "pluginId"] = card.ResourceId });
            var all = card.IsWorkflow ? result.Deserialize<List<WorkflowPublication>>(WorkflowJson.Options)!.Select(x => new SpaceCardModel { Workflow = x }).ToList()
                : result.Deserialize<List<PluginPublication>>(WorkflowJson.Options)!.Select(x => new SpaceCardModel { Plugin = x }).ToList();
            if (revision == detailVersion && loaded) await ShowDetailAsync(card, all);
        }, "SpaceAllVersions"));
        if (card.Workflow is { } workflow)
        {
            detail.Children.Add(Caption(card.Capabilities));
            detail.Children.Add(ActionButton("预览图形与代码", async () =>
            {
                using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                var data = await Services.Space.PreviewWorkflowAsync(workflow, timeout.Token);
                if (!loaded || revision != detailVersion) return;
                using var preview = new WorkflowPreviewControl(data) { Width = Math.Max(320, Math.Min(1180, XamlRoot.Size.Width - 110)), Height = Math.Max(260, Math.Min(700, XamlRoot.Size.Height - 210)) };
                var dialog = new ContentDialog { Title = workflow.Workflow.Name + " · v" + workflow.Workflow.Version, Content = preview, CloseButtonText = "关闭", XamlRoot = XamlRoot };
                dialog.Resources["ContentDialogMaxWidth"] = 1300d; AutomationProperties.SetAutomationId(dialog, "SpaceWorkflowPreviewDialog"); await dialog.ShowAsync();
            }, "SpacePreviewWorkflow"));
            var dependencies = workflow.Workflow.PluginVersions;
            var dependencyText = dependencies.Count == 0 ? "无需额外插件" : string.Join("\n", dependencies.Select(pair => pair.Key + "  " + pair.Value +
                (Services.Plugins.Installed.Any(p => p.Manifest.Id == pair.Key && p.Manifest.Version == pair.Value && !p.PendingRemoval && p.Enabled) ? " · 已安装并启用" : " · 待安装或启用")));
            detail.Children.Add(new Expander { Header = $"插件依赖 · {dependencies.Count}", Content = Label(dependencyText), IsExpanded = true, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch });
            if (workflow.Status == PublicationStatus.Published)
            {
                var install = new CheckBox { Content = "自动安装并启用锁定版本的插件", IsChecked = true, Visibility = dependencies.Count > 0 ? Visibility.Visible : Visibility.Collapsed };
                AutomationProperties.SetAutomationId(install, "SpaceWorkflowDependencies"); detail.Children.Add(install);
                detail.Children.Add(ActionButton("下载并导入工作流", async () =>
                {
                    var imported = await Services.Space.DownloadWorkflowAsync(workflow, Services.Paths, Services.Plugins, Services.Workflows, install.IsChecked == true,
                        new Progress<double>(p => { if (loaded) Status.Text = $"下载 {p:P0}"; }));
                    await Services.Scheduler.RefreshAsync(); Status.Text = "已导入“" + imported.Name + "”,可在工作流列表中开启";
                    if (revision == detailVersion && loaded)
                    {
                        await ShowDetailAsync(card, versions);
                        detail.Children.OfType<CheckBox>().Single().IsChecked = install.IsChecked;
                        var download = detail.Children.OfType<Button>().Single(b => AutomationProperties.GetAutomationId(b) == "SpaceDownloadWorkflow");
                        detail.Children.Insert(detail.Children.IndexOf(download) + 1, ActionButton("打开工作流编辑器", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<WorkflowEditorPage>(new WorkflowNavigationTarget(imported.Id)); return Task.CompletedTask; }, "SpaceOpenImportedWorkflow", true));
                    }
                }, "SpaceDownloadWorkflow", true));
                detail.Children.Add(Caption("导入为默认关闭的新副本,随后可编辑或在工作流列表中开启。"));
            }
            detail.Children.Add(new Expander { Header = "输入与输出", Content = Label("输入:\n" + Ports(workflow.Workflow.Inputs) + "\n\n输出:\n" + Ports(workflow.Workflow.Outputs)), HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch });
        }
        if (card.Plugin is { } plugin)
        {
            if (plugin.Manifest.Dependencies.Count > 0) detail.Children.Add(Caption("依赖(安装时自动获取):\n" + string.Join("\n", plugin.Manifest.Dependencies.Select(x => x.Id + " " + (x.ExactVersion ?? ">=" + x.MinimumVersion)))));
            if (plugin.Status == PublicationStatus.Published) detail.Children.Add(ActionButton("下载并安装插件", async () =>
            { await Services.Space.DownloadAsync(plugin, Services.Paths, Services.Plugins, new Progress<double>(p => { if (loaded) Status.Text = $"下载 {p:P0}"; })); Status.Text = "插件与依赖已安装,节点与页面已更新"; }, "SpaceDownloadPlugin", true));
            var capabilities = new StackPanel { Spacing = 10 };
            foreach (var capability in plugin.Manifest.Capabilities) { capabilities.Children.Add(Label(capability.Name + (capability.IsTrigger ? " · 触发器" : ""))); capabilities.Children.Add(Caption(capability.Description)); }
            if (plugin.Manifest.Capabilities.Count > 0) detail.Children.Add(new Expander { Header = $"提供的能力 · {plugin.Manifest.Capabilities.Count}", Content = capabilities, IsExpanded = true, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch });
            foreach (var page in plugin.Manifest.Pages) { detail.Children.Add(Label("页面 · " + page.Name)); detail.Children.Add(Caption(page.Description)); }
        }
        if (section == "mine" && card.Status == PublicationStatus.Published) detail.Children.Add(ActionButton("下架此版本", () => ReviewAsync(card, "withdraw"), "SpaceWithdraw"));
        if (section == "review" && Services.Space.User?.Role == SpaceRole.Administrator)
        {
            var actions = new AdaptiveWrapPanel();
            if (card.Status == PublicationStatus.Pending) { actions.Children.Add(ActionButton("审核上架", () => ReviewAsync(card, "publish"), "SpaceApprove", true)); actions.Children.Add(ActionButton("拒绝", () => ReviewAsync(card, "reject"), "SpaceReject")); }
            if (card.Status == PublicationStatus.Published) actions.Children.Add(ActionButton("下架", () => ReviewAsync(card, "withdraw"), "SpaceWithdraw"));
            detail.Children.Add(actions);
        }
        detail.Children.Add(ActionButton("查看发布信息", () => ShowTextAsync(card.Name, card.IsWorkflow ? WorkflowJson.SerializeDisplay(card.Workflow!) : WorkflowJson.SerializeDisplay(card.Plugin!)), "SpacePublicationInfo"));
        return Task.CompletedTask;
    }
    private static string Ports(IReadOnlyList<PortDefinition> ports) => ports.Count == 0 ? "无" : string.Join("\n", ports.Select(x => (string.IsNullOrEmpty(x.Label) ? x.Name : x.Label + " · " + x.Name) + " · " + x.Type));
}