using System.Text.Json; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Markup; using Microsoft.UI.Xaml.Navigation; using XFEWorkflow.Abstractions; using XFEWorkflow.Controls; using XFEWorkflow.Services; using XFEWorkflow.Space.Contracts; namespace XFEWorkflow.Views; public sealed partial class SpacePage : ManagementPage { private const int PageSize = 24; private readonly Pivot sections = new() { Height = 52 }; private readonly PivotItem pluginsTab = new() { Header = "插件", Tag = "plugins" }; private readonly PivotItem workflowsTab = new() { Header = "工作流", Tag = "workflows" }; private readonly PivotItem mineTab = new() { Header = "我的发布", Tag = "mine" }; private readonly PivotItem reviewTab = new() { Header = "审核中心", Tag = "review" }; private readonly TextBox query = new() { PlaceholderText = "搜索名称、描述或作者", Width = 280 }; private readonly ComboBox resourceKind = new() { ItemsSource = new[] { "插件", "工作流" }, SelectedIndex = 0, Width = 120 }; private readonly ComboBox stateFilter = new() { ItemsSource = new[] { "全部状态", "待审核", "已上架", "已拒绝", "已下架" }, SelectedIndex = 0, Width = 130 }; private readonly GridView catalog = new() { SelectionMode = ListViewSelectionMode.Single, HorizontalContentAlignment = HorizontalAlignment.Stretch }; private readonly StackPanel detail = new() { Spacing = 14 }; private readonly TextBlock empty = new() { Text = "正在加载 Space…", TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center, MaxWidth = 340, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .65, IsHitTestVisible = false }; private readonly TextBlock pageLabel = new() { VerticalAlignment = VerticalAlignment.Center }; private readonly Button login, previous, next; private readonly DetailsWorkspace panels = new("space.details"); private List cards = []; private string mode = "plugins"; private int page, total, queryVersion, detailVersion; private bool loaded; private CancellationTokenSource? loading; private bool IsCatalog => mode is "plugins" or "workflows"; private string Kind => mode == "workflows" || !IsCatalog && resourceKind.SelectedIndex == 1 ? "workflow" : "plugin"; public SpacePage() : base("Space", "发现与分享自动化插件、工作流") { InitializeComponent(); HeaderActions.Children.Add(ActionButton("刷新", ReloadAsync, "RefreshSpace")); HeaderActions.Children.Add(ActionButton("上传插件", UploadPluginAsync, "SpaceUploadPlugin")); HeaderActions.Children.Add(ActionButton("上传工作流", UploadWorkflowAsync, "SpaceUploadWorkflow", true)); foreach (var tab in new[] { pluginsTab, workflowsTab, mineTab }) sections.Items.Add(tab); sections.SelectedItem = pluginsTab; AutomationProperties.SetAutomationId(sections, "SpaceSections"); AutomationProperties.SetAutomationId(resourceKind, "SpaceResourceKind"); AutomationProperties.SetAutomationId(query, "SpaceSearch"); AutomationProperties.SetAutomationId(catalog, "SpaceCatalog"); login = ActionButton("登录 / 注册", async () => { if (await AccountDialog.ShowAsync(XamlRoot)) await ReloadAsync(); }, "SpaceLogin"); var filters = new AdaptiveWrapPanel(); filters.Children.Add(query); filters.Children.Add(resourceKind); filters.Children.Add(stateFilter); filters.Children.Add(ActionButton("搜索", () => ResetAndReloadAsync(), "SearchSpace")); filters.Children.Add(login); var toolbar = new StackPanel { Spacing = 8 }; toolbar.Children.Add(sections); toolbar.Children.Add(filters); Toolbar.Children.Add(toolbar); Toolbar.SizeChanged += (_, e) => { toolbar.Width = e.NewSize.Width; query.Width = Math.Min(280, Math.Max(160, e.NewSize.Width - 16)); }; catalog.ItemTemplate = (DataTemplate)Application.Current.Resources["PluginCenterCardTemplate"]; catalog.ItemContainerStyle = new Style(typeof(GridViewItem)) { Setters = { new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Stretch), new Setter(VerticalContentAlignmentProperty, VerticalAlignment.Stretch), new Setter(PaddingProperty, new Thickness(4)) } }; catalog.ItemsPanel = (ItemsPanelTemplate)XamlReader.Load(""); catalog.SizeChanged += (_, e) => { if (catalog.ItemsPanelRoot is ItemsWrapGrid wrap) wrap.ItemWidth = Math.Max(240, (e.NewSize.Width - 16) / Math.Max(1, Math.Floor((e.NewSize.Width - 16) / 300))); }; var list = new Grid(); list.Children.Add(catalog); list.Children.Add(empty); previous = PageButton("上一页", -1, "SpacePrevious"); next = PageButton("下一页", 1, "SpaceNext"); var pager = Row(previous, pageLabel, next); pager.HorizontalAlignment = HorizontalAlignment.Center; pager.Margin = new(0, 8, 0, 0); var master = new Grid(); master.RowDefinitions.Add(new()); master.RowDefinitions.Add(new() { Height = GridLength.Auto }); master.Children.Add(list); Grid.SetRow(pager, 1); master.Children.Add(pager); panels.Master.Content = master; panels.Details.Content = Card(new ScrollViewer { Content = detail, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); Workspace.Children.Add(panels); catalog.SelectionChanged += async (_, _) => { if (catalog.SelectedItem is SpaceCardModel card) await Guard(() => ShowDetailAsync(card)); }; sections.SelectionChanged += async (_, _) => { if (sections.SelectedItem is PivotItem item) { mode = (string)item.Tag; if (loaded) await Guard(ResetAndReloadAsync); } }; resourceKind.SelectionChanged += async (_, _) => { if (loaded && !IsCatalog) await Guard(ResetAndReloadAsync); }; stateFilter.SelectionChanged += (_, _) => { if (!IsCatalog) { page = 0; ApplyCards(); } }; query.KeyDown += async (_, e) => { if (e.Key == Windows.System.VirtualKey.Enter) { e.Handled = true; await Guard(ResetAndReloadAsync); } }; Loaded += async (_, _) => { loaded = true; Services.Space.UserChanged += AccountChanged; UpdateAccount(); await Guard(ReloadAsync); }; Unloaded += (_, _) => { loaded = false; Services.Space.UserChanged -= AccountChanged; queryVersion++; detailVersion++; loading?.Cancel(); }; } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); UpdateAccount(); sections.SelectedItem = (e.Parameter as string) switch { "workflows" => workflowsTab, "mine" => mineTab, "review" when Services.Space.User?.Role == SpaceRole.Administrator => reviewTab, _ => pluginsTab }; } private void AccountChanged() => DispatcherQueue.TryEnqueue(() => { if (!loaded) return; UpdateAccount(); _ = Guard(ResetAndReloadAsync); }); private void UpdateAccount() { login.Visibility = Services.Space.User is null ? Visibility.Visible : Visibility.Collapsed; if (Services.Space.User?.Role == SpaceRole.Administrator) { if (!sections.Items.Contains(reviewTab)) sections.Items.Add(reviewTab); } else if (sections.Items.Contains(reviewTab)) { if (ReferenceEquals(sections.SelectedItem, reviewTab)) sections.SelectedItem = pluginsTab; sections.Items.Remove(reviewTab); } resourceKind.Visibility = stateFilter.Visibility = IsCatalog ? Visibility.Collapsed : Visibility.Visible; } private Task ResetAndReloadAsync() { page = 0; return ReloadAsync(); } private Button PageButton(string text, int direction, string id) { var button = new Button { Content = text }; AutomationProperties.SetAutomationId(button, id); button.Click += async (_, _) => { previous.IsEnabled = next.IsEnabled = false; await Guard(async () => { page = Math.Clamp(page + direction, 0, Math.Max(0, (total - 1) / PageSize)); await ReloadAsync(); }); previous.IsEnabled = page > 0; next.IsEnabled = (page + 1) * PageSize < total; }; return button; } private async Task ReloadAsync() { var revision = ++queryVersion; var section = mode; var kind = Kind; var currentPage = page; loading?.Cancel(); var request = new CancellationTokenSource(TimeSpan.FromSeconds(30)); loading = request; UpdateAccount(); cards = []; total = 0; ApplyCards(); empty.Text = "正在加载 Space…"; try { if (!IsCatalog && Services.Space.User is null) { empty.Text = "登录后可上传插件与工作流,查看发布和审核状态。"; return; } var route = IsCatalog ? section + "/search" : section == "mine" ? kind == "workflow" ? "workflows/mine" : "plugins/mine" : "reviews/list"; var response = await Services.Space.RequestAsync(route, new() { ["kind"] = kind, ["query"] = query.Text.Trim(), ["offset"] = currentPage * PageSize, ["limit"] = PageSize }, request.Token); if (revision != queryVersion || !loaded) return; if (kind == "workflow") { var result = IsCatalog ? response.Deserialize(WorkflowJson.Options)! : new() { Items = response.Deserialize>(WorkflowJson.Options)! }; cards = result.Items.Select(x => new SpaceCardModel { Workflow = x }).ToList(); total = result.Total; } else { var result = IsCatalog ? response.Deserialize(WorkflowJson.Options)! : new() { Items = response.Deserialize>(WorkflowJson.Options)! }; cards = result.Items.Select(x => new SpaceCardModel { Plugin = x }).ToList(); total = result.Total; } page = currentPage; if (IsCatalog && page > Math.Max(0, (total - 1) / PageSize)) { page = Math.Max(0, (total - 1) / PageSize); await ReloadAsync(); return; } ApplyCards(); } catch (OperationCanceledException) when (!loaded || revision != queryVersion) { } catch { if (revision != queryVersion || !loaded) return; empty.Text = "暂时无法连接 Space,请启动本地服务器后刷新。"; throw; } finally { if (ReferenceEquals(loading, request)) loading = null; request.Dispose(); } } private void ApplyCards() { var selected = (catalog.SelectedItem as SpaceCardModel)?.Id; IEnumerable visible = cards; if (!IsCatalog) { var terms = query.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); visible = visible.Where(x => terms.All(t => x.SearchText.Contains(t, StringComparison.OrdinalIgnoreCase)) && (stateFilter.SelectedIndex == 0 || x.StateLabel == (string)stateFilter.SelectedItem)); var filtered = visible.ToArray(); total = filtered.Length; page = Math.Min(page, Math.Max(0, (total - 1) / PageSize)); visible = filtered.Skip(page * PageSize).Take(PageSize); } var items = visible.ToArray(); catalog.ItemsSource = items; empty.Text = "没有找到内容。可以上传自己的插件或工作流。"; empty.Visibility = items.Length == 0 ? Visibility.Visible : Visibility.Collapsed; catalog.SelectedItem = items.FirstOrDefault(x => x.Id == selected) ?? items.FirstOrDefault(); previous.IsEnabled = page > 0; next.IsEnabled = (page + 1) * PageSize < total; pageLabel.Text = $"{page + 1} / {Math.Max(1, (total + PageSize - 1) / PageSize)}"; if (items.Length == 0) { detailVersion++; detail.Children.Clear(); detail.Children.Add(Caption("选择内容查看介绍、版本、依赖与发布状态。")); } Status.Text = $"{total} 项 · " + Services.State.SpaceAddress; } }