Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement NavigateFromAsync method without recreating a page. #3182

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions e2e/Maui/MauiModule/ViewModels/ViewModelBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ protected ViewModelBase(BaseServices baseServices)
ShowDialog = new DelegateCommand(OnShowDialogCommand, () => !string.IsNullOrEmpty(SelectedDialog))
.ObservesProperty(() => SelectedDialog);
GoBack = new DelegateCommand<string>(OnGoToBack);
NavigateFrom = new DelegateCommand(OnNavigateFrom);
}

public IEnumerable<string> AvailableDialogs { get; }
Expand All @@ -55,6 +56,8 @@ public string SelectedDialog

public DelegateCommand<string> GoBack { get; }

public DelegateCommand NavigateFrom { get; }

private void OnNavigateCommandExecuted(string uri)
{
Messages.Add($"OnNavigateCommandExecuted: {uri}");
Expand Down Expand Up @@ -83,6 +86,12 @@ private void OnGoToBack(string viewName)
_navigationService.GoBackToAsync(viewName);
}

private void OnNavigateFrom()
{
Messages.Add($"On Navigate From B To C");
_navigationService.NavigateFromAsync("ViewB", "ViewC");
}

public void Initialize(INavigationParameters parameters)
{
Messages.Add("ViewModel Initialized");
Expand Down
7 changes: 6 additions & 1 deletion e2e/Maui/MauiModule/Views/ViewD.xaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:loc="clr-namespace:MauiModule.ViewModels"
Expand Down Expand Up @@ -63,5 +63,10 @@
Margin="10"
Grid.Row="4"
Grid.Column="0"/>
<Button Text="Navigate From"
Command="{Binding NavigateFrom}"
Margin="10"
Grid.Row="4"
Grid.Column="1"/>
</Grid>
</ContentPage>
63 changes: 63 additions & 0 deletions src/Maui/Prism.Maui/Common/MvvmHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Prism.Dialogs;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;
using Prism.Navigation.Xaml;
Expand Down Expand Up @@ -404,4 +405,66 @@ internal static bool IsSameOrSubclassOf<T>(Type potentialDescendant)
return potentialDescendant.GetTypeInfo().IsSubclassOf(potentialBase)
|| potentialDescendant == potentialBase;
}

internal static async Task<Page?> FindPageByNameAsync(Page? current, string name)
{
if (current == null) return null;

Page? navPage = current.Navigation.NavigationStack.LastOrDefault();
if(navPage == null)
{
navPage = current.Parent switch
{
Page parentPage => parentPage,
Window window => window.Page,
_ => null,
};
}

var modal = current.Navigation.ModalStack.LastOrDefault();
while (modal != null)
{
var target = await FindPageRecursivelyAsync(modal, name);
if (target != null) return target;

modal = GetPreviousPage(modal, modal.Navigation.ModalStack);
if(modal != null) await modal.Navigation.PopModalAsync();
}

return await FindPageRecursivelyAsync(navPage, name);
}

private static async Task<Page?> FindPageRecursivelyAsync(Page? target, string name)
{
if (target != null && ViewModelLocator.GetNavigationName(target) == name) return target;

switch (target)
{
case NavigationPage navigation:
var page = navigation.Navigation.NavigationStack.LastOrDefault();
while (page != null)
{
if (ViewModelLocator.GetNavigationName(page) == name) return page;
if (navigation.Navigation.NavigationStack.Count == 1) break;

await navigation.Navigation.PopAsync();
page = navigation.Navigation.NavigationStack.LastOrDefault();
}
return navigation.Parent switch
{
Page parentPage => await FindPageRecursivelyAsync(parentPage, name),
_ => null,
};
case TabbedPage:
case FlyoutPage:
case ContentPage:
return target.Parent switch
{
Page parentPage => await FindPageRecursivelyAsync(parentPage, name),
_ => null,
};
}

return null;
}
}
9 changes: 9 additions & 0 deletions src/Maui/Prism.Maui/Navigation/INavigationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ public interface INavigationService
/// </example>
Task<INavigationResult> NavigateAsync(Uri uri, INavigationParameters parameters);

/// <summary>
/// Initiates navigation from the <paramref name="viewName"/> using the specified <paramref name="route"/>.
/// </summary>
/// <param name="viewName">The name of the View to navigate from</param>
/// <param name="route">The route Uri to navigate from that view</param>
/// <param name="parameters">The navigation parameters</param>
/// <returns>If <c>true</c> a navigate from operation was successful. If <c>false</c> the navigate from operation failed.</returns>
Task<INavigationResult> NavigateFromAsync(string viewName, Uri route, INavigationParameters parameters);

/// <summary>
/// Selects a Tab of the TabbedPage parent and Navigates to a specified Uri
/// </summary>
Expand Down
31 changes: 31 additions & 0 deletions src/Maui/Prism.Maui/Navigation/INavigationServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,37 @@ public static Task<INavigationResult> NavigateAsync(this INavigationService navi
return navigationService.NavigateAsync(name, GetNavigationParameters(parameters));
}

/// <summary>
/// Initiates navigation to the target specified by the <paramref name="viewName"/> from the <paramref name="route"/>.
/// </summary>
/// <param name="navigationService">Service for handling navigation between views</param>
/// <param name="viewName">The name of the View to navigate to</param>
/// <param name="route">The route Uri to navigate to</param>
/// <returns>If <c>true</c> a navigate from operation was successful. If <c>false</c> the navigate from operation failed.</returns>
public static Task<INavigationResult> NavigateFromAsync(this INavigationService navigationService, string viewName, Uri route) =>
navigationService.NavigateFromAsync(viewName, route, new NavigationParameters());
Comment on lines +116 to +117
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would need some overloads that take a string for the route as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have addressed this in the following commit: 5ce2b81

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dansiegel 
We have completed the implementation to ensure it works across both Modal and Non-Modal Navigation Stacks. In our unit tests, it is working as expected. Could you please review and confirm? Let us know if there are any issues or further improvements needed.

https://github.com/PrismLibrary/Prism/pull/3182/files#diff-9e3b8256829a294f2c8f84c0d97935ff6f651e725308d7509d6b4d8bfad773b1R613-R659


/// <summary>
/// Initiates navigation to the target specified by the <paramref name="viewName"/> from the <paramref name="route"/>.
/// </summary>
/// <param name="navigationService">Service for handling navigation between views</param>
/// <param name="viewName">The name of the View to navigate to</param>
/// <param name="route">The route as a string to navigate to</param>
/// <returns>If <c>true</c> a navigate from operation was successful. If <c>false</c> the navigate from operation failed.</returns>
public static Task<INavigationResult> NavigateFromAsync(this INavigationService navigationService, string viewName, string route) =>
navigationService.NavigateFromAsync(viewName, new Uri(route, UriKind.RelativeOrAbsolute), new NavigationParameters());

/// <summary>
/// Initiates navigation to the target specified by the <paramref name="viewName"/> from the <paramref name="route"/>.
/// </summary>
/// <param name="navigationService">Service for handling navigation between views</param>
/// <param name="viewName">The name of the View to navigate to</param>
/// <param name="route">The route as a string to navigate to</param>
/// <param name="parameters">Additional parameters for the navigation.</param>
/// <returns>If <c>true</c> a navigate from operation was successful. If <c>false</c> the navigate from operation failed.</returns>
public static Task<INavigationResult> NavigateFromAsync(this INavigationService navigationService, string viewName, string route, INavigationParameters parameters) =>
navigationService.NavigateFromAsync(viewName, new Uri(route, UriKind.RelativeOrAbsolute), parameters);

/// <summary>
/// Provides an easy to use way to provide an Error Callback without using await NavigationService
/// </summary>
Expand Down
34 changes: 34 additions & 0 deletions src/Maui/Prism.Maui/Navigation/PageNavigationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,40 @@ public virtual async Task<INavigationResult> NavigateAsync(Uri uri, INavigationP
}
}

/// <inheritdoc />
public virtual async Task<INavigationResult> NavigateFromAsync(string viewName, Uri route, INavigationParameters parameters)
{
await WaitForPendingNavigationRequests();

try
{
if (route.IsAbsoluteUri)
throw new NavigationException(NavigationException.UnsupportedAbsoluteUri);

parameters ??= new NavigationParameters();

NavigationSource = PageNavigationSource.NavigationService;

var navigationSegments = UriParsingHelper.GetUriSegments(route);

var targetPage = await MvvmHelpers.FindPageByNameAsync(GetCurrentPage(), viewName);

await ProcessNavigation(targetPage, navigationSegments, parameters, null, null);

return Notify(route, parameters);
}
catch (Exception ex)
{
return Notify(route, parameters, ex);
}
finally
{
_lastNavigate = DateTime.Now;
NavigationSource = PageNavigationSource.Device;
_semaphore.Release();
}
}

/// <summary>
/// Selects a Tab of the TabbedPage parent.
/// </summary>
Expand Down
5 changes: 5 additions & 0 deletions src/Prism.Core/Navigation/NavigationException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ public class NavigationException : Exception
/// </summary>
public const string UnknownException = "An unknown error occurred. You may need to specify whether to Use Modal Navigation or not.";

/// <summary>
/// The <see cref="NavigationException"/> Message returned when an absolute path is specified but not supported.
/// </summary>
public const string UnsupportedAbsoluteUri = "Absolute Uri's are not supported when Navigated from a named source View. Please use a relative Uri.";

/// <summary>
/// Initializes a new instance of the <see cref="NavigationException"/>
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,106 @@ public async Task Navigation_Animation_IsFalse()
Assert.False(push.Animated);
}

[Fact]
public async Task Navigation_FromPageUsingRoute()
{
var mauiApp = CreateBuilder(prism => prism.CreateWindow("NavigationPage/MockViewA/MockViewB/MockViewC"))
.Build();
var window = GetWindow(mauiApp);
var navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
var currentNavigationStackUri = string.Join("/", window.CurrentPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA/MockViewB/MockViewC", currentNavigationStackUri);

var result = await navigationService.NavigateFromAsync("MockViewA", UriParsingHelper.Parse("MockViewD/MockViewE"), null);

Assert.True(result.Success);
currentNavigationStackUri = string.Join("/", window.CurrentPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA/MockViewD/MockViewE", currentNavigationStackUri);
}

[Fact]
public async Task Navigation_FromRootNavigationPageUsingRoute()
{
var mauiApp = CreateBuilder(prism => prism.CreateWindow("NavigationPage/MockViewA/MockViewB/MockViewC"))
.Build();
var window = GetWindow(mauiApp);
var navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
var currentNavigationStackUri = string.Join("/", window.CurrentPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA/MockViewB/MockViewC", currentNavigationStackUri);

var result = await navigationService.NavigateFromAsync("NavigationPage", UriParsingHelper.Parse("MockViewD/MockViewE"), null);

Assert.True(result.Success);
currentNavigationStackUri = string.Join("/", window.CurrentPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewD/MockViewE", currentNavigationStackUri);
}

[Fact]
public async Task Navigation_FromFlyoutPageUsingRoute()
{
var mauiApp = CreateBuilder(prism => prism.CreateWindow("MockHome/NavigationPage/MockViewA"))
.Build();
var window = GetWindow(mauiApp);

var mockHome = (FlyoutPage)window.Page;
var navigationPage = (NavigationPage)mockHome.Detail;
Assert.IsType<MockViewA>(navigationPage.CurrentPage);

var navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
var result = await navigationService.NavigateFromAsync("MockHome", UriParsingHelper.Parse("MockViewB"), null);

Assert.True(result.Success);
Assert.IsType<MockViewB>(mockHome.Detail);
}

[Fact]
public async Task Navigation_FromModalPage()
{
var mauiApp = CreateBuilder(prism => prism.CreateWindow("NavigationPage/MockViewA"))
.Build();
var window = GetWindow(mauiApp);
var navigationPage = (NavigationPage)window.Page;
var currentNavigationStackUri = string.Join("/", navigationPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA", currentNavigationStackUri);

var navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
await navigationService.NavigateAsync("MockViewB/MockViewC", new NavigationParameters { { KnownNavigationParameters.UseModalNavigation, true } });
var currentModalStackUri = string.Join("/", window.CurrentPage.Navigation.ModalStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewB/MockViewC", currentModalStackUri);

navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
var result = await navigationService.NavigateFromAsync("MockViewB", UriParsingHelper.Parse("MockViewD"), null);

Assert.True(result.Success);
currentNavigationStackUri = string.Join("/", navigationPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA", currentNavigationStackUri);
currentModalStackUri = string.Join("/", navigationPage.Navigation.ModalStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewB/MockViewD", currentModalStackUri);
}

[Fact]
public async Task Navigation_FromModalPageToNavigationPage()
{
var mauiApp = CreateBuilder(prism => prism.CreateWindow("NavigationPage/MockViewA"))
.Build();
var window = GetWindow(mauiApp);
var navigationPage = (NavigationPage)window.Page;
var currentNavigationStackUri = string.Join("/", navigationPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA", currentNavigationStackUri);

var navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
await navigationService.NavigateAsync("MockViewB/MockViewC", new NavigationParameters { { KnownNavigationParameters.UseModalNavigation, true } });
var currentModalStackUri = string.Join("/", window.CurrentPage.Navigation.ModalStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewB/MockViewC", currentModalStackUri);

navigationService = Prism.Navigation.Xaml.Navigation.GetNavigationService(window.CurrentPage);
var result = await navigationService.NavigateFromAsync("MockViewA", UriParsingHelper.Parse("MockViewB/MockViewD"), null);

Assert.True(result.Success);
currentNavigationStackUri = string.Join("/", navigationPage.Navigation.NavigationStack.Select(v => v.GetType().Name));
Assert.Equal("MockViewA/MockViewB/MockViewD", currentNavigationStackUri);
}

[Theory]
[InlineData("MockViewA", "MockViewB", null)]
[InlineData("NavigationPage/MockViewA", "MockViewB?useModalNavigation=true", true)]
Expand Down
Loading