using Microsoft.UI.Xaml.Automation; using XFEWorkflow.Abstractions; using XFEWorkflow.Core.Runtime; using XFEWorkflow.Services; namespace XFEWorkflow.Views; public sealed partial class WorkflowListPage : ManagementPage { private readonly TextBox search = new() { PlaceholderText = "搜索工作流", Width = 300 }; private readonly ComboBox stateFilter = new() { ItemsSource = new[] { "全部工作流", "已开启", "已关闭" }, SelectedIndex = 0, Width = 140 }; private readonly StackPanel rows = new() { Spacing = 10 }; private List workflows = []; private readonly List updateRuntimeStatus = []; private bool loaded; public WorkflowListPage() : base("工作流", "管理自动化任务 · 开启工作流后自动监听触发节点") { InitializeComponent(); NavigationCacheMode = Microsoft.UI.Xaml.Navigation.NavigationCacheMode.Required; HeaderActions.Children.Add(ActionButton("新建工作流", NewAsync, "CreateWorkflow", true)); HeaderActions.Children.Add(ActionButton("打开编辑器", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo(); return Task.CompletedTask; }, "OpenWorkflowEditors")); Toolbar.Children.Add(search); Toolbar.Children.Add(stateFilter); Toolbar.Children.Add(ActionButton("导入", ImportAsync, "ImportWorkflow")); Toolbar.Children.Add(ActionButton("刷新", ReloadAsync, "RefreshWorkflows")); Toolbar.Children.Add(ActionButton("展开全部", () => { SetExpanded(true); return Task.CompletedTask; })); Toolbar.Children.Add(ActionButton("收起全部", () => { SetExpanded(false); return Task.CompletedTask; })); Workspace.Children.Add(new ScrollViewer { Content = rows, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); search.TextChanged += (_, _) => Render(); stateFilter.SelectionChanged += (_, _) => Render(); Loaded += async (_, _) => { loaded = true; Services.Scheduler.Changed += ScheduleChanged; await Guard(ReloadAsync); }; Unloaded += (_, _) => { loaded = false; Services.Scheduler.Changed -= ScheduleChanged; }; } private void ScheduleChanged() => DispatcherQueue.TryEnqueue(() => { if (loaded) foreach (var update in updateRuntimeStatus) update(); }); private async Task ReloadAsync() { workflows = await Services.Workflows.ListAsync(); Render(); } private void SetExpanded(bool value) { foreach (var expander in rows.Children.OfType()) expander.IsExpanded = value; } private void Render() { var expanded = rows.Children.OfType().Where(x => x.IsExpanded).Select(x => x.Tag as string).ToHashSet(); updateRuntimeStatus.Clear(); rows.Children.Clear(); var filtered = workflows.Where(x => x.Name.Contains(search.Text, StringComparison.OrdinalIgnoreCase) && (stateFilter.SelectedIndex == 0 || x.Enabled == (stateFilter.SelectedIndex == 1))).OrderByDescending(x => x.Priority).ThenByDescending(x => x.ModifiedAt).ToArray(); foreach (var workflow in filtered) { var heading = new Grid { ColumnSpacing = 14, Padding = new(0, 6, 0, 6) }; heading.ColumnDefinitions.Add(new() { Width = new(32) }); heading.ColumnDefinitions.Add(new()); heading.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); heading.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); heading.Children.Add(new FontIcon { Glyph = "\uEF90", FontSize = 22 }); var name = new StackPanel { Spacing = 4 }; name.Children.Add(new TextBlock { Text = workflow.Name, FontSize = 16, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, TextTrimming = TextTrimming.CharacterEllipsis }); var statuses = Services.Scheduler.StatusFor(workflow); name.Children.Add(Caption((workflow.Enabled == true ? "已开启" : "已关闭") + " · " + (workflow.Kind == WorkflowKind.Graph ? "图形化" : "C#") + " · " + statuses.Count + " 个触发节点")); Grid.SetColumn(name, 1); heading.Children.Add(name); var toggle = new ToggleSwitch { IsOn = workflow.Enabled == true, OnContent = "开启", OffContent = "关闭", VerticalAlignment = VerticalAlignment.Center }; AutomationProperties.SetName(toggle, "启停工作流 " + workflow.Name); Grid.SetColumn(toggle, 2); heading.Children.Add(toggle); var editButton = ActionButton("编辑", () => OpenAsync(workflow.Id), "EditWorkflow-" + workflow.Id); editButton.Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { new FontIcon { Glyph = "\uE70F", FontSize = 14 }, new TextBlock { Text = "编辑" } } }; AutomationProperties.SetName(editButton, "编辑工作流 " + workflow.Name); Grid.SetColumn(editButton, 3); heading.Children.Add(editButton); var details = new StackPanel { Spacing = 12, Padding = new(0, 0, 0, 6) }; if (workflow.Description.Length > 0) details.Children.Add(Label(workflow.Description)); var runtimeStatus = new StackPanel { Spacing = 4 }; details.Children.Add(runtimeStatus); void UpdateStatus() { runtimeStatus.Children.Clear(); foreach (var status in Services.Scheduler.StatusFor(workflow)) runtimeStatus.Children.Add(Caption(status.Label + (status.NextRun is { } due ? " · 下次 " + due.ToLocalTime().ToString("MM-dd HH:mm:ss") : "") + (status.Error is { } error ? " · " + error : ""))); } updateRuntimeStatus.Add(UpdateStatus); UpdateStatus(); if (statuses.Count == 0) details.Children.Add(Caption("手动运行 · 在编辑器中添加触发节点可自动执行")); var priority = new NumberBox { Header = "优先级(较大值优先)", Value = workflow.Priority, Minimum = -10000, Maximum = 10000, SmallChange = 1, SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact, Width = 240, HorizontalAlignment = HorizontalAlignment.Left }; priority.LostFocus += async (_, _) => await Guard(async () => { if (!double.IsFinite(priority.Value)) return; var latest = await Services.Workflows.GetAsync(workflow.Id); if (latest.Priority == (int)priority.Value) return; await Services.Workflows.SetActivationAsync(workflow.Id, latest.Enabled == true, (int)priority.Value); workflow.Priority = (int)priority.Value; await Services.Scheduler.RefreshAsync(); }); details.Children.Add(priority); var actions = new Controls.AdaptiveWrapPanel(); actions.Children.Add(ActionButton("运行一次", async () => { await WorkflowEditorPage.SaveOpenAsync(workflow.Id); var result = await Services.Runs.RunAsync(await Services.Workflows.GetAsync(workflow.Id)); Status.Text = workflow.Name + " · " + result.Status; })); actions.Children.Add(ActionButton("复制", async () => { var copy = WorkflowJson.Clone(await Services.Workflows.GetAsync(workflow.Id)); copy.Id = Guid.NewGuid().ToString("N"); copy.Name += " 副本"; copy.Enabled = false; await Services.Workflows.SaveAsync(copy); await ReloadAsync(); })); actions.Children.Add(ActionButton("删除", async () => { var dialog = new ContentDialog { Title = "删除工作流", Content = "删除“" + workflow.Name + "”并停止其自动触发?运行日志会保留。", PrimaryButtonText = "删除", CloseButtonText = "取消", XamlRoot = XamlRoot }; if (await dialog.ShowAsync() != ContentDialogResult.Primary) return; await WorkflowEditorPage.CloseOpenAsync(workflow.Id); await Services.Runs.StopAsync(workflow.Id); await Services.Workflows.DeleteAsync(workflow.Id); await Services.Scheduler.RefreshAsync(); await ReloadAsync(); })); details.Children.Add(actions); var expander = new Expander { Tag = workflow.Id, Header = heading, Content = details, IsExpanded = expanded.Contains(workflow.Id), HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch }; expander.SizeChanged += (_, e) => heading.Width = Math.Max(200, e.NewSize.Width - 80); rows.Children.Add(expander); var updatingToggle = false; toggle.Toggled += async (_, _) => { if (updatingToggle) return; updatingToggle = true; toggle.IsEnabled = false; try { await Guard(async () => { await SetEnabledAsync(workflow.Id, toggle.IsOn); await ReloadAsync(); }); await Guard(async () => { toggle.IsOn = (await Services.Workflows.GetAsync(workflow.Id)).Enabled == true; }); } finally { toggle.IsEnabled = true; updatingToggle = false; } }; } if (filtered.Length == 0) rows.Children.Add(Caption("没有工作流,点击“新建工作流”开始编排。")); Status.Text = $"{filtered.Length} 个工作流 · {workflows.Count(x => x.Enabled == true)} 个已开启"; } internal async Task SetEnabledAsync(string id, bool enabled) { await WorkflowEditorPage.SaveOpenAsync(id); var workflow = await Services.Workflows.GetAsync(id); workflow.Enabled = enabled; if (enabled) { var errors = GraphValidator.Validate(workflow, Services.Plugins.Catalog(workflow)); if (errors.Any(x => x.IsError)) throw new ArgumentException(string.Join("\n", errors.Select(x => x.Message))); Services.Plugins.Resolve(workflow); } await Services.Workflows.SetActivationAsync(id, enabled); if (!enabled) await Services.Runs.StopAsync(id); await Services.Scheduler.RefreshAsync(); } internal Task OpenAsync(string id) { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo(new WorkflowNavigationTarget(id)); return Task.CompletedTask; } private async Task NewAsync() { if (await CreateWorkflowAsync(XamlRoot) is { } workflow) await OpenAsync(workflow.Id); } internal static async Task CreateWorkflowAsync(XamlRoot root) { var name = new TextBox { Header = "工作流名称", Text = "新的工作流", MinWidth = 320 }; var dialog = new ContentDialog { Title = "新建工作流", Content = name, PrimaryButtonText = "创建", CloseButtonText = "取消", XamlRoot = root }; dialog.PrimaryButtonClick += (_, e) => e.Cancel = string.IsNullOrWhiteSpace(name.Text); if (await dialog.ShowAsync() != ContentDialogResult.Primary) return null; var workflow = WorkflowTemplates.CreateGraph(); workflow.Name = name.Text.Trim(); workflow.Enabled = false; await AppServices.Current.Workflows.SaveAsync(workflow); return workflow; } private async Task ImportAsync() { if (await PickAsync(".xfeworkflow") is { } file) { var workflow = await Services.Workflows.ImportAsync(file); await Services.Scheduler.RefreshAsync(); await OpenAsync(workflow.Id); } } }