refactor(ui/shared): introduce IDialogService + DialogHost

Eliminates the per-page <ConfirmDialog @ref="_confirmDialog"
ConfirmButtonClass="btn-danger" /> boilerplate. Pages now inject
IDialogService and call ConfirmAsync(title, message, danger: true)
programmatically.

New scoped service holds a single active dialog (throws on nested
calls), with a global DialogHost mounted once in MainLayout that
renders the modal markup, owns body scroll-lock via Bootstrap's
modal-open class, traps focus on the modal element, and handles
Escape-to-cancel.

Same service also exposes PromptAsync, used to replace the bespoke
NewFolderDialog. Both ConfirmDialog and NewFolderDialog components
are deleted — their callers (~13 pages across Admin/Design/Deployment
/Monitoring) now go through the service.

DiffDialog stays as-is — different use case (before/after content).

bUnit tests in TopologyPageTests, DataConnectionsPageTests, and
TemplatesPageTests register IDialogService in their service
collection.

Also: a top-of-file Razor comment on Sites.razor pointing future
implementers at it as the reference list-page pattern.
This commit is contained in:
Joseph Doherty
2026-05-12 03:57:37 -04:00
parent e21791adb0
commit 8038aa7cb5
21 changed files with 351 additions and 260 deletions

View File

@@ -1,131 +0,0 @@
@* Reusable confirmation dialog using Bootstrap modal.
z-index ladder: Toast container 1090 > this modal 1055 > this backdrop 1040. *@
@inject IJSRuntime JS
@implements IAsyncDisposable
@if (_visible)
{
<div class="modal-backdrop fade show"></div>
<div @ref="_modalRef"
class="modal fade show d-block"
tabindex="-1"
role="dialog"
@onkeydown="OnKeyDownAsync">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">@Title</h5>
<button type="button" class="btn-close" @onclick="Cancel"></button>
</div>
<div class="modal-body">
<p>@Message</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary btn-sm" @onclick="Cancel">Cancel</button>
<button type="button" class="btn @ConfirmButtonClass btn-sm" @onclick="Confirm">@ConfirmText</button>
</div>
</div>
</div>
</div>
}
@code {
private bool _visible;
private bool _bodyLocked;
private TaskCompletionSource<bool>? _tcs;
private ElementReference _modalRef;
[Parameter] public string Title { get; set; } = "Confirm";
[Parameter] public string Message { get; set; } = "Are you sure?";
[Parameter] public string ConfirmText { get; set; } = "Confirm";
[Parameter] public string ConfirmButtonClass { get; set; } = "btn-primary";
public Task<bool> ShowAsync(string? message = null, string? title = null)
{
if (message != null) Message = message;
if (title != null) Title = title;
_visible = true;
_tcs = new TaskCompletionSource<bool>();
StateHasChanged();
return _tcs.Task;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (_visible && !_bodyLocked)
{
_bodyLocked = true;
await TryLockBodyAsync();
// Focus the modal so the @onkeydown handler receives Escape.
try { await _modalRef.FocusAsync(); }
catch { /* prerender or detached: ignore */ }
}
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
await CancelAsync();
}
}
private void Confirm()
{
Close(true);
}
private void Cancel()
{
Close(false);
}
private Task CancelAsync()
{
Close(false);
return Task.CompletedTask;
}
private void Close(bool result)
{
_visible = false;
_ = TryUnlockBodyAsync();
_tcs?.TrySetResult(result);
}
private async Task TryLockBodyAsync()
{
try
{
await JS.InvokeVoidAsync("document.body.classList.add", "modal-open");
}
catch
{
// Prerendering has no JS runtime; log only.
try { await JS.InvokeVoidAsync("console.debug", "ConfirmDialog: JS interop unavailable for body lock."); }
catch { /* swallow */ }
}
}
private async Task TryUnlockBodyAsync()
{
_bodyLocked = false;
try
{
await JS.InvokeVoidAsync("document.body.classList.remove", "modal-open");
}
catch
{
try { await JS.InvokeVoidAsync("console.debug", "ConfirmDialog: JS interop unavailable for body unlock."); }
catch { /* swallow */ }
}
}
public async ValueTask DisposeAsync()
{
if (_bodyLocked)
{
await TryUnlockBodyAsync();
}
}
}

View File

@@ -0,0 +1,136 @@
@* Single global host component for IDialogService. Mounted once in MainLayout.
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
@inject IDialogService Service
@inject IJSRuntime JS
@if (Service is DialogService svc && svc.Current is { } state)
{
<div class="modal-backdrop fade show"></div>
<div @ref="_modalRef"
class="modal fade show d-block"
tabindex="-1"
role="dialog"
aria-modal="true"
@onkeydown="OnKeyDown">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 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>
}
else
{
<label class="form-label">@state.Body</label>
<input class="form-control form-control-sm"
placeholder="@state.Placeholder"
value="@_promptValue"
@oninput="OnPromptInput" />
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary btn-sm" @onclick="Cancel">Cancel</button>
<button type="button"
class="btn @(state.Danger ? "btn-danger" : "btn-primary") btn-sm"
@onclick="Confirm">
@ConfirmLabel(state)
</button>
</div>
</div>
</div>
</div>
}
@code {
private ElementReference _modalRef;
private string _promptValue = string.Empty;
private DialogState? _lastSeenState;
protected override void OnInitialized()
{
// OnChange lives on the concrete DialogService — the interface stays
// narrow (just ConfirmAsync / PromptAsync). DI hands us the concrete
// instance, so a cast here is safe.
if (Service is DialogService svc) svc.OnChange += OnServiceChanged;
}
public void Dispose()
{
if (Service is DialogService svc) svc.OnChange -= OnServiceChanged;
}
private void OnServiceChanged()
{
// Seed prompt input value when a new prompt dialog opens.
if (Service is DialogService s && s.Current is { Kind: DialogKind.Prompt } promptState
&& !ReferenceEquals(promptState, _lastSeenState))
{
_promptValue = promptState.PromptInitial;
}
_lastSeenState = (Service as DialogService)?.Current;
InvokeAsync(StateHasChanged);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var current = (Service as DialogService)?.Current;
if (current is not null)
{
try { await JS.InvokeVoidAsync("document.body.classList.add", "modal-open"); }
catch { /* prerender: no JS — ignore */ }
try { await _modalRef.FocusAsync(); }
catch { /* element not yet attached: ignore */ }
}
else
{
try { await JS.InvokeVoidAsync("document.body.classList.remove", "modal-open"); }
catch { /* prerender: no JS — ignore */ }
}
}
private void OnKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
Cancel();
}
}
private void OnPromptInput(ChangeEventArgs e)
{
_promptValue = e.Value?.ToString() ?? string.Empty;
}
private void Cancel()
{
if (Service is not DialogService svc || svc.Current is null) return;
var resolveValue = svc.Current.Kind == DialogKind.Confirm
? (object)false
: (object?)null;
_promptValue = string.Empty;
svc.Resolve(resolveValue);
}
private void Confirm()
{
if (Service is not DialogService svc || svc.Current is null) return;
var resolveValue = svc.Current.Kind == DialogKind.Confirm
? (object)true
: (object?)_promptValue;
_promptValue = string.Empty;
svc.Resolve(resolveValue);
}
private static string ConfirmLabel(DialogState state) => state.Kind switch
{
DialogKind.Prompt => "Save",
_ => state.Danger ? "Delete" : "Confirm",
};
}

View File

@@ -0,0 +1,94 @@
namespace ScadaLink.CentralUI.Components.Shared;
/// <summary>
/// Default <see cref="IDialogService"/> implementation. Holds the currently
/// open dialog state in <see cref="Current"/> and notifies subscribers (the
/// <c>DialogHost</c> component) via <see cref="OnChange"/>. Only a single
/// dialog can be open at a time; attempting to open another while one is
/// already active throws <see cref="InvalidOperationException"/> — there is
/// no nested-dialog use case today and surfacing the bug is preferable to
/// silently queuing.
/// </summary>
public class DialogService : IDialogService
{
/// <summary>
/// Raised whenever <see cref="Current"/> changes (dialog opened or closed).
/// The host component subscribes and calls <c>StateHasChanged</c>.
/// </summary>
public event Action? OnChange;
/// <summary>
/// The dialog currently being displayed, or <c>null</c> when no dialog is
/// open. The host reads this to decide what (if anything) to render.
/// </summary>
public DialogState? Current { get; private set; }
private TaskCompletionSource<object?>? _tcs;
public Task<bool> ConfirmAsync(string title, string message, bool danger = false)
{
EnsureNoActiveDialog();
var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
_tcs = tcs;
Current = new DialogState(title, DialogKind.Confirm, message, danger, PromptInitial: string.Empty, Placeholder: null);
OnChange?.Invoke();
return tcs.Task.ContinueWith(t => t.Result is bool b && b, TaskScheduler.Default);
}
public Task<string?> PromptAsync(string title, string label, string initialValue = "", string? placeholder = null)
{
EnsureNoActiveDialog();
var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
_tcs = tcs;
Current = new DialogState(title, DialogKind.Prompt, label, Danger: false, PromptInitial: initialValue, Placeholder: placeholder);
OnChange?.Invoke();
return tcs.Task.ContinueWith(t => t.Result as string, TaskScheduler.Default);
}
/// <summary>
/// Called by the host component when the user dismisses or confirms the
/// dialog. <paramref name="result"/> must be a <c>bool</c> for confirms
/// and a <c>string?</c> for prompts (null = cancel).
/// </summary>
internal void Resolve(object? result)
{
var tcs = _tcs;
_tcs = null;
Current = null;
OnChange?.Invoke();
tcs?.TrySetResult(result);
}
private void EnsureNoActiveDialog()
{
if (Current is not null)
{
throw new InvalidOperationException(
"A dialog is already open. IDialogService does not support nested dialogs.");
}
}
}
/// <summary>
/// Snapshot of a dialog's display state, exposed read-only on
/// <see cref="DialogService.Current"/> for the host component to render.
/// </summary>
/// <param name="Title">Modal title text.</param>
/// <param name="Kind">Discriminates between confirm and prompt rendering.</param>
/// <param name="Body">For confirm: the message; for prompt: the input label.</param>
/// <param name="Danger">When true, the confirm button uses danger styling.</param>
/// <param name="PromptInitial">Initial value for prompt-kind dialogs.</param>
/// <param name="Placeholder">Placeholder shown when the prompt input is empty.</param>
public record DialogState(
string Title,
DialogKind Kind,
string Body,
bool Danger,
string PromptInitial,
string? Placeholder);
public enum DialogKind
{
Confirm,
Prompt
}

View File

@@ -0,0 +1,32 @@
namespace ScadaLink.CentralUI.Components.Shared;
/// <summary>
/// Centralised dialog/modal service. Pages inject this service and call
/// <see cref="ConfirmAsync"/> or <see cref="PromptAsync"/> programmatically
/// instead of embedding per-page modal components. A single <c>DialogHost</c>
/// rendered in <c>MainLayout</c> displays the resulting dialog state.
/// </summary>
public interface IDialogService
{
/// <summary>
/// Shows a confirmation dialog and resolves to <c>true</c> when the user
/// confirms, or <c>false</c> when the user cancels (button click, Escape,
/// or backdrop dismiss).
/// </summary>
/// <param name="title">Modal title text.</param>
/// <param name="message">Body text shown to the user.</param>
/// <param name="danger">When <c>true</c>, the confirm button renders in
/// <c>btn-danger</c> styling with the label "Delete"; otherwise a primary
/// "Confirm" button is shown.</param>
Task<bool> ConfirmAsync(string title, string message, bool danger = false);
/// <summary>
/// Shows a single-line text prompt and resolves to the entered value, or
/// <c>null</c> if the user cancels.
/// </summary>
/// <param name="title">Modal title text.</param>
/// <param name="label">Label rendered above the input field.</param>
/// <param name="initialValue">Pre-populated value for the input field.</param>
/// <param name="placeholder">Optional placeholder shown when the input is empty.</param>
Task<string?> PromptAsync(string title, string label, string initialValue = "", string? placeholder = null);
}

View File

@@ -1,53 +0,0 @@
@if (IsVisible)
{
<div class="modal-backdrop fade show"></div>
<div class="modal fade show d-block" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">New Folder</h6>
<button type="button" class="btn-close" @onclick="Close"></button>
</div>
<div class="modal-body">
<input class="form-control form-control-sm" placeholder="Folder name" @bind="_name" />
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-1">@ErrorMessage</div> }
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit">Create</button>
</div>
</div>
</div>
</div>
}
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
[Parameter] public int? ParentFolderId { get; set; }
[Parameter] public string? ErrorMessage { get; set; }
[Parameter] public EventCallback<(int? ParentFolderId, string Name)> OnSubmit { get; set; }
private bool _wasVisible;
private string _name = string.Empty;
protected override void OnParametersSet()
{
// Reset internal state on transition from hidden -> visible.
if (IsVisible && !_wasVisible)
{
_name = string.Empty;
}
_wasVisible = IsVisible;
}
private async Task Close()
{
await IsVisibleChanged.InvokeAsync(false);
}
private async Task Submit()
{
await OnSubmit.InvokeAsync((ParentFolderId, _name.Trim()));
}
}