Skip to content

Navigate with "replace" param #33751

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

Merged
merged 20 commits into from
Jun 30, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 53 additions & 3 deletions src/Components/Components/src/NavigationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,46 @@ protected set
/// <param name="uri">The destination URI. This can be absolute, or relative to the base URI
/// (as returned by <see cref="BaseUri"/>).</param>
/// <param name="forceLoad">If true, bypasses client-side routing and forces the browser to load the new page from the server, whether or not the URI would normally be handled by the client-side router.</param>
public void NavigateTo(string uri, bool forceLoad = false)
public void NavigateTo(string uri, bool forceLoad) // This overload is for binary back-compat with < 6.0
=> NavigateTo(uri, forceLoad, replace: false);

/// <summary>
/// Navigates to the specified URI.
/// </summary>
/// <param name="uri">The destination URI. This can be absolute, or relative to the base URI
/// (as returned by <see cref="BaseUri"/>).</param>
/// <param name="forceLoad">If true, bypasses client-side routing and forces the browser to load the new page from the server, whether or not the URI would normally be handled by the client-side router.</param>
/// <param name="replace">If true, replaces the currently entry in the history stack. If false, appends the new entry to the history stack.</param>
public void NavigateTo(string uri, bool forceLoad = false, bool replace = false)
{
AssertInitialized();

if (replace)
{
NavigateToCore(uri, new NavigationOptions
{
ForceLoad = forceLoad,
ReplaceHistoryEntry = replace,
});
}
else
{
// For back-compatibility, we must call the (string, bool) overload of NavigateToCore from here,
// because that's the only overload guaranteed to be implemented in subclasses.
NavigateToCore(uri, forceLoad);
}
}

/// <summary>
/// Navigates to the specified URI.
/// </summary>
/// <param name="uri">The destination URI. This can be absolute, or relative to the base URI
/// (as returned by <see cref="BaseUri"/>).</param>
/// <param name="options">Provides additional <see cref="NavigationOptions"/>.</param>
public void NavigateTo(string uri, NavigationOptions options)
{
AssertInitialized();
NavigateToCore(uri, forceLoad);
NavigateToCore(uri, options);
}

/// <summary>
Expand All @@ -102,7 +138,21 @@ public void NavigateTo(string uri, bool forceLoad = false)
/// <param name="uri">The destination URI. This can be absolute, or relative to the base URI
/// (as returned by <see cref="BaseUri"/>).</param>
/// <param name="forceLoad">If true, bypasses client-side routing and forces the browser to load the new page from the server, whether or not the URI would normally be handled by the client-side router.</param>
protected abstract void NavigateToCore(string uri, bool forceLoad);
// The reason this overload exists and is virtual is for back-compat with < 6.0. Existing NavigationManager subclasses may
// already override this, so the framework needs to keep using it for the cases when only pre-6.0 options are used.
// However, for anyone implementing a new NavigationManager post-6.0, we don't want them to have to override this
// overload any more, so there's now a default implementation that calls the updated overload.
protected virtual void NavigateToCore(string uri, bool forceLoad)
=> NavigateToCore(uri, new NavigationOptions { ForceLoad = forceLoad });

/// <summary>
/// Navigates to the specified URI.
/// </summary>
/// <param name="uri">The destination URI. This can be absolute, or relative to the base URI
/// (as returned by <see cref="BaseUri"/>).</param>
/// <param name="options">Provides additional <see cref="NavigationOptions"/>.</param>
protected virtual void NavigateToCore(string uri, NavigationOptions options) =>
throw new NotImplementedException($"The type {GetType().FullName} does not support supplying {nameof(NavigationOptions)}. To add support, that type should override {nameof(NavigateToCore)}(string uri, {nameof(NavigationOptions)} options).");

/// <summary>
/// Called to initialize BaseURI and current URI before these values are used for the first time.
Expand Down
22 changes: 22 additions & 0 deletions src/Components/Components/src/NavigationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNetCore.Components
{
/// <summary>
/// Additional options for navigating to another URI.
/// </summary>
public readonly struct NavigationOptions
{
/// <summary>
/// If true, bypasses client-side routing and forces the browser to load the new page from the server, whether or not the URI would normally be handled by the client-side router.
/// </summary>
public bool ForceLoad { get; init; }

/// <summary>
/// If true, replaces the currently entry in the history stack.
/// If false, appends the new entry to the history stack.
/// </summary>
public bool ReplaceHistoryEntry { get; init; }
}
Copy link
Member Author

Choose a reason for hiding this comment

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

In an earlier edition of this PR, NavigationOptions was a flags enum. I've changed it to a full-fledged struct because I don't want to get into this situation again in the future where we need to add some other option and have to multiply out the number of overloads and obscure rules for what methods you have to implement in subclasses.

With a struct, even if we need new options of type string, or rules about which combinations of options are legal to use simultaneously, it should be possible to model that (e.g., as different constructor overloads).

}
13 changes: 13 additions & 0 deletions src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
*REMOVED*static Microsoft.AspNetCore.Components.ParameterView.FromDictionary(System.Collections.Generic.IDictionary<string!, object!>! parameters) -> Microsoft.AspNetCore.Components.ParameterView
*REMOVED*virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.DispatchEventAsync(ulong eventHandlerId, Microsoft.AspNetCore.Components.RenderTree.EventFieldInfo! fieldInfo, System.EventArgs! eventArgs) -> System.Threading.Tasks.Task!
*REMOVED*readonly Microsoft.AspNetCore.Components.RenderTree.RenderTreeEdit.RemovedAttributeName -> string!
*REMOVED*Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(string! uri, bool forceLoad = false) -> void
*REMOVED*abstract Microsoft.AspNetCore.Components.NavigationManager.NavigateToCore(string! uri, bool forceLoad) -> void
Copy link
Member Author

Choose a reason for hiding this comment

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

Although these show as removed, there should be no back-compat loss (source or binary) because of adding new equivalents. I think our PublicAPI tooling doesn't reflect some details about how adding new optional params.

But if you're code-reviewing this, please check you agree with my claim here :)

Microsoft.AspNetCore.Components.ComponentApplicationState
Microsoft.AspNetCore.Components.ComponentApplicationState.OnPersisting -> Microsoft.AspNetCore.Components.ComponentApplicationState.OnPersistingCallback!
Microsoft.AspNetCore.Components.ComponentApplicationState.OnPersistingCallback
Expand Down Expand Up @@ -29,6 +31,15 @@ Microsoft.AspNetCore.Components.Lifetime.ComponentApplicationLifetime.State.get
Microsoft.AspNetCore.Components.Lifetime.IComponentApplicationStateStore
Microsoft.AspNetCore.Components.Lifetime.IComponentApplicationStateStore.GetPersistedStateAsync() -> System.Threading.Tasks.Task<System.Collections.Generic.IDictionary<string!, byte[]!>!>!
Microsoft.AspNetCore.Components.Lifetime.IComponentApplicationStateStore.PersistStateAsync(System.Collections.Generic.IReadOnlyDictionary<string!, byte[]!>! state) -> System.Threading.Tasks.Task!
Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(string! uri, Microsoft.AspNetCore.Components.NavigationOptions options) -> void
Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(string! uri, bool forceLoad = false, bool replace = false) -> void
Copy link
Member

Choose a reason for hiding this comment

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

Do we need this overload?

I think we should force people into using the navigation options directly and set ourselves for success in the future.

Copy link
Member Author

Choose a reason for hiding this comment

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

Personally I find:

navManager.NavigateTo("something", replace: true);

to be a lot more readable than:

navManager.NavigateTo("something", new NavigationOptions { ReplaceHistoryEntry = true });

However I understand it's always a subjective balance when we consider adding overloads just for convenience. It depends on how universal we think the convenience-overload pattern will be, and whether it will stand the test of time as being the only extra convenience we need, vs something that ends up getting multiplied out into many other overload variants. (I know you know this; just giving context for anyone else reading)

We do need at least to keep the NavigateTo(string, bool) overload for back-compat. To me it felt a bit rough if this other equally-often-used flag was not available in a similar shorthand format.

Shall we leave a final call on this until we get to API review, or do you feel strongly now?

Copy link
Member

Choose a reason for hiding this comment

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

I don't feel strongly about it, it was mainly a suggestion.

Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(string! uri, bool forceLoad) -> void
Microsoft.AspNetCore.Components.NavigationOptions
Microsoft.AspNetCore.Components.NavigationOptions.ForceLoad.get -> bool
Microsoft.AspNetCore.Components.NavigationOptions.ForceLoad.init -> void
Microsoft.AspNetCore.Components.NavigationOptions.NavigationOptions() -> void
Microsoft.AspNetCore.Components.NavigationOptions.ReplaceHistoryEntry.get -> bool
Microsoft.AspNetCore.Components.NavigationOptions.ReplaceHistoryEntry.init -> void
Microsoft.AspNetCore.Components.RenderHandle.IsHotReloading.get -> bool
Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.Dispose() -> void
Microsoft.AspNetCore.Components.Routing.Router.PreferExactMatches.get -> bool
Expand All @@ -49,6 +60,8 @@ Microsoft.AspNetCore.Components.RenderTree.Renderer.GetEventArgsType(ulong event
abstract Microsoft.AspNetCore.Components.ErrorBoundaryBase.OnErrorAsync(System.Exception! exception) -> System.Threading.Tasks.Task!
override Microsoft.AspNetCore.Components.LayoutComponentBase.SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) -> System.Threading.Tasks.Task!
static Microsoft.AspNetCore.Components.ParameterView.FromDictionary(System.Collections.Generic.IDictionary<string!, object?>! parameters) -> Microsoft.AspNetCore.Components.ParameterView
virtual Microsoft.AspNetCore.Components.NavigationManager.NavigateToCore(string! uri, Microsoft.AspNetCore.Components.NavigationOptions options) -> void
virtual Microsoft.AspNetCore.Components.NavigationManager.NavigateToCore(string! uri, bool forceLoad) -> void
virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.DispatchEventAsync(ulong eventHandlerId, Microsoft.AspNetCore.Components.RenderTree.EventFieldInfo? fieldInfo, System.EventArgs! eventArgs) -> System.Threading.Tasks.Task!
readonly Microsoft.AspNetCore.Components.RenderTree.RenderTreeEdit.RemovedAttributeName -> string?
*REMOVED*Microsoft.AspNetCore.Components.CascadingValue<TValue>.Value.get -> TValue
Expand Down
2 changes: 0 additions & 2 deletions src/Components/Components/test/Routing/RouterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,6 @@ internal class TestNavigationManager : NavigationManager
public TestNavigationManager() =>
Initialize("https://www.example.com/subdir/", "https://www.example.com/subdir/jan");

protected override void NavigateToCore(string uri, bool forceLoad) => throw new NotImplementedException();

public void NotifyLocationChanged(string uri, bool intercepted)
{
Uri = uri;
Expand Down
16 changes: 9 additions & 7 deletions src/Components/Server/src/Circuits/RemoteNavigationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
Expand Down Expand Up @@ -65,30 +66,31 @@ public void NotifyLocationChanged(string uri, bool intercepted)
}

/// <inheritdoc />
protected override void NavigateToCore(string uri, bool forceLoad)
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(NavigationOptions))]
protected override void NavigateToCore(string uri, NavigationOptions options)
{
Log.RequestingNavigation(_logger, uri, forceLoad);
Log.RequestingNavigation(_logger, uri, options);

if (_jsRuntime == null)
{
var absoluteUriString = ToAbsoluteUri(uri).ToString();
throw new NavigationException(absoluteUriString);
}

_jsRuntime.InvokeAsync<object>(Interop.NavigateTo, uri, forceLoad).Preserve();
_jsRuntime.InvokeVoidAsync(Interop.NavigateTo, uri, options).Preserve();
}

private static class Log
{
private static readonly Action<ILogger, string, bool, Exception> _requestingNavigation =
LoggerMessage.Define<string, bool>(LogLevel.Debug, new EventId(1, "RequestingNavigation"), "Requesting navigation to URI {Uri} with forceLoad={ForceLoad}");
private static readonly Action<ILogger, string, bool, bool, Exception> _requestingNavigation =
LoggerMessage.Define<string, bool, bool>(LogLevel.Debug, new EventId(1, "RequestingNavigation"), "Requesting navigation to URI {Uri} with forceLoad={ForceLoad}, replace={Replace}");

private static readonly Action<ILogger, string, bool, Exception> _receivedLocationChangedNotification =
LoggerMessage.Define<string, bool>(LogLevel.Debug, new EventId(2, "ReceivedLocationChangedNotification"), "Received notification that the URI has changed to {Uri} with isIntercepted={IsIntercepted}");

public static void RequestingNavigation(ILogger logger, string uri, bool forceLoad)
public static void RequestingNavigation(ILogger logger, string uri, NavigationOptions options)
{
_requestingNavigation(logger, uri, forceLoad, null);
_requestingNavigation(logger, uri, options.ForceLoad, options.ReplaceHistoryEntry, null);
}

public static void ReceivedLocationChangedNotification(ILogger logger, string uri, bool isIntercepted)
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.server.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.webview.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/Components/Web.JS/src/GlobalExports.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { navigateTo, internalFunctions as navigationManagerInternalFunctions } from './Services/NavigationManager';
import { navigateTo, internalFunctions as navigationManagerInternalFunctions, NavigationOptions } from './Services/NavigationManager';
import { domFunctions } from './DomWrapper';
import { Virtualize } from './Virtualize';
import { registerCustomEventType, EventTypeOptions } from './Rendering/Events/EventTypes';
Expand All @@ -10,7 +10,7 @@ import { WebAssemblyStartOptions } from './Platform/WebAssemblyStartOptions';
import { Platform, Pointer, System_String, System_Array, System_Object, System_Boolean, System_Byte, System_Int } from './Platform/Platform';

interface IBlazor {
navigateTo: (uri: string, forceLoad: boolean, replace: boolean) => void;
navigateTo: (uri: string, options: NavigationOptions) => void;
registerCustomEventType: (eventName: string, options: EventTypeOptions) => void;

disconnect?: () => void;
Expand Down
54 changes: 39 additions & 15 deletions src/Components/Web.JS/src/Services/NavigationManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,46 +60,64 @@ export function attachToEventDelegator(eventDelegator: EventDelegator) {

if (isWithinBaseUriSpace(absoluteHref)) {
event.preventDefault();
performInternalNavigation(absoluteHref, true);
performInternalNavigation(absoluteHref, /* interceptedLink */ true, /* replace */ false);
}
}
});
}

export function navigateTo(uri: string, forceLoad: boolean, replace: boolean = false) {
// For back-compat, we need to accept multiple overloads
export function navigateTo(uri: string, options: NavigationOptions): void;
export function navigateTo(uri: string, forceLoad: boolean): void;
export function navigateTo(uri: string, forceLoad: boolean, replace: boolean): void;
export function navigateTo(uri: string, forceLoadOrOptions: NavigationOptions | boolean, replaceIfUsingOldOverload: boolean = false) {
Comment on lines +69 to +73
Copy link
Member

Choose a reason for hiding this comment

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

I haven't seen this used in a while in TS 😄.

I believe navigateTo ends up in our internal namespace. The only thing that uses that overload is the auth bits in one place. I'm happy if you update those and avoid having to deal with the special case here, since we can consider this API internal and for our consumption, akin to private reflection.

Copy link
Member

Choose a reason for hiding this comment

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

It's actually not within internal, however it's here

Copy link
Member Author

Choose a reason for hiding this comment

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

Blazor.navigateTo (the JS API) is very much public and supported. It's the only way to trigger a client-side Blazor navigation from JS code, so is certainly needed.

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, I saw that later. If you want to update the auth package as part of this change to rely on that, It would be nice.

const absoluteUri = toAbsoluteUri(uri);

if (!forceLoad && isWithinBaseUriSpace(absoluteUri)) {
// It's an internal URL, so do client-side navigation
performInternalNavigation(absoluteUri, false, replace);
} else if (forceLoad && location.href === uri) {
// Force-loading the same URL you're already on requires special handling to avoid
// triggering browser-specific behavior issues.
// Normalize the parameters to the newer overload (i.e., using NavigationOptions)
const options: NavigationOptions = forceLoadOrOptions instanceof Object
? forceLoadOrOptions
: { forceLoad: forceLoadOrOptions, replaceHistoryEntry: replaceIfUsingOldOverload };

if (!options.forceLoad && isWithinBaseUriSpace(absoluteUri)) {
performInternalNavigation(absoluteUri, false, options.replaceHistoryEntry);
} else {
// For external navigation, we work in terms of the originally-supplied uri string,
// not the computed absoluteUri. This is in case there are some special URI formats
// we're unable to translate into absolute URIs.
performExternalNavigation(uri, options.replaceHistoryEntry);
}
}

function performExternalNavigation(uri: string, replace: boolean) {
if (location.href === uri) {
// If you're already on this URL, you can't append another copy of it to the history stack,
// so we can ignore the 'replace' flag. However, reloading the same URL you're already on
// requires special handling to avoid triggering browser-specific behavior issues.
// For details about what this fixes and why, see https://github.com/dotnet/aspnetcore/pull/10839
const temporaryUri = uri + '?';
history.replaceState(null, '', temporaryUri);
location.replace(uri);
} else if (replace){
history.replaceState(null, '', absoluteUri)
} else if (replace) {
location.replace(uri);
} else {
// It's either an external URL, or forceLoad is requested, so do a full page load
location.href = uri;
}
}

function performInternalNavigation(absoluteInternalHref: string, interceptedLink: boolean, replace: boolean = false) {
function performInternalNavigation(absoluteInternalHref: string, interceptedLink: boolean, replace: boolean) {
// Since this was *not* triggered by a back/forward gesture (that goes through a different
// code path starting with a popstate event), we don't want to preserve the current scroll
// position, so reset it.
// To avoid ugly flickering effects, we don't want to change the scroll position until the
// To avoid ugly flickering effects, we don't want to change the scroll position until
// we render the new page. As a best approximation, wait until the next batch.
resetScrollAfterNextBatch();

if(!replace){
if (!replace) {
history.pushState(null, /* ignored title */ '', absoluteInternalHref);
}else{
} else {
history.replaceState(null, /* ignored title */ '', absoluteInternalHref);
}

notifyLocationChanged(interceptedLink);
}

Expand Down Expand Up @@ -166,3 +184,9 @@ function canProcessAnchor(anchorTarget: HTMLAnchorElement) {
const opensInSameFrame = !targetAttributeValue || targetAttributeValue === '_self';
return opensInSameFrame && anchorTarget.hasAttribute('href') && !anchorTarget.hasAttribute('download');
}

// Keep in sync with Components/src/NavigationOptions.cs
export interface NavigationOptions {
forceLoad: boolean;
replaceHistoryEntry: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.JSInterop;
using Interop = Microsoft.AspNetCore.Components.Web.BrowserNavigationManagerInterop;

Expand Down Expand Up @@ -29,14 +30,15 @@ public void SetLocation(string uri, bool isInterceptedLink)
}

/// <inheritdoc />
protected override void NavigateToCore(string uri, bool forceLoad)
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(NavigationOptions))]
protected override void NavigateToCore(string uri, NavigationOptions options)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}

DefaultWebAssemblyJSRuntime.Instance.InvokeVoid(Interop.NavigateTo, uri, forceLoad);
DefaultWebAssemblyJSRuntime.Instance.InvokeVoid(Interop.NavigateTo, uri, options);
}
}
}
6 changes: 4 additions & 2 deletions src/Components/WebView/WebView/src/IpcSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.JSInterop;
Expand Down Expand Up @@ -33,9 +34,10 @@ public void ApplyRenderBatch(long batchId, RenderBatch renderBatch)
DispatchMessageWithErrorHandling(message);
}

public void Navigate(string uri, bool forceLoad)
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(NavigationOptions))]
public void Navigate(string uri, NavigationOptions options)
{
DispatchMessageWithErrorHandling(IpcCommon.Serialize(IpcCommon.OutgoingMessageType.Navigate, uri, forceLoad));
DispatchMessageWithErrorHandling(IpcCommon.Serialize(IpcCommon.OutgoingMessageType.Navigate, uri, options));
}

public void AttachToDocument(int componentId, string selector)
Expand Down
Loading