This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ShellNavigationManager.cs
520 lines (430 loc) · 16.2 KB
/
ShellNavigationManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Forms
{
internal class ShellNavigationManager
{
readonly Shell _shell;
ShellNavigatedEventArgs _accumulatedEvent;
bool _accumulateNavigatedEvents;
public event EventHandler<ShellNavigatedEventArgs> Navigated;
public event EventHandler<ShellNavigatingEventArgs> Navigating;
public ShellNavigationManager(Shell shell)
{
_shell = shell;
}
public Task GoToAsync(ShellNavigationState state, bool? animate, bool enableRelativeShellRoutes, ShellNavigatingEventArgs deferredArgs = null)
{
return GoToAsync(new ShellNavigationParameters
{
TargetState = state,
Animated = animate,
EnableRelativeShellRoutes = enableRelativeShellRoutes,
DeferredArgs = deferredArgs
});
}
public async Task GoToAsync(ShellNavigationParameters shellNavigationParameters)
{
if (shellNavigationParameters.PagePushing != null)
Routing.RegisterImplicitPageRoute(shellNavigationParameters.PagePushing);
var state = shellNavigationParameters.TargetState ?? new ShellNavigationState(Routing.GetRoute(shellNavigationParameters.PagePushing), false);
bool? animate = shellNavigationParameters.Animated;
bool enableRelativeShellRoutes = shellNavigationParameters.EnableRelativeShellRoutes;
ShellNavigatingEventArgs deferredArgs = shellNavigationParameters.DeferredArgs;
var navigationRequest = ShellUriHandler.GetNavigationRequest(_shell, state.FullLocation, enableRelativeShellRoutes, shellNavigationParameters: shellNavigationParameters);
bool isRelativePopping = ShellUriHandler.IsTargetRelativePop(shellNavigationParameters);
ShellNavigationSource source = CalculateNavigationSource(_shell, _shell.CurrentState, navigationRequest);
// If the deferredArgs are non null that means we are processing a delayed navigation
// so the user has indicated they want to go forward with navigation
// This scenario only comes up from UI iniated navigation (i.e. switching tabs)
if (deferredArgs == null)
{
var navigatingArgs = ProposeNavigation(source, state, _shell.CurrentState != null, animate ?? true);
if (navigatingArgs != null)
{
bool accept = !navigatingArgs.NavigationDelayedOrCancelled;
if (navigatingArgs.DeferredTask != null)
accept = await navigatingArgs.DeferredTask;
if (!accept)
return;
}
}
Routing.RegisterImplicitPageRoutes(_shell);
_accumulateNavigatedEvents = true;
var uri = navigationRequest.Request.FullUri;
var queryString = navigationRequest.Query;
var queryData = ParseQueryString(queryString);
ApplyQueryAttributes(_shell, queryData, false, false);
var shellItem = navigationRequest.Request.Item;
var shellSection = navigationRequest.Request.Section;
var currentShellSection = _shell.CurrentItem?.CurrentItem;
var nextActiveSection = shellSection ?? shellItem?.CurrentItem;
ShellContent shellContent = navigationRequest.Request.Content;
bool modalStackPreBuilt = false;
// If we're replacing the whole stack and there are global routes then build the navigation stack before setting the shell section visible
if (navigationRequest.Request.GlobalRoutes.Count > 0 &&
nextActiveSection != null &&
navigationRequest.StackRequest == NavigationRequest.WhatToDoWithTheStack.ReplaceIt)
{
modalStackPreBuilt = true;
bool? isAnimated = (nextActiveSection != currentShellSection) ? false : animate;
await nextActiveSection.GoToAsync(navigationRequest, queryData, isAnimated, isRelativePopping);
}
if (shellItem != null)
{
ApplyQueryAttributes(shellItem, queryData, navigationRequest.Request.Section == null, false);
bool navigatedToNewShellElement = false;
if (shellSection != null && shellContent != null)
{
ApplyQueryAttributes(shellContent, queryData, navigationRequest.Request.GlobalRoutes.Count == 0, isRelativePopping);
if (shellSection.CurrentItem != shellContent)
{
shellSection.SetValueFromRenderer(ShellSection.CurrentItemProperty, shellContent);
navigatedToNewShellElement = true;
}
}
if (shellSection != null)
{
ApplyQueryAttributes(shellSection, queryData, navigationRequest.Request.Content == null, false);
if (shellItem.CurrentItem != shellSection)
{
shellItem.SetValueFromRenderer(ShellItem.CurrentItemProperty, shellSection);
navigatedToNewShellElement = true;
}
}
if (_shell.CurrentItem != shellItem)
{
_shell.SetValueFromRenderer(Shell.CurrentItemProperty, shellItem);
navigatedToNewShellElement = true;
}
if (!modalStackPreBuilt && currentShellSection?.Navigation.ModalStack.Count > 0)
{
// - navigating to new shell element so just pop everything
// - or route contains no global route requests
if (navigatedToNewShellElement || navigationRequest.Request.GlobalRoutes.Count == 0)
{
// remove all non visible pages first so the transition just smoothly goes from
// currently visible modal to base page
if (navigationRequest.Request.GlobalRoutes.Count == 0)
{
for (int i = currentShellSection.Stack.Count - 1; i >= 1; i--)
currentShellSection.Navigation.RemovePage(currentShellSection.Stack[i]);
}
await currentShellSection.PopModalStackToPage(null, animate);
}
}
if (navigationRequest.Request.GlobalRoutes.Count > 0 && navigationRequest.StackRequest != NavigationRequest.WhatToDoWithTheStack.ReplaceIt)
{
// 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);
});
}
else if (navigationRequest.Request.GlobalRoutes.Count == 0 &&
navigationRequest.StackRequest == NavigationRequest.WhatToDoWithTheStack.ReplaceIt &&
currentShellSection?.Navigation?.NavigationStack?.Count > 1)
{
// 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);
});
}
}
else
{
await _shell.CurrentItem.CurrentItem.GoToAsync(navigationRequest, queryData, animate, isRelativePopping);
}
_accumulateNavigatedEvents = false;
// this can be null in the event that no navigation actually took place!
if (_accumulatedEvent != null)
HandleNavigated(_accumulatedEvent);
}
public void HandleNavigated(ShellNavigatedEventArgs args)
{
if (_accumulateNavigatedEvents)
{
if (_accumulatedEvent == null)
_accumulatedEvent = args;
}
else
{
_accumulatedEvent = null;
BaseShellItem baseShellItem = _shell.CurrentItem?.CurrentItem?.CurrentItem;
if (baseShellItem != null)
{
baseShellItem.OnAppearing(() =>
{
FireNavigatedEvents(args, _shell);
});
}
else
{
FireNavigatedEvents(args, _shell);
}
void FireNavigatedEvents(ShellNavigatedEventArgs a, Shell shell)
{
Navigated?.Invoke(this, args);
// reset active page route tree
Routing.ClearImplicitPageRoutes();
Routing.RegisterImplicitPageRoutes(_shell);
}
}
}
public static void ApplyQueryAttributes(Element element, IDictionary<string, string> query, bool isLastItem, bool isPopping)
{
string prefix = "";
if (!isLastItem)
{
var route = Routing.GetRoute(element);
if (string.IsNullOrEmpty(route) || Routing.IsImplicit(route))
return;
prefix = route + ".";
}
//if the lastItem is implicitly wrapped, get the actual ShellContent
if (isLastItem)
{
if (element is IShellItemController shellitem && shellitem.GetItems().FirstOrDefault() is ShellSection section)
element = section;
if (element is IShellSectionController shellsection && shellsection.GetItems().FirstOrDefault() is ShellContent content)
element = content;
if (element is ShellContent shellcontent && shellcontent.Content is Element e)
element = e;
}
if (!(element is BaseShellItem baseShellItem))
baseShellItem = element?.Parent as BaseShellItem;
//filter the query to only apply the keys with matching prefix
var filteredQuery = new Dictionary<string, string>(query.Count);
foreach (var q in query)
{
if (!q.Key.StartsWith(prefix, StringComparison.Ordinal))
continue;
var key = q.Key.Substring(prefix.Length);
if (key.Contains("."))
continue;
filteredQuery.Add(key, q.Value);
}
if (baseShellItem is ShellContent)
baseShellItem.ApplyQueryAttributes(MergeData(element, filteredQuery, isPopping));
else if (isLastItem)
element.SetValue(ShellContent.QueryAttributesProperty, MergeData(element, query, isPopping));
IDictionary<string, string> MergeData(Element shellElement, IDictionary<string, string> data, bool isPopping)
{
if (!isPopping)
return data;
var returnValue = new Dictionary<string, string>(data);
var existing = (IDictionary<string, string>)shellElement.GetValue(ShellContent.QueryAttributesProperty);
if (existing == null)
return data;
foreach (var datum in existing)
{
if (!returnValue.ContainsKey(datum.Key))
returnValue[datum.Key] = datum.Value;
}
return returnValue;
}
}
// This is used for cases where the user is navigating via native UI navigation i.e. clicking on Tabs
// If the user defers this type of navigation we generate the equivalent GotoAsync call
// so when the deferral is completed the same navigation can complete
public bool ProposeNavigationOutsideGotoAsync(
ShellNavigationSource source,
ShellItem shellItem,
ShellSection shellSection,
ShellContent shellContent,
IReadOnlyList<Page> stack,
bool canCancel,
bool isAnimated)
{
if (_accumulateNavigatedEvents)
return true;
var proposedState = GetNavigationState(shellItem, shellSection, shellContent, stack, shellSection.Navigation.ModalStack);
var navArgs = ProposeNavigation(source, proposedState, canCancel, isAnimated);
if (navArgs.DeferralCount > 0)
{
navArgs.RegisterDeferralCompletedCallBack(async () =>
{
if (navArgs.Cancelled)
{
return;
}
Func<Task> navigationTask = () => GoToAsync(navArgs.Target, navArgs.Animate, false, navArgs);
if (Device.IsInvokeRequired)
await Device.InvokeOnMainThreadAsync(navigationTask);
else
await navigationTask();
});
}
return !navArgs.NavigationDelayedOrCancelled;
}
ShellNavigatingEventArgs ProposeNavigation(
ShellNavigationSource source,
ShellNavigationState proposedState,
bool canCancel,
bool isAnimated)
{
if (_accumulateNavigatedEvents)
return null;
var navArgs = new ShellNavigatingEventArgs(_shell.CurrentState, proposedState, source, canCancel)
{
Animate = isAnimated
};
HandleNavigating(navArgs);
return navArgs;
}
public void HandleNavigating(ShellNavigatingEventArgs args)
{
if (!args.DeferredEventArgs)
{
Navigating?.Invoke(this, args);
}
else
{
return;
}
}
public static ShellNavigationSource CalculateNavigationSource(Shell shell, ShellNavigationState current, NavigationRequest request)
{
if (request.StackRequest == NavigationRequest.WhatToDoWithTheStack.PushToIt)
return ShellNavigationSource.Push;
if (current == null)
return ShellNavigationSource.ShellItemChanged;
var targetUri = ShellUriHandler.ConvertToStandardFormat(shell, request.Request.FullUri);
var currentUri = ShellUriHandler.ConvertToStandardFormat(shell, current.FullLocation);
var targetPaths = ShellUriHandler.RetrievePaths(targetUri.PathAndQuery);
var currentPaths = ShellUriHandler.RetrievePaths(currentUri.PathAndQuery);
var targetPathsLength = targetPaths.Length;
var currentPathsLength = currentPaths.Length;
if (targetPathsLength < 4 || currentPathsLength < 4)
return ShellNavigationSource.Unknown;
if (targetPaths[1] != currentPaths[1])
return ShellNavigationSource.ShellItemChanged;
if (targetPaths[2] != currentPaths[2])
return ShellNavigationSource.ShellSectionChanged;
if (targetPaths[3] != currentPaths[3])
return ShellNavigationSource.ShellContentChanged;
if (targetPathsLength == currentPathsLength)
return ShellNavigationSource.Unknown;
if (targetPathsLength < currentPathsLength)
{
for (var i = 0; i < targetPathsLength; i++)
{
var targetPath = targetPaths[i];
if (targetPath != currentPaths[i])
break;
if (i == targetPathsLength - 1)
{
if (targetPathsLength == 4)
return ShellNavigationSource.PopToRoot;
return ShellNavigationSource.Pop;
}
}
if (targetPaths[targetPathsLength - 1] == currentPaths[currentPathsLength - 1])
return ShellNavigationSource.Remove;
if (targetPathsLength == 4)
return ShellNavigationSource.PopToRoot;
return ShellNavigationSource.Pop;
}
else if (targetPathsLength > currentPathsLength)
{
for (var i = 0; i < currentPathsLength; i++)
{
if (targetPaths[i] != currentPaths[i])
break;
if (i == targetPathsLength - 1)
return ShellNavigationSource.Push;
}
}
if (targetPaths[targetPathsLength - 1] == currentPaths[currentPathsLength - 1])
return ShellNavigationSource.Insert;
return ShellNavigationSource.Push;
}
static Dictionary<string, string> ParseQueryString(string query)
{
if (query.StartsWith("?", StringComparison.Ordinal))
query = query.Substring(1);
Dictionary<string, string> lookupDict = new Dictionary<string, string>();
if (query == null)
return lookupDict;
foreach (var part in query.Split('&'))
{
var p = part.Split('=');
if (p.Length != 2)
continue;
lookupDict[p[0]] = p[1];
}
return lookupDict;
}
public static ShellNavigationState GetNavigationState(ShellItem shellItem, ShellSection shellSection, ShellContent shellContent, IReadOnlyList<Page> sectionStack, IReadOnlyList<Page> modalStack)
{
List<string> routeStack = new List<string>();
bool stackAtRoot = sectionStack == null || sectionStack.Count <= 1;
bool hasUserDefinedRoute =
(Routing.IsUserDefined(shellItem)) ||
(Routing.IsUserDefined(shellSection)) ||
(Routing.IsUserDefined(shellContent));
if (shellItem != null)
{
var shellItemRoute = shellItem.Route;
routeStack.Add(shellItemRoute);
if (shellSection != null)
{
var shellSectionRoute = shellSection.Route;
routeStack.Add(shellSectionRoute);
if (shellContent != null)
{
var shellContentRoute = shellContent.Route;
routeStack.Add(shellContentRoute);
}
if (!stackAtRoot)
{
for (int i = 1; i < sectionStack.Count; i++)
{
var page = sectionStack[i];
routeStack.AddRange(ShellUriHandler.CollapsePath(Routing.GetRoute(page), routeStack, hasUserDefinedRoute));
}
}
if (modalStack != null && modalStack.Count > 0)
{
for (int i = 0; i < modalStack.Count; i++)
{
var topPage = modalStack[i];
routeStack.AddRange(ShellUriHandler.CollapsePath(Routing.GetRoute(topPage), routeStack, hasUserDefinedRoute));
for (int j = 1; j < topPage.Navigation.NavigationStack.Count; j++)
{
routeStack.AddRange(ShellUriHandler.CollapsePath(Routing.GetRoute(topPage.Navigation.NavigationStack[j]), routeStack, hasUserDefinedRoute));
}
}
}
}
}
if (routeStack.Count > 0)
routeStack.Insert(0, "/");
return new ShellNavigationState(String.Join("/", routeStack), true);
}
public static List<Page> BuildFlattenedNavigationStack(Shell shell)
{
var section = shell.CurrentItem.CurrentItem;
return BuildFlattenedNavigationStack(section.Stack, section.Navigation.ModalStack);
}
public static List<Page> BuildFlattenedNavigationStack(IReadOnlyList<Page> startingList, IReadOnlyList<Page> modalStack)
{
var returnValue = startingList.ToList();
if (modalStack == null)
return returnValue;
for (int i = 0; i < modalStack.Count; i++)
{
returnValue.Add(modalStack[i]);
for (int j = 1; j < modalStack[i].Navigation.NavigationStack.Count; j++)
{
returnValue.Add(modalStack[i].Navigation.NavigationStack[j]);
}
}
return returnValue;
}
}
}