Skip to content
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
69 changes: 69 additions & 0 deletions src/Components/Components/src/NavigationManagerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -762,4 +762,73 @@ private static bool TryRebuildExistingQueryFromUri(

return true;
}

/// <summary>
/// Returns a URI constructed from <see cref="NavigationManager.Uri"/> with a hash
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="hash">The hash string. If empty or null, the hash will be removed from the URI.</param>
/// <returns>The URI with the specified hash.</returns>
/// <remarks>
/// <para>
/// If <paramref name="hash"/> does not start with <c>#</c>, then <c>#</c> will be prepended.
/// </para>
/// <para>
/// This method is useful when the document's <c>baseURI</c> differs from its location,
/// such as when a <c>&lt;base&gt;</c> element is used, since relative hash URLs are resolved
/// relative to the <c>baseURI</c>.
/// </para>
/// <example>
/// <code>
/// @inject NavigationManager Nav
/// &lt;a href="@Nav.GetUriWithHash("section1")"&gt;Go to section 1&lt;/a&gt;
/// </code>
/// </example>
/// </remarks>
public static string GetUriWithHash(this NavigationManager navigationManager, string? hash)
{
ArgumentNullException.ThrowIfNull(navigationManager);

var uri = navigationManager.Uri;
var existingHashIndex = uri.IndexOf('#');

// Determine the length of the URI without the existing hash
var uriWithoutHashLength = existingHashIndex < 0 ? uri.Length : existingHashIndex;

if (string.IsNullOrEmpty(hash))
{
// If removing hash and there wasn't one, return original URI
if (existingHashIndex < 0)
{
return uri;
}

// Return just the URI part without hash
return uri.Substring(0, uriWithoutHashLength);
}

var hashStartsWithSymbol = hash[0] == '#';

// Calculate the total length needed
var totalLength = uriWithoutHashLength + (hashStartsWithSymbol ? hash.Length : hash.Length + 1);

return string.Create(totalLength, (uri, hash, uriWithoutHashLength, hashStartsWithSymbol), static (chars, state) =>
{
var (uriValue, hashValue, uriLength, startsWithSymbol) = state;

// Copy URI without hash
uriValue.AsSpan(0, uriLength).CopyTo(chars);
var position = uriLength;

// Add '#' if hash doesn't start with one
if (!startsWithSymbol)
{
chars[position++] = '#';
}

// Copy hash
hashValue.AsSpan().CopyTo(chars[position..]);
});
}
}
1 change: 1 addition & 0 deletions src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static Microsoft.AspNetCore.Components.NavigationManagerExtensions.GetUriWithHash(this Microsoft.AspNetCore.Components.NavigationManager! navigationManager, string? hash) -> string!
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 see a point of hash being nullable.

  1. name GetUriWithHash does not make sense then, we don't get uri with hash calling this method. You see code navigationManager.GetUriWithHash() and you expect some hash to be retuned by that method.
  2. if we really want to cheat the system and get the uri without hash, we can pass String.Empty to that param

42 changes: 42 additions & 0 deletions src/Components/Components/test/NavigationManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,48 @@ public void GetUriWithQueryParameters_ThrowsWhenAnyParameterNameIsEmpty(string b
Assert.StartsWith("Cannot have empty query parameter names.", exception.Message);
}

[Theory]
[InlineData("scheme://host/", "section1", "scheme://host/#section1")]
[InlineData("scheme://host/", "#section1", "scheme://host/#section1")]
[InlineData("scheme://host/path", "section1", "scheme://host/path#section1")]
[InlineData("scheme://host/path/", "section1", "scheme://host/path/#section1")]
[InlineData("scheme://host/path?query=value", "section1", "scheme://host/path?query=value#section1")]
[InlineData("scheme://host/path?query=value#oldHash", "section1", "scheme://host/path?query=value#section1")]
[InlineData("scheme://host/path#oldHash", "newHash", "scheme://host/path#newHash")]
[InlineData("scheme://host/path#old", "#new", "scheme://host/path#new")]
public void GetUriWithHash_AddsOrReplacesHash(string baseUri, string hash, string expectedUri)
Copy link
Member

Choose a reason for hiding this comment

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

None of these tests really checks base uri different than root. In the issue we had an example of a case with <base href="/subdir/">, we should test it.

{
var navigationManager = new TestNavigationManager(baseUri);
var actualUri = navigationManager.GetUriWithHash(hash);

Assert.Equal(expectedUri, actualUri);
}

[Theory]
[InlineData("scheme://host/", "scheme://host/")]
[InlineData("scheme://host/path", "scheme://host/path")]
[InlineData("scheme://host/path#hash", "scheme://host/path")]
[InlineData("scheme://host/path?query=value#hash", "scheme://host/path?query=value")]
public void GetUriWithHash_RemovesHashWhenHashIsNullOrEmpty(string baseUri, string expectedUri)
{
var navigationManager = new TestNavigationManager(baseUri);

var actualUriWithNull = navigationManager.GetUriWithHash(null);
Assert.Equal(expectedUri, actualUriWithNull);

var actualUriWithEmpty = navigationManager.GetUriWithHash(string.Empty);
Assert.Equal(expectedUri, actualUriWithEmpty);
}

[Fact]
public void GetUriWithHash_ThrowsWhenNavigationManagerIsNull()
{
NavigationManager navigationManager = null;

var exception = Assert.Throws<ArgumentNullException>(() => navigationManager.GetUriWithHash("hash"));
Assert.Equal("navigationManager", exception.ParamName);
}

[Fact]
public void LocationChangingHandlers_CanContinueTheNavigationSynchronously_WhenOneHandlerIsRegistered()
{
Expand Down
Loading