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

Add shell parameters for passing complex objects #2004

Merged
merged 2 commits into from
Aug 9, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Controls/src/Core/Shell/BaseShellItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ EffectiveFlowDirection IFlowDirectionController.EffectiveFlowDirection
bool IFlowDirectionController.ApplyEffectiveFlowDirectionToChildContainer => true;
double IFlowDirectionController.Width => (Parent as VisualElement)?.Width ?? 0;

internal virtual void ApplyQueryAttributes(IDictionary<string, string> query)
internal virtual void ApplyQueryAttributes(ShellRouteParameters query)
{
}

Expand Down Expand Up @@ -444,6 +444,6 @@ internal static DataTemplate CreateDefaultFlyoutItemCell(string textBinding, str

public interface IQueryAttributable
{
void ApplyQueryAttributes(IDictionary<string, string> query);
void ApplyQueryAttributes(IDictionary<string, object> query);
}
}
10 changes: 10 additions & 0 deletions src/Controls/src/Core/Shell/Shell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,16 @@ public Task GoToAsync(ShellNavigationState state, bool animate)
return _navigationManager.GoToAsync(state, animate, false);
}

public Task GoToAsync(ShellNavigationState state, IDictionary<string, object> parameters)
{
return _navigationManager.GoToAsync(state, null, false, parameters: new ShellRouteParameters(parameters));
}

public Task GoToAsync(ShellNavigationState state, bool animate, IDictionary<string, object> parameters)
{
return _navigationManager.GoToAsync(state, animate, false, parameters: new ShellRouteParameters(parameters));
}

public void AddLogicalChild(Element element)
{
if (element == null)
Expand Down
18 changes: 9 additions & 9 deletions src/Controls/src/Core/Shell/ShellContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class ShellContent : BaseShellItem, IShellContentController, IVisualTreeE
BindableProperty.Create(nameof(ContentTemplate), typeof(DataTemplate), typeof(ShellContent), null, BindingMode.OneTime);

internal static readonly BindableProperty QueryAttributesProperty =
BindableProperty.CreateAttached("QueryAttributes", typeof(IDictionary<string, string>), typeof(ShellContent), defaultValue: null, propertyChanged: OnQueryAttributesPropertyChanged);
BindableProperty.CreateAttached("QueryAttributes", typeof(ShellRouteParameters), typeof(ShellContent), defaultValue: null, propertyChanged: OnQueryAttributesPropertyChanged);

public MenuItemCollection MenuItems => (MenuItemCollection)GetValue(MenuItemsProperty);

Expand Down Expand Up @@ -70,7 +70,7 @@ Page IShellContentController.GetOrCreateContent()
if (result == null)
throw new InvalidOperationException($"No Content found for {nameof(ShellContent)}, Title:{Title}, Route {Route}");

if (GetValue(QueryAttributesProperty) is IDictionary<string, string> delayedQueryParams)
if (GetValue(QueryAttributesProperty) is ShellRouteParameters delayedQueryParams)
result.SetValue(QueryAttributesProperty, delayedQueryParams);

return result;
Expand Down Expand Up @@ -241,7 +241,7 @@ void MenuItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs
}
}

internal override void ApplyQueryAttributes(IDictionary<string, string> query)
internal override void ApplyQueryAttributes(ShellRouteParameters query)
{
base.ApplyQueryAttributes(query);
SetValue(QueryAttributesProperty, query);
Expand All @@ -252,13 +252,13 @@ internal override void ApplyQueryAttributes(IDictionary<string, string> query)

static void OnQueryAttributesPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
ApplyQueryAttributes(bindable, newValue as IDictionary<string, string>, oldValue as IDictionary<string, string>);
ApplyQueryAttributes(bindable, newValue as ShellRouteParameters, oldValue as ShellRouteParameters);
}

static void ApplyQueryAttributes(object content, IDictionary<string, string> query, IDictionary<string, string> oldQuery)
static void ApplyQueryAttributes(object content, ShellRouteParameters query, ShellRouteParameters oldQuery)
{
query = query ?? new Dictionary<string, string>();
oldQuery = oldQuery ?? new Dictionary<string, string>();
query = query ?? new ShellRouteParameters();
oldQuery = oldQuery ?? new ShellRouteParameters();

if (content is IQueryAttributable attributable)
attributable.ApplyQueryAttributes(query);
Expand Down Expand Up @@ -286,10 +286,10 @@ static void ApplyQueryAttributes(object content, IDictionary<string, string> que

if (prop != null && prop.CanWrite && prop.SetMethod.IsPublic)
{
if (prop.PropertyType == typeof(String))
if (prop.PropertyType == typeof(string))
{
if (value != null)
value = global::System.Net.WebUtility.UrlDecode(value);
value = global::System.Net.WebUtility.UrlDecode((string)value);

prop.SetValue(content, value);
}
Expand Down
34 changes: 18 additions & 16 deletions src/Controls/src/Core/Shell/ShellNavigationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ public ShellNavigationManager(Shell shell)
_shell = shell;
}

public Task GoToAsync(ShellNavigationState state, bool? animate, bool enableRelativeShellRoutes, ShellNavigatingEventArgs deferredArgs = null)
public Task GoToAsync(ShellNavigationState state, bool? animate, bool enableRelativeShellRoutes, ShellNavigatingEventArgs deferredArgs = null, ShellRouteParameters parameters = null)
{
return GoToAsync(new ShellNavigationParameters
{
TargetState = state,
Animated = animate,
EnableRelativeShellRoutes = enableRelativeShellRoutes,
DeferredArgs = deferredArgs
DeferredArgs = deferredArgs,
Parameters = parameters
});
}

Expand All @@ -43,6 +44,7 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)

var navigationRequest = ShellUriHandler.GetNavigationRequest(_shell, state.FullLocation, enableRelativeShellRoutes, shellNavigationParameters: shellNavigationParameters);
bool isRelativePopping = ShellUriHandler.IsTargetRelativePop(shellNavigationParameters);
var parameters = shellNavigationParameters.Parameters ?? new ShellRouteParameters();

ShellNavigationSource source = CalculateNavigationSource(_shell, _shell.CurrentState, navigationRequest);

Expand Down Expand Up @@ -71,8 +73,8 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)
var uri = navigationRequest.Request.FullUri;
var queryString = navigationRequest.Query;
var queryData = ParseQueryString(queryString);

ApplyQueryAttributes(_shell, queryData, false, false);
parameters.Merge(queryData);
ApplyQueryAttributes(_shell, parameters, false, false);

var shellItem = navigationRequest.Request.Item;
var shellSection = navigationRequest.Request.Section;
Expand All @@ -90,17 +92,17 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)
modalStackPreBuilt = true;

bool? isAnimated = (nextActiveSection != currentShellSection) ? false : animate;
await nextActiveSection.GoToAsync(navigationRequest, queryData, isAnimated, isRelativePopping);
await nextActiveSection.GoToAsync(navigationRequest, parameters, isAnimated, isRelativePopping);
}

if (shellItem != null)
{
ApplyQueryAttributes(shellItem, queryData, navigationRequest.Request.Section == null, false);
ApplyQueryAttributes(shellItem, parameters, navigationRequest.Request.Section == null, false);
bool navigatedToNewShellElement = false;

if (shellSection != null && shellContent != null)
{
ApplyQueryAttributes(shellContent, queryData, navigationRequest.Request.GlobalRoutes.Count == 0, isRelativePopping);
ApplyQueryAttributes(shellContent, parameters, navigationRequest.Request.GlobalRoutes.Count == 0, isRelativePopping);
if (shellSection.CurrentItem != shellContent)
{
shellSection.SetValueFromRenderer(ShellSection.CurrentItemProperty, shellContent);
Expand All @@ -110,7 +112,7 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)

if (shellSection != null)
{
ApplyQueryAttributes(shellSection, queryData, navigationRequest.Request.Content == null, false);
ApplyQueryAttributes(shellSection, parameters, navigationRequest.Request.Content == null, false);
if (shellItem.CurrentItem != shellSection)
{
shellItem.SetValueFromRenderer(ShellItem.CurrentItemProperty, shellSection);
Expand Down Expand Up @@ -147,7 +149,7 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)
// TODO get rid of this hack and fix so if there's a stack the current page doesn't display
await Device.InvokeOnMainThreadAsync(() =>
{
return _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, queryData, animate, isRelativePopping);
return _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, parameters, animate, isRelativePopping);
});
}
else if (navigationRequest.Request.GlobalRoutes.Count == 0 &&
Expand All @@ -157,13 +159,13 @@ public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)
// TODO get rid of this hack and fix so if there's a stack the current page doesn't display
await Device.InvokeOnMainThreadAsync(() =>
{
return _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, queryData, animate, isRelativePopping);
return _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, parameters, animate, isRelativePopping);
});
}
}
else
{
await _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, queryData, animate, isRelativePopping);
await _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, parameters, animate, isRelativePopping);
}

(_shell as IShellController).UpdateCurrentState(source);
Expand Down Expand Up @@ -208,7 +210,7 @@ void FireNavigatedEvents(ShellNavigatedEventArgs a, Shell shell)
}
}

public static void ApplyQueryAttributes(Element element, IDictionary<string, string> query, bool isLastItem, bool isPopping)
public static void ApplyQueryAttributes(Element element, ShellRouteParameters query, bool isLastItem, bool isPopping)
{
string prefix = "";
if (!isLastItem)
Expand All @@ -234,7 +236,7 @@ public static void ApplyQueryAttributes(Element element, IDictionary<string, str
baseShellItem = element?.Parent as BaseShellItem;

//filter the query to only apply the keys with matching prefix
var filteredQuery = new Dictionary<string, string>(query.Count);
var filteredQuery = new ShellRouteParameters(query.Count);

foreach (var q in query)
{
Expand All @@ -252,14 +254,14 @@ public static void ApplyQueryAttributes(Element element, IDictionary<string, str
else if (isLastItem)
element.SetValue(ShellContent.QueryAttributesProperty, MergeData(element, query, isPopping));

IDictionary<string, string> MergeData(Element shellElement, IDictionary<string, string> data, bool isPopping)
ShellRouteParameters MergeData(Element shellElement, ShellRouteParameters data, bool isPopping)
{
if (!isPopping)
return data;

var returnValue = new Dictionary<string, string>(data);
var returnValue = new ShellRouteParameters(data);

var existing = (IDictionary<string, string>)shellElement.GetValue(ShellContent.QueryAttributesProperty);
var existing = (ShellRouteParameters)shellElement.GetValue(ShellContent.QueryAttributesProperty);

if (existing == null)
return data;
Expand Down
1 change: 1 addition & 0 deletions src/Controls/src/Core/Shell/ShellNavigationParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ internal class ShellNavigationParameters
public bool PopAllPagesNotSpecifiedOnTargetState { get; set; }
// This is used to service Navigation.PushAsync style APIs where the user doesn't use routes at all
public Page PagePushing { get; set; }
public ShellRouteParameters Parameters { get; set; }
}
}
45 changes: 45 additions & 0 deletions src/Controls/src/Core/Shell/ShellRouteParameters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.Maui.Controls
{
internal class ShellRouteParameters : Dictionary<string, object>
{
public ShellRouteParameters()
{
}

public ShellRouteParameters(ShellRouteParameters shellRouteParams) : base(shellRouteParams)
{
}

public ShellRouteParameters(IDictionary<string, object> shellRouteParams) : base(shellRouteParams)
{
}

public ShellRouteParameters(int count)
: base(count)
{
}

internal void Merge(IDictionary<string, string> input)
{
if (input == null || input.Count == 0)
return;

foreach (var item in input)
Add(item.Key, item.Value);
}
}


internal static class ShellParameterExtensions
{
public static void Deconstruct(this KeyValuePair<string, object> tuple, out string key, out object value)
{
key = tuple.Key;
value = tuple.Value;
}
}
}
6 changes: 3 additions & 3 deletions src/Controls/src/Core/Shell/ShellSection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ internal static ShellSection CreateFromTemplatedPage(TemplatedPage page)
return (ShellSection)(ShellContent)page;
}

async Task PrepareCurrentStackForBeingReplaced(NavigationRequest request, IDictionary<string, string> queryData, bool? animate, List<string> globalRoutes, bool isRelativePopping)
async Task PrepareCurrentStackForBeingReplaced(NavigationRequest request, ShellRouteParameters queryData, bool? animate, List<string> globalRoutes, bool isRelativePopping)
{
string route = "";
List<Page> navStack = null;
Expand Down Expand Up @@ -468,7 +468,7 @@ void RemoveExcessPathsWithinTheRoute()
}
}

Page GetOrCreateFromRoute(string route, IDictionary<string, string> queryData, bool isLast, bool isPopping)
Page GetOrCreateFromRoute(string route, ShellRouteParameters queryData, bool isLast, bool isPopping)
{
var content = Routing.GetOrCreateContent(route) as Page;
if (content == null)
Expand All @@ -480,7 +480,7 @@ Page GetOrCreateFromRoute(string route, IDictionary<string, string> queryData, b
return content;
}

internal async Task GoToAsync(NavigationRequest request, IDictionary<string, string> queryData, bool? animate, bool isRelativePopping)
internal async Task GoToAsync(NavigationRequest request, ShellRouteParameters queryData, bool? animate, bool isRelativePopping)
{
List<string> globalRoutes = request.Request.GlobalRoutes;
if (globalRoutes == null || globalRoutes.Count == 0)
Expand Down
77 changes: 77 additions & 0 deletions src/Controls/tests/Core.UnitTests/ShellParameterPassingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -301,5 +301,82 @@ public async Task NavigatingBackToShellContentAbsolutelyClearsQueryParameter()
await shell.GoToAsync($"//content");
Assert.AreEqual(null, page.SomeQueryParameter);
}

[Test]
public async Task BasicShellParameterTest()
{
var shell = new Shell();

var item = CreateShellItem(shellSectionRoute: "section2");
Routing.RegisterRoute("details", typeof(ShellTestPage));
shell.Items.Add(item);
var obj = new object();
var parameter = new ShellRouteParameters
{
{"DoubleQueryParameter", 2d },
{ "ComplexObject", obj}
};

await shell.GoToAsync(new ShellNavigationState($"details?{nameof(ShellTestPage.SomeQueryParameter)}=1234"), parameter);
var testPage = (shell.CurrentItem.CurrentItem as IShellSectionController).PresentedPage as ShellTestPage;
Assert.AreEqual("1234", testPage.SomeQueryParameter);
Assert.AreEqual(2d, testPage.DoubleQueryParameter);
Assert.AreEqual(obj, testPage.ComplexObject);
}

[Test]
public async Task DotDotNavigationPassesShellParameters()
{
Routing.RegisterRoute(nameof(DotDotNavigationPassesParameters), typeof(ContentPage));
var shell = new Shell();
var one = new ShellItem { Route = "one" };

var tabone = MakeSimpleShellSection("tabone", "content");

one.Items.Add(tabone);

shell.Items.Add(one);

one.CurrentItem.CurrentItem.ContentTemplate = new DataTemplate(() =>
{
ShellTestPage pagetoTest = new ShellTestPage();
pagetoTest.BindingContext = pagetoTest;
return pagetoTest;
});

var obj = new object();
var parameter = new ShellRouteParameters
{
{"DoubleQueryParameter", 2d },
{ "ComplexObject", obj}
};

var page = (ShellTestPage)(one.CurrentItem.CurrentItem as IShellContentController).GetOrCreateContent();
Assert.AreEqual(null, page.SomeQueryParameter);
await shell.GoToAsync(nameof(DotDotNavigationPassesParameters));
await shell.GoToAsync($"..?{nameof(ShellTestPage.SomeQueryParameter)}=1234", parameter);
Assert.AreEqual("1234", page.SomeQueryParameter);
Assert.AreEqual(2d, page.DoubleQueryParameter);
Assert.AreEqual(obj, page.ComplexObject);
}

[Test]
public async Task PassesUrlInShellParameter()
{
var shell = new Shell();
var item = CreateShellItem();
Routing.RegisterRoute("details", typeof(ShellTestPage));
shell.Items.Add(item);
string urlTest = @"https://www.somewebsite.com/id/545/800/600.jpg";

var parameter = new ShellRouteParameters
{
{ nameof(ShellTestPage.SomeQueryParameter) ,urlTest }
};

await shell.GoToAsync(new ShellNavigationState($"details"), parameter);
var testPage = shell.CurrentPage as ShellTestPage;
Assert.AreEqual(urlTest, testPage.SomeQueryParameter);
}
}
}