-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCustomRouter.cs
320 lines (265 loc) · 12.6 KB
/
CustomRouter.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable warnings
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.Extensions.Logging;
using Mirality.Blazor.Routing.Internals;
using NavigationContext = Mirality.Blazor.Routing.Internals.NavigationContext;
namespace Mirality.Blazor.Routing;
/// <summary>
/// A component that supplies route data corresponding to the current navigation state.
/// </summary>
public class CustomRouter : IComponent, IHandleAfterRender, IDisposable
{
static readonly char[] _queryOrHashStartChar = new[] { '?', '#' };
// Dictionary is intentionally used instead of ReadOnlyDictionary to reduce Blazor size
static readonly IReadOnlyDictionary<string, object> _emptyParametersDictionary
= new Dictionary<string, object>();
RenderHandle _renderHandle;
string _baseUri;
string _locationAbsolute;
bool _navigationInterceptionEnabled;
ILogger<CustomRouter> _logger;
private CancellationTokenSource _onNavigateCts;
private Task _previousOnNavigateTask = Task.CompletedTask;
private RouteKey _routeTableLastBuiltForRouteKey;
private bool _onNavigateCalled;
// **** THIS IS THE ONLY CHANGE IN THIS ENTIRE CLASS TREE, TO SWAP THE TYPE... ****
[Inject] private ICustomNavigationManager NavigationManager { get; set; }
[Inject] private INavigationInterception NavigationInterception { get; set; }
[Inject] private ILoggerFactory LoggerFactory { get; set; }
/// <summary>
/// Gets or sets the assembly that should be searched for components matching the URI.
/// </summary>
[Parameter]
[EditorRequired]
public Assembly AppAssembly { get; set; }
/// <summary>
/// Gets or sets a collection of additional assemblies that should be searched for components
/// that can match URIs.
/// </summary>
[Parameter] public IEnumerable<Assembly> AdditionalAssemblies { get; set; }
/// <summary>
/// Gets or sets the content to display when no match is found for the requested route.
/// </summary>
[Parameter]
[EditorRequired]
public RenderFragment NotFound { get; set; }
/// <summary>
/// Gets or sets the content to display when a match is found for the requested route.
/// </summary>
[Parameter]
[EditorRequired]
public RenderFragment<RouteData> Found { get; set; }
/// <summary>
/// Get or sets the content to display when asynchronous navigation is in progress.
/// </summary>
[Parameter] public RenderFragment? Navigating { get; set; }
/// <summary>
/// Gets or sets a handler that should be called before navigating to a new page.
/// </summary>
[Parameter] public EventCallback<NavigationContext> OnNavigateAsync { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether route matching should prefer exact matches
/// over wildcards.
/// <para>This property is obsolete and configuring it does nothing.</para>
/// </summary>
[Parameter] public bool PreferExactMatches { get; set; }
private RouteTable Routes { get; set; }
/// <inheritdoc />
public void Attach(RenderHandle renderHandle)
{
_logger = LoggerFactory.CreateLogger<CustomRouter>();
_renderHandle = renderHandle;
_baseUri = NavigationManager.BaseUri;
_locationAbsolute = NavigationManager.Uri;
NavigationManager.LocationChanged += OnLocationChanged;
HotReloadManager.OnDeltaApplied += ClearRouteCaches;
}
/// <inheritdoc />
public async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (AppAssembly == null)
{
throw new InvalidOperationException($"The {nameof(CustomRouter)} component requires a value for the parameter {nameof(AppAssembly)}.");
}
// Found content is mandatory, because even though we could use something like <RouteView ...> as a
// reasonable default, if it's not declared explicitly in the template then people will have no way
// to discover how to customize this (e.g., to add authorization).
if (Found == null)
{
throw new InvalidOperationException($"The {nameof(CustomRouter)} component requires a value for the parameter {nameof(Found)}.");
}
// NotFound content is mandatory, because even though we could display a default message like "Not found",
// it has to be specified explicitly so that it can also be wrapped in a specific layout
if (NotFound == null)
{
throw new InvalidOperationException($"The {nameof(CustomRouter)} component requires a value for the parameter {nameof(NotFound)}.");
}
if (!_onNavigateCalled)
{
_onNavigateCalled = true;
await RunOnNavigateAsync(NavigationManager.ToBaseRelativePath(_locationAbsolute), isNavigationIntercepted: false);
}
Refresh(isNavigationIntercepted: false);
}
/// <inheritdoc />
public void Dispose()
{
NavigationManager.LocationChanged -= OnLocationChanged;
HotReloadManager.OnDeltaApplied -= ClearRouteCaches;
}
private static string StringUntilAny(string str, char[] chars)
{
var firstIndex = str.IndexOfAny(chars);
return firstIndex < 0
? str
: str.Substring(0, firstIndex);
}
private void RefreshRouteTable()
{
var routeKey = new RouteKey(AppAssembly, AdditionalAssemblies);
if (!routeKey.Equals(_routeTableLastBuiltForRouteKey))
{
_routeTableLastBuiltForRouteKey = routeKey;
Routes = RouteTableFactory.Create(routeKey);
}
}
private void ClearRouteCaches()
{
RouteTableFactory.ClearCaches();
_routeTableLastBuiltForRouteKey = default;
}
internal virtual void Refresh(bool isNavigationIntercepted)
{
// If an `OnNavigateAsync` task is currently in progress, then wait
// for it to complete before rendering. Note: because _previousOnNavigateTask
// is initialized to a CompletedTask on initialization, this will still
// allow first-render to complete successfully.
if (_previousOnNavigateTask.Status != TaskStatus.RanToCompletion)
{
if (Navigating != null)
{
_renderHandle.Render(Navigating);
}
return;
}
RefreshRouteTable();
var locationPath = NavigationManager.ToBaseRelativePath(_locationAbsolute);
locationPath = StringUntilAny(locationPath, _queryOrHashStartChar);
var context = new RouteContext(locationPath);
Routes.Route(context);
if (context.Handler != null)
{
if (!typeof(IComponent).IsAssignableFrom(context.Handler))
{
throw new InvalidOperationException($"The type {context.Handler.FullName} " +
$"does not implement {typeof(IComponent).FullName}.");
}
Log.NavigatingToComponent(_logger, context.Handler, locationPath, _baseUri);
var routeData = new RouteData(
context.Handler,
context.Parameters ?? _emptyParametersDictionary);
_renderHandle.Render(Found(routeData));
}
else
{
if (!isNavigationIntercepted)
{
Log.DisplayingNotFound(_logger, locationPath, _baseUri);
// We did not find a Component that matches the route.
// Only show the NotFound content if the application developer programatically got us here i.e we did not
// intercept the navigation. In all other cases, force a browser navigation since this could be non-Blazor content.
_renderHandle.Render(NotFound);
}
else
{
Log.NavigatingToExternalUri(_logger, _locationAbsolute, locationPath, _baseUri);
NavigationManager.NavigateTo(_locationAbsolute, forceLoad: true);
}
}
}
internal async ValueTask RunOnNavigateAsync(string path, bool isNavigationIntercepted)
{
// Cancel the CTS instead of disposing it, since disposing does not
// actually cancel and can cause unintended Object Disposed Exceptions.
// This effectivelly cancels the previously running task and completes it.
_onNavigateCts?.Cancel();
// Then make sure that the task has been completely cancelled or completed
// before starting the next one. This avoid race conditions where the cancellation
// for the previous task was set but not fully completed by the time we get to this
// invocation.
await _previousOnNavigateTask;
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_previousOnNavigateTask = tcs.Task;
if (!OnNavigateAsync.HasDelegate)
{
Refresh(isNavigationIntercepted);
}
_onNavigateCts = new CancellationTokenSource();
var navigateContext = new NavigationContext(path, _onNavigateCts.Token);
var cancellationTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
navigateContext.CancellationToken.Register(state =>
((TaskCompletionSource)state).SetResult(), cancellationTcs);
try
{
// Task.WhenAny returns a Task<Task> so we need to await twice to unwrap the exception
var task = await Task.WhenAny(OnNavigateAsync.InvokeAsync(navigateContext), cancellationTcs.Task);
await task;
tcs.SetResult();
Refresh(isNavigationIntercepted);
}
catch (Exception e)
{
_renderHandle.Render(builder => ExceptionDispatchInfo.Throw(e));
}
}
private void OnLocationChanged(object sender, LocationChangedEventArgs args)
{
_locationAbsolute = args.Location;
if (_renderHandle.IsInitialized && Routes != null)
{
_ = RunOnNavigateAsync(NavigationManager.ToBaseRelativePath(_locationAbsolute), args.IsNavigationIntercepted).Preserve();
}
}
Task IHandleAfterRender.OnAfterRenderAsync()
{
if (!_navigationInterceptionEnabled)
{
_navigationInterceptionEnabled = true;
return NavigationInterception.EnableNavigationInterceptionAsync();
}
return Task.CompletedTask;
}
private static class Log
{
private static readonly Action<ILogger, string, string, Exception> _displayingNotFound =
LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(1, "DisplayingNotFound"), $"Displaying {nameof(NotFound)} because path '{{Path}}' with base URI '{{BaseUri}}' does not match any component route");
private static readonly Action<ILogger, Type, string, string, Exception> _navigatingToComponent =
LoggerMessage.Define<Type, string, string>(LogLevel.Debug, new EventId(2, "NavigatingToComponent"), "Navigating to component {ComponentType} in response to path '{Path}' with base URI '{BaseUri}'");
private static readonly Action<ILogger, string, string, string, Exception> _navigatingToExternalUri =
LoggerMessage.Define<string, string, string>(LogLevel.Debug, new EventId(3, "NavigatingToExternalUri"), "Navigating to non-component URI '{ExternalUri}' in response to path '{Path}' with base URI '{BaseUri}'");
internal static void DisplayingNotFound(ILogger logger, string path, string baseUri)
{
_displayingNotFound(logger, path, baseUri, null);
}
internal static void NavigatingToComponent(ILogger logger, Type componentType, string path, string baseUri)
{
_navigatingToComponent(logger, componentType, path, baseUri, null);
}
internal static void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri)
{
_navigatingToExternalUri(logger, externalUri, path, baseUri, null);
}
}
}