8000 [Blazor] Add ability to filter persistent component state callbacks based on persistence reason by Copilot · Pull Request #62394 · dotnet/aspnetcore · GitHub
[go: up one dir, main page]

Skip to content

[Blazor] Add ability to filter persistent component state callbacks based on persistence reason #62394

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

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Implement core persistence reason interfaces and filtering logic
Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>
  • Loading branch information
Copilot and javiercn committed Jun 18, 2025
commit 2519ee84df2e78e7441aa8001b3bdef830a0180f
15 changes: 15 additions & 0 deletions src/Components/Components/src/IPersistenceReason.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Represents a reason for persisting component state.
/// </summary>
public interface IPersistenceReason
{
/// <summary>
/// Gets a value indicating whether state should be persisted by default for this reason.
/// </summary>
bool PersistByDefault { get; }
}
17 changes: 17 additions & 0 deletions src/Components/Components/src/IPersistenceReasonFilter.cs
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Filters component state persistence based on the reason for persistence.
/// </summary>
public interface IPersistenceReasonFilter
{
/// <summary>
/// Determines whether state should be persisted for the given reason.
/// </summary>
/// <param name="reason">The reason for persistence.</param>
/// <returns><c>true</c> to persist state, <c>false</c> to skip persistence, or <c>null</c> to defer to other filters or default behavior.</returns>
bool? ShouldPersist(IPersistenceReason reason);
}
Original file line number Diff line number Diff line change
8000 Expand Up @@ -5,9 +5,12 @@ namespace Microsoft.AspNetCore.Components;

internal readonly struct PersistComponentStateRegistration(
Func<Task> callback,
IComponentRenderMode? renderMode)
IComponentRenderMode? renderMode,
IReadOnlyList<IPersistenceReasonFilter>? reasonFilters = null)
{
public Func<Task> Callback { get; } = callback;

public IComponentRenderMode? RenderMode { get; } = renderMode;

public IReadOnlyList<IPersistenceReasonFilter>? ReasonFilters { get; } = reasonFilters;
Copy link
Member

Choose a reason for hiding this comment

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

public IReadOnlyList<IPersistenceReasonFilter> ReasonFilters { get; } = reasonFilters ?? Array.Empty<IPersistenceReasonFilter>();

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated PersistComponentStateRegistration.ReasonFilters property initialization to use the suggested pattern: reasonFilters ?? Array.Empty&lt;IPersistenceReasonFilter&gt;(). The property is now non-nullable and always returns a valid collection. (a2c9f1c)

}
34 changes: 34 additions & 0 deletions src/Components/Components/src/PersistReasonFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Base class for filtering component state persistence based on specific persistence reasons.
/// </summary>
/// <typeparam name="TReason">The type of persistence reason this filter handles.</typeparam>
public abstract class PersistReasonFilter<TReason> : Attribute, IPersistenceReasonFilter
where TReason : IPersistenceReason
{
private readonly bool _persist;

/// <summary>
/// Initializes a new instance of the <see cref="PersistReasonFilter{TReason}"/> class.
/// </summary>
/// <param name="persist">Whether to persist state for the specified reason type.</param>
protected PersistReasonFilter(bool persist)
{
_persist = persist;
}

/// <inheritdoc />
public bool? ShouldPersist(IPersistenceReason reason)
{
if (reason is TReason)
{
return _persist;
}

return null;
}
}
31 changes: 31 additions & 0 deletions src/Components/Components/src/PersistenceReasons.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Represents persistence during prerendering.
/// </summary>
public class PersistOnPrerendering : IPersistenceReason
{
/// <inheritdoc />
public bool PersistByDefault { get; } = true;
}

/// <summary>
/// Represents persistence during enhanced navigation.
/// </summary>
public class PersistOnEnhancedNavigation : IPersistenceReason
{
/// <inheritdoc />
public bool PersistByDefault { get; }
}

/// <summary>
/// Represents persistence when a circuit is paused.
/// </summary>
public class PersistOnCircuitPause : IPersistenceReason
{
/// <inheritdoc />
public bool PersistByDefault { get; } = true;
}
24 changes: 24 additions & 0 deletions src/Components/Components/src/PersistentComponentState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ internal void InitializeExistingState(IDictionary<string, byte[]> existingState)
public PersistingComponentStateSubscription RegisterOnPersisting(Func<Task> callback)
=> RegisterOnPersisting(callback, null);

/// <summary>
/// Register a callback to persist the component state when the application is about to be paused.
/// Registered callbacks can use this opportunity to persist their state so that it can be retrieved when the application resumes.
/// </summary>
/// <param name="callback">The callback to invoke when the application is being paused.</param>
/// <param name="renderMode"></param>
/// <param name="reasonFilters">Filters to control when the callback should be invoked based on the persistence reason.</param>
/// <returns>A subscription that can be used to unregister the callback when disposed.</returns>
public PersistingComponentStateSubscription RegisterOnPersisting(Func<Task> callback, IComponentRenderMode? renderMode, IReadOnlyList<IPersistenceReasonFilter>? reasonFilters)
Copy link
Member

Choose a reason for hiding this comment

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

IReadOnlyList? reasonFilters <= Make this mandatory

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Made the reasonFilters parameter mandatory in the RegisterOnPersisting overload that accepts filters. Updated the legacy overloads to pass Array.Empty<IPersistenceReasonFilter>() when no filters are provided. (a2c9f1c)

{
ArgumentNullException.ThrowIfNull(callback);

if (PersistingState)
{
throw new InvalidOperationException("Registering a callback while persisting state is not allowed.");
}

var persistenceCallback = new PersistComponentStateRegistration(callback, renderMode, reasonFilters);

_registeredCallbacks.Add(persistenceCallback);

return new PersistingComponentStateSubscription(_registeredCallbacks, persistenceCallback);
}

/// <summary>
/// Register a callback to persist the component state when the application is about to be paused.
/// Registered callbacks can use this opportunity to persist their state so that it can be retrieved when the application resumes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ public async Task RestoreStateAsync(IPersistentComponentStateStore store)
/// <param name="renderer">The <see cref="Renderer"/> that components are being rendered.</param>
/// <returns>A <see cref="Task"/> that will complete when the state has been restored.</returns>
public Task PersistStateAsync(IPersistentComponentStateStore store, Renderer renderer)
=> PersistStateAsync(store, renderer, new PersistOnPrerendering());

/// <summary>
/// Persists the component application state into the given <see cref="IPersistentComponentStateStore"/>.
/// </summary>
/// <param name="store">The <see cref="IPersistentComponentStateStore"/> to restore the application state from.</param>
/// <param name="renderer">The <see cref="Renderer"/> that components are being rendered.</param>
/// <param name="persistenceReason">The reason for persisting the state.</param>
/// <returns>A <see cref="Task"/> that will complete when the state has been restored.</returns>
public Task PersistStateAsync(IPersistentComponentStateStore store, Renderer renderer, IPersistenceReason persistenceReason)
{
if (_stateIsPersisted)
{
Expand Down Expand Up @@ -113,7 +123,7 @@ async Task PauseAndPersistState()

async Task<bool> TryPersistState(IPersistentComponentStateStore store)
{
if (!await TryPauseAsync(store))
if (!await TryPauseAsync(store, persistenceReason))
{
_currentState.Clear();
return false;
Expand Down Expand Up @@ -159,7 +169,7 @@ private void InferRenderModes(Renderer renderer)
var componentRenderMode = renderer.GetComponentRenderMode(component);
if (componentRenderMode != null)
{
_registeredCallbacks[i] = new PersistComponentStateRegistration(registration.Callback, componentRenderMode);
_registeredCallbacks[i] = new PersistComponentStateRegistration(registration.Callback, componentRenderMode, registration.ReasonFilters);
}
else
{
Expand All @@ -177,6 +187,9 @@ private void InferRenderModes(Renderer renderer)
}

internal Task<bool> TryPauseAsync(IPersistentComponentStateStore store)
=> TryPauseAsync(store, new PersistOnPrerendering());

internal Task<bool> TryPauseAsync(IPersistentComponentStateStore store, IPersistenceReason persistenceReason)
{
List<Task<bool>>? pendingCallbackTasks = null;

Expand All @@ -199,6 +212,27 @@ internal Task<bool> TryPauseAsync(IPersistentComponentStateStore store)
continue;
}

// Evaluate reason filters to determine if the callback should be executed for this persistence reason
if (registration.ReasonFilters != null)
{
var shouldPersist = EvaluateReasonFilters(registration.ReasonFilters, persistenceReason);
if (shouldPersist.HasValue && !shouldPersist.Value)
{
// Filters explicitly indicate not to persist for this reason
continue;
}
else if (!shouldPersist.HasValue && !persistenceReason.PersistByDefault)
{
// No filter matched and default is not to persist
continue;
}
}
else if (!persistenceReason.PersistByDefault)
{
// No filters defined and default is not to persist
continue;
}

var result = TryExecuteCallback(registration.Callback, _logger);
if (!result.IsCompletedSuccessfully)
{
Expand Down Expand Up @@ -271,4 +305,19 @@ static async Task<bool> AnyTaskFailed(List<Task<bool>> pendingCallbackTasks)
return true;
}
}

private static bool? EvaluateReasonFilters(IReadOnlyList<IPersistenceReasonFilter> reasonFilters, IPersistenceReason persistenceReason)
{
foreach (var reasonFilter in reasonFilters)
{
var shouldPersist = reasonFilter.ShouldPersist(persistenceReason);
if (shouldPersist.HasValue)
{
return shouldPersist.Value;
}
}

// No filter matched
return null;
}
}
18 changes: 18 additions & 0 deletions src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,27 @@ Microsoft.AspNetCore.Components.Routing.NotFoundEventArgs.NotFoundEventArgs(stri
Microsoft.AspNetCore.Components.Routing.NotFoundEventArgs.Path.get -> string!
Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager.ComponentStatePersistenceManager(Microsoft.Extensions.Logging.ILogger<Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager!>! logger, System.IServiceProvider! serviceProvider) -> void
Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager.SetPlatformRenderMode(Microsoft.AspNetCore.Components.IComponentRenderMode! renderMode) -> void
Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager.PersistStateAsync(Microsoft.AspNetCore.Components.IPersistentComponentStateStore! store, Microsoft.AspNetCore.Components.RenderTree.Renderer! renderer, Microsoft.AspNetCore.Components.IPersistenceReason! persistenceReason) -> System.Threading.Tasks.Task
Microsoft.AspNetCore.Components.Infrastructure.RegisterPersistentComponentStateServiceCollectionExtensions
Microsoft.AspNetCore.Components.SupplyParameterFromPersistentComponentStateAttribute
Microsoft.AspNetCore.Components.SupplyParameterFromPersistentComponentStateAttribute.SupplyParameterFromPersistentComponentStateAttribute() -> void
Microsoft.AspNetCore.Components.IPersistenceReason
Microsoft.AspNetCore.Components.IPersistenceReason.PersistByDefault.get -> bool
Microsoft.AspNetCore.Components.IPersistenceReasonFilter
Microsoft.AspNetCore.Components.IPersistenceReasonFilter.ShouldPersist(Microsoft.AspNetCore.Components.IPersistenceReason! reason) -> bool?
Microsoft.AspNetCore.Components.PersistOnCircuitPause
Microsoft.AspNetCore.Components.PersistOnCircuitPause.PersistByDefault.get -> bool
Microsoft.AspNetCore.Components.PersistOnCircuitPause.PersistOnCircuitPause() -> void
Microsoft.AspNetCore.Components.PersistOnEnhancedNavigation
Microsoft.AspNetCore.Components.PersistOnEnhancedNavigation.PersistByDefault.get -> bool
Microsoft.AspNetCore.Components.PersistOnEnhancedNavigation.PersistOnEnhancedNavigation() -> void
Microsoft.AspNetCore.Components.PersistOnPrerendering
Microsoft.AspNetCore.Components.PersistOnPrerendering.PersistByDefault.get -> bool
Microsoft.AspNetCore.Components.PersistOnPrerendering.PersistOnPrerendering() -> void
Microsoft.AspNetCore.Components.PersistReasonFilter<TReason>
Microsoft.AspNetCore.Components.PersistReasonFilter<TReason>.PersistReasonFilter(bool persist) -> void
Microsoft.AspNetCore.Components.PersistReasonFilter<TReason>.ShouldPersist(Microsoft.AspNetCore.Components.IPersistenceReason! reason) -> bool?
Microsoft.AspNetCore.Components.PersistentComponentState.RegisterOnPersisting(System.Func<System.Threading.Tasks.Task!>! callback, Microsoft.AspNetCore.Components.IComponentRenderMode? renderMode, System.Collections.Generic.IReadOnlyList<Microsoft.AspNetCore.Components.IPersistenceReasonFilter!>? reasonFilters) -> Microsoft.AspNetCore.Components.PersistingComponentStateSubscription
Microsoft.Extensions.DependencyInjection.SupplyParameterFromPersistentComponentStateProviderServiceCollectionExtensions
static Microsoft.AspNetCore.Components.Infrastructure.RegisterPersistentComponentStateServiceCollectionExtensions.AddPersistentServiceRegistration<TService>(Microsoft.Extensions.DependencyInjection.IServiceCollection! services, Microsoft.AspNetCore.Components.IComponentRenderMode! componentRenderMode) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.AspNetCore.Components.Infrastructure.ComponentsMetricsServiceCollectionExtensions.AddComponentsMetrics(Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
Expand Down
21 changes: 21 additions & 0 deletions src/Components/Web/src/PersistenceReasonFilters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Components;

namespace Microsoft.AspNetCore.Components.Web;

/// <summary>
/// Filter that controls whether component state should be persisted during prerendering.
/// </summary>
public class PersistOnPrerenderingFilter(bool persist = true) : PersistReasonFilter<PersistOnPrerendering>(persist);

/// <summary>
/// Filter that controls whether component state should be persisted during enhanced navigation.
/// </summary>
public class PersistOnEnhancedNavigationFilter(bool persist = true) : PersistReasonFilter<PersistOnEnhancedNavigation>(persist);

/// <summary>
/// Filter that controls whether component state should be persisted when a circuit is paused.
/// </summary>
public class PersistOnCircuitPauseFilter(bool persist = true) : PersistReasonFilter<PersistOnCircuitPause>(persist);
Loading
0