Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs
T
Joseph Doherty a606407fc4 perf(dashboard): NativeDialog sends update() only on busy/generation change or a reported submit (DSH-008, #258)
JS now reports when a submit raises its in-flight pending flag, and a cancel
request marks the same, so the next render clears pending through update()
without update() running on every snapshot tick. Escape still works after a
rejected submit.
2026-12-03 13:04:28 -05:00

329 lines
14 KiB
C#

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"));
}
/// <summary>An open, idle dialog sends no update() while the parent re-renders unchanged.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenDialog_WhenParentRerendersUnchanged_DoesNotCallUpdate()
{
(RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync();
await using ServiceProvider providerScope = provider;
await using TestRenderer rendererScope = renderer;
await SetOpenAsync(renderer, handle, true);
await RerenderAsync(renderer, handle, 10);
Assert.Equal(1, js.ModuleCalls.Count(call => call == "open"));
Assert.Equal(0, js.ModuleCalls.Count(call => call == "update"));
}
/// <summary>A busy transition reaches JS once per change, not once per render.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenDialog_WhenBusyChanges_CallsUpdateOncePerChange()
{
(RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync();
await using ServiceProvider providerScope = provider;
await using TestRenderer rendererScope = renderer;
await SetOpenAsync(renderer, handle, true);
await SetBusyAsync(renderer, handle, true);
await RerenderAsync(renderer, handle, 5);
Assert.Equal([true], js.UpdateBusyArguments);
await SetBusyAsync(renderer, handle, false);
await RerenderAsync(renderer, handle, 5);
Assert.Equal([true, false], js.UpdateBusyArguments);
}
/// <summary>
/// A rejected submit (JS raised pending, the parent re-rendered without going busy or closing)
/// sends exactly one update(), which is what clears JS pending, and Escape then cancels.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RejectedSubmit_SendsOneUpdate_ThenEscapeCancels()
{
(RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync();
await using ServiceProvider providerScope = provider;
await using TestRenderer rendererScope = renderer;
await SetOpenAsync(renderer, handle, true);
await RerenderAsync(renderer, handle, 3);
Assert.Equal(0, js.ModuleCalls.Count(call => call == "update"));
long generation = js.OpenGeneration;
// JS: submit clicked -> pending raised and reported; the handler rejects and the parent
// re-renders with nothing changed.
await handle.Host!.Dialog!.NotifyPendingAsync(generation);
await RerenderAsync(renderer, handle, 1);
Assert.Equal([generation], js.UpdateGenerations);
// Further ticks do not repeat it.
await RerenderAsync(renderer, handle, 5);
Assert.Equal([generation], js.UpdateGenerations);
// JS: Escape with pending cleared -> RequestCancelAsync -> parent cancel.
await handle.Host.Dialog.RequestCancelAsync(generation);
Assert.Equal(1, handle.Host.CancelCount);
}
/// <summary>An Escape the parent ignores still gets JS pending cleared on the next render.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task IgnoredCancel_SendsUpdateOnNextRender()
{
(RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync();
await using ServiceProvider providerScope = provider;
await using TestRenderer rendererScope = renderer;
await SetOpenAsync(renderer, handle, true);
long generation = js.OpenGeneration;
await handle.Host!.Dialog!.RequestCancelAsync(generation);
await RerenderAsync(renderer, handle, 3);
Assert.Equal(1, handle.Host.CancelCount);
Assert.Equal([generation], js.UpdateGenerations);
}
/// <summary>A pending report for a superseded generation is ignored.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task NotifyPending_ForStaleGeneration_DoesNotCallUpdate()
{
(RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync();
await using ServiceProvider providerScope = provider;
await using TestRenderer rendererScope = renderer;
await SetOpenAsync(renderer, handle, true);
await handle.Host!.Dialog!.NotifyPendingAsync(js.OpenGeneration - 1);
await RerenderAsync(renderer, handle, 3);
Assert.Equal(0, js.ModuleCalls.Count(call => call == "update"));
}
private static async Task<(RecordingJsRuntime Js, ServiceProvider Provider, TestRenderer Renderer, HostHandle Handle)> MountAsync()
{
RecordingJsRuntime js = new();
ServiceCollection services = new();
services.AddLogging();
services.AddSingleton<IJSRuntime>(js);
ServiceProvider provider = services.BuildServiceProvider();
TestRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
HostHandle handle = new();
await renderer.MountAsync(handle);
return (js, provider, renderer, handle);
}
private static async Task RerenderAsync(TestRenderer renderer, HostHandle handle, int count)
{
for (int i = 0; i < count; i++)
{
await renderer.Dispatcher.InvokeAsync(() => handle.Host!.Rerender());
await Task.Delay(10);
}
}
private static async Task SetBusyAsync(TestRenderer renderer, HostHandle handle, bool busy)
{
await renderer.Dispatcher.InvokeAsync(() =>
{
handle.Host!.Busy = busy;
handle.Host.Rerender();
});
await Task.Delay(50);
}
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>Gets or sets a value indicating whether the parent reports in-flight work.</summary>
public bool Busy { get; set; }
/// <summary>Gets the number of cancel callbacks; the parent ignores them (stays open).</summary>
public int CancelCount { get; private set; }
/// <summary>Gets the rendered dialog instance.</summary>
public NativeDialog? Dialog { get; private 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.AddAttribute(4, nameof(NativeDialog.IsBusy), Busy);
builder.AddAttribute(5, nameof(NativeDialog.OnCancel), EventCallback.Factory.Create(this, () => CancelCount++));
builder.AddComponentReferenceCapture(6, dialog => Dialog = (NativeDialog)dialog);
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;
/// <summary>Gets the generation passed to the most recent open() call.</summary>
public long OpenGeneration => _module.OpenGeneration;
/// <summary>Gets the generation argument of each update() call, in order.</summary>
public List<long> UpdateGenerations => _module.UpdateGenerations;
/// <summary>Gets the busy argument of each update() call, in order.</summary>
public List<bool> UpdateBusyArguments => _module.UpdateBusyArguments;
/// <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; } = [];
/// <summary>Gets the generation passed to the most recent open() call.</summary>
public long OpenGeneration { get; private set; }
/// <summary>Gets the generation argument of each update() call, in order.</summary>
public List<long> UpdateGenerations { get; } = [];
/// <summary>Gets the busy argument of each update() call, in order.</summary>
public List<bool> UpdateBusyArguments { get; } = [];
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
{
lock (Calls)
{
Calls.Add(identifier);
if (identifier == "open")
{
OpenGeneration = (long)args![2]!;
}
else if (identifier == "update")
{
UpdateGenerations.Add((long)args![1]!);
UpdateBusyArguments.Add((bool)args[2]!);
}
}
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;
}
}