Merge pull request #105 from irihitech/nav

Nav Menu Refactoring Step 1.
This commit is contained in:
Dong Bin
2024-02-14 21:09:55 +08:00
committed by GitHub
15 changed files with 1220 additions and 8 deletions

View File

@@ -5,6 +5,7 @@ using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Media;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
@@ -75,13 +76,7 @@ public class TwoTonePathIcon: TemplatedControl
ForegroundProperty,
ActiveForegroundProperty,
ActiveStrokeBrushProperty);
IsActiveProperty.Changed.AddClassHandler<TwoTonePathIcon, bool>((o, e) => o.OnIsActiveChanged(e));
}
private void OnIsActiveChanged(AvaloniaPropertyChangedEventArgs<bool> args)
{
var newValue = args.NewValue.Value;
PseudoClasses.Set(PC_Active, newValue);
PropertyToPseudoClassMixin.Attach<TwoTonePathIcon>(IsActiveProperty, PC_Active);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)

View File

@@ -0,0 +1,276 @@
using System.Diagnostics;
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
[PseudoClasses(PC_HorizontalCollapsed)]
public class NavMenu: ItemsControl
{
public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public static readonly StyledProperty<object?> SelectedItemProperty = AvaloniaProperty.Register<NavMenu, object?>(
nameof(SelectedItem), defaultBindingMode: BindingMode.TwoWay);
public object? SelectedItem
{
get => GetValue(SelectedItemProperty);
set => SetValue(SelectedItemProperty, value);
}
public static readonly StyledProperty<IBinding?> IconBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(IconBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? IconBinding
{
get => GetValue(IconBindingProperty);
set => SetValue(IconBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> HeaderBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(HeaderBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? HeaderBinding
{
get => GetValue(HeaderBindingProperty);
set => SetValue(HeaderBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> SubMenuBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(SubMenuBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? SubMenuBinding
{
get => GetValue(SubMenuBindingProperty);
set => SetValue(SubMenuBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> CommandBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(CommandBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? CommandBinding
{
get => GetValue(CommandBindingProperty);
set => SetValue(CommandBindingProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> HeaderTemplateProperty = AvaloniaProperty.Register<NavMenu, IDataTemplate?>(
nameof(HeaderTemplate));
/// <summary>
/// Header Template is used for MenuItem headers, not menu header.
/// </summary>
public IDataTemplate? HeaderTemplate
{
get => GetValue(HeaderTemplateProperty);
set => SetValue(HeaderTemplateProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> IconTemplateProperty = AvaloniaProperty.Register<NavMenu, IDataTemplate?>(
nameof(IconTemplate));
public IDataTemplate? IconTemplate
{
get => GetValue(IconTemplateProperty);
set => SetValue(IconTemplateProperty, value);
}
public static readonly StyledProperty<double> SubMenuIndentProperty = AvaloniaProperty.Register<NavMenu, double>(
nameof(SubMenuIndent));
public double SubMenuIndent
{
get => GetValue(SubMenuIndentProperty);
set => SetValue(SubMenuIndentProperty, value);
}
public static readonly StyledProperty<bool> IsHorizontalCollapsedProperty = AvaloniaProperty.Register<NavMenu, bool>(
nameof(IsHorizontalCollapsed));
public bool IsHorizontalCollapsed
{
get => GetValue(IsHorizontalCollapsedProperty);
set => SetValue(IsHorizontalCollapsedProperty, value);
}
public static readonly StyledProperty<object?> HeaderProperty =
HeaderedContentControl.HeaderProperty.AddOwner<NavMenu>();
public object? Header
{
get => GetValue(HeaderProperty);
set => SetValue(HeaderProperty, value);
}
public static readonly StyledProperty<object?> FooterProperty = AvaloniaProperty.Register<NavMenu, object?>(
nameof(Footer));
public object? Footer
{
get => GetValue(FooterProperty);
set => SetValue(FooterProperty, value);
}
public static readonly AttachedProperty<bool> CanToggleProperty =
AvaloniaProperty.RegisterAttached<NavMenu, InputElement, bool>("CanToggle");
public static void SetCanToggle(InputElement obj, bool value) => obj.SetValue(CanToggleProperty, value);
public static bool GetCanToggle(InputElement obj) => obj.GetValue(CanToggleProperty);
public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<NavMenu, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble);
public event EventHandler<SelectionChangedEventArgs>? SelectionChanged
{
add => AddHandler(SelectionChangedEvent, value);
remove => RemoveHandler(SelectionChangedEvent, value);
}
static NavMenu()
{
SelectedItemProperty.Changed.AddClassHandler<NavMenu, object?>((o, e) => o.OnSelectedItemChange(e));
PropertyToPseudoClassMixin.Attach<NavMenu>(IsHorizontalCollapsedProperty, PC_HorizontalCollapsed);
CanToggleProperty.Changed.AddClassHandler<InputElement, bool>(OnInputRegisteredAsToggle);
}
private static void OnInputRegisteredAsToggle(InputElement input, AvaloniaPropertyChangedEventArgs<bool> e)
{
if (e.NewValue.Value)
{
input.AddHandler(PointerPressedEvent, OnElementToggle);
}
else
{
input.RemoveHandler(PointerPressedEvent, OnElementToggle);
}
}
private static void OnElementToggle(object? sender, RoutedEventArgs args)
{
if (sender is not InputElement input) return;
var nav = input.FindLogicalAncestorOfType<NavMenu>();
if(nav is null) return;
bool collapsed = nav.IsHorizontalCollapsed;
nav.IsHorizontalCollapsed = !collapsed;
}
/// <summary>
/// this implementation only works in the case that only leaf menu item is allowed to select. It will be changed if we introduce parent level selection in the future.
/// </summary>
/// <param name="args"></param>
private void OnSelectedItemChange(AvaloniaPropertyChangedEventArgs<object?> args)
{
SelectionChangedEventArgs a = new SelectionChangedEventArgs(
SelectionChangedEvent,
new [] { args.OldValue.Value },
new [] { args.NewValue.Value });
if (_updateFromUI)
{
RaiseEvent(a);
return;
}
var newValue = args.NewValue.Value;
if (newValue is null)
{
ClearAll();
RaiseEvent(a);
return;
}
var leaves = GetLeafMenus();
bool found = false;
foreach (var leaf in leaves)
{
if (leaf == newValue || leaf.DataContext == newValue)
{
leaf.SelectItem(leaf);
found = true;
}
}
if (!found)
{
ClearAll();
}
RaiseEvent(a);
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new NavMenuItem();
}
private bool _updateFromUI;
internal void SelectItem(NavMenuItem item, NavMenuItem parent)
{
_updateFromUI = true;
foreach (var child in LogicalChildren)
{
if (child == parent)
{
continue;
}
if (child is NavMenuItem navMenuItem)
{
navMenuItem.ClearSelection();
}
}
if (item.DataContext is not null && item.DataContext != this.DataContext)
{
SelectedItem = item.DataContext;
}
else
{
SelectedItem = item;
}
item.BringIntoView();
_updateFromUI = false;
}
private IEnumerable<NavMenuItem> GetLeafMenus()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var leafs = item.GetLeafMenus();
foreach (var leaf in leafs)
{
yield return leaf;
}
}
}
}
private void ClearAll()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
item.ClearSelection();
}
}
}
}

View File

@@ -0,0 +1,352 @@
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
/// <summary>
/// Navigation Menu Item
/// </summary>
[PseudoClasses(PC_Highlighted, PC_HorizontalCollapsed, PC_VerticalCollapsed, PC_FirstLevel, PC_Selector)]
public class NavMenuItem: HeaderedItemsControl
{
public const string PC_Highlighted = ":highlighted";
public const string PC_FirstLevel = ":first-level";
public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public const string PC_VerticalCollapsed = ":vertical-collapsed";
public const string PC_Selector = ":selector";
private NavMenu? _rootMenu;
private Panel? _popupPanel;
private Popup? _popup;
private Panel? _overflowPanel;
public static readonly StyledProperty<object?> IconProperty = AvaloniaProperty.Register<NavMenuItem, object?>(
nameof(Icon));
public object? Icon
{
get => GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> IconTemplateProperty = AvaloniaProperty.Register<NavMenuItem, IDataTemplate?>(
nameof(IconTemplate));
public IDataTemplate? IconTemplate
{
get => GetValue(IconTemplateProperty);
set => SetValue(IconTemplateProperty, value);
}
public static readonly StyledProperty<ICommand?> CommandProperty = Button.CommandProperty.AddOwner<NavMenuItem>();
public ICommand? Command
{
get => GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public static readonly StyledProperty<object?> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<NavMenuItem>();
public object? CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
public static readonly StyledProperty<bool> IsSelectedProperty =
SelectingItemsControl.IsSelectedProperty.AddOwner<NavMenuItem>();
public bool IsSelected
{
get => GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent = RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>("IsSelectedChanged", RoutingStrategies.Bubble);
private bool _isHighlighted;
public static readonly DirectProperty<NavMenuItem, bool> IsHighlightedProperty =
AvaloniaProperty.RegisterDirect<NavMenuItem, bool>(
nameof(IsHighlighted), o => o.IsHighlighted, (o, v) => o.IsHighlighted = v,
defaultBindingMode: BindingMode.TwoWay);
public bool IsHighlighted
{
get => _isHighlighted;
private set => SetAndRaise(IsHighlightedProperty, ref _isHighlighted, value);
}
public static readonly StyledProperty<bool> IsHorizontalCollapsedProperty =
NavMenu.IsHorizontalCollapsedProperty.AddOwner<NavMenuItem>();
public bool IsHorizontalCollapsed
{
get => GetValue(IsHorizontalCollapsedProperty);
set => SetValue(IsHorizontalCollapsedProperty, value);
}
public static readonly StyledProperty<bool> IsVerticalCollapsedProperty = AvaloniaProperty.Register<NavMenuItem, bool>(
nameof(IsVerticalCollapsed));
public bool IsVerticalCollapsed
{
get => GetValue(IsVerticalCollapsedProperty);
set => SetValue(IsVerticalCollapsedProperty, value);
}
public static readonly StyledProperty<double> SubMenuIndentProperty =
NavMenu.SubMenuIndentProperty.AddOwner<NavMenuItem>();
public double SubMenuIndent
{
get => GetValue(SubMenuIndentProperty);
set => SetValue(SubMenuIndentProperty, value);
}
internal static readonly DirectProperty<NavMenuItem, int> LevelProperty = AvaloniaProperty.RegisterDirect<NavMenuItem, int>(
nameof(Level), o => o.Level, (o, v) => o.Level = v);
private int _level;
internal int Level
{
get => _level;
set => SetAndRaise(LevelProperty, ref _level, value);
}
public static readonly StyledProperty<bool> IsSeparatorProperty = AvaloniaProperty.Register<NavMenuItem, bool>(
nameof(IsSeparator));
public bool IsSeparator
{
get => GetValue(IsSeparatorProperty);
set => SetValue(IsSeparatorProperty, value);
}
static NavMenuItem()
{
// SelectableMixin.Attach<NavMenuItem>(IsSelectedProperty);
PressedMixin.Attach<NavMenuItem>();
LevelProperty.Changed.AddClassHandler<NavMenuItem, int>((item, args) => item.OnLevelChange(args));
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsHighlightedProperty, PC_Highlighted);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsHorizontalCollapsedProperty, PC_HorizontalCollapsed);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsVerticalCollapsedProperty, PC_VerticalCollapsed);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsSelectedProperty, ":selected", IsSelectedChangedEvent);
IsHorizontalCollapsedProperty.Changed.AddClassHandler<NavMenuItem, bool>((item, args) =>
item.OnIsHorizontalCollapsedChanged(args));
}
private void OnIsHorizontalCollapsedChanged(AvaloniaPropertyChangedEventArgs<bool> args)
{
if (args.NewValue.Value)
{
if (this.ItemsPanelRoot is OverflowStackPanel s)
{
s.MoveChildrenToOverflowPanel();
}
}
else
{
if (this.ItemsPanelRoot is OverflowStackPanel s)
{
s.MoveChildrenToMainPanel();
}
}
}
private void OnLevelChange(AvaloniaPropertyChangedEventArgs<int> args)
{
PseudoClasses.Set(PC_FirstLevel, args.NewValue.Value == 1);
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new NavMenuItem();
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
_rootMenu = GetRootMenu();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
SetCurrentValue(LevelProperty,CalculateDistanceFromLogicalParent<NavMenu>(this));
_popup = e.NameScope.Find<Popup>("PART_Popup");
_overflowPanel = e.NameScope.Find<Panel>("PART_OverflowPanel");
if (_rootMenu is not null)
{
if (_rootMenu.IconBinding is not null)
{
this[!IconProperty] = _rootMenu.IconBinding;
}
if (_rootMenu.HeaderBinding is not null)
{
this[!HeaderProperty] = _rootMenu.HeaderBinding;
}
if (_rootMenu.SubMenuBinding is not null)
{
this[!ItemsSourceProperty] = _rootMenu.SubMenuBinding;
}
if (_rootMenu.CommandBinding is not null)
{
this[!CommandProperty] = _rootMenu.CommandBinding;
}
this[!IconTemplateProperty] = _rootMenu[!NavMenu.IconTemplateProperty];
this[!HeaderTemplateProperty] = _rootMenu[!NavMenu.HeaderTemplateProperty];
this[!SubMenuIndentProperty] = _rootMenu[!NavMenu.SubMenuIndentProperty];
this[!IsHorizontalCollapsedProperty] = _rootMenu[!NavMenu.IsHorizontalCollapsedProperty];
}
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var root = this.ItemsPanelRoot;
if (root is OverflowStackPanel stack)
{
stack.OverflowPanel = _overflowPanel;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (IsSeparator)
{
e.Handled = true;
return;
}
base.OnPointerPressed(e);
if (this.ItemCount == 0)
{
SelectItem(this);
}
else
{
if (!IsHorizontalCollapsed)
{
SetCurrentValue(IsVerticalCollapsedProperty, !IsVerticalCollapsed);
}
else
{
if (_popup is not null)
{
if (_popup.IsOpen)
{
_popup.Close();
}
else
{
_popup.Open();
}
}
}
}
Command?.Execute(CommandParameter);
e.Handled = true;
}
internal void SelectItem(NavMenuItem item)
{
if (item == this)
{
SetCurrentValue(IsSelectedProperty, true);
SetCurrentValue(IsHighlightedProperty, true);
}
else
{
SetCurrentValue(IsSelectedProperty, false);
SetCurrentValue(IsHighlightedProperty, true);
}
if (this.Parent is NavMenuItem menuItem)
{
menuItem.SelectItem(item);
var items = menuItem.LogicalChildren.OfType<NavMenuItem>();
foreach (var child in items)
{
if (child != this)
{
child.ClearSelection();
}
}
}
else if (this.Parent is NavMenu menu)
{
menu.SelectItem(item, this);
}
}
internal void ClearSelection()
{
SetCurrentValue(IsHighlightedProperty, false);
SetCurrentValue(IsSelectedProperty, false);
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
item.ClearSelection();
}
}
}
private NavMenu? GetRootMenu()
{
var root = this.FindAncestorOfType<NavMenu>() ?? this.FindLogicalAncestorOfType<NavMenu>();
return root;
}
private static int CalculateDistanceFromLogicalParent<T>(ILogical? logical, int @default = -1) where T : class
{
var result = 0;
while (logical != null && !(logical is T))
{
if (logical is NavMenuItem)
{
result++;
}
logical = logical.LogicalParent;
}
return logical != null ? result : @default;
}
internal IEnumerable<NavMenuItem> GetLeafMenus()
{
if (this.ItemCount == 0)
{
yield return this;
yield break;
}
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var items = item.GetLeafMenus();
foreach (var i in items)
{
yield return i;
}
}
}
}
}

View File

@@ -0,0 +1,30 @@
using Avalonia.Controls;
namespace Ursa.Controls;
public class OverflowStackPanel: StackPanel
{
public Panel? OverflowPanel { get; set; }
public void MoveChildrenToOverflowPanel()
{
var children = this.Children.ToList();
foreach (var child in children)
{
Children.Remove(child);
OverflowPanel?.Children.Add(child);
}
}
public void MoveChildrenToMainPanel()
{
var children = this.OverflowPanel?.Children.ToList();
if (children != null && children.Count > 0)
{
foreach (var child in children)
{
OverflowPanel?.Children.Remove(child);
Children.Add(child);
}
}
}
}

View File

@@ -14,7 +14,7 @@
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Irihi.Avalonia.Shared" Version="0.1.1" />
<PackageReference Include="Irihi.Avalonia.Shared" Version="0.1.2" />
</ItemGroup>
</Project>