using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Controls;
/// <summary>Literal JSON values edited as typed fields, without expression interpolation.</summary>
public sealed class WorkflowValueEditor : UserControl
{
public static bool HasInvalidValues(DependencyObject root)
{
if (root is WorkflowValueEditor editor && !editor.IsValid) return true;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++) if (HasInvalidValues(VisualTreeHelper.GetChild(root, i))) return true;
return false;
}
private JsonNode? value;
private readonly WorkflowValueType declaredType;
private readonly bool compact;
private readonly int depth;
private readonly List<WorkflowValueEditor> children = [];
private readonly StackPanel body = new() { Spacing = 5 };
private readonly TextBlock error = new() { TextWrapping = TextWrapping.Wrap, FontSize = 11, Visibility = Visibility.Collapsed, Foreground = (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"] };
private int revision;
private int collectionPage;
private int itemTypeIndex;
public JsonNode? Value => value?.DeepClone();
public bool IsValid => error.Visibility != Visibility.Visible && children.All(x => x.IsValid);
public bool LastChangeStructural { get; private set; }
public event Action<JsonNode?>? ValueChanged;
public WorkflowValueEditor(JsonNode? initial, WorkflowValueType type = WorkflowValueType.Any, bool compact = false, int depth = 0)
{
value = initial?.DeepClone(); declaredType = type; this.compact = compact; this.depth = depth;
FontSize = compact ? 11 : 14; HorizontalContentAlignment = HorizontalAlignment.Stretch;
var layout = new StackPanel { Spacing = 4 }; layout.Children.Add(body); layout.Children.Add(error); Content = layout; Build();
}
public void SetValue(JsonNode? next) { value = next?.DeepClone(); Build(); }
private void Publish(JsonNode? next, bool rebuild = false, bool structureChange = false)
{ value = next?.DeepClone(); LastChangeStructural = rebuild || structureChange; error.Visibility = Visibility.Collapsed; if (rebuild) Build(); ValueChanged?.Invoke(Value); }
private Button Button(string glyph, string name, Action action)
{
var button = new Button { Content = new FontIcon { Glyph = glyph, FontSize = 12 }, Padding = new(5), MinWidth = 26, MinHeight = 26 };
AutomationProperties.SetName(button, name); ToolTipService.SetToolTip(button, name); button.Click += (_, _) => action(); return button;
}
private ComboBox? TakeTypeSelector()
{ var selector = body.Children.OfType<ComboBox>().FirstOrDefault(); if (selector is not null) body.Children.Remove(selector); return selector; }
private void Build()
{
var stamp = ++revision; body.Children.Clear(); children.Clear(); error.Visibility = Visibility.Collapsed;
if (declaredType == WorkflowValueType.Any)
{
var type = new ComboBox { ItemsSource = WorkflowLiteralValues.TypeNames, SelectedIndex = WorkflowLiteralValues.TypeIndex(value), HorizontalAlignment = HorizontalAlignment.Stretch, FontSize = FontSize, MinHeight = compact ? 26 : 32 };
AutomationProperties.SetAutomationId(type, "LiteralType"); type.SelectionChanged += (_, _) => { if (stamp == revision && type.SelectedIndex >= 0 && type.SelectedIndex != WorkflowLiteralValues.TypeIndex(value)) Publish(WorkflowLiteralValues.Default(type.SelectedIndex), true); }; body.Children.Add(type);
}
if (value is JsonArray array) { Collection(array, null, stamp); return; }
if (value is JsonObject obj) { Collection(null, obj, stamp); return; }
if (value?.GetValueKind() is JsonValueKind.True or JsonValueKind.False)
{
var toggle = new ToggleSwitch { IsOn = value.GetValue<bool>(), OnContent = "是", OffContent = "否", MinWidth = 0 }; AutomationProperties.SetAutomationId(toggle, "LiteralBoolean");
toggle.Toggled += (_, _) => { if (stamp == revision) Publish(JsonValue.Create(toggle.IsOn)); }; body.Children.Add(toggle); return;
}
if (value is null && declaredType is WorkflowValueType.Any)
{ body.Children.Add(new TextBlock { Text = "null", Opacity = .7, FontSize = FontSize }); return; }
if (value is null)
{
body.Children.Add(new TextBlock { Text = "null", Opacity = .7, FontSize = FontSize });
var reset = new Button { Content = "设置值", FontSize = FontSize };
reset.Click += (_, _) => Publish(WorkflowLiteralValues.Default(declaredType switch { WorkflowValueType.Array => 4, WorkflowValueType.Object => 3, WorkflowValueType.Number => 1, WorkflowValueType.Boolean => 2, _ => 0 }), true); body.Children.Add(reset); return;
}
var number = declaredType == WorkflowValueType.Number || value?.GetValueKind() == JsonValueKind.Number;
var text = new TextBox { Text = number ? value?.Display() ?? "0" : value?.GetValueKind() == JsonValueKind.String ? value.GetValue<string>() : "", FontSize = FontSize, MinWidth = 0,
MinHeight = compact ? 26 : 32, Padding = compact ? new(6, 3, 6, 3) : new(10, 5, 10, 5), TextWrapping = TextWrapping.Wrap, AcceptsReturn = !number, MaxHeight = compact ? 76 : 140 };
AutomationProperties.SetAutomationId(text, number ? "LiteralNumber" : "LiteralText");
text.TextChanged += (_, _) =>
{
if (stamp != revision) return;
try { Publish(number ? WorkflowLiteralValues.ParseNumber(text.Text) : JsonValue.Create(text.Text)); }
catch (ArgumentException ex) { error.Text = ex.Message; error.Visibility = Visibility.Visible; }
};
body.Children.Add(text);
}
private void Collection(JsonArray? array, JsonObject? obj, int stamp)
{
var count = array?.Count ?? obj!.Count;
body.Children.Add(new TextBlock { Text = $"{count} {(array is null ? "个字段" : "项")}", FontSize = FontSize, Opacity = .7 });
if (depth >= 12) { body.Children.Add(new TextBlock { Text = "嵌套超过 12 层,请在高级参数中编辑", FontSize = FontSize, TextWrapping = TextWrapping.Wrap }); return; }
var rows = new StackPanel { Spacing = 6 };
collectionPage = Math.Clamp(collectionPage, 0, Math.Max(0, (count - 1) / 25));
for (var i = collectionPage * 25; i < Math.Min(count, (collectionPage + 1) * 25); i++)
{
var index = i; var key = obj?.ElementAt(i).Key; var item = array is null ? obj![key!] : array[i];
var row = new StackPanel { Spacing = 4 };
WorkflowValueEditor Editor()
{
var editor = new WorkflowValueEditor(item, compact: compact, depth: depth + 1); children.Add(editor);
editor.ValueChanged += next => { if (stamp != revision) return; if (array is not null) array[index] = next?.DeepClone(); else obj![key!] = next?.DeepClone(); Publish(array ?? (JsonNode)obj!, rebuild: compact && editor.LastChangeStructural, structureChange: editor.LastChangeStructural); };
return editor;
}
var header = new Grid { ColumnSpacing = 4 }; header.ColumnDefinitions.Add(new()); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
if (obj is not null)
{
var field = new TextBox { Text = key, FontSize = FontSize, MinHeight = 26, Padding = new(6, 3, 6, 3), PlaceholderText = "字段名称" };
field.LostFocus += (_, _) =>
{
if (stamp != revision) return;
if (field.Text == key) { error.Visibility = Visibility.Collapsed; return; }
if (string.IsNullOrWhiteSpace(field.Text) || obj.ContainsKey(field.Text)) { error.Text = "字段名称不能为空或重复"; error.Visibility = Visibility.Visible; return; }
var changed = new JsonObject(); foreach (var pair in obj) changed[pair.Key == key ? field.Text : pair.Key] = pair.Value?.DeepClone(); Publish(changed, true);
}; header.Children.Add(field);
}
else header.Children.Add(new TextBlock { Text = $"[{i}]", FontSize = FontSize, Opacity = .65, VerticalAlignment = VerticalAlignment.Center });
var remove = Button("\uE74D", "删除第 " + (i + 1) + " 项", () => { if (array is not null) array.RemoveAt(index); else obj!.Remove(key!); Publish(array ?? (JsonNode)obj!, true); });
AutomationProperties.SetAutomationId(remove, "LiteralRemove-" + index); Grid.SetColumn(remove, 1); header.Children.Add(remove);
row.Children.Add(header);
if (item is JsonArray or JsonObject)
{
var expand = new Expander { Header = item is JsonArray ? "数组" : "对象", HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch };
expand.Expanding += (_, _) => expand.Content ??= Editor(); row.Children.Add(expand);
}
else
{
var editor = Editor();
if (compact && array is not null && editor.TakeTypeSelector() is { } selector)
{
header.ColumnDefinitions.Clear(); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); header.ColumnDefinitions.Add(new()); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
Grid.SetColumn(remove, 2); Grid.SetColumn(selector, 1); header.Children.Add(selector);
}
row.Children.Add(editor);
}
rows.Children.Add(new Border { Padding = new(compact ? 5 : 8), CornerRadius = new(5), BorderThickness = new(1), BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"], Child = row });
}
body.Children.Add(new ScrollViewer { Content = rows, MaxHeight = compact ? 250 : 360, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled });
if (count > 25)
{
var pages = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
var previous = Button("\uE76B", "上一页单元", () => { collectionPage--; Build(); }); previous.IsEnabled = collectionPage > 0;
var next = Button("\uE76C", "下一页单元", () => { collectionPage++; Build(); }); next.IsEnabled = (collectionPage + 1) * 25 < count;
pages.Children.Add(previous); pages.Children.Add(new TextBlock { Text = $"{collectionPage + 1}/{(count + 24) / 25}", FontSize = FontSize, VerticalAlignment = VerticalAlignment.Center }); pages.Children.Add(next); body.Children.Add(pages);
}
var addRow = new Grid { ColumnSpacing = 6 }; addRow.ColumnDefinitions.Add(new()); addRow.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
var itemType = new ComboBox { ItemsSource = WorkflowLiteralValues.TypeNames, SelectedIndex = itemTypeIndex, HorizontalAlignment = HorizontalAlignment.Stretch, FontSize = FontSize, MinHeight = compact ? 26 : 32 };
itemType.SelectionChanged += (_, _) => { if (itemType.SelectedIndex >= 0) itemTypeIndex = itemType.SelectedIndex; };
AutomationProperties.SetAutomationId(itemType, "LiteralItemType"); AutomationProperties.SetName(itemType, "新单元类型"); addRow.Children.Add(itemType);
var add = Button("\uE710", array is null ? "添加字段" : "添加单元", () =>
{
if (count >= 1000) { error.Text = "可视编辑最多 1000 项"; error.Visibility = Visibility.Visible; return; }
var item = WorkflowLiteralValues.Default(itemType.SelectedIndex);
if (array is not null) array.Add(item); else { var n = obj!.Count + 1; while (obj.ContainsKey("字段" + n)) n++; obj["字段" + n] = item; }
Publish(array ?? (JsonNode)obj!, true);
});
add.IsEnabled = count < 1000;
AutomationProperties.SetAutomationId(add, "LiteralAdd"); Grid.SetColumn(add, 1); addRow.Children.Add(add); body.Children.Add(addRow);
}
}
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Controls;
/// <summary>Literal JSON values edited as typed fields, without expression interpolation.</summary>
public sealed class WorkflowValueEditor : UserControl
{
public static bool HasInvalidValues(DependencyObject root)
{
if (root is WorkflowValueEditor editor && !editor.IsValid) return true;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++) if (HasInvalidValues(VisualTreeHelper.GetChild(root, i))) return true;
return false;
}
private JsonNode? value;
private readonly WorkflowValueType declaredType;
private readonly bool compact;
private readonly int depth;
private readonly List<WorkflowValueEditor> children = [];
private readonly StackPanel body = new() { Spacing = 5 };
private readonly TextBlock error = new() { TextWrapping = TextWrapping.Wrap, FontSize = 11, Visibility = Visibility.Collapsed, Foreground = (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"] };
private int revision;
private int collectionPage;
private int itemTypeIndex;
public JsonNode? Value => value?.DeepClone();
public bool IsValid => error.Visibility != Visibility.Visible && children.All(x => x.IsValid);
public bool LastChangeStructural { get; private set; }
public event Action<JsonNode?>? ValueChanged;
public WorkflowValueEditor(JsonNode? initial, WorkflowValueType type = WorkflowValueType.Any, bool compact = false, int depth = 0)
{
value = initial?.DeepClone(); declaredType = type; this.compact = compact; this.depth = depth;
FontSize = compact ? 11 : 14; HorizontalContentAlignment = HorizontalAlignment.Stretch;
var layout = new StackPanel { Spacing = 4 }; layout.Children.Add(body); layout.Children.Add(error); Content = layout; Build();
}
public void SetValue(JsonNode? next) { value = next?.DeepClone(); Build(); }
private void Publish(JsonNode? next, bool rebuild = false, bool structureChange = false)
{ value = next?.DeepClone(); LastChangeStructural = rebuild || structureChange; error.Visibility = Visibility.Collapsed; if (rebuild) Build(); ValueChanged?.Invoke(Value); }
private Button Button(string glyph, string name, Action action)
{
var button = new Button { Content = new FontIcon { Glyph = glyph, FontSize = 12 }, Padding = new(5), MinWidth = 26, MinHeight = 26 };
AutomationProperties.SetName(button, name); ToolTipService.SetToolTip(button, name); button.Click += (_, _) => action(); return button;
}
private ComboBox? TakeTypeSelector()
{ var selector = body.Children.OfType<ComboBox>().FirstOrDefault(); if (selector is not null) body.Children.Remove(selector); return selector; }
private void Build()
{
var stamp = ++revision; body.Children.Clear(); children.Clear(); error.Visibility = Visibility.Collapsed;
if (declaredType == WorkflowValueType.Any)
{
var type = new ComboBox { ItemsSource = WorkflowLiteralValues.TypeNames, SelectedIndex = WorkflowLiteralValues.TypeIndex(value), HorizontalAlignment = HorizontalAlignment.Stretch, FontSize = FontSize, MinHeight = compact ? 26 : 32 };
AutomationProperties.SetAutomationId(type, "LiteralType"); type.SelectionChanged += (_, _) => { if (stamp == revision && type.SelectedIndex >= 0 && type.SelectedIndex != WorkflowLiteralValues.TypeIndex(value)) Publish(WorkflowLiteralValues.Default(type.SelectedIndex), true); }; body.Children.Add(type);
}
if (value is JsonArray array) { Collection(array, null, stamp); return; }
if (value is JsonObject obj) { Collection(null, obj, stamp); return; }
if (value?.GetValueKind() is JsonValueKind.True or JsonValueKind.False)
{
var toggle = new ToggleSwitch { IsOn = value.GetValue<bool>(), OnContent = "是", OffContent = "否", MinWidth = 0 }; AutomationProperties.SetAutomationId(toggle, "LiteralBoolean");
toggle.Toggled += (_, _) => { if (stamp == revision) Publish(JsonValue.Create(toggle.IsOn)); }; body.Children.Add(toggle); return;
}
if (value is null && declaredType is WorkflowValueType.Any)
{ body.Children.Add(new TextBlock { Text = "null", Opacity = .7, FontSize = FontSize }); return; }
if (value is null)
{
body.Children.Add(new TextBlock { Text = "null", Opacity = .7, FontSize = FontSize });
var reset = new Button { Content = "设置值", FontSize = FontSize };
reset.Click += (_, _) => Publish(WorkflowLiteralValues.Default(declaredType switch { WorkflowValueType.Array => 4, WorkflowValueType.Object => 3, WorkflowValueType.Number => 1, WorkflowValueType.Boolean => 2, _ => 0 }), true); body.Children.Add(reset); return;
}
var number = declaredType == WorkflowValueType.Number || value?.GetValueKind() == JsonValueKind.Number;
var text = new TextBox { Text = number ? value?.Display() ?? "0" : value?.GetValueKind() == JsonValueKind.String ? value.GetValue<string>() : "", FontSize = FontSize, MinWidth = 0,
MinHeight = compact ? 26 : 32, Padding = compact ? new(6, 3, 6, 3) : new(10, 5, 10, 5), TextWrapping = TextWrapping.Wrap, AcceptsReturn = !number, MaxHeight = compact ? 76 : 140 };
AutomationProperties.SetAutomationId(text, number ? "LiteralNumber" : "LiteralText");
text.TextChanged += (_, _) =>
{
if (stamp != revision) return;
try { Publish(number ? WorkflowLiteralValues.ParseNumber(text.Text) : JsonValue.Create(text.Text)); }
catch (ArgumentException ex) { error.Text = ex.Message; error.Visibility = Visibility.Visible; }
};
body.Children.Add(text);
}
private void Collection(JsonArray? array, JsonObject? obj, int stamp)
{
var count = array?.Count ?? obj!.Count;
body.Children.Add(new TextBlock { Text = $"{count} {(array is null ? "个字段" : "项")}", FontSize = FontSize, Opacity = .7 });
if (depth >= 12) { body.Children.Add(new TextBlock { Text = "嵌套超过 12 层,请在高级参数中编辑", FontSize = FontSize, TextWrapping = TextWrapping.Wrap }); return; }
var rows = new StackPanel { Spacing = 6 };
collectionPage = Math.Clamp(collectionPage, 0, Math.Max(0, (count - 1) / 25));
for (var i = collectionPage * 25; i < Math.Min(count, (collectionPage + 1) * 25); i++)
{
var index = i; var key = obj?.ElementAt(i).Key; var item = array is null ? obj![key!] : array[i];
var row = new StackPanel { Spacing = 4 };
WorkflowValueEditor Editor()
{
var editor = new WorkflowValueEditor(item, compact: compact, depth: depth + 1); children.Add(editor);
editor.ValueChanged += next => { if (stamp != revision) return; if (array is not null) array[index] = next?.DeepClone(); else obj![key!] = next?.DeepClone(); Publish(array ?? (JsonNode)obj!, rebuild: compact && editor.LastChangeStructural, structureChange: editor.LastChangeStructural); };
return editor;
}
var header = new Grid { ColumnSpacing = 4 }; header.ColumnDefinitions.Add(new()); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
if (obj is not null)
{
var field = new TextBox { Text = key, FontSize = FontSize, MinHeight = 26, Padding = new(6, 3, 6, 3), PlaceholderText = "字段名称" };
field.LostFocus += (_, _) =>
{
if (stamp != revision) return;
if (field.Text == key) { error.Visibility = Visibility.Collapsed; return; }
if (string.IsNullOrWhiteSpace(field.Text) || obj.ContainsKey(field.Text)) { error.Text = "字段名称不能为空或重复"; error.Visibility = Visibility.Visible; return; }
var changed = new JsonObject(); foreach (var pair in obj) changed[pair.Key == key ? field.Text : pair.Key] = pair.Value?.DeepClone(); Publish(changed, true);
}; header.Children.Add(field);
}
else header.Children.Add(new TextBlock { Text = $"[{i}]", FontSize = FontSize, Opacity = .65, VerticalAlignment = VerticalAlignment.Center });
var remove = Button("\uE74D", "删除第 " + (i + 1) + " 项", () => { if (array is not null) array.RemoveAt(index); else obj!.Remove(key!); Publish(array ?? (JsonNode)obj!, true); });
AutomationProperties.SetAutomationId(remove, "LiteralRemove-" + index); Grid.SetColumn(remove, 1); header.Children.Add(remove);
row.Children.Add(header);
if (item is JsonArray or JsonObject)
{
var expand = new Expander { Header = item is JsonArray ? "数组" : "对象", HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch };
expand.Expanding += (_, _) => expand.Content ??= Editor(); row.Children.Add(expand);
}
else
{
var editor = Editor();
if (compact && array is not null && editor.TakeTypeSelector() is { } selector)
{
header.ColumnDefinitions.Clear(); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); header.ColumnDefinitions.Add(new()); header.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
Grid.SetColumn(remove, 2); Grid.SetColumn(selector, 1); header.Children.Add(selector);
}
row.Children.Add(editor);
}
rows.Children.Add(new Border { Padding = new(compact ? 5 : 8), CornerRadius = new(5), BorderThickness = new(1), BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"], Child = row });
}
body.Children.Add(new ScrollViewer { Content = rows, MaxHeight = compact ? 250 : 360, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled });
if (count > 25)
{
var pages = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
var previous = Button("\uE76B", "上一页单元", () => { collectionPage--; Build(); }); previous.IsEnabled = collectionPage > 0;
var next = Button("\uE76C", "下一页单元", () => { collectionPage++; Build(); }); next.IsEnabled = (collectionPage + 1) * 25 < count;
pages.Children.Add(previous); pages.Children.Add(new TextBlock { Text = $"{collectionPage + 1}/{(count + 24) / 25}", FontSize = FontSize, VerticalAlignment = VerticalAlignment.Center }); pages.Children.Add(next); body.Children.Add(pages);
}
var addRow = new Grid { ColumnSpacing = 6 }; addRow.ColumnDefinitions.Add(new()); addRow.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
var itemType = new ComboBox { ItemsSource = WorkflowLiteralValues.TypeNames, SelectedIndex = itemTypeIndex, HorizontalAlignment = HorizontalAlignment.Stretch, FontSize = FontSize, MinHeight = compact ? 26 : 32 };
itemType.SelectionChanged += (_, _) => { if (itemType.SelectedIndex >= 0) itemTypeIndex = itemType.SelectedIndex; };
AutomationProperties.SetAutomationId(itemType, "LiteralItemType"); AutomationProperties.SetName(itemType, "新单元类型"); addRow.Children.Add(itemType);
var add = Button("\uE710", array is null ? "添加字段" : "添加单元", () =>
{
if (count >= 1000) { error.Text = "可视编辑最多 1000 项"; error.Visibility = Visibility.Visible; return; }
var item = WorkflowLiteralValues.Default(itemType.SelectedIndex);
if (array is not null) array.Add(item); else { var n = obj!.Count + 1; while (obj.ContainsKey("字段" + n)) n++; obj["字段" + n] = item; }
Publish(array ?? (JsonNode)obj!, true);
});
add.IsEnabled = count < 1000;
AutomationProperties.SetAutomationId(add, "LiteralAdd"); Grid.SetColumn(add, 1); addRow.Children.Add(add); body.Children.Add(addRow);
}
}