Name dialogs and contain native overlay keyboard focus
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
@implements IAsyncDisposable
|
||||
@inject IJSRuntime JS
|
||||
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
||||
|
||||
@@ -11,14 +13,15 @@
|
||||
{
|
||||
<div class="offcanvas-backdrop fade show" data-test="drawer-backdrop"
|
||||
@onclick="HandleClose"></div>
|
||||
<div class="offcanvas offcanvas-end show audit-drilldown-drawer"
|
||||
<div id="@_overlayId" role="dialog" aria-modal="true" aria-labelledby="@(_overlayId + "-title")"
|
||||
@onkeydown="HandleKeyDown" class="offcanvas offcanvas-end show audit-drilldown-drawer"
|
||||
tabindex="-1"
|
||||
style="visibility: visible;"
|
||||
data-test="audit-drilldown-drawer">
|
||||
<div class="offcanvas-header border-bottom">
|
||||
<div>
|
||||
<div class="text-muted small text-uppercase">Audit event</div>
|
||||
<h5 class="offcanvas-title mb-0">Audit Event @ShortEventId(Event.EventId)</h5>
|
||||
<h5 id="@(_overlayId + "-title")" class="offcanvas-title mb-0">Audit Event @ShortEventId(Event.EventId)</h5>
|
||||
</div>
|
||||
<button type="button" class="btn-close" aria-label="Close"
|
||||
data-test="drawer-close"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Microsoft.JSInterop;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||
|
||||
@@ -36,6 +37,39 @@ public partial class AuditDrilldownDrawer
|
||||
/// </summary>
|
||||
[Parameter] public EventCallback OnClose { get; set; }
|
||||
|
||||
private readonly string _overlayId = "sb-audit-drawer-" + Guid.NewGuid().ToString("N");
|
||||
private bool _activated;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
var visible = IsOpen && Event is not null;
|
||||
if (visible == _activated) return;
|
||||
_activated = visible;
|
||||
try
|
||||
{
|
||||
if (visible)
|
||||
{
|
||||
var activated = await JS.InvokeAsync<bool?>("sbDialog.activate", _overlayId);
|
||||
if (activated == false) await HandleClose();
|
||||
}
|
||||
else await JS.InvokeVoidAsync("sbDialog.deactivate", _overlayId);
|
||||
}
|
||||
catch (Microsoft.JSInterop.JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { /* prerender */ }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try { await JS.InvokeVoidAsync("sbDialog.deactivate", _overlayId); }
|
||||
catch (Microsoft.JSInterop.JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { /* prerender */ }
|
||||
}
|
||||
|
||||
private Task HandleKeyDown(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs e) =>
|
||||
e.Key == "Escape" ? HandleClose() : Task.CompletedTask;
|
||||
|
||||
private static string ShortEventId(Guid eventId)
|
||||
{
|
||||
// Mirror the "first 8 hex digits" presentation common across the UI.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Listens to DialogService.OnChange and renders the current dialog state.
|
||||
z-index ladder follows the same convention as ConfirmDialog/DiffDialog:
|
||||
Toast container 1090 > this modal 1055 > this backdrop 1040. *@
|
||||
@implements IDisposable
|
||||
@implements IAsyncDisposable
|
||||
@inject IDialogService Service
|
||||
@inject IJSRuntime JS
|
||||
|
||||
@@ -11,22 +11,24 @@
|
||||
@* `sb-modal-backdrop` is a tokenized hook: a separate task attaches the
|
||||
var-driven background rule to it. No inline style here. *@
|
||||
<div class="modal-backdrop fade show sb-modal-backdrop"></div>
|
||||
<div @ref="_modalRef"
|
||||
<div id="@_overlayId" @ref="_modalRef"
|
||||
class="modal fade show d-block"
|
||||
tabindex="-1"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="@TitleId"
|
||||
aria-describedby="@(state.Kind == DialogKind.Confirm ? BodyId : null)"
|
||||
@onkeydown="OnKeyDown">
|
||||
<div class="modal-dialog modal-dialog-centered@(state.Size is null ? "" : $" {state.Size}")" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">@state.Title</h5>
|
||||
<h5 id="@TitleId" class="modal-title">@state.Title</h5>
|
||||
<button type="button" class="btn-close" aria-label="Close" @onclick="Cancel"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@if (state.Kind == DialogKind.Confirm)
|
||||
{
|
||||
<p class="mb-0">@state.Body</p>
|
||||
<p id="@BodyId" class="mb-0">@state.Body</p>
|
||||
}
|
||||
else if (state.Kind == DialogKind.Custom)
|
||||
{
|
||||
@@ -34,8 +36,8 @@
|
||||
}
|
||||
else
|
||||
{
|
||||
<label class="form-label">@state.Body</label>
|
||||
<input @ref="_promptInputRef"
|
||||
<label for="@PromptId" class="form-label">@state.Body</label>
|
||||
<input id="@PromptId" @ref="_promptInputRef"
|
||||
class="form-control form-control-sm"
|
||||
placeholder="@state.Placeholder"
|
||||
value="@_promptValue"
|
||||
@@ -63,6 +65,10 @@
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly string _overlayId = "sb-dialog-" + Guid.NewGuid().ToString("N");
|
||||
private string TitleId => _overlayId + "-title";
|
||||
private string BodyId => _overlayId + "-body";
|
||||
private string PromptId => _overlayId + "-prompt";
|
||||
private ElementReference _modalRef;
|
||||
private ElementReference _promptInputRef;
|
||||
private string _promptValue = string.Empty;
|
||||
@@ -77,9 +83,13 @@
|
||||
if (Service is DialogService svc) svc.OnChange += OnServiceChanged;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Service is DialogService svc) svc.OnChange -= OnServiceChanged;
|
||||
Cancel(); // A disposed host must not leave its local dialog result pending.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.deactivate", _overlayId); }
|
||||
catch (JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { /* prerender */ }
|
||||
}
|
||||
|
||||
private void OnServiceChanged()
|
||||
@@ -97,67 +107,32 @@
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
var current = (Service as DialogService)?.Current;
|
||||
if (current is not null)
|
||||
if (current is not null && !ReferenceEquals(current, _focusedForState))
|
||||
{
|
||||
try { await JS.InvokeVoidAsync("document.body.classList.add", "modal-open"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
|
||||
// Focus once per opened dialog. Without this guard, every input
|
||||
// keystroke triggers a re-render which would re-focus the modal
|
||||
// element and yank the caret off the prompt input.
|
||||
if (!ReferenceEquals(current, _focusedForState))
|
||||
_focusedForState = current;
|
||||
try
|
||||
{
|
||||
_focusedForState = current;
|
||||
|
||||
// Stash the element that had focus when the dialog opened so it
|
||||
// can be restored on close. Must run BEFORE the modal steals
|
||||
// focus below, otherwise we'd capture a modal element.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.captureActiveElement"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
|
||||
try
|
||||
{
|
||||
if (current.Kind == DialogKind.Prompt)
|
||||
await _promptInputRef.FocusAsync();
|
||||
else
|
||||
await _modalRef.FocusAsync();
|
||||
}
|
||||
catch { /* element not yet attached: ignore */ }
|
||||
var activated = await JS.InvokeAsync<bool?>("sbDialog.activate", _overlayId,
|
||||
current.Kind == DialogKind.Prompt ? "#" + PromptId : null);
|
||||
if (activated == false) Cancel(); // Single-active-overlay contract.
|
||||
}
|
||||
catch (JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { /* prerender */ }
|
||||
}
|
||||
else
|
||||
else if (current is null && _focusedForState is not null)
|
||||
{
|
||||
// Only clean up on the actual open→closed transition. Skipping when
|
||||
// _focusedForState is already null avoids spurious JS interop on
|
||||
// the initial render and every steady-state no-dialog render.
|
||||
if (_focusedForState is not null)
|
||||
{
|
||||
_focusedForState = null;
|
||||
try { await JS.InvokeVoidAsync("document.body.classList.remove", "modal-open"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
|
||||
// Return focus to whatever element triggered the dialog so keyboard
|
||||
// users are not dumped at the top of the document on close.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.restoreActiveElement"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
}
|
||||
_focusedForState = null;
|
||||
try { await JS.InvokeVoidAsync("sbDialog.deactivate", _overlayId); }
|
||||
catch (JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { /* prerender */ }
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnKeyDown(KeyboardEventArgs e)
|
||||
private void OnKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Escape")
|
||||
{
|
||||
Cancel();
|
||||
}
|
||||
else if (e.Key == "Tab")
|
||||
{
|
||||
// Trap Tab/Shift+Tab inside the modal so focus cannot escape to the
|
||||
// (inert) page behind the backdrop. The JS helper wraps focus at the
|
||||
// first/last focusable element and prevents the default move there.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.focusTrap", _modalRef, e.ShiftKey); }
|
||||
catch { /* prerender / no JS: skip — native Tab order still applies */ }
|
||||
}
|
||||
// Native DOM keydown owns synchronous Tab containment; Escape retains
|
||||
// the service's existing typed cancellation path.
|
||||
if (e.Key == "Escape") Cancel();
|
||||
}
|
||||
|
||||
private void OnPromptInput(ChangeEventArgs e)
|
||||
|
||||
@@ -1,63 +1,88 @@
|
||||
// Focus management helpers for the centralised DialogHost (T33a). Small and
|
||||
// dependency-free: capture/restore the trigger element's focus across a modal's
|
||||
// lifetime, and trap Tab focus inside an open modal. Blazor calls these via
|
||||
// JS interop (window.sbDialog.*); they are no-ops when there is nothing to act
|
||||
// on, so prerender / loose-mode test calls do no harm.
|
||||
// Local overlay pilot: synchronous native Tab handling and per-instance cleanup.
|
||||
// Generic extraction waits for a second consumer. No dependency on window.event.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// CSS selector for elements that can receive keyboard focus within the modal.
|
||||
const FOCUSABLE =
|
||||
"a[href],button:not([disabled]),input:not([disabled])," +
|
||||
"select:not([disabled]),textarea:not([disabled])," +
|
||||
"[tabindex]:not([tabindex='-1'])";
|
||||
|
||||
// The element that had focus when the most recent dialog opened. Module-level
|
||||
// so it survives between the capture (on open) and restore (on close) calls.
|
||||
let savedActiveElement = null;
|
||||
|
||||
window.sbDialog = {
|
||||
// Stash the currently focused element so it can be restored on close.
|
||||
// Called BEFORE the modal steals focus.
|
||||
captureActiveElement: function () {
|
||||
savedActiveElement = document.activeElement;
|
||||
},
|
||||
|
||||
// Return focus to the stashed element if it is still in the document,
|
||||
// then clear the stash so a later dialog starts fresh.
|
||||
restoreActiveElement: function () {
|
||||
const el = savedActiveElement;
|
||||
savedActiveElement = null;
|
||||
if (el && typeof el.focus === 'function' && el.isConnected) {
|
||||
el.focus();
|
||||
}
|
||||
},
|
||||
|
||||
// Cycle focus within the modal: at the first focusable element a
|
||||
// Shift+Tab wraps to the last; at the last a Tab wraps to the first. In
|
||||
// both cases the default browser move (which would leave the modal) is
|
||||
// prevented. Anywhere else, the native Tab order applies untouched.
|
||||
focusTrap: function (modalEl, shiftKey) {
|
||||
if (!modalEl) return;
|
||||
const focusable = modalEl.querySelectorAll(FOCUSABLE);
|
||||
if (focusable.length === 0) return;
|
||||
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
const active = document.activeElement;
|
||||
|
||||
// Blazor interop does not hand us the DOM event, but window.event is
|
||||
// populated during the synchronous keydown dispatch on the engines we
|
||||
// target — guard the preventDefault so the wrap still works if it is
|
||||
// ever absent (the explicit .focus() override is the real trap).
|
||||
const evt = window.event;
|
||||
if (shiftKey && active === first) {
|
||||
last.focus();
|
||||
if (evt) evt.preventDefault();
|
||||
} else if (!shiftKey && active === last) {
|
||||
first.focus();
|
||||
if (evt) evt.preventDefault();
|
||||
const selector = 'a[href],button,input,select,textarea,[tabindex]';
|
||||
const states = new Map();
|
||||
const inertLocks = new Map();
|
||||
let hadModalOpen = false;
|
||||
function focusable(root) {
|
||||
return Array.from(root.querySelectorAll(selector)).filter(el =>
|
||||
el.tabIndex >= 0 && !el.matches(':disabled') && !el.closest('[inert],[hidden]') &&
|
||||
el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden');
|
||||
}
|
||||
function lock(el) {
|
||||
const old = inertLocks.get(el);
|
||||
if (old) old.count++;
|
||||
else { inertLocks.set(el, { count: 1, previous: el.inert }); el.inert = true; }
|
||||
}
|
||||
function unlock(el) {
|
||||
const old = inertLocks.get(el);
|
||||
if (!old || --old.count) return;
|
||||
el.inert = old.previous; inertLocks.delete(el);
|
||||
}
|
||||
function deactivate(id) {
|
||||
const state = states.get(id);
|
||||
if (!state) return;
|
||||
const wasTop = Array.from(states.keys()).at(-1) === id;
|
||||
states.delete(id);
|
||||
state.el.removeEventListener('keydown', state.keydown);
|
||||
state.locked.forEach(unlock);
|
||||
if (!states.size && !hadModalOpen) document.body.classList.remove('modal-open');
|
||||
if (!wasTop) return;
|
||||
if (state.trigger?.isConnected && !state.trigger.closest('[inert]')) state.trigger.focus();
|
||||
// A connected trigger may now be disabled, hidden, or unfocusable.
|
||||
// Verify the browser accepted focus rather than trusting connectivity.
|
||||
if (document.activeElement !== state.trigger) {
|
||||
const fallback = document.querySelector('main h1,.page h1') || document.querySelector('main,.page');
|
||||
if (fallback) {
|
||||
const previous = fallback.getAttribute('tabindex');
|
||||
fallback.setAttribute('tabindex', '-1'); fallback.focus();
|
||||
// Removing tabindex immediately blurs an otherwise nonfocusable
|
||||
// heading in Chromium. Restore its markup only after focus leaves.
|
||||
if (previous === null) fallback.addEventListener('blur', () => fallback.removeAttribute('tabindex'), { once: true });
|
||||
else fallback.setAttribute('tabindex', previous);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function activate(id, initialSelector) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return false;
|
||||
if (states.has(id)) return true;
|
||||
// One active overlay is supported. Reject sibling and descendant opens;
|
||||
// callers cancel the rejected presentation through existing close paths.
|
||||
if (states.size || el.closest('[inert]')) return false;
|
||||
if (!states.size) hadModalOpen = document.body.classList.contains('modal-open');
|
||||
const state = { el, trigger: document.activeElement, locked: [] };
|
||||
// Inert siblings along the ancestor path, never the dialog or its host.
|
||||
for (let node = el; node.parentElement; node = node.parentElement) {
|
||||
for (const sibling of node.parentElement.children) {
|
||||
if (sibling === node || sibling.matches('script,style,link,.modal-backdrop,.offcanvas-backdrop')) continue;
|
||||
lock(sibling); state.locked.push(sibling);
|
||||
}
|
||||
if (node.parentElement === document.body) break;
|
||||
}
|
||||
state.keydown = event => {
|
||||
if (Array.from(states.keys()).at(-1) !== id) return;
|
||||
if (event.key === 'Escape') event.preventDefault(); // Blazor retains cancellation semantics.
|
||||
if (event.key !== 'Tab') return;
|
||||
const items = focusable(el);
|
||||
const first = items[0], last = items.at(-1), active = document.activeElement;
|
||||
if (!items.length) { event.preventDefault(); el.focus(); }
|
||||
else if (event.shiftKey && (active === first || !items.includes(active))) {
|
||||
event.preventDefault(); last.focus();
|
||||
} else if (!event.shiftKey && (active === last || !items.includes(active))) {
|
||||
event.preventDefault(); first.focus();
|
||||
}
|
||||
};
|
||||
states.set(id, state); el.addEventListener('keydown', state.keydown);
|
||||
document.body.classList.add('modal-open');
|
||||
const initial = initialSelector ? el.querySelector(initialSelector) : null;
|
||||
(initial || el).focus();
|
||||
return true;
|
||||
}
|
||||
new MutationObserver(() => {
|
||||
for (const [id, state] of states) if (!state.el.isConnected) deactivate(id);
|
||||
}).observe(document.documentElement, { childList: true, subtree: true });
|
||||
window.sbDialog = { activate, deactivate };
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user