Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions src/Controls/src/Core/Handlers/Shell/ShellItemHandler.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public partial class ShellItemHandler : ElementHandler<ShellItem, FrameworkEleme
SearchHandler? _currentSearchHandler;
IShellAppearanceElement? _shellAppearanceElement;
readonly HashSet<ShellSection> _trackedShellSections = new();
ItemsRepeater? _overflowMenuItemsHost;

public ShellItemHandler() : base(Mapper, CommandMapper)
{
Expand Down Expand Up @@ -78,7 +79,11 @@ protected override void ConnectHandler(FrameworkElement platformView)
base.ConnectHandler(platformView);

if (mauiNavView is not null)
{
mauiNavView.SelectionChanged += OnNavigationTabChanged;
mauiNavView.OnApplyTemplateFinished += OnNavigationViewApplyTemplateFinished;
TrackOverflowMenuItems(mauiNavView.TopNavMenuItemsOverflowHost);
}

if (VirtualView.Parent is Shell shell)
{
Expand All @@ -93,6 +98,7 @@ protected override void DisconnectHandler(FrameworkElement platformView)
if (platformView is MauiNavigationView mnv)
{
mnv.SelectionChanged -= OnNavigationTabChanged;
mnv.OnApplyTemplateFinished -= OnNavigationViewApplyTemplateFinished;
if (mnv.AutoSuggestBox is { } autoSuggestBox)
{
autoSuggestBox.TextChanged -= OnSearchBoxTextChanged;
Expand All @@ -105,6 +111,7 @@ protected override void DisconnectHandler(FrameworkElement platformView)
}

platformView.Loaded -= OnNavigationViewLoaded;
TrackOverflowMenuItems(null);

if (_currentShellSection != null)
_currentShellSection.PropertyChanged -= OnCurrentShellSectionPropertyChanged;
Expand Down Expand Up @@ -232,6 +239,70 @@ private void OnNavigationTabChanged(NavigationView sender, NavigationViewSelecti
}
}

void OnNavigationViewApplyTemplateFinished(object? sender, EventArgs e)
{
if (sender is MauiNavigationView mauiNavView)
TrackOverflowMenuItems(mauiNavView.TopNavMenuItemsOverflowHost);
}

void TrackOverflowMenuItems(ItemsRepeater? overflowMenuItemsHost)
{
if (_overflowMenuItemsHost == overflowMenuItemsHost)
return;

if (_overflowMenuItemsHost is not null)
{
_overflowMenuItemsHost.ElementPrepared -= OnOverflowMenuItemPrepared;
_overflowMenuItemsHost.ElementClearing -= OnOverflowMenuItemClearing;
}

_overflowMenuItemsHost = overflowMenuItemsHost;

if (_overflowMenuItemsHost is not null)
{
_overflowMenuItemsHost.ElementPrepared += OnOverflowMenuItemPrepared;
_overflowMenuItemsHost.ElementClearing += OnOverflowMenuItemClearing;
}
}

static void OnOverflowMenuItemPrepared(ItemsRepeater sender, ItemsRepeaterElementPreparedEventArgs args)
{
if (args.Element is NavigationViewItem item)
UpdateOverflowMenuItemSelectsOnInvoked(item);
}

static void OnOverflowMenuItemClearing(ItemsRepeater sender, ItemsRepeaterElementClearingEventArgs args)
{
// Containers are reused between the overflow menu and the tab bar
if (args.Element is NavigationViewItem item)
item.ClearValue(NavigationViewItem.SelectsOnInvokedProperty);
}

// MapMenuItems can add or remove the sub tabs of a tab that already sits in the overflow menu
void UpdateOverflowMenuItems()
{
if (_overflowMenuItemsHost?.ItemsSourceView is not { } overflowMenuItems)
return;

for (int i = 0; i < overflowMenuItems.Count; i++)
{
if (_overflowMenuItemsHost.TryGetElement(i) is NavigationViewItem item)
UpdateOverflowMenuItemSelectsOnInvoked(item);
}
}

// WinUI can't select a data bound item that has children while it sits in the overflow menu of the
// top tab bar. It doesn't find the item's container there, and expanding the item right after the
// click fails with E_BOUNDS (https://github.com/dotnet/maui/issues/37985). So in the overflow menu
// a tab with sub tabs only expands, and the navigation happens when one of its sub tabs is picked.
static void UpdateOverflowMenuItemSelectsOnInvoked(NavigationViewItem item)
{
if (item.DataContext is NavigationViewItemViewModel { MenuItemsSource: not null })
item.SelectsOnInvoked = false;
else
item.ClearValue(NavigationViewItem.SelectsOnInvokedProperty);
}

internal void MapMenuItems()
{
// Unsubscribe from previously tracked sections to prevent duplicate PropertyChanged subscriptions
Expand Down Expand Up @@ -323,6 +394,8 @@ void SetValues(BaseShellItem bsi, NavigationViewItemViewModel vm)
}
});

UpdateOverflowMenuItems();

if (PlatformView is NavigationView navView && navView.SelectedItem != selectedItem)
navView.SelectedItem = selectedItem;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
using Microsoft.Maui.Controls.Handlers;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Platform;
using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI.Xaml.Automation.Provider;
using Xunit;
using static Microsoft.Maui.DeviceTests.AssertHelpers;
using NavigationView = Microsoft.UI.Xaml.Controls.NavigationView;
using WButton = Microsoft.UI.Xaml.Controls.Button;
using WFrameworkElement = Microsoft.UI.Xaml.FrameworkElement;
using WNavigationViewItem = Microsoft.UI.Xaml.Controls.NavigationViewItem;
using WVisualTreeHelper = Microsoft.UI.Xaml.Media.VisualTreeHelper;


namespace Microsoft.Maui.DeviceTests
Expand Down Expand Up @@ -61,6 +66,230 @@ await RunShellTabBarTests(shell => { },
});
}

[Fact(DisplayName = "Tab With Several ShellContents Opens From TabBar Overflow Menu")]
public async Task TabWithSeveralShellContentsOpensFromTabBarOverflowMenu()
{
// https://github.com/dotnet/maui/issues/37985
// Clicking such a tab in the overflow menu of the tab bar crashed the app with E_BOUNDS
var subTabB = new ShellContent() { Title = "Sub B", Content = new ContentPage() };
var nestedTab = new Tab()
{
Title = "Nested",
Items =
{
new ShellContent() { Title = "Sub A", Content = new ContentPage() },
subTabB
}
};

await RunTabBarOverflowMenuTest(nestedTab, async (shell, navView, overflowButton) =>
{
// A tab with one ShellContent still gets selected right away
var singleTab = shell.CurrentItem.Items[6];
var singleTabItem = await OpenOverflowMenuAndGetItem(navView, overflowButton, singleTab);
Assert.True(singleTabItem.SelectsOnInvoked);
ClickNavigationViewItem(singleTabItem);
await AssertEventually(() => shell.CurrentItem.CurrentItem == singleTab, message: "Did not navigate to \"Tab 7\"");

var nestedItem = await OpenOverflowMenuAndGetItem(navView, overflowButton, nestedTab);

// When the click selects this tab, WinUI fails fast and takes the whole test app down.
// Check it first, so the test just fails instead.
Assert.False(nestedItem.SelectsOnInvoked, "Clicking \"Nested\" in the overflow menu selects it");

ClickNavigationViewItem(nestedItem);

// The tab only expands to show its sub tabs, the current page stays the same
Assert.True(nestedItem.IsExpanded);
Assert.Equal(singleTab, shell.CurrentItem.CurrentItem);

WNavigationViewItem subTabBItem = null;
await AssertEventually(() => (subTabBItem = nestedItem.GetChildren<WNavigationViewItem>().FirstOrDefault(item => IsNavigationViewItemFor(item, subTabB))) is not null, message: "\"Sub B\" is not shown");

ClickNavigationViewItem(subTabBItem);
await AssertEventually(() => shell.CurrentItem.CurrentItem == nestedTab && nestedTab.CurrentItem == subTabB, message: "Did not navigate to \"Sub B\"");

// Opening and closing the overflow menu again keeps working
overflowButton.Flyout.ShowAt(overflowButton);
await AssertEventually(() => overflowButton.Flyout.IsOpen, message: "The overflow menu did not open again");
overflowButton.Flyout.Hide();
await AssertEventually(() => !overflowButton.Flyout.IsOpen, message: "The overflow menu did not close");
Comment thread
Empiree marked this conversation as resolved.
Resolved
Assert.Equal(subTabB, nestedTab.CurrentItem);
});
}

[Fact(DisplayName = "TabBar Overflow Menu Tab Follows Its ShellContent Changes")]
public async Task TabBarOverflowMenuTabFollowsItsShellContentChanges()
{
// https://github.com/dotnet/maui/issues/37985
// A tab can get or lose its sub tabs while it already sits in the overflow menu
var subTabB = new ShellContent() { Title = "Sub B", Content = new ContentPage() };
var changingTab = new Tab()
{
Title = "Changing",
Items = { new ShellContent() { Title = "Sub A", Content = new ContentPage() } }
};

await RunTabBarOverflowMenuTest(changingTab, async (shell, navView, overflowButton) =>
{
var changingItem = await OpenOverflowMenuAndGetItem(navView, overflowButton, changingTab);
Assert.True(changingItem.SelectsOnInvoked);

// The tab bar picks up the sub tabs of other tabs when it refreshes, a title change is enough for that
changingTab.Items.Add(subTabB);
shell.CurrentItem.Title = "Refreshed";
Assert.NotNull(changingItem.MenuItemsSource);
Assert.False(changingItem.SelectsOnInvoked, "Clicking \"Changing\" in the overflow menu selects it");

changingTab.Items.Remove(subTabB);
shell.CurrentItem.Title = "Refreshed again";
Assert.Null(changingItem.MenuItemsSource);
Assert.True(changingItem.SelectsOnInvoked);

ClickNavigationViewItem(changingItem);
await AssertEventually(() => shell.CurrentItem.CurrentItem == changingTab, message: "Did not navigate to \"Changing\"");
});
}

[Fact(DisplayName = "Tab With Several ShellContents Is Selected Again After Leaving TabBar Overflow Menu")]
public async Task TabWithSeveralShellContentsIsSelectedAgainAfterLeavingTabBarOverflowMenu()
{
// https://github.com/dotnet/maui/issues/37985
// Such a tab only expands while it sits in the overflow menu, back in the bar it gets selected like before
var nestedTab = new Tab()
{
Title = "Nested",
Items =
{
new ShellContent() { Title = "Sub A", Content = new ContentPage() },
new ShellContent() { Title = "Sub B", Content = new ContentPage() }
}
};

await RunTabBarOverflowMenuTest(nestedTab, async (shell, navView, overflowButton) =>
{
var nestedItem = await OpenOverflowMenuAndGetItem(navView, overflowButton, nestedTab);
Assert.False(nestedItem.SelectsOnInvoked, "Clicking \"Nested\" in the overflow menu selects it");
overflowButton.Flyout.Hide();

// Wide enough for all three tabs, so "Nested" moves into the bar
navView.Width = 400;
WNavigationViewItem barItem = null;
await AssertEventually(() => (barItem = GetNavigationViewItems(navView).FirstOrDefault(item => IsNavigationViewItemFor(item, nestedTab))) is not null, message: "\"Nested\" did not move into the tab bar");
Assert.True(barItem.SelectsOnInvoked);

ClickNavigationViewItem(barItem);
await AssertEventually(() => shell.CurrentItem.CurrentItem == nestedTab, message: "Did not navigate to \"Nested\"");
}, singleTabCount: 2, tabBarWidth: 150);
}

[Fact(DisplayName = "Tab With Several ShellContents Only Expands In New TabBar Overflow Menu After Template Is Applied Again")]
public async Task TabWithSeveralShellContentsOnlyExpandsInNewTabBarOverflowMenuAfterTemplateIsAppliedAgain()
{
// https://github.com/dotnet/maui/issues/37985
// Applying the template again creates a new overflow menu, the handler has to follow it
var nestedTab = new Tab()
{
Title = "Nested",
Items =
{
new ShellContent() { Title = "Sub A", Content = new ContentPage() },
new ShellContent() { Title = "Sub B", Content = new ContentPage() }
}
};

await RunTabBarOverflowMenuTest(nestedTab, async (shell, navView, overflowButton) =>
{
var nestedItem = await OpenOverflowMenuAndGetItem(navView, overflowButton, nestedTab);
Assert.False(nestedItem.SelectsOnInvoked, "Clicking \"Nested\" in the overflow menu selects it");
overflowButton.Flyout.Hide();
await AssertEventually(() => !overflowButton.Flyout.IsOpen, message: "The overflow menu did not close");

var template = navView.Template;
navView.Template = null;
navView.Template = template;
navView.ApplyTemplate();

WButton newOverflowButton = null;
await AssertEventually(() => (newOverflowButton = navView.GetDescendantByName<WButton>("TopNavOverflowButton")) is not null && newOverflowButton != overflowButton && newOverflowButton.Visibility == UI.Xaml.Visibility.Visible, message: "The tab bar has no new overflow menu");

nestedItem = await OpenOverflowMenuAndGetItem(navView, newOverflowButton, nestedTab);
Assert.False(nestedItem.SelectsOnInvoked, "Clicking \"Nested\" in the new overflow menu selects it");

ClickNavigationViewItem(nestedItem);

// The tab only expands to show its sub tabs, the current page stays the same
Assert.True(nestedItem.IsExpanded);
Assert.Equal(shell.CurrentItem.Items[0], shell.CurrentItem.CurrentItem);
});
}

// Tabs with one ShellContent each and then lastTab, in a tab bar narrow enough
// to push the last tabs into the overflow menu
async Task RunTabBarOverflowMenuTest(Tab lastTab, Func<Shell, MauiNavigationView, WButton, Task> runTest, int singleTabCount = 7, double tabBarWidth = 400)
{
SetupBuilder();

var shell = await CreateShellAsync((shell) =>
{
var tabBar = new TabBar();
for (int i = 1; i <= singleTabCount; i++)
{
tabBar.Items.Add(new Tab()
{
Title = $"Tab {i}",
Items = { new ShellContent() { Content = new ContentPage() } }
});
}

tabBar.Items.Add(lastTab);
shell.Items.Add(tabBar);
});

await CreateHandlerAndAddToWindow<ShellHandler>(shell, async (handler) =>
{
var navView = shell.CurrentItem.Handler.PlatformView as MauiNavigationView;
var overflowButton = navView.GetDescendantByName<WButton>("TopNavOverflowButton");

navView.Width = tabBarWidth;
await AssertEventually(() => overflowButton.Visibility == UI.Xaml.Visibility.Visible, message: "The tab bar has no overflow menu");

try
{
await runTest(shell, navView, overflowButton);
}
finally
{
// The test can apply the template again, so look the button up again
navView.GetDescendantByName<WButton>("TopNavOverflowButton")?.Flyout.Hide();
}
});
}

static async Task<WNavigationViewItem> OpenOverflowMenuAndGetItem(NavigationView navView, WButton overflowButton, BaseShellItem shellItem)
{
// Clicking a tab without sub tabs closes the menu, wait for that before opening it again
await AssertEventually(() => !overflowButton.Flyout.IsOpen, message: "The overflow menu did not close");
overflowButton.Flyout.ShowAt(overflowButton);

WNavigationViewItem item = null;
await AssertEventually(() => (item = GetOverflowMenuItem(navView, shellItem)) is not null, message: $"\"{shellItem.Title}\" is not in the overflow menu");
return item;
}

static WNavigationViewItem GetOverflowMenuItem(NavigationView navView, BaseShellItem shellItem) =>
WVisualTreeHelper.GetOpenPopupsForXamlRoot(navView.XamlRoot)
.Where(popup => popup.Child is not null)
.SelectMany(popup => popup.Child.GetChildren<WNavigationViewItem>())
.FirstOrDefault(item => IsNavigationViewItemFor(item, shellItem));

static bool IsNavigationViewItemFor(WNavigationViewItem item, BaseShellItem shellItem) =>
(item?.DataContext as NavigationViewItemViewModel)?.Data == shellItem;

// Same path as a mouse click. The automation peer doesn't report the Invoke pattern, but it implements it.
static void ClickNavigationViewItem(WNavigationViewItem item) =>
((IInvokeProvider)FrameworkElementAutomationPeer.CreatePeerForElement(item)).Invoke();

[Fact(DisplayName = "Disabled tab added dynamically after appearance inherits TabBarDisabledColor (Windows)")]
public async Task DynamicallyAddedDisabledTabInheritsTabBarDisabledColor()
{
Expand Down
2 changes: 2 additions & 0 deletions src/Core/src/Platform/Windows/MauiNavigationView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public partial class MauiNavigationView : NavigationView

internal StackPanel? TopNavArea { get; private set; }
internal ItemsRepeater? TopNavMenuItemsHost { get; private set; }
internal ItemsRepeater? TopNavMenuItemsOverflowHost { get; private set; }
internal Grid? PaneContentGrid { get; private set; }
internal event EventHandler? OnApplyTemplateFinished;
internal SplitView? RootSplitView { get; private set; }
Expand Down Expand Up @@ -83,6 +84,7 @@ protected override void OnApplyTemplate()
RootSplitView = (SplitView)GetTemplateChild("RootSplitView");
TopNavArea = (StackPanel)GetTemplateChild("TopNavArea");
TopNavMenuItemsHost = (ItemsRepeater)GetTemplateChild("TopNavMenuItemsHost");
TopNavMenuItemsOverflowHost = (ItemsRepeater)GetTemplateChild("TopNavMenuItemsOverflowHost");
ContentPaneTopPadding = (Grid)GetTemplateChild("ContentPaneTopPadding");
PaneToggleButtonGrid = (Grid)GetTemplateChild("PaneToggleButtonGrid");
ButtonHolderGrid = (Grid)GetTemplateChild("ButtonHolderGrid");
Expand Down
Loading