perf(dashboard): NativeDialog skips repeat close() interop once the dialog is closed (DSH-008, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:42:16 -05:00
parent 17a42ab292
commit 449b483046
2 changed files with 168 additions and 1 deletions
@@ -22,6 +22,10 @@
private bool _cancelPending;
private object? _lastTarget;
private long _generation;
// Generation the JS side was last told to close. close() on an already-closed dialog is a
// no-op there, and the host pages re-render every snapshot tick, so without this a dismissed
// dialog cost one interop round trip per tick for the life of the tab (DSH-008).
private long _closedGeneration = -1;
private Task? _disposeTask;
/// <summary>Whether the parent requests an interactive native modal.</summary>
@@ -72,7 +76,11 @@
if (_module is null) return;
if (!IsOpen)
{
await _module.InvokeVoidAsync("close", _element);
if (_closedGeneration != generation)
{
await _module.InvokeVoidAsync("close", _element);
_closedGeneration = generation;
}
}
else if (_needsOpen)
{
@@ -82,6 +90,9 @@
openedNow = opened;
if (!opened) rejectedGeneration = generation;
}
// update() is deliberately not de-duplicated: the JS side clears its in-flight "pending"
// flag there, and a re-render with unchanged parameters is how a rejected submit
// (validation error, guarded handler) re-enables Escape-to-cancel.
if (!openedNow && !_disposed && generation == _generation && IsOpen)
await _module.InvokeVoidAsync("update", _element, generation, IsBusy);
}
@@ -0,0 +1,156 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components.Shared;
namespace ZB.MOM.WW.MxGateway.Tests.Dashboard;
/// <summary>DSH-008: a dismissed <see cref="NativeDialog"/> must not cost JS interop on every parent render.</summary>
public sealed class NativeDialogInteropTests
{
/// <summary>Open then close, then ten parent re-renders: only the one close call reaches JS.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ClosedDialog_WhenParentRerenders_DoesNotCallCloseAgain()
{
RecordingJsRuntime js = new();
ServiceCollection services = new();
services.AddLogging();
services.AddSingleton<IJSRuntime>(js);
await using ServiceProvider provider = services.BuildServiceProvider();
await using TestRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
HostHandle handle = new();
await renderer.MountAsync(handle);
await SetOpenAsync(renderer, handle, true);
Assert.Equal(1, js.ModuleCalls.Count(call => call == "open"));
await SetOpenAsync(renderer, handle, false);
Assert.Equal(1, js.ModuleCalls.Count(call => call == "close"));
for (int i = 0; i < 10; i++)
{
await renderer.Dispatcher.InvokeAsync(() => handle.Host!.Rerender());
await Task.Delay(10);
}
Assert.Equal(1, js.ModuleCalls.Count(call => call == "close"));
}
private static async Task SetOpenAsync(TestRenderer renderer, HostHandle handle, bool open)
{
await renderer.Dispatcher.InvokeAsync(() =>
{
handle.Host!.Open = open;
handle.Host.Rerender();
});
await Task.Delay(50);
}
// Minimal renderer that runs OnAfterRenderAsync (the static HtmlRenderer does not), which is
// where NativeDialog makes its interop calls. BL0006 is suppressed for this test-only scaffold.
#pragma warning disable BL0006
private sealed class TestRenderer(IServiceProvider services, ILoggerFactory loggerFactory)
: Renderer(services, loggerFactory)
{
/// <inheritdoc />
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
/// <summary>Mounts the host component and renders it.</summary>
/// <param name="handle">Handle the host publishes itself through.</param>
/// <returns>A task that completes once the first render has been dispatched.</returns>
public Task MountAsync(HostHandle handle) => Dispatcher.InvokeAsync(() =>
{
DialogHost host = (DialogHost)InstantiateComponent(typeof(DialogHost));
host.Handle = handle;
int id = AssignRootComponentId(host);
return RenderRootComponentAsync(id);
});
/// <inheritdoc />
protected override void HandleException(Exception exception) => throw new InvalidOperationException("render fault", exception);
/// <inheritdoc />
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask;
}
#pragma warning restore BL0006
private sealed class HostHandle
{
/// <summary>Gets or sets the mounted host.</summary>
public DialogHost? Host { get; set; }
}
private sealed class DialogHost : ComponentBase
{
/// <summary>Gets or sets the handle the test uses to reach this instance.</summary>
public HostHandle Handle { get; set; } = null!;
/// <summary>Gets or sets a value indicating whether the dialog is open.</summary>
public bool Open { get; set; }
/// <summary>Requests a render, as a snapshot tick does for the host pages.</summary>
public void Rerender() => StateHasChanged();
/// <inheritdoc />
protected override void OnInitialized() => Handle.Host = this;
/// <inheritdoc />
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenComponent<NativeDialog>(0);
builder.AddAttribute(1, nameof(NativeDialog.IsOpen), Open);
builder.AddAttribute(2, nameof(NativeDialog.LabelledBy), "title");
// A RenderFragment is not a change-detectable parameter, so the dialog re-renders with
// its host exactly as it does on the real pages.
builder.AddAttribute(3, nameof(NativeDialog.ChildContent), (RenderFragment)(content => { }));
builder.CloseComponent();
}
}
private sealed class RecordingJsRuntime : IJSRuntime
{
private readonly RecordingModule _module = new();
/// <summary>Gets the module-level calls made, in order.</summary>
public List<string> ModuleCalls => _module.Calls;
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args) =>
new((TValue)(object)_module);
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args) =>
InvokeAsync<TValue>(identifier, args);
}
private sealed class RecordingModule : IJSObjectReference
{
/// <summary>Gets the calls made, in order.</summary>
public List<string> Calls { get; } = [];
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
{
lock (Calls)
{
Calls.Add(identifier);
}
return new(typeof(TValue) == typeof(bool) ? (TValue)(object)true : default!);
}
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args) =>
InvokeAsync<TValue>(identifier, args);
/// <inheritdoc />
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}