fix(dashboard): pilot native dialog focus and safe dismissal

This commit is contained in:
Joseph Doherty
2026-11-13 17:51:02 -05:00
parent 3e004708d4
commit 260d58afa1
32 changed files with 1750 additions and 40 deletions
@@ -51,9 +51,7 @@ else
@if (IsCreateDialogOpen)
{
<div class="modal-backdrop fade show"></div>
<div class="modal fade show api-key-create-modal" role="dialog" aria-modal="true" aria-labelledby="createApiKeyTitle">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<NativeDialog IsOpen="true" IsBusy="@IsBusy" LabelledBy="createApiKeyTitle" Class="api-key-create-modal" OnCancel="CloseCreateDialog">
<div class="modal-content">
@* Master SiteForm pattern: card-wrapped body with stacked
subsections (h6 text-muted border-bottom). Modal chrome
@@ -63,8 +61,12 @@ else
inline at the bottom of the card-body (no modal-footer). *@
<div class="modal-header">
<h2 class="modal-title h5" id="createApiKeyTitle">Create API Key</h2>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseCreateDialog"></button>
<button type="button" class="btn-close" aria-label="Close create API key" disabled="@IsBusy" @onclick="CloseCreateDialog"></button>
</div>
@if (!LastOperationSucceeded && !string.IsNullOrWhiteSpace(ResultMessage))
{
<p class="alert alert-danger native-dialog-feedback" role="alert">@ResultMessage</p>
}
<div class="modal-body">
<EditForm Model="@CreateModel" OnSubmit="@CreateApiKeyAsync">
<div class="card mb-3">
@@ -72,7 +74,7 @@ else
<h6 class="card-title">Create API Key</h6>
<div class="mb-2">
<label for="keyId" class="form-label small">Key ID</label>
<input id="keyId" class="form-control form-control-sm" @bind="CreateModel.KeyId" @bind:event="oninput" />
<input id="keyId" data-dialog-initial class="form-control form-control-sm" @bind="CreateModel.KeyId" @bind:event="oninput" />
</div>
<div class="mb-3">
<label for="displayName" class="form-label small">Display Name</label>
@@ -148,7 +150,7 @@ else
<div class="mt-3">
<div class="btn-group btn-group-sm" role="group" aria-label="Create API key actions">
<button type="submit" class="btn btn-success" disabled="@IsBusy">Save</button>
<button type="submit" class="btn btn-success" data-dialog-submit disabled="@IsBusy">Save</button>
<button type="button" class="btn btn-outline-secondary" disabled="@IsBusy" @onclick="CloseCreateDialog">Cancel</button>
</div>
</div>
@@ -157,8 +159,7 @@ else
</EditForm>
</div>
</div>
</div>
</div>
</NativeDialog>
}
}
@@ -1,40 +1,25 @@
@if (IsOpen)
{
<div class="modal-backdrop fade show"></div>
<div class="modal fade show" role="dialog" aria-modal="true" aria-labelledby="@TitleId" tabindex="-1" style="display: block;">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title h5" id="@TitleId">@Title</h2>
<button type="button" class="btn-close" aria-label="Close"
disabled="@IsBusy"
@onclick="OnCancel"></button>
</div>
<div class="modal-body">
<p class="mb-0">@Message</p>
</div>
<div class="modal-footer">
<div class="btn-group" role="group" aria-label="Confirm or cancel">
<button type="button" class="btn btn-outline-secondary"
disabled="@IsBusy"
@onclick="OnCancel">
Cancel
</button>
<button type="button" class="btn @ConfirmButtonClass"
disabled="@IsBusy"
@onclick="OnConfirm">
@ConfirmLabel
</button>
</div>
</div>
<NativeDialog IsOpen="@IsOpen" IsBusy="@IsBusy" Target="@((Title, Message))"
LabelledBy="@TitleId" DescribedBy="@MessageId" OnCancel="OnCancel">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title h5" id="@TitleId">@Title</h2>
<button type="button" class="btn-close" aria-label="Close confirmation" disabled="@IsBusy" @onclick="OnCancel"></button>
</div>
<div class="modal-body"><p class="mb-0" id="@MessageId">@Message</p></div>
<div class="modal-footer">
<div class="btn-group" role="group" aria-label="Confirm or cancel">
<button type="button" class="btn btn-outline-secondary" data-dialog-initial disabled="@IsBusy" @onclick="OnCancel">Cancel</button>
<button type="button" class="btn @ConfirmButtonClass" data-dialog-submit disabled="@IsBusy" @onclick="OnConfirm">@ConfirmLabel</button>
</div>
</div>
</div>
}
</NativeDialog>
@code {
private readonly string TitleId = $"confirm-dialog-{Guid.NewGuid():N}";
private string MessageId => $"{TitleId}-message";
[Parameter]
public bool IsOpen { get; set; }
@@ -0,0 +1,123 @@
@using Microsoft.JSInterop
@using Microsoft.Extensions.DependencyInjection
@implements IAsyncDisposable
@inject IServiceProvider Services
<dialog @ref="_element" class="dashboard-native-dialog @Class" aria-labelledby="@LabelledBy"
aria-describedby="@DescribedBy" aria-busy="@(IsBusy ? "true" : "false")" data-busy="@(IsBusy ? "true" : "false")">
@if (IsOpen)
{
@ChildContent
}
</dialog>
@code {
private readonly SemaphoreSlim _lifecycle = new(1, 1);
private ElementReference _element;
private IJSObjectReference? _module;
private DotNetObjectReference<NativeDialog>? _self;
private bool _disposed;
private bool _lastOpen;
private bool _needsOpen;
private bool _cancelPending;
private object? _lastTarget;
private long _generation;
private Task? _disposeTask;
/// <summary>Whether the parent requests an interactive native modal.</summary>
[Parameter] public bool IsOpen { get; set; }
/// <summary>Parent-owned in-flight state; it prevents safe cancellation.</summary>
[Parameter] public bool IsBusy { get; set; }
/// <summary>Identity of the confirmation target, excluding confidential content.</summary>
[Parameter] public object? Target { get; set; }
/// <summary>ID of the visible title.</summary>
[Parameter] public string LabelledBy { get; set; } = string.Empty;
/// <summary>ID of the consequence or descriptive text.</summary>
[Parameter] public string? DescribedBy { get; set; }
/// <summary>Optional local sizing class.</summary>
[Parameter] public string? Class { get; set; }
/// <summary>Parent-owned controls and content; this adapter never submits an operation.</summary>
[Parameter] public RenderFragment? ChildContent { get; set; }
/// <summary>Safe cancellation callback.</summary>
[Parameter] public EventCallback OnCancel { get; set; }
/// <inheritdoc />
protected override void OnParametersSet()
{
if (_lastOpen == IsOpen && Equals(_lastTarget, Target)) return;
_lastOpen = IsOpen;
_lastTarget = Target;
++_generation;
_needsOpen = IsOpen;
_cancelPending = false;
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await _lifecycle.WaitAsync();
long rejectedGeneration = -1;
bool openedNow = false;
try
{
if (_disposed) return;
long generation = _generation;
if (IsOpen && _module is null)
{
// Resolve before the first await; do not reach through a disposed circuit scope.
IJSRuntime js = Services.GetRequiredService<IJSRuntime>();
_module = await js.InvokeAsync<IJSObjectReference>("import", "./js/dashboard-dialog.js");
}
if (_disposed || generation != _generation) return;
if (_module is null) return;
if (!IsOpen)
{
await _module.InvokeVoidAsync("close", _element);
}
else if (_needsOpen)
{
_needsOpen = false;
_self ??= DotNetObjectReference.Create(this);
bool opened = await _module.InvokeAsync<bool>("open", _element, _self, generation);
openedNow = opened;
if (!opened) rejectedGeneration = generation;
}
if (!openedNow && !_disposed && generation == _generation && IsOpen)
await _module.InvokeVoidAsync("update", _element, generation, IsBusy);
}
catch (JSDisconnectedException) { }
finally { _lifecycle.Release(); }
if (rejectedGeneration == _generation) await RequestCancelAsync(rejectedGeneration);
}
/// <summary>Cancels only the current, idle presentation; invoked by the native cancel event.</summary>
[JSInvokable]
public Task RequestCancelAsync(long generation) => InvokeAsync(async () =>
{
if (_disposed || !IsOpen || IsBusy || _cancelPending || generation != _generation) return;
_cancelPending = true;
try { await OnCancel.InvokeAsync(); }
finally { if (generation == _generation) _cancelPending = false; }
});
/// <inheritdoc />
public ValueTask DisposeAsync() => new(_disposeTask ??= DisposeCoreAsync());
private async Task DisposeCoreAsync()
{
_disposed = true;
++_generation;
await _lifecycle.WaitAsync();
try
{
if (_module is not null)
{
try { await _module.InvokeVoidAsync("close", _element); }
catch (JSDisconnectedException) { }
try { await _module.DisposeAsync(); }
catch (JSDisconnectedException) { }
}
}
finally { _self?.Dispose(); _lifecycle.Release(); }
}
}
@@ -15,7 +15,7 @@
<PackageReference Include="ZB.MOM.WW.Auth.ApiKeys" Version="0.4.1" />
<PackageReference Include="ZB.MOM.WW.Auth.AspNetCore" Version="0.4.1" />
<PackageReference Include="ZB.MOM.WW.Audit" Version="0.1.0" />
<PackageReference Include="ZB.MOM.WW.Theme" Version="0.5.0" />
<PackageReference Include="ZB.MOM.WW.Theme" Version="1.0.1" />
<PackageReference Include="ZB.MOM.WW.Configuration" Version="0.1.0" />
<PackageReference Include="ZB.MOM.WW.Health" Version="0.3.0" />
<PackageReference Include="ZB.MOM.WW.Telemetry" Version="0.3.1" />
@@ -270,7 +270,7 @@ code {
white-space: normal;
font-family: var(--mono);
}
.api-key-create-modal { display: block; }
/* Native dialog owns open/closed display; never force a closed dialog visible. */
.api-key-create-modal .modal-body {
max-height: min(70vh, 44rem);
overflow-y: auto;
@@ -522,3 +522,28 @@ code {
@media (max-width: 960px) {
.browse-layout { grid-template-columns: minmax(0, 1fr); }
}
/* Local native-modal pilot: canonical palette/chrome, one native backdrop. */
.dashboard-native-dialog {
padding: 0; border: 1px solid var(--rule-strong); border-radius: 8px;
width: min(32rem, calc(100% - 2rem)); max-width: calc(100% - 2rem);
max-height: calc(100dvh - 2rem); overflow: auto;
background: var(--card); color: var(--ink);
}
.dashboard-native-dialog::backdrop { background: rgb(0 0 0 / .45); }
.dashboard-native-dialog.api-key-create-modal { width: min(70rem, calc(100% - 2rem)); }
.dashboard-native-dialog .modal-content { border: 0; }
.dashboard-native-dialog .modal-header {
display: flex; align-items: center; justify-content: space-between; gap: 1rem;
padding: 1rem; border-bottom: 1px solid var(--rule);
}
.dashboard-native-dialog .modal-header .btn-close { margin: 0; padding: .5rem; flex: none; }
.dashboard-native-dialog .modal-body { padding: 1rem; }
.dashboard-native-dialog .modal-footer { padding: .75rem 1rem; border-top: 1px solid var(--rule); gap: .5rem; }
/* Keep user-triggered validation visible while only the long form body scrolls. */
.dashboard-native-dialog .modal-content { max-height: calc(100dvh - 2rem - 2px); }
.dashboard-native-dialog .modal-header, .dashboard-native-dialog .modal-footer { flex-shrink: 0; }
.dashboard-native-dialog.api-key-create-modal .modal-body { min-height: 0; max-height: none; overflow-y: auto; }
.dashboard-native-dialog .native-dialog-feedback { margin: 0; border-radius: 0; flex-shrink: 0; }
@@ -0,0 +1,79 @@
// Local native-dialog pilot. No operation, form value or token crosses this adapter.
const states = new WeakMap();
let active;
const usable = node => {
if (!node?.isConnected || node.matches(':disabled') || node.getAttribute('aria-disabled') === 'true' || !node.getClientRects().length) return false;
for (let ancestor = node; ancestor; ancestor = ancestor.parentElement) {
const style = getComputedStyle(ancestor);
if (ancestor.hidden || ancestor.inert || style.display === 'none' || ['hidden', 'collapse'].includes(style.visibility)) return false;
}
return true;
};
export function open(dialog, dotnet, generation) {
close(dialog);
if (!dialog?.isConnected || (active?.isConnected && active.open && active !== dialog) || document.querySelector('dialog:modal')) return false;
const state = { trigger: document.activeElement, generation, pending: false, busy: dialog.dataset.busy === 'true' };
state.cancel = event => {
// Native cancel must be prevented synchronously, before any circuit round trip.
event.preventDefault();
if (state.busy || state.pending || dialog.dataset.busy === 'true') return;
state.pending = true;
dotnet.invokeMethodAsync('RequestCancelAsync', generation).catch(() => {});
};
state.operation = event => {
if (event.type === 'submit' || event.target.closest('[data-dialog-submit]')) state.pending = true;
};
states.set(dialog, state);
dialog.addEventListener('cancel', state.cancel);
dialog.addEventListener('click', state.operation);
dialog.addEventListener('submit', state.operation);
// Client-owned cleanup also runs when a disconnected circuit removes the node
// before server disposal can invoke interop.
state.observer = new MutationObserver(() => {
if (!dialog.isConnected) close(dialog);
});
state.observer.observe(document.body, { childList: true, subtree: true });
try {
dialog.showModal();
active = dialog;
dialog.querySelector('[data-dialog-initial]')?.focus({ preventScroll: true });
return true;
} catch (error) {
close(dialog);
throw error;
}
}
export function update(dialog, generation, busy) {
const state = states.get(dialog);
if (!state || state.generation !== generation) return;
state.busy = busy;
state.pending = false;
}
export function close(dialog) {
const state = states.get(dialog);
if (!state) return;
states.delete(dialog);
state.observer.disconnect();
dialog.removeEventListener('cancel', state.cancel);
dialog.removeEventListener('click', state.operation);
dialog.removeEventListener('submit', state.operation);
if (dialog.open) dialog.close();
if (active === dialog) active = null;
requestAnimationFrame(() => {
if (active?.open || document.querySelector('dialog:modal')) return;
const current = document.activeElement;
if (usable(current) && ![state.trigger, document.body, document.documentElement].includes(current) && !dialog.contains(current)) return;
const fallback = document.querySelector('main h1');
for (const target of [state.trigger, fallback]) {
if (!usable(target)) continue;
const oldTabindex = target.getAttribute('tabindex');
if (target === fallback && oldTabindex === null) target.tabIndex = -1;
target.focus({ preventScroll: true });
if (target === document.activeElement) {
if (target === fallback && oldTabindex === null)
target.addEventListener('blur', () => target.removeAttribute('tabindex'), { once: true });
return;
}
}
});
}
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components.Shared;
namespace ZB.MOM.WW.MxGateway.Tests.Dashboard;
/// <summary>Semantic contracts only; actual modal/focus behavior is browser-verified.</summary>
public sealed class ConfirmDialogRenderTests
{
/// <summary>Confirmations name their native modal and expose complete escaped consequences.</summary>
[Fact]
public async Task RequestedConfirmation_RendersNamedNativeDialogAndSafeCancel()
{
string html = await RenderAsync(new()
{
[nameof(ConfirmDialog.IsOpen)] = true,
[nameof(ConfirmDialog.Title)] = "Close session example",
[nameof(ConfirmDialog.Message)] = "Clients disconnect <script>fixture</script>.",
});
Assert.Contains("<dialog", html, StringComparison.Ordinal);
Assert.Contains("aria-labelledby=", html, StringComparison.Ordinal);
Assert.Contains("aria-describedby=", html, StringComparison.Ordinal);
Assert.Contains("Close session example", html, StringComparison.Ordinal);
Assert.Contains("Cancel", html, StringComparison.Ordinal);
Assert.Contains("&lt;script&gt;fixture&lt;/script&gt;", html, StringComparison.Ordinal);
Assert.DoesNotContain("modal-backdrop", html, StringComparison.Ordinal);
}
/// <summary>Busy ownership remains visible and both operation controls remain disabled.</summary>
[Fact]
public async Task BusyConfirmation_ExposesBusyStateAndRetainsDisabledActions()
{
string html = await RenderAsync(new()
{
[nameof(ConfirmDialog.IsOpen)] = true,
[nameof(ConfirmDialog.IsBusy)] = true,
});
Assert.Contains("aria-busy=\"true\"", html, StringComparison.Ordinal);
Assert.Equal(3, html.Split(" disabled", StringSplitOptions.None).Length - 1);
}
private static async Task<string> RenderAsync(Dictionary<string, object?> parameters)
{
ServiceCollection services = new();
services.AddLogging();
await using ServiceProvider provider = services.BuildServiceProvider();
await using HtmlRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
return await renderer.Dispatcher.InvokeAsync(async () =>
(await renderer.RenderComponentAsync<ConfirmDialog>(ParameterView.FromDictionary(parameters))).ToHtmlString());
}
}