feat: add keyboard navigation to NavMenu

This commit is contained in:
SignorParabellaux
2025-05-31 22:28:22 +03:00
parent 87b971654a
commit f1c8d7a542
3 changed files with 380 additions and 37 deletions

View File

@@ -10,30 +10,31 @@
<Setter Property="SubMenuIndent" Value="24" /> <Setter Property="SubMenuIndent" Value="24" />
<Setter Property="Template"> <Setter Property="Template">
<ControlTemplate TargetType="u:NavMenu"> <ControlTemplate TargetType="u:NavMenu">
<DockPanel LastChildFill="True"> <Grid RowDefinitions="Auto, *, Auto">
<ContentPresenter Content="{TemplateBinding Header}" DockPanel.Dock="Top" /> <ContentPresenter Content="{TemplateBinding Header}" />
<ContentPresenter Content="{TemplateBinding Footer}" DockPanel.Dock="Bottom" /> <ScrollViewer
<ScrollViewer Grid.Row="1"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
HorizontalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled"
AllowAutoHide="True" AllowAutoHide="True"
VerticalScrollBarVisibility="Auto"> VerticalScrollBarVisibility="Auto">
<ScrollViewer.Styles> <ScrollViewer.Styles>
<Style Selector="ScrollViewer /template/ ScrollBar"> <Style Selector="ScrollViewer /template/ ScrollBar">
<Setter Property="Opacity" Value="0" /> <Setter Property="Opacity" Value="0" />
</Style> </Style>
<Style Selector="ScrollViewer:pointerover"> <Style Selector="ScrollViewer:pointerover">
<Style Selector="^ /template/ ScrollBar#PART_HorizontalScrollBar"> <Style Selector="^ /template/ ScrollBar#PART_HorizontalScrollBar">
<Setter Property="Opacity" Value="1" /> <Setter Property="Opacity" Value="1" />
</Style> </Style>
<Style Selector="^ /template/ ScrollBar#PART_VerticalScrollBar"> <Style Selector="^ /template/ ScrollBar#PART_VerticalScrollBar">
<Setter Property="Opacity" Value="1" /> <Setter Property="Opacity" Value="1" />
</Style> </Style>
</Style> </Style>
</ScrollViewer.Styles> </ScrollViewer.Styles>
<ItemsPresenter ItemsPanel="{TemplateBinding ItemsPanel}" /> <ItemsPresenter Name="PART_ItemsPresenter" ItemsPanel="{TemplateBinding ItemsPanel}" />
</ScrollViewer> </ScrollViewer>
</DockPanel> <ContentPresenter Grid.Row="2" Content="{TemplateBinding Footer}" />
</Grid>
</ControlTemplate> </ControlTemplate>
</Setter> </Setter>
<Style Selector="^:not(:horizontal-collapsed)"> <Style Selector="^:not(:horizontal-collapsed)">
@@ -182,6 +183,12 @@
<Style Selector="^ /template/ ContentPresenter#PART_HeaderPresenter:pointerover"> <Style Selector="^ /template/ ContentPresenter#PART_HeaderPresenter:pointerover">
<Setter Property="Foreground" Value="{DynamicResource ListBoxItemPointeroverForeground}" /> <Setter Property="Foreground" Value="{DynamicResource ListBoxItemPointeroverForeground}" />
</Style> </Style>
<Style Selector="^:focus /template/ Border#PART_Border">
<Setter Property="Background" Value="{DynamicResource ListBoxItemPointeroverBackground}" />
</Style>
<Style Selector="^:focus /template/ ContentPresenter#PART_HeaderPresenter">
<Setter Property="Foreground" Value="{DynamicResource ListBoxItemPointeroverForeground}" />
</Style>
<Style Selector="^:horizontal-collapsed:first-level"> <Style Selector="^:horizontal-collapsed:first-level">
<Setter Property="HorizontalAlignment" Value="Stretch" /> <Setter Property="HorizontalAlignment" Value="Stretch" />
<Style Selector="^ /template/ Border#PART_Border"> <Style Selector="^ /template/ Border#PART_Border">

View File

@@ -1,6 +1,7 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Metadata; using Avalonia.Controls.Metadata;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates; using Avalonia.Controls.Templates;
using Avalonia.Data; using Avalonia.Data;
@@ -8,13 +9,17 @@ using Avalonia.Input;
using Avalonia.Interactivity; using Avalonia.Interactivity;
using Avalonia.LogicalTree; using Avalonia.LogicalTree;
using Avalonia.Metadata; using Avalonia.Metadata;
using Avalonia.VisualTree;
using Irihi.Avalonia.Shared.Helpers; using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls; namespace Ursa.Controls;
[TemplatePart(PART_ItemsPresenter, typeof(ItemsPresenter))]
[PseudoClasses(PC_HorizontalCollapsed)] [PseudoClasses(PC_HorizontalCollapsed)]
public class NavMenu : ItemsControl public class NavMenu : ItemsControl, ICustomKeyboardNavigation
{ {
public const string PART_ItemsPresenter = "PART_ItemsPresenter";
public const string PC_HorizontalCollapsed = ":horizontal-collapsed"; public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public static readonly StyledProperty<object?> SelectedItemProperty = AvaloniaProperty.Register<NavMenu, object?>( public static readonly StyledProperty<object?> SelectedItemProperty = AvaloniaProperty.Register<NavMenu, object?>(
@@ -69,7 +74,9 @@ public class NavMenu : ItemsControl
public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent =
RoutedEvent.Register<NavMenu, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble); RoutedEvent.Register<NavMenu, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble);
private ItemsPresenter? _itemsPresenter = null;
private bool _isSelectionFromUI = false; private bool _isSelectionFromUI = false;
private bool _isNavigatingMenu = false;
static NavMenu() static NavMenu()
{ {
@@ -193,12 +200,34 @@ public class NavMenu : ItemsControl
return new NavMenuItem(); return new NavMenuItem();
} }
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_itemsPresenter = e.NameScope.Find<ItemsPresenter>(PART_ItemsPresenter);
if (_itemsPresenter is not null)
KeyboardNavigation.SetTabNavigation(_itemsPresenter, KeyboardNavigationMode.Once);
}
protected override void OnLoaded(RoutedEventArgs e) protected override void OnLoaded(RoutedEventArgs e)
{ {
base.OnLoaded(e); base.OnLoaded(e);
TryToSelectItem(SelectedItem); TryToSelectItem(SelectedItem);
} }
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Handled) return;
var source = GetContainerFromEventSource(e.Source);
if (GetNextItem(source, e.Key) is { } target)
{
if (e.Key is Key.Up or Key.Down && source is { Level: 1 } firstLevelSource)
firstLevelSource.CloseAllOpenPopups();
e.Handled = target.Focus(NavigationMethod.Directional);
}
}
/// <summary> /// <summary>
/// this implementation only works in the case that only leaf menu item is allowed to select. It will be changed if we /// 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. /// introduce parent level selection in the future.
@@ -269,6 +298,96 @@ public class NavMenu : ItemsControl
item.ClearSelection(); item.ClearSelection();
} }
(bool handled, IInputElement? next) ICustomKeyboardNavigation.GetNext(IInputElement element, NavigationDirection direction)
{
if (direction is not NavigationDirection.Next and not NavigationDirection.Previous ||
_isNavigatingMenu ||
_itemsPresenter is null) return (false, null);
var visual = element as Visual;
if (!_itemsPresenter.IsVisualAncestorOf(visual))
{
_isNavigatingMenu = true;
var next = KeyboardNavigationHandler.GetNext(element, direction);
_isNavigatingMenu = false;
if (_itemsPresenter.IsVisualAncestorOf(next as Visual))
{
var target = IsHorizontalCollapsed
? GetRootMenuItem(GetContainerForItem(SelectedItem))
: GetUncollapsedOrTopmostMenuItem(GetContainerForItem(SelectedItem));
target ??= ContainerFromIndex(this, 0);
return (target is not null, target);
}
}
else
{
_isNavigatingMenu = true;
var next = KeyboardNavigationHandler.GetNext(_itemsPresenter, direction);
_isNavigatingMenu = false;
if (element is NavMenuItem { Level: 1 } firstLevelItem) firstLevelItem.CloseAllOpenPopups();
return (true, next);
}
return (false, null);
}
private NavMenuItem? GetNextItem(NavMenuItem? current, Key key, bool skipChildren = false)
{
if (current?.Parent is not ItemsControl parent) return null;
var index = IndexFromContainer(parent, current);
return key switch
{
Key.Up => NavigateUp(),
Key.Down => NavigateDown(),
Key.Right when !IsHorizontalCollapsed => NavigateDown(),
Key.Left or Key.Escape => parent as NavMenuItem,
Key.Right or Key.Enter => FirstChild(current),
_ => null
};
NavMenuItem? NavigateUp()
{
if (FindSibling(parent, index - 1, -1) is { } previous)
return !IsHorizontalCollapsed && !previous.IsVerticalCollapsed && previous.ItemCount > 0
? LastChild(previous)
: previous;
return IsHorizontalCollapsed ? LastChild(parent) : parent as NavMenuItem;
}
NavMenuItem? NavigateDown()
{
if (!skipChildren &&
!IsHorizontalCollapsed &&
!current.IsVerticalCollapsed &&
current.ItemCount > 0 &&
FirstChild(current) is { } firstChild) return firstChild;
if (FindSibling(parent, index + 1, 1) is { } next) return next;
if (IsHorizontalCollapsed) return FirstChild(parent);
return GetNextItem(parent as NavMenuItem, key, true);
}
static NavMenuItem? FirstChild(ItemsControl control) => FindSibling(control, 0, 1);
static NavMenuItem? LastChild(ItemsControl control) => FindSibling(control, control.ItemCount - 1, -1);
static NavMenuItem? FindSibling(ItemsControl control, int start, int step)
{
for (var i = start; i >= 0 && i < control.ItemCount; i += step)
if (ContainerFromIndex(control, i) is { IsEnabled: true, IsSeparator: false } item) return item;
return null;
}
}
private bool TryToSelectItem(object? item) private bool TryToSelectItem(object? item)
{ {
if (item is null) return false; if (item is null) return false;
@@ -293,4 +412,78 @@ public class NavMenu : ItemsControl
foreach (var leaf in leafs) yield return leaf; foreach (var leaf in leafs) yield return leaf;
} }
} }
public NavMenuItem? GetContainerForItem(object? item)
{
if (item == null) return null;
return GetContainerForItem(this, item);
static NavMenuItem? GetContainerForItem(ItemsControl control, object item)
{
if (ContainerFromItem(control, item) is NavMenuItem container) return container;
var children = GetRealizedContainers(control);
foreach (var child in children)
if (GetContainerForItem(child, item) is { } childContainer) return childContainer;
return null;
}
}
private NavMenuItem? GetContainerFromEventSource(object? eventSource)
{
if (eventSource is not Visual visual) return null;
return visual.GetSelfAndVisualAncestors()
.OfType<NavMenuItem>()
.FirstOrDefault(i => i.RootMenu == this);
}
private static NavMenuItem? ContainerFromIndex(ItemsControl itemsControl, int index) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareContainerFromIndex(index)
: (NavMenuItem?)itemsControl.ContainerFromIndex(index);
private static NavMenuItem? ContainerFromItem(ItemsControl itemsControl, object item) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareContainerFromItem(item)
: (NavMenuItem?)itemsControl.ContainerFromItem(item);
private static int IndexFromContainer(ItemsControl itemsControl, NavMenuItem container) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareIndexFromContainer(container)
: itemsControl.IndexFromContainer(container);
private static IEnumerable<NavMenuItem> GetRealizedContainers(ItemsControl itemsControl)
{
var realizedContainers = itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareRealizedContainers()
: itemsControl.GetRealizedContainers();
return realizedContainers.OfType<NavMenuItem>();
}
private static NavMenuItem? GetRootMenuItem(NavMenuItem? item)
{
if (item is null) return null;
return item.GetSelfAndLogicalAncestors()
.OfType<NavMenuItem>()
.FirstOrDefault(i => i.Level == 1);
}
private static NavMenuItem? GetUncollapsedOrTopmostMenuItem(NavMenuItem? item)
{
NavMenuItem? result = null;
while (item is not null)
{
var currentParent = item.Parent as NavMenuItem;
result ??= currentParent?.IsVerticalCollapsed is false ? item : null;
if (item.Level == 1) return result ?? item;
item = currentParent;
}
return null;
}
} }

View File

@@ -78,8 +78,6 @@ public class NavMenuItem : HeaderedItemsControl
private bool _isPointerDown = false; private bool _isPointerDown = false;
private Popup? _popup; private Popup? _popup;
private NavMenu? _rootMenu;
static NavMenuItem() static NavMenuItem()
{ {
// SelectableMixin.Attach<NavMenuItem>(IsSelectedProperty); // SelectableMixin.Attach<NavMenuItem>(IsSelectedProperty);
@@ -160,6 +158,8 @@ public class NavMenuItem : HeaderedItemsControl
set => SetValue(IsSeparatorProperty, value); set => SetValue(IsSeparatorProperty, value);
} }
internal NavMenu? RootMenu { get; private set; }
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey) protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{ {
return NeedsContainer<NavMenuItem>(item, out recycleKey); return NeedsContainer<NavMenuItem>(item, out recycleKey);
@@ -173,7 +173,7 @@ public class NavMenuItem : HeaderedItemsControl
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{ {
base.OnAttachedToVisualTree(e); base.OnAttachedToVisualTree(e);
_rootMenu = GetRootMenu(); RootMenu = GetRootMenu();
} }
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
@@ -182,16 +182,16 @@ public class NavMenuItem : HeaderedItemsControl
SetCurrentValue(LevelProperty, CalculateDistanceFromLogicalParent<NavMenu>(this)); SetCurrentValue(LevelProperty, CalculateDistanceFromLogicalParent<NavMenu>(this));
_popup = e.NameScope.Find<Popup>("PART_Popup"); _popup = e.NameScope.Find<Popup>("PART_Popup");
_overflowPanel = e.NameScope.Find<Panel>("PART_OverflowPanel"); _overflowPanel = e.NameScope.Find<Panel>("PART_OverflowPanel");
if (_rootMenu is not null) if (RootMenu is not null)
{ {
this.TryBind(IconProperty, _rootMenu.IconBinding); this.TryBind(IconProperty, RootMenu.IconBinding);
this.TryBind(HeaderProperty, _rootMenu.HeaderBinding); this.TryBind(HeaderProperty, RootMenu.HeaderBinding);
this.TryBind(ItemsSourceProperty, _rootMenu.SubMenuBinding); this.TryBind(ItemsSourceProperty, RootMenu.SubMenuBinding);
this.TryBind(CommandProperty, _rootMenu.CommandBinding); this.TryBind(CommandProperty, RootMenu.CommandBinding);
this[!IconTemplateProperty] = _rootMenu[!NavMenu.IconTemplateProperty]; this[!IconTemplateProperty] = RootMenu[!NavMenu.IconTemplateProperty];
this[!HeaderTemplateProperty] = _rootMenu[!NavMenu.HeaderTemplateProperty]; this[!HeaderTemplateProperty] = RootMenu[!NavMenu.HeaderTemplateProperty];
this[!SubMenuIndentProperty] = _rootMenu[!NavMenu.SubMenuIndentProperty]; this[!SubMenuIndentProperty] = RootMenu[!NavMenu.SubMenuIndentProperty];
this[!IsHorizontalCollapsedProperty] = _rootMenu[!NavMenu.IsHorizontalCollapsedProperty]; this[!IsHorizontalCollapsedProperty] = RootMenu[!NavMenu.IsHorizontalCollapsedProperty];
} }
} }
@@ -202,6 +202,100 @@ public class NavMenuItem : HeaderedItemsControl
if (root is OverflowStackPanel stack) stack.OverflowPanel = _overflowPanel; if (root is OverflowStackPanel stack) stack.OverflowPanel = _overflowPanel;
} }
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Handled) return;
if (e.Key is Key.Enter)
{
if (IsSeparator)
{
e.Handled = true;
return;
}
else if (ItemCount == 0)
{
SelectAndExecute();
e.Handled = true;
return;
}
}
if (!IsHorizontalCollapsed)
{
var handler = e.Key switch
{
Key.Left => ApplyToItemOrRecursivelyIfCtrl(FocusAwareCollapseItem, e.KeyModifiers),
Key.Right => ApplyToItemOrRecursivelyIfCtrl(ExpandItem, e.KeyModifiers),
Key.Enter => ApplyToItemOrRecursivelyIfCtrl(IsVerticalCollapsed ? ExpandItem : CollapseItem, e.KeyModifiers),
Key.Subtract => FocusAwareCollapseItem,
Key.Add => ExpandItem,
Key.Divide => ApplyToSubtree(CollapseItem),
Key.Multiply => ApplyToSubtree(ExpandItem),
_ => null
};
if (handler is not null)
e.Handled = handler(this);
static bool ToggleCollapse(NavMenuItem item, bool collapse)
{
if (item.ItemCount > 0 && item.IsVerticalCollapsed != collapse)
{
item.SetCurrentValue(IsVerticalCollapsedProperty, collapse);
return true;
}
return false;
}
static bool ExpandItem(NavMenuItem item) => ToggleCollapse(item, false);
static bool CollapseItem(NavMenuItem item) => ToggleCollapse(item, true);
static bool FocusAwareCollapseItem(NavMenuItem item)
{
if (item.ItemCount > 0 && !item.IsVerticalCollapsed)
{
if (item.IsFocused)
item.SetCurrentValue(IsVerticalCollapsedProperty, true);
else
item.Focus(NavigationMethod.Directional);
return true;
}
return false;
}
static Func<NavMenuItem, bool> ApplyToItemOrRecursivelyIfCtrl(Func<NavMenuItem, bool> f, KeyModifiers keyModifiers) => keyModifiers.HasFlag(KeyModifiers.Control)
? ApplyToSubtree(f)
: f;
static Func<NavMenuItem, bool> ApplyToSubtree(Func<NavMenuItem, bool> f) => i => Subtree(i)
.ToList()
.Select(i => f(i))
.Aggregate(false, (p, c) => p || c);
static IEnumerable<NavMenuItem> Subtree(NavMenuItem item)
{
yield return item;
var children = item.LogicalChildren
.OfType<NavMenuItem>()
.SelectMany(child => Subtree(child));
foreach (var child in children) yield return child;
}
}
else if (e.Key is Key.Right or Key.Enter)
{
TogglePopup(e.Source, true, true);
}
else if (e.Key is Key.Left or Key.Escape)
{
TogglePopup(e.Source, false, false);
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e) protected override void OnPointerPressed(PointerPressedEventArgs e)
{ {
if (IsSeparator) if (IsSeparator)
@@ -256,6 +350,35 @@ public class NavMenuItem : HeaderedItemsControl
PseudoClasses.Set(PC_FirstLevel, args.NewValue.Value == 1); PseudoClasses.Set(PC_FirstLevel, args.NewValue.Value == 1);
} }
public NavMenuItem? CollapsedAwareContainerFromIndex(int index) =>
IsHorizontalCollapsed && _overflowPanel is not null
? index >= 0 && index < _overflowPanel.Children.Count
? (NavMenuItem?)_overflowPanel.Children[index]
: null
: (NavMenuItem?)ContainerFromIndex(index);
public NavMenuItem? CollapsedAwareContainerFromItem(object item)
{
var index = Items.IndexOf(item);
return index >= 0 ? CollapsedAwareContainerFromIndex(index) : null;
}
public int CollapsedAwareIndexFromContainer(NavMenuItem container) =>
IsHorizontalCollapsed && _overflowPanel is not null
? _overflowPanel.Children.IndexOf(container)
: IndexFromContainer((Control)container);
public object? CollapsedAwareItemFromContainer(NavMenuItem container)
{
var index = CollapsedAwareIndexFromContainer(container);
return index >= 0 && index < Items.Count ? Items[index] : null;
}
public IEnumerable<Control> CollapsedAwareRealizedContainers() =>
IsHorizontalCollapsed && _overflowPanel is not null
? _overflowPanel.Children
: GetRealizedContainers();
internal void SelectItem(NavMenuItem item) internal void SelectItem(NavMenuItem item)
{ {
SetCurrentValue(IsSelectedProperty, item == this); SetCurrentValue(IsSelectedProperty, item == this);
@@ -338,6 +461,26 @@ public class NavMenuItem : HeaderedItemsControl
} }
} }
internal void CloseAllOpenPopups()
{
var items = GetItemsWithChildren(this).Reverse();
foreach (var item in items)
if (item._popup is { IsOpen: true } popup) popup.Close();
static IEnumerable<NavMenuItem> GetItemsWithChildren(NavMenuItem item)
{
if (item.ItemCount > 0)
{
yield return item;
var children = item.LogicalChildren
.OfType<NavMenuItem>()
.SelectMany(child => GetItemsWithChildren(child));
foreach (var child in children) yield return child;
}
}
}
private NavMenu? GetRootMenu() private NavMenu? GetRootMenu()
{ {
var root = this.FindAncestorOfType<NavMenu>() ?? this.FindLogicalAncestorOfType<NavMenu>(); var root = this.FindAncestorOfType<NavMenu>() ?? this.FindLogicalAncestorOfType<NavMenu>();