Skip to content

Commit

Permalink
refactor: 精简代码
Browse files Browse the repository at this point in the history
  • Loading branch information
ArgoZhang committed Oct 13, 2024
1 parent 190c6cf commit 581de17
Show file tree
Hide file tree
Showing 13 changed files with 5 additions and 684 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
namespace BootstrapBlazor.Components;

/// <summary>
///
/// BootstrapBlazorAuthorizeView 组件
/// </summary>
public class BootstrapBlazorAuthorizeView : ComponentBase
{
Expand Down Expand Up @@ -49,16 +49,14 @@ public class BootstrapBlazorAuthorizeView : ComponentBase
[Inject]
private IAuthorizationService? AuthorizationService { get; set; }

#if NET6_0_OR_GREATER
[Inject]
[NotNull]
private NavigationManager? NavigationManager { get; set; }
#endif

private bool Authorized { get; set; }

/// <summary>
/// OnInitializedAsync 方法
/// <inheritdoc/>
/// </summary>
/// <returns></returns>
protected override async Task OnInitializedAsync()
Expand All @@ -68,7 +66,7 @@ protected override async Task OnInitializedAsync()
}

/// <summary>
/// BuildRenderTree 方法
/// <inheritdoc/>
/// </summary>
/// <param name="builder"></param>
protected override void BuildRenderTree(RenderTreeBuilder builder)
Expand All @@ -82,17 +80,14 @@ protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddAttribute(index++, kv.Key, kv.Value);
}
#if NET6_0_OR_GREATER
BuildQueryParameters();
#endif
builder.CloseComponent();
}
else
{
builder.AddContent(0, NotAuthorized);
}

#if NET6_0_OR_GREATER
void BuildQueryParameters()
{
var queryParameterSupplier = QueryParameterValueSupplier.ForType(Type);
Expand All @@ -106,6 +101,5 @@ void BuildQueryParameters()
queryParameterSupplier.RenderParametersFromQueryString(builder, query);
}
}
#endif
}
}
16 changes: 0 additions & 16 deletions src/BootstrapBlazor/Components/Tab/Route/IRouteTable.cs

This file was deleted.

81 changes: 0 additions & 81 deletions src/BootstrapBlazor/Components/Tab/Route/RouteConstraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,86 +5,6 @@
namespace Microsoft.AspNetCore.Components.Routing;

[ExcludeFromCodeCoverage]
#if NET5_0
internal abstract class RouteConstraint
{
// note: the things that prevent this cache from growing unbounded is that
// we're the only caller to this code path, and the fact that there are only
// 8 possible instances that we create.
//
// The values passed in here for parsing are always static text defined in route attributes.
private static readonly ConcurrentDictionary<string, RouteConstraint> _cachedConstraints
= new ConcurrentDictionary<string, RouteConstraint>();

public abstract bool Match(string pathSegment, out object? convertedValue);

public static RouteConstraint Parse(string template, string segment, string constraint)
{
if (string.IsNullOrEmpty(constraint))
{
throw new ArgumentException($"Malformed segment '{segment}' in route '{template}' contains an empty constraint.");
}

if (_cachedConstraints.TryGetValue(constraint, out var cachedInstance))
{
return cachedInstance;
}
else
{
var newInstance = CreateRouteConstraint(constraint);
if (newInstance != null)
{
// We've done to the work to create the constraint now, but it's possible
// we're competing with another thread. GetOrAdd can ensure only a single
// instance is returned so that any extra ones can be GC'ed.
return _cachedConstraints.GetOrAdd(constraint, newInstance);
}
else
{
throw new ArgumentException($"Unsupported constraint '{constraint}' in route '{template}'.");
}
}
}

/// <summary>
/// Creates a structured RouteConstraint object given a string that contains
/// the route constraint. A constraint is the place after the colon in a
/// parameter definition, for example `{age:int?}`.
/// </summary>
/// <param name="constraint">String representation of the constraint</param>
/// <returns>Type-specific RouteConstraint object</returns>
private static RouteConstraint? CreateRouteConstraint(string constraint)
{
switch (constraint)
{
case "bool":
return new TypeRouteConstraint<bool>(bool.TryParse);
case "datetime":
return new TypeRouteConstraint<DateTime>((string str, out DateTime result)
=> DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, out result));
case "decimal":
return new TypeRouteConstraint<decimal>((string str, out decimal result)
=> decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result));
case "double":
return new TypeRouteConstraint<double>((string str, out double result)
=> double.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result));
case "float":
return new TypeRouteConstraint<float>((string str, out float result)
=> float.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result));
case "guid":
return new TypeRouteConstraint<Guid>(Guid.TryParse);
case "int":
return new TypeRouteConstraint<int>((string str, out int result)
=> int.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result));
case "long":
return new TypeRouteConstraint<long>((string str, out long result)
=> long.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result));
default:
return null;
}
}
}
#else
internal static class RouteConstraint
{
public static UrlValueConstraint Parse(string template, string segment, string constraint)
Expand Down Expand Up @@ -116,4 +36,3 @@ public static UrlValueConstraint Parse(string template, string segment, string c
_ => null,
};
}
#endif
2 changes: 0 additions & 2 deletions src/BootstrapBlazor/Components/Tab/Route/RouteContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ public RouteContext(string path)

public string[] Segments { get; }

#if NET6_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
public Type? Handler { get; set; }

public IReadOnlyDictionary<string, object>? Parameters { get; set; }
Expand Down
141 changes: 2 additions & 139 deletions src/BootstrapBlazor/Components/Tab/Route/RouteEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,144 +9,6 @@
namespace Microsoft.AspNetCore.Components.Routing;

[ExcludeFromCodeCoverage]
#if NET5_0
[DebuggerDisplay("Handler = {Handler}, Template = {Template}")]
internal class RouteEntry
{
public RouteEntry(RouteTemplate template, Type handler, string[] unusedRouteParameterNames)
{
Template = template;
UnusedRouteParameterNames = unusedRouteParameterNames;
Handler = handler;
}

public RouteTemplate Template { get; }

public string[] UnusedRouteParameterNames { get; }

public Type Handler { get; }

internal void Match(RouteContext context)
{
var pathIndex = 0;
var templateIndex = 0;
Dictionary<string, object> parameters = null;
// We will iterate over the path segments and the template segments until we have consumed
// one of them.
// There are three cases we need to account here for:
// * Path is shorter than template ->
// * This can match only if we have t-p optional parameters at the end.
// * Path and template have the same number of segments
// * This can happen when the catch-all segment matches 1 segment
// * This can happen when an optional parameter has been specified.
// * This can happen when the route only contains literals and parameters.
// * Path is longer than template -> This can only match if the parameter has a catch-all at the end.
// * We still need to iterate over all the path segments if the catch-all is constrained.
// * We still need to iterate over all the template/path segments before the catch-all
while (pathIndex < context.Segments.Length && templateIndex < Template.Segments.Length)
{
var pathSegment = context.Segments[pathIndex];
var templateSegment = Template.Segments[templateIndex];

var matches = templateSegment.Match(pathSegment, out var match);
if (!matches)
{
// A constraint or literal didn't match
return;
}

if (!templateSegment.IsCatchAll)
{
// We were dealing with a literal or a parameter, so just advance both cursors.
pathIndex++;
templateIndex++;

if (templateSegment.IsParameter)
{
parameters ??= new(StringComparer.OrdinalIgnoreCase);
parameters[templateSegment.Value] = match;
}
}
else
{
if (templateSegment.Constraints.Length == 0)
{

// Unconstrained catch all, we can stop early
parameters ??= new(StringComparer.OrdinalIgnoreCase);
parameters[templateSegment.Value] = string.Join('/', context.Segments, pathIndex, context.Segments.Length - pathIndex);

// Mark the remaining segments as consumed.
pathIndex = context.Segments.Length;

// Catch-alls are always last.
templateIndex++;

// We are done, so break out of the loop.
break;
}
else
{
// For constrained catch-alls, we advance the path index but keep the template index on the catch-all.
pathIndex++;
if (pathIndex == context.Segments.Length)
{
parameters ??= new(StringComparer.OrdinalIgnoreCase);
parameters[templateSegment.Value] = string.Join('/', context.Segments, templateIndex, context.Segments.Length - templateIndex);

// This is important to signal that we consumed the entire template.
templateIndex++;
}
}
}
}

var hasRemainingOptionalSegments = templateIndex < Template.Segments.Length &&
RemainingSegmentsAreOptional(pathIndex, Template.Segments);

if ((pathIndex == context.Segments.Length && templateIndex == Template.Segments.Length) || hasRemainingOptionalSegments)
{
if (hasRemainingOptionalSegments)
{
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
AddDefaultValues(parameters, templateIndex, Template.Segments);
}
if (UnusedRouteParameterNames?.Length > 0)
{
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
for (var i = 0; i < UnusedRouteParameterNames.Length; i++)
{
parameters[UnusedRouteParameterNames[i]] = null;
}
}
context.Handler = Handler;
context.Parameters = parameters;
}
}

private void AddDefaultValues(Dictionary<string, object> parameters, int templateIndex, TemplateSegment[] segments)
{
for (var i = templateIndex; i < segments.Length; i++)
{
var currentSegment = segments[i];
parameters[currentSegment.Value] = null;
}
}

private bool RemainingSegmentsAreOptional(int index, TemplateSegment[] segments)
{
for (var i = index; index < segments.Length - 1; index++)
{
if (!segments[i].IsOptional)
{
return false;
}
}

return segments[^1].IsOptional || segments[^1].IsCatchAll;
}
}
#else
[DebuggerDisplay("Handler = {Handler}, Template = {Template}")]
internal class RouteEntry
{
Expand Down Expand Up @@ -284,4 +146,5 @@ private bool RemainingSegmentsAreOptional(int index, TemplateSegment[] segments)
return segments[^1].IsOptional || segments[^1].IsCatchAll;
}
}
#endif

#nullable restore warnings
2 changes: 0 additions & 2 deletions src/BootstrapBlazor/Components/Tab/Route/RouteKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

namespace Microsoft.AspNetCore.Components.Routing;

#if NET6_0_OR_GREATER
[ExcludeFromCodeCoverage]
internal readonly struct RouteKey : IEquatable<RouteKey>
{
Expand Down Expand Up @@ -61,4 +60,3 @@ public override int GetHashCode()
return HashCode.Combine(AppAssembly, AdditionalAssemblies.Count);
}
}
#endif
4 changes: 0 additions & 4 deletions src/BootstrapBlazor/Components/Tab/Route/RouteTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
namespace Microsoft.AspNetCore.Components.Routing;

[ExcludeFromCodeCoverage]
#if NET5_0
internal class RouteTable : IRouteTable
#else
internal class RouteTable
#endif
{
public RouteTable(RouteEntry[] routes)
{
Expand Down
Loading

0 comments on commit 581de17

Please sign in to comment.