refactor(centralui): migrate Move/Rename/Compose dialogs to DialogService.ShowAsync host (T33b)

This commit is contained in:
Joseph Doherty
2026-06-18 19:53:19 -04:00
parent c8915e8638
commit e0d085481f
9 changed files with 327 additions and 464 deletions
@@ -42,12 +42,6 @@
<ToastNotification @ref="_toast" />
<MoveDataConnectionDialog @bind-IsVisible="_showMoveDialog"
ConnectionId="_moveConnectionId"
ConnectionName="@_moveConnectionName"
SiteOptions="MoveTargetSiteOptions()"
OnMoved="OnConnectionMoved" />
@if (_loading)
{
<LoadingSpinner IsLoading="true" />
@@ -425,37 +419,37 @@
}
}
// ── M9-T24b: Move connection to another site ──
// The dialog dispatches MoveDataConnectionCommand through the guard-running
// ManagementActor path (IDataConnectionMoveService) — NOT a direct repository
// write — so the server enforces the Designer gate and every move guard. The
// page only opens the dialog, supplies the candidate target sites (the current
// site excluded), and reloads the tree once the move succeeds.
private bool _showMoveDialog;
private int _moveConnectionId;
private int _moveConnectionSiteId;
private string _moveConnectionName = string.Empty;
private void OpenMoveDialog(DataConnection conn)
// ── M9-T24b / T33b: Move connection to another site ──
// Opened via IDialogService.ShowAsync. The body dispatches MoveDataConnectionCommand
// through the guard-running ManagementActor path (IDataConnectionMoveService) — NOT
// a direct repository write — so the server enforces the Designer gate and every
// move guard, showing any guard error inline and staying open. On success the body
// closes with true; the page then toasts and reloads the tree.
private async Task OpenMoveDialog(DataConnection conn)
{
_moveConnectionId = conn.Id;
_moveConnectionSiteId = conn.SiteId;
_moveConnectionName = conn.Name;
_showMoveDialog = true;
var connId = conn.Id;
var connName = conn.Name;
var options = MoveTargetSiteOptions(conn.SiteId);
var moved = await Dialog.ShowAsync<bool>(
$"Move '{connName}' to site…",
ctx => @<MoveDataConnectionDialog Context="ctx"
ConnectionId="connId"
ConnectionName="@connName"
SiteOptions="options" />);
if (moved)
{
_toast.ShowSuccess($"Connection '{connName}' moved.");
await LoadDataAsync();
}
}
// Candidate target sites for the move: every site EXCEPT the connection's
// current one. Sourced from the already-loaded tree roots (each root is a site).
private IEnumerable<(int Id, string Label)> MoveTargetSiteOptions() =>
private IEnumerable<(int Id, string Label)> MoveTargetSiteOptions(int currentSiteId) =>
_treeRoots
.Where(r => r.SiteId is int sid && sid != _moveConnectionSiteId)
.Select(r => (r.SiteId!.Value, r.Label));
private async Task OnConnectionMoved()
{
_toast.ShowSuccess($"Connection '{_moveConnectionName}' moved.");
await LoadDataAsync();
}
.Where(r => r.SiteId is int sid && sid != currentSiteId)
.Select(r => (r.SiteId!.Value, r.Label))
.ToList();
// M9-T25: enum → Bootstrap badge class. Mirrors the Health dashboard's
// GetConnectionHealthBadge (Components/Pages/Monitoring/Health.razor) so the
@@ -17,33 +17,6 @@
<div class="container-fluid mt-3">
<ToastNotification @ref="_toast" />
<RenameFolderDialog @bind-IsVisible="_showRenameFolderDialog"
FolderId="_renameFolderId"
InitialName="@_renameFolderInitialName"
ErrorMessage="@_renameFolderError"
OnSubmit="SubmitRenameFolder" />
<MoveTemplateDialog @bind-IsVisible="_showMoveTemplateDialog"
TemplateId="_moveTemplateId"
TemplateName="@_moveTemplateName"
FolderOptions="EnumerateFolderOptions()"
ErrorMessage="@_moveTemplateError"
OnSubmit="SubmitMoveTemplate" />
<MoveFolderDialog @bind-IsVisible="_showMoveFolderDialog"
FolderId="_moveFolderId"
FolderName="@_moveFolderName"
FolderOptions="EnumerateFolderOptionsExcluding(_moveFolderId)"
ErrorMessage="@_moveFolderError"
OnSubmit="SubmitMoveFolder" />
<ComposeIntoDialog @bind-IsVisible="_showComposeDialog"
SourceTemplateId="_composeSourceId"
SourceName="@_composeSourceName"
ParentOptions="EnumerateComposableParents(_composeSourceId)"
ErrorMessage="@_composeError"
OnSubmit="SubmitCompose" />
@if (_loading)
{
<LoadingSpinner IsLoading="true" />
@@ -314,34 +287,26 @@
}
}
// Move-template dialog state
private bool _showMoveTemplateDialog;
private int _moveTemplateId;
private string _moveTemplateName = string.Empty;
private string? _moveTemplateError;
private void OpenMoveTemplateDialog(int templateId, string label)
// Move-template dialog: opened via IDialogService.ShowAsync. The body returns
// the picked folder id (null = Root) on Move, or null on Cancel; validation runs
// here after the dialog closes and surfaces server guard failures via a toast.
private async Task OpenMoveTemplateDialog(int templateId, string label)
{
_moveTemplateId = templateId;
_moveTemplateName = label;
_moveTemplateError = null;
_showMoveTemplateDialog = true;
}
var result = await Dialog.ShowAsync<MoveTemplateDialog.MoveTemplateResult>(
$"Move '{label}' to…",
ctx => @<MoveTemplateDialog Context="ctx" FolderOptions="EnumerateFolderOptions()" />);
if (result is null) return;
private async Task SubmitMoveTemplate((int TemplateId, int? NewFolderId) req)
{
_moveTemplateError = null;
var user = await GetCurrentUserAsync();
var result = await TemplateService.MoveTemplateAsync(req.TemplateId, req.NewFolderId, user);
if (result.IsSuccess)
var moved = await TemplateService.MoveTemplateAsync(templateId, result.NewFolderId, user);
if (moved.IsSuccess)
{
_showMoveTemplateDialog = false;
_toast.ShowSuccess($"Template '{_moveTemplateName}' moved.");
_toast.ShowSuccess($"Template '{label}' moved.");
await LoadTemplatesAsync();
}
else
{
_moveTemplateError = result.Error;
_toast.ShowError(moved.Error);
}
}
@@ -373,34 +338,27 @@
}
}
// Move-folder dialog state
private bool _showMoveFolderDialog;
private int _moveFolderId;
private string _moveFolderName = string.Empty;
private string? _moveFolderError;
private void OpenMoveFolderDialog(int folderId, string label)
// Move-folder dialog: opened via IDialogService.ShowAsync. The picker prunes the
// folder + its descendants (server still validates cycles). The body returns the
// picked parent id (null = Root) on Move, or null on Cancel; server guard failures
// surface via a toast.
private async Task OpenMoveFolderDialog(int folderId, string label)
{
_moveFolderId = folderId;
_moveFolderName = label;
_moveFolderError = null;
_showMoveFolderDialog = true;
}
var result = await Dialog.ShowAsync<MoveFolderDialog.MoveFolderResult>(
$"Move '{label}' to…",
ctx => @<MoveFolderDialog Context="ctx" FolderOptions="EnumerateFolderOptionsExcluding(folderId)" />);
if (result is null) return;
private async Task SubmitMoveFolder((int FolderId, int? NewParentId) req)
{
_moveFolderError = null;
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.MoveFolderAsync(req.FolderId, req.NewParentId, user);
if (result.IsSuccess)
var moved = await TemplateFolderService.MoveFolderAsync(folderId, result.NewParentId, user);
if (moved.IsSuccess)
{
_showMoveFolderDialog = false;
_toast.ShowSuccess($"Folder '{_moveFolderName}' moved.");
_toast.ShowSuccess($"Folder '{label}' moved.");
await LoadTemplatesAsync();
}
else
{
_moveFolderError = result.Error;
_toast.ShowError(moved.Error);
}
}
@@ -467,34 +425,27 @@
private void DismissRootContextMenu() => _showRootMenu = false;
// Rename folder dialog state
private bool _showRenameFolderDialog;
private int _renameFolderId;
private string _renameFolderInitialName = string.Empty;
private string? _renameFolderError;
private void OpenRenameFolderDialog(int folderId, string currentName)
// Rename folder dialog: opened via IDialogService.ShowAsync. The body seeds the
// input from the current name and returns the trimmed new name on Save, or null on
// Cancel; server guard failures surface via a toast.
private async Task OpenRenameFolderDialog(int folderId, string currentName)
{
_renameFolderId = folderId;
_renameFolderInitialName = currentName;
_renameFolderError = null;
_showRenameFolderDialog = true;
}
var newName = await Dialog.ShowAsync<string>(
"Rename Folder",
ctx => @<RenameFolderDialog Context="ctx" InitialName="@currentName" />,
size: "modal-sm");
if (string.IsNullOrWhiteSpace(newName)) return;
private async Task SubmitRenameFolder((int FolderId, string NewName) req)
{
_renameFolderError = null;
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.RenameFolderAsync(req.FolderId, req.NewName, user);
var result = await TemplateFolderService.RenameFolderAsync(folderId, newName, user);
if (result.IsSuccess)
{
_showRenameFolderDialog = false;
_toast.ShowSuccess("Folder renamed.");
await LoadTemplatesAsync();
}
else
{
_renameFolderError = result.Error;
_toast.ShowError(result.Error);
}
}
@@ -545,17 +496,31 @@
}
// ---- Compose-into dialog ----
private bool _showComposeDialog;
private int _composeSourceId;
private string _composeSourceName = string.Empty;
private string? _composeError;
private void OpenComposeDialog(Template source)
// Opened via IDialogService.ShowAsync. The body returns the chosen parent template
// + slot name on Compose (its own client-side guard keeps the button disabled until
// both are set), or null on Cancel; server guard failures surface via a toast.
private async Task OpenComposeDialog(Template source)
{
_composeSourceId = source.Id;
_composeSourceName = source.Name;
_composeError = null;
_showComposeDialog = true;
var sourceId = source.Id;
var sourceName = source.Name;
var result = await Dialog.ShowAsync<ComposeIntoDialog.ComposeResult>(
$"Compose '{sourceName}' into…",
ctx => @<ComposeIntoDialog Context="ctx"
SourceName="@sourceName"
ParentOptions="EnumerateComposableParents(sourceId)" />);
if (result is null) return;
var user = await GetCurrentUserAsync();
var composed = await TemplateService.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user);
if (composed.IsSuccess)
{
_toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'.");
await LoadTemplatesAsync();
}
else
{
_toast.ShowError(composed.Error);
}
}
// Possible parents for a compose: every non-derived template except the source itself.
@@ -568,23 +533,6 @@
.Select(t => (t.Id, t.Name));
}
private async Task SubmitCompose((int SourceTemplateId, int ParentTemplateId, string SlotName) req)
{
_composeError = null;
var user = await GetCurrentUserAsync();
var result = await TemplateService.AddCompositionAsync(req.ParentTemplateId, req.SourceTemplateId, req.SlotName, user);
if (result.IsSuccess)
{
_showComposeDialog = false;
_toast.ShowSuccess($"Composed '{_composeSourceName}' as '{req.SlotName}'.");
await LoadTemplatesAsync();
}
else
{
_composeError = result.Error;
}
}
// ---- Composition leaf: rename + delete ----
private async Task RenameComposition(TemplateComposition composition)
{
@@ -1,68 +1,57 @@
@if (IsVisible)
{
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Compose '@SourceName' into…</h6>
<button type="button" class="btn-close" @onclick="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label small text-muted mb-1">Parent template</label>
<select class="form-select form-select-sm" @bind="_parentTemplateId">
<option value="0" disabled selected>Select a parent template…</option>
@foreach (var opt in ParentOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
</div>
<div class="mb-1">
<label class="form-label small text-muted mb-1">Slot name</label>
<input type="text" class="form-control form-control-sm"
placeholder="Slot name"
@bind="_slotName" />
</div>
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-2">@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" disabled="@(_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName))">Compose</button>
</div>
</div>
</div>
</div>
}
@*
T33b: body component for the "Compose into" dialog hosted by
IDialogService.ShowAsync. Renders ONLY the parent/slot fields + action buttons
inside the host's .modal-body; the host owns the backdrop, header, and focus
trap. Closes with a ComposeResult (parent template id + slot name); Cancel
resolves to null. The Compose button stays disabled until both a parent and a
non-blank slot are chosen (client-side guard, preserved from the original).
Server-side compose failures are surfaced by the parent via a toast.
*@
<div class="mb-3">
<label class="form-label small text-muted mb-1">Parent template</label>
<select class="form-select form-select-sm" @bind="_parentTemplateId">
<option value="0" disabled selected>Select a parent template…</option>
@foreach (var opt in ParentOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
</div>
<div class="mb-1">
<label class="form-label small text-muted mb-1">Slot name</label>
<input type="text" class="form-control form-control-sm"
placeholder="Slot name"
@bind="_slotName" @bind:event="oninput" />
</div>
<div class="modal-footer px-0 pb-0 mt-3">
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit"
disabled="@(_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName))">Compose</button>
</div>
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
[Parameter] public int SourceTemplateId { get; set; }
/// <summary>Host-supplied context used to close (with the chosen parent + slot) or cancel.</summary>
[Parameter] public DialogContext<ComposeResult> Context { get; set; } = default!;
[Parameter] public string SourceName { get; set; } = string.Empty;
[Parameter] public IEnumerable<(int Id, string Label)> ParentOptions { get; set; } = Array.Empty<(int, string)>();
[Parameter] public string? ErrorMessage { get; set; }
[Parameter] public EventCallback<(int SourceTemplateId, int ParentTemplateId, string SlotName)> OnSubmit { get; set; }
private bool _wasVisible;
private int _parentTemplateId;
private string _slotName = string.Empty;
protected override void OnParametersSet()
{
if (IsVisible && !_wasVisible)
{
_parentTemplateId = 0;
_slotName = SourceName;
}
_wasVisible = IsVisible;
}
protected override void OnInitialized() => _slotName = SourceName;
private async Task Close() => await IsVisibleChanged.InvokeAsync(false);
private async Task Submit()
private void Submit()
{
if (_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName)) return;
await OnSubmit.InvokeAsync((SourceTemplateId, _parentTemplateId, _slotName.Trim()));
Context.Close(new ComposeResult(_parentTemplateId, _slotName.Trim()));
}
/// <summary>
/// Result of the compose picker: the parent template to compose into and the
/// slot name. ShowAsync resolves to this record on Compose, or <c>null</c> on Cancel.
/// </summary>
/// <param name="ParentTemplateId">The template the source is composed into.</param>
/// <param name="SlotName">The trimmed slot (composition instance) name.</param>
public sealed record ComposeResult(int ParentTemplateId, string SlotName);
}
@@ -2,84 +2,55 @@
@inject IDataConnectionMoveService MoveService
@*
M9-T24b: Move a data connection to another site. The picker lists the candidate
target sites (the page excludes the connection's current site). On confirm the
dialog dispatches MoveDataConnectionCommand through IDataConnectionMoveService —
the guard-running ManagementActor path, NOT a direct repository write — so the
server's Designer gate and every move guard (target exists, no name collision, no
instance binding, no native-alarm-source name reference) run. A guard error is
shown inline and the dialog stays open; success closes the dialog and raises
OnMoved so the page reloads the tree. Mirrors the MoveFolderDialog idiom.
M9-T24b / T33b: body component for the "Move data connection" dialog hosted by
IDialogService.ShowAsync. Renders ONLY the site picker + action buttons inside
the host's .modal-body; the host owns the backdrop, header, and focus trap.
The body still injects IDataConnectionMoveService and dispatches the
MoveDataConnectionCommand through the guard-running ManagementActor path (NOT a
direct repository write) so the server's Designer gate and every move guard run.
A guard error is shown inline and the dialog STAYS OPEN; success closes the
dialog with Close(true) so the parent reloads the tree. Cancel resolves to false.
*@
@if (IsVisible)
@if (SiteOptions.Any())
{
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Move '@ConnectionName' to site…</h6>
<button type="button" class="btn-close" @onclick="Close" disabled="@_busy"></button>
</div>
<div class="modal-body">
@if (SiteOptions.Any())
{
<select class="form-select form-select-sm" @bind="_targetSiteId">
@foreach (var opt in SiteOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
}
else
{
<div class="text-muted small">No other site is available to move this connection to.</div>
}
@if (!string.IsNullOrEmpty(_error))
{
<div class="text-danger small mt-2" data-test="move-connection-error">@_error</div>
}
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-sm" @onclick="Close" disabled="@_busy">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit"
disabled="@(_busy || !SiteOptions.Any())">Move</button>
</div>
</div>
</div>
</div>
<select class="form-select form-select-sm" @bind="_targetSiteId">
@foreach (var opt in SiteOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
}
else
{
<div class="text-muted small">No other site is available to move this connection to.</div>
}
@if (!string.IsNullOrEmpty(_error))
{
<div class="text-danger small mt-2" data-test="move-connection-error">@_error</div>
}
<div class="modal-footer px-0 pb-0 mt-3">
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()" disabled="@_busy">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit"
disabled="@(_busy || !SiteOptions.Any())">Move</button>
</div>
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
/// <summary>Host-supplied context: Close(true) on a successful move, Cancel on dismiss.</summary>
[Parameter] public DialogContext<bool> Context { get; set; } = default!;
[Parameter] public int ConnectionId { get; set; }
[Parameter] public string ConnectionName { get; set; } = string.Empty;
[Parameter] public IEnumerable<(int Id, string Label)> SiteOptions { get; set; } = Array.Empty<(int, string)>();
/// <summary>Raised after a successful move so the page can reload the tree.</summary>
[Parameter] public EventCallback OnMoved { get; set; }
private bool _wasVisible;
private int? _targetSiteId;
private string? _error;
private bool _busy;
protected override void OnParametersSet()
protected override void OnInitialized()
{
// Reset internal state on transition from hidden -> visible: default the
// picker to the first candidate site and clear any prior error.
if (IsVisible && !_wasVisible)
{
_targetSiteId = SiteOptions.Select(o => (int?)o.Id).FirstOrDefault();
_error = null;
_busy = false;
}
_wasVisible = IsVisible;
}
private async Task Close()
{
await IsVisibleChanged.InvokeAsync(false);
// Default the picker to the first candidate site.
_targetSiteId = SiteOptions.Select(o => (int?)o.Id).FirstOrDefault();
}
private async Task Submit()
@@ -94,8 +65,9 @@
if (result.Success)
{
await IsVisibleChanged.InvokeAsync(false);
await OnMoved.InvokeAsync();
// Success closes the dialog; the parent's post-ShowAsync block toasts
// and reloads the tree.
Context.Close(true);
}
else
{
@@ -1,58 +1,38 @@
@if (IsVisible)
{
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Move '@FolderName' to…</h6>
<button type="button" class="btn-close" @onclick="Close"></button>
</div>
<div class="modal-body">
<select class="form-select form-select-sm" @bind="_targetParentId">
@foreach (var opt in FolderOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
@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">Move</button>
</div>
</div>
</div>
</div>
}
@*
T33b: body component for the "Move folder" dialog hosted by
IDialogService.ShowAsync. Renders ONLY the picker + action buttons inside the
host's .modal-body; the host owns the backdrop, header, and focus trap. The
body closes with a MoveFolderResult carrying the picked parent id (null = Root,
which is why a result record is used: Close(null) would otherwise be
indistinguishable from a Cancel). The parent validates after the dialog closes
and toasts any server guard failure.
*@
<select class="form-select form-select-sm" @bind="_targetParentId">
@foreach (var opt in FolderOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
<div class="modal-footer px-0 pb-0 mt-3">
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
</div>
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
[Parameter] public int FolderId { get; set; }
[Parameter] public string FolderName { get; set; } = string.Empty;
/// <summary>Host-supplied context used to close (with the picked parent id) or cancel.</summary>
[Parameter] public DialogContext<MoveFolderResult> Context { get; set; } = default!;
[Parameter] public IEnumerable<(int? Id, string Label)> FolderOptions { get; set; } = Array.Empty<(int?, string)>();
[Parameter] public string? ErrorMessage { get; set; }
[Parameter] public EventCallback<(int FolderId, int? NewParentId)> OnSubmit { get; set; }
private bool _wasVisible;
private int? _targetParentId;
protected override void OnParametersSet()
{
if (IsVisible && !_wasVisible)
{
_targetParentId = null;
}
_wasVisible = IsVisible;
}
private void Submit() => Context.Close(new MoveFolderResult(_targetParentId));
private async Task Close()
{
await IsVisibleChanged.InvokeAsync(false);
}
private async Task Submit()
{
await OnSubmit.InvokeAsync((FolderId, _targetParentId));
}
/// <summary>
/// Result of the move-folder picker. A reference type so a non-null close is
/// distinguishable from a cancel even when the picked parent is null (Root):
/// ShowAsync resolves to this record on Move and to <c>null</c> on Cancel.
/// </summary>
/// <param name="NewParentId">The chosen parent folder id, or <c>null</c> for Root.</param>
public sealed record MoveFolderResult(int? NewParentId);
}
@@ -1,59 +1,36 @@
@if (IsVisible)
{
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Move '@TemplateName' to…</h6>
<button type="button" class="btn-close" @onclick="Close"></button>
</div>
<div class="modal-body">
<select class="form-select form-select-sm" @bind="_targetFolderId">
@foreach (var opt in FolderOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
@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">Move</button>
</div>
</div>
</div>
</div>
}
@*
T33b: body component for the "Move template" dialog hosted by
IDialogService.ShowAsync. Renders ONLY the picker + action buttons inside the
host's .modal-body; the host owns the backdrop, header, and focus trap. Closes
with a MoveTemplateResult carrying the picked folder id (null = Root) — a result
record so Close(null) for the Root choice stays distinguishable from a Cancel.
*@
<select class="form-select form-select-sm" @bind="_targetFolderId">
@foreach (var opt in FolderOptions)
{
<option value="@opt.Id">@opt.Label</option>
}
</select>
<div class="modal-footer px-0 pb-0 mt-3">
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
</div>
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
[Parameter] public int TemplateId { get; set; }
[Parameter] public string TemplateName { get; set; } = string.Empty;
/// <summary>Host-supplied context used to close (with the picked folder id) or cancel.</summary>
[Parameter] public DialogContext<MoveTemplateResult> Context { get; set; } = default!;
[Parameter] public IEnumerable<(int? Id, string Label)> FolderOptions { get; set; } = Array.Empty<(int?, string)>();
[Parameter] public string? ErrorMessage { get; set; }
[Parameter] public EventCallback<(int TemplateId, int? NewFolderId)> OnSubmit { get; set; }
private bool _wasVisible;
private int? _targetFolderId;
protected override void OnParametersSet()
{
// Reset internal state on transition from hidden -> visible.
if (IsVisible && !_wasVisible)
{
_targetFolderId = null;
}
_wasVisible = IsVisible;
}
private void Submit() => Context.Close(new MoveTemplateResult(_targetFolderId));
private async Task Close()
{
await IsVisibleChanged.InvokeAsync(false);
}
private async Task Submit()
{
await OnSubmit.InvokeAsync((TemplateId, _targetFolderId));
}
/// <summary>
/// Result of the move-template picker. A reference type so a non-null close is
/// distinguishable from a cancel even when the picked folder is null (Root):
/// ShowAsync resolves to this record on Move and to <c>null</c> on Cancel.
/// </summary>
/// <param name="NewFolderId">The chosen destination folder id, or <c>null</c> for Root.</param>
public sealed record MoveTemplateResult(int? NewFolderId);
}
@@ -1,53 +1,31 @@
@if (IsVisible)
{
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Rename Folder</h6>
<button type="button" class="btn-close" @onclick="Close"></button>
</div>
<div class="modal-body">
<input class="form-control form-control-sm" @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">Save</button>
</div>
</div>
</div>
</div>
}
@*
T33b: body component for the "Rename folder" dialog hosted by
IDialogService.ShowAsync. Renders ONLY the input + action buttons inside the
host's .modal-body; the host owns the backdrop, header, and focus trap. Closes
with the trimmed new name (string); Cancel resolves to null. Save is disabled
while the field is blank (client-side guard); server-side rename failures are
surfaced by the parent via a toast.
*@
<input class="form-control form-control-sm" @bind="_name" @bind:event="oninput" />
<div class="modal-footer px-0 pb-0 mt-3">
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
<button class="btn btn-primary btn-sm" @onclick="Submit"
disabled="@string.IsNullOrWhiteSpace(_name)">Save</button>
</div>
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
[Parameter] public int FolderId { get; set; }
/// <summary>Host-supplied context used to close (with the trimmed name) or cancel.</summary>
[Parameter] public DialogContext<string> Context { get; set; } = default!;
[Parameter] public string InitialName { get; set; } = string.Empty;
[Parameter] public string? ErrorMessage { get; set; }
[Parameter] public EventCallback<(int FolderId, string NewName)> 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 = InitialName;
}
_wasVisible = IsVisible;
}
protected override void OnInitialized() => _name = InitialName;
private async Task Close()
private void Submit()
{
await IsVisibleChanged.InvokeAsync(false);
}
private async Task Submit()
{
await OnSubmit.InvokeAsync((FolderId, _name.Trim()));
if (string.IsNullOrWhiteSpace(_name)) return;
Context.Close(_name.Trim());
}
}
@@ -250,13 +250,21 @@ public class DataConnectionsPageTests : BunitContext
},
connections: new[] { new DataConnection("PLC-1", "OpcUa", 1) { Id = 100 } });
// T33b: the move dialog is now opened via IDialogService.ShowAsync and rendered
// by the shared DialogHost (which lives in MainLayout in production). Render a
// host in the same DI scope so the dialog the page opens is displayed; the host's
// focus-trap JS interop runs as no-ops under loose mode.
JSInterop.Mode = JSRuntimeMode.Loose;
var host = Render<DialogHost>();
var cut = Render<DataConnectionsPage>();
FindToggleForLabel(cut, "Plant-A")!.Click();
cut.FindAll("button").First(b => b.TextContent.Contains("Move to Site")).Click();
host.Render();
// The dialog renders with a site picker; the current site is excluded.
var dialog = cut.Find(".modal.show");
var dialog = host.Find(".modal.show");
var optionLabels = dialog.QuerySelectorAll("select option")
.Select(o => o.TextContent).ToList();
Assert.Contains(optionLabels, l => l.Contains("Plant-B"));
@@ -8,65 +8,87 @@ using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Shared;
/// <summary>
/// bUnit tests for the <see cref="MoveDataConnectionDialog"/> (M9-T24b). The dialog
/// surfaces a target-site picker (excluding the connection's current site) and, on
/// confirm, dispatches a <c>MoveDataConnectionCommand</c> through the management
/// path via <see cref="IDataConnectionMoveService"/> — the SAME guard-running seam
/// the server uses. A guard error must be shown inline and the dialog must stay open;
/// a success must close the dialog and raise the refresh signal.
/// bUnit tests for the <see cref="MoveDataConnectionDialog"/> body component
/// (M9-T24b, migrated to the DialogService.ShowAsync host in T33b). The dialog is
/// now opened through <see cref="IDialogService.ShowAsync{TResult}"/>: a single
/// <c>DialogHost</c> owns the backdrop/header/focus-trap, and the body renders only
/// the target-site picker (excluding the connection's current site) plus its own
/// action buttons. On confirm the body dispatches a <c>MoveDataConnectionCommand</c>
/// through the management path via <see cref="IDataConnectionMoveService"/> — the
/// SAME guard-running seam the server uses. A guard error must be shown inline and
/// the dialog must stay open (the awaited ShowAsync task must NOT complete); a
/// success must close the dialog and resolve the task with <c>true</c> so the page
/// reloads the tree.
///
/// The service is substituted so the tests capture the dispatched (connectionId,
/// targetSiteId) and simulate both a success and a guard-error response without a
/// real ManagementActor in scope.
/// The tests render a real <see cref="DialogService"/> behind a live
/// <c>DialogHost</c> and open the body via <c>ShowAsync&lt;bool&gt;</c> so the
/// host-driven flow is exercised end to end. The move service is substituted so the
/// tests capture the dispatched (connectionId, targetSiteId) and simulate both a
/// success and a guard-error response without a real ManagementActor in scope. bUnit
/// cannot run real JS interop, so the host's <c>sbDialog.*</c> focus calls run in
/// <see cref="JSRuntimeMode.Loose"/> mode where they become no-ops.
/// </summary>
public class MoveDataConnectionDialogTests : BunitContext
{
private readonly IDataConnectionMoveService _service = Substitute.For<IDataConnectionMoveService>();
private readonly DialogService _dialog = new();
public MoveDataConnectionDialogTests()
{
Services.AddSingleton(_service);
// Register the concrete service as the interface so DialogHost (which injects
// IDialogService and casts to DialogService) resolves the same instance the
// test drives.
Services.AddSingleton<IDialogService>(_dialog);
JSInterop.Mode = JSRuntimeMode.Loose;
}
private IRenderedComponent<MoveDataConnectionDialog> RenderDialog(
/// <summary>
/// Renders a live <c>DialogHost</c> and opens the move dialog via
/// <c>ShowAsync&lt;bool&gt;</c>, returning the rendered host and the pending task
/// the page would await.
/// </summary>
private (IRenderedComponent<DialogHost> Host, Task<bool> Pending) OpenDialog(
IRenderedComponent<DialogHost> host,
int connectionId = 100,
string connectionName = "PLC-1",
bool visible = true,
IEnumerable<(int Id, string Label)>? siteOptions = null,
EventCallback? onMoved = null,
EventCallback<bool>? visibleChanged = null)
IEnumerable<(int Id, string Label)>? siteOptions = null)
{
siteOptions ??= new[] { (2, "Plant-B"), (3, "Plant-C") };
return Render<MoveDataConnectionDialog>(p => p
.Add(d => d.IsVisible, visible)
.Add(d => d.ConnectionId, connectionId)
.Add(d => d.ConnectionName, connectionName)
.Add(d => d.SiteOptions, siteOptions)
.Add(d => d.OnMoved, onMoved ?? default)
.Add(d => d.IsVisibleChanged, visibleChanged ?? default));
Task<bool> pending = null!;
host.InvokeAsync(() =>
{
pending = _dialog.ShowAsync<bool>(
$"Move '{connectionName}' to site…",
ctx => builder =>
{
builder.OpenComponent<MoveDataConnectionDialog>(0);
builder.AddAttribute(1, nameof(MoveDataConnectionDialog.Context), ctx);
builder.AddAttribute(2, nameof(MoveDataConnectionDialog.ConnectionId), connectionId);
builder.AddAttribute(3, nameof(MoveDataConnectionDialog.ConnectionName), connectionName);
builder.AddAttribute(4, nameof(MoveDataConnectionDialog.SiteOptions), siteOptions);
builder.CloseComponent();
});
}).GetAwaiter().GetResult();
host.Render();
return (host, pending);
}
[Fact]
public void Visible_RendersTargetSitePicker_WithSuppliedOptions()
public void ShownViaHost_RendersTargetSitePicker_WithSuppliedOptions()
{
// (a) The dialog opens with a site picker whose options are exactly the
// supplied target sites (the page excludes the connection's current site).
var cut = RenderDialog(siteOptions: new[] { (2, "Plant-B"), (3, "Plant-C") });
// (a) When opened via ShowAsync, the body renders a site picker whose options
// are exactly the supplied target sites (the page excludes the current site),
// and the connection name appears in the host header title.
var host = Render<DialogHost>();
var (cut, _) = OpenDialog(host, siteOptions: new[] { (2, "Plant-B"), (3, "Plant-C") });
var options = cut.FindAll("select option");
Assert.Contains(options, o => o.TextContent.Contains("Plant-B"));
Assert.Contains(options, o => o.TextContent.Contains("Plant-C"));
// Picker reflects the connection name in the header.
Assert.Contains("PLC-1", cut.Markup);
}
[Fact]
public void Hidden_RendersNothing()
{
var cut = RenderDialog(visible: false);
Assert.Empty(cut.Markup.Trim());
}
[Fact]
public void Confirm_DispatchesMoveCommand_WithConnectionAndTargetSiteIds()
{
@@ -75,7 +97,8 @@ public class MoveDataConnectionDialogTests : BunitContext
_service.MoveAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(DataConnectionMoveResult.Ok()));
var cut = RenderDialog(connectionId: 100, siteOptions: new[] { (2, "Plant-B"), (3, "Plant-C") });
var host = Render<DialogHost>();
var (cut, _) = OpenDialog(host, connectionId: 100, siteOptions: new[] { (2, "Plant-B"), (3, "Plant-C") });
// Pick Plant-C (id 3) and confirm.
cut.Find("select").Change("3");
@@ -87,47 +110,41 @@ public class MoveDataConnectionDialogTests : BunitContext
[Fact]
public void GuardError_IsShownInline_AndDialogStaysOpen()
{
// (c) A guard-error response is rendered inline and the dialog does NOT close
// (IsVisibleChanged is not raised with false; OnMoved is not raised).
// (c) A guard-error response is rendered inline and the dialog does NOT close:
// the awaited ShowAsync task stays incomplete (no result resolved).
const string guardError =
"Cannot move data connection 'PLC-1' (ID 100): it is referenced by 1 instance binding(s).";
_service.MoveAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(DataConnectionMoveResult.Fail(guardError)));
var closed = false;
var moved = false;
var cut = RenderDialog(
connectionId: 100,
siteOptions: new[] { (2, "Plant-B") },
onMoved: EventCallback.Factory.Create(this, () => moved = true),
visibleChanged: EventCallback.Factory.Create<bool>(this, v => { if (!v) closed = true; }));
var host = Render<DialogHost>();
var (cut, pending) = OpenDialog(host, connectionId: 100, siteOptions: new[] { (2, "Plant-B") });
cut.Find("select").Change("2");
cut.FindAll("button").First(b => b.TextContent.Contains("Move")).Click();
Assert.Contains(guardError, cut.Markup);
Assert.False(closed, "Dialog must stay open on a guard error.");
Assert.False(moved, "OnMoved must not fire on a guard error.");
Assert.False(pending.IsCompleted, "Dialog must stay open on a guard error.");
// The body is still rendered inside the host (not torn down).
Assert.NotNull(cut.Find("[data-test='move-connection-error']"));
}
[Fact]
public void Success_ClosesDialog_AndRaisesRefreshSignal()
public async Task Success_ClosesDialog_AndResolvesTrue()
{
// (d) A successful move closes the dialog and resolves the awaited task with
// true so the page reloads the tree.
_service.MoveAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(DataConnectionMoveResult.Ok()));
var closed = false;
var moved = false;
var cut = RenderDialog(
connectionId: 100,
siteOptions: new[] { (2, "Plant-B") },
onMoved: EventCallback.Factory.Create(this, () => moved = true),
visibleChanged: EventCallback.Factory.Create<bool>(this, v => { if (!v) closed = true; }));
var host = Render<DialogHost>();
var (cut, pending) = OpenDialog(host, connectionId: 100, siteOptions: new[] { (2, "Plant-B") });
cut.Find("select").Change("2");
cut.FindAll("button").First(b => b.TextContent.Contains("Move")).Click();
Assert.True(closed, "Dialog must close on success.");
Assert.True(moved, "OnMoved must fire on success to refresh the tree.");
var completed = await Task.WhenAny(pending, Task.Delay(TimeSpan.FromSeconds(2)));
Assert.Same(pending, completed);
Assert.True(await pending, "Dialog must resolve true on success so the page refreshes.");
}
}