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.
This commit is contained in:
Joseph Doherty
2026-12-03 13:04:28 -05:00
parent 6804341152
commit a606407fc4
4 changed files with 222 additions and 5 deletions
@@ -26,6 +26,15 @@
// 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;
// Last generation/busy pair sent to JS through open() or update(). update() runs only when
// that pair changes or JS reported its in-flight "pending" flag set, so an open dialog no
// longer costs one interop round trip per snapshot tick (DSH-008).
private long _updatedGeneration = -1;
private bool _updatedBusy;
// Set when JS reports a submit/cancel that raised its "pending" flag. The next render
// (normally the parent's re-render after handling that submit) sends update() to clear it, so
// a rejected submit (validation error, guarded handler) re-enables Escape-to-cancel.
private bool _pendingClearRequested;
private Task? _disposeTask;
/// <summary>Whether the parent requests an interactive native modal.</summary>
@@ -54,6 +63,7 @@
++_generation;
_needsOpen = IsOpen;
_cancelPending = false;
_pendingClearRequested = false;
}
/// <inheritdoc />
@@ -86,15 +96,24 @@
{
_needsOpen = false;
_self ??= DotNetObjectReference.Create(this);
// open() reads busy from the rendered data-busy attribute and starts with pending
// cleared, so it counts as an update for this generation.
_updatedGeneration = generation;
_updatedBusy = IsBusy;
bool opened = await _module.InvokeAsync<bool>("open", _element, _self, generation);
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)
if (!openedNow && !_disposed && generation == _generation && IsOpen
&& (_pendingClearRequested || _updatedGeneration != generation || _updatedBusy != IsBusy))
{
// Record before the await: a pending report that arrives while update() is in
// flight must survive to the next render.
_pendingClearRequested = false;
_updatedGeneration = generation;
_updatedBusy = IsBusy;
await _module.InvokeVoidAsync("update", _element, generation, IsBusy);
}
}
catch (JSDisconnectedException) { }
finally { _lifecycle.Release(); }
@@ -105,12 +124,27 @@
[JSInvokable]
public Task RequestCancelAsync(long generation) => InvokeAsync(async () =>
{
// JS raised its pending flag before calling here; a rejected cancel must still clear it.
if (generation == _generation) _pendingClearRequested = true;
if (_disposed || !IsOpen || IsBusy || _cancelPending || generation != _generation) return;
_cancelPending = true;
try { await OnCancel.InvokeAsync(); }
finally { if (generation == _generation) _cancelPending = false; }
});
/// <summary>
/// Invoked by JS when a submit raised its in-flight pending flag. No render is requested: the
/// parent's re-render after handling the submit (or the next snapshot tick) sends update(),
/// which clears the flag, so Escape works again after a rejected submit.
/// </summary>
/// <param name="generation">Presentation generation the submit belongs to.</param>
/// <returns>A task that completes once the report is recorded.</returns>
[JSInvokable]
public Task NotifyPendingAsync(long generation) => InvokeAsync(() =>
{
if (!_disposed && generation == _generation) _pendingClearRequested = true;
});
/// <inheritdoc />
public ValueTask DisposeAsync() => new(_disposeTask ??= DisposeCoreAsync());
@@ -21,7 +21,11 @@ export function open(dialog, dotnet, generation) {
dotnet.invokeMethodAsync('RequestCancelAsync', generation).catch(() => {});
};
state.operation = event => {
if (event.type === 'submit' || event.target.closest('[data-dialog-submit]')) state.pending = true;
if (event.type !== 'submit' && !event.target.closest('[data-dialog-submit]')) return;
state.pending = true;
// The server sends update() (which clears pending) only after this report, not on every
// render, so a rejected submit must say it happened.
dotnet.invokeMethodAsync('NotifyPendingAsync', generation).catch(() => {});
};
states.set(dialog, state);
dialog.addEventListener('cancel', state.cancel);
@@ -42,6 +42,139 @@ public sealed class NativeDialogInteropTests
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(() =>
@@ -94,6 +227,15 @@ public sealed class NativeDialogInteropTests
/// <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();
@@ -110,6 +252,9 @@ public sealed class NativeDialogInteropTests
// 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();
}
}
@@ -121,6 +266,15 @@ public sealed class NativeDialogInteropTests
/// <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);
@@ -135,12 +289,30 @@ public sealed class NativeDialogInteropTests
/// <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!);