feat(ui/admin): Topology-style refresh of Data Connections page

Brings the Data Connections admin page up to the same UX standard as the
Topology page:
- Search box with dim non-matches (opacity 0.4, shape preserved)
- Toolbar: + Connection (disabled until a site is selected), Refresh,
  Expand, Collapse
- Site context menu gains "Add Connection here" that navigates with
  ?siteId= so the form preselects + locks the Site field
- Form gains "Primary Endpoint" / "Backup Endpoint" h6 subsection
  headers matching the SiteForm convention; Failover Retry Count moved
  inside the Backup subsection
- URL renamed: /admin/connections (primary) + /admin/data-connections
  (legacy secondary @page). Same dual-route treatment on the form
- Nav label: "Data Connections" -> "Connections"
- Adds DataConnectionsPageTests bUnit suite (6 tests)
This commit is contained in:
Joseph Doherty
2026-05-11 22:42:48 -04:00
parent f3386d0278
commit da5fdf0e63
6 changed files with 447 additions and 45 deletions

View File

@@ -0,0 +1,126 @@
# Data Connections page — Topology-style refresh
Date: 2026-05-11
Status: Design
## Goal
Bring the Data Connections admin page up to the same UX standard as the new Topology page (`/deployment/topology`). The page already uses TreeView and the form already navigates as a separate page, so the refresh is a layered enhancement, not a rewrite.
## Decisions (captured from Q&A)
1. **Features to add** (others explicitly excluded):
- Search with dim non-matches (opacity 0.4, shape preserved — Topology behavior)
- Toolbar: **+ Connection**, **Refresh**, **Expand**, **Collapse**
- **No** per-node icons / protocol badges beyond what's already rendered
- **No** selection persistence via sessionStorage (selection is in-memory only)
2. **Site context menu** gains an "Add Connection here" item that navigates to the create form with `?siteId=N` preselecting and locking the Site field.
3. **+ Connection toolbar button** is **disabled until a site is selected**. Selecting either a site node or one of its connection nodes resolves to that site; the create form then preselects and locks Site.
4. **No move support** — moving a connection between sites is out of scope (would require a net-new service method and has knock-on effects on `InstanceConnectionBinding`).
5. **Empty sites still appear** at the top level (so they can be right-clicked to add a connection).
6. **URL renames**:
- List page: `/admin/connections` (primary) + `/admin/data-connections` (legacy secondary).
- Form: `/admin/connections/create` and `/admin/connections/{Id}/edit` (primary) + `/admin/data-connections/create` and `/admin/data-connections/{Id}/edit` (legacy secondaries).
- Nav menu label changes from "Data Connections" to **"Connections"**.
7. **Form cleanup** to match the canonical `SiteForm.razor` style (per `feedback_form_layout` memory):
- Add explicit `<h6 class="text-muted border-bottom pb-1">` subsection headers: **Primary Endpoint** and **Backup Endpoint**.
- Move Failover Retry Count inside the Backup subsection (it only applies when backup is enabled).
- Site field stays first; read-only in edit mode; preselected & disabled when `?siteId=` is passed on create.
## Files to modify
### `src/ScadaLink.CentralUI/Components/Pages/Admin/DataConnections.razor`
- Add primary route `@page "/admin/connections"` and secondary legacy `@page "/admin/data-connections"`.
- Inject `IJSRuntime` only if needed (search doesn't need it; no sessionStorage).
- Add toolbar row above the tree:
- Search input (`@bind="_searchText" @bind:event="oninput" @bind:after="OnSearchChanged"`)
- btn-group with: **+ Connection** (disabled-bind to `!HasSiteSelected`), **Refresh**, **Expand**, **Collapse**.
- TreeView wiring:
- Add `@ref="_tree"` and use `_tree?.ExpandAll()` / `CollapseAll()`.
- Set `Selectable="true"` and `SelectedKeyChanged="OnTreeNodeSelected"`. Keep selected key in `_selectedKey` (in-memory only).
- Search dim:
- Recompute a `HashSet<string> _matchKeys` of keys whose own label or any descendant's label contains the search text.
- In `NodeContent`, wrap the label `<span>` with `style="opacity: 0.4"` if a search is active and the node is not in `_matchKeys`.
- Always-show-empty sites: current code already creates a Site node per Site regardless of children — keep as-is.
- Site context menu: add an item **"Add Connection here"** that navigates to `/admin/connections/create?siteId=@node.SiteId`.
- Connection context menu: keep Edit + Delete; update the Edit href to the new `/admin/connections/{id}/edit` path.
### `src/ScadaLink.CentralUI/Components/Pages/Admin/DataConnectionForm.razor`
- Add primary routes:
```razor
@page "/admin/connections/create"
@page "/admin/connections/{Id:int}/edit"
@page "/admin/data-connections/create"
@page "/admin/data-connections/{Id:int}/edit"
```
- Add `[SupplyParameterFromQuery] public int? SiteId { get; set; }`.
- On `OnInitializedAsync`, if `Id` is null and `SiteId` has a value, set `_formSiteId = SiteId.Value` and render the Site field as a disabled `<input>` (same pattern as edit mode) — also set `_siteName` for display.
- Reorganize fields to subsections per `SiteForm.razor` reference:
- Site (already first), Name, Protocol.
- `<h6 class="text-muted border-bottom pb-1">Primary Endpoint</h6>` then Primary Endpoint Configuration.
- `<h6 class="text-muted border-bottom pb-1">Backup Endpoint</h6>` — collapsed (Add Backup Endpoint button) by default; when toggled on, render: Backup Configuration, Failover Retry Count, Remove Backup button.
- `GoBack()` → `NavigationManager.NavigateTo("/admin/connections")`.
### `src/ScadaLink.CentralUI/Components/Layout/NavMenu.razor`
- Change `<NavLink class="nav-link" href="/admin/data-connections">Data Connections</NavLink>` to:
```razor
<NavLink class="nav-link" href="/admin/connections">Connections</NavLink>
```
### `tests/ScadaLink.CentralUI.PlaywrightTests/NavigationTests.cs`
- Update the AdminNavLinks theory: `[InlineData("Data Connections", "/admin/data-connections")]` → `[InlineData("Connections", "/admin/connections")]`.
## New tests
### `tests/ScadaLink.CentralUI.Tests/DataConnectionsPageTests.cs` (new)
bUnit rendering tests, modeled after `TopologyPageTests`:
1. `Renders_EmptyState_WhenNoSites` — no sites configured.
2. `Renders_EmptySite_AsTopLevelNode` — site with no connections still appears.
3. `Renders_SiteConnection_Nesting` — connection nested under site after click-expand.
4. `Search_DimsNonMatches_PreservesShape` — typing in search dims unmatched siblings.
5. `AddConnectionButton_DisabledUntilSiteSelected` — toolbar `+ Connection` is `disabled` initially, becomes enabled after clicking a site row.
6. `LegacyDataConnectionsRoute_IsDeclaredOnListPage` — both `/admin/connections` and `/admin/data-connections` routes are present (reflection check).
JSInterop stubs (TreeView calls `treeviewStorage.load`/`save` even when `StorageKey` isn't supplied — verify):
- `JSInterop.Setup<string?>("treeviewStorage.load", _ => true).SetResult(null);`
- `JSInterop.SetupVoid("treeviewStorage.save", _ => true);`
## Out of scope
- Moving connections between sites (would require new service method + binding consequences).
- Connection status indicators (live state) — DCL connection state isn't surfaced in this page; deferred.
- Drag-and-drop reorder.
- Selection persistence across page reloads.
## Verification
1. `dotnet build` clean.
2. `dotnet test tests/ScadaLink.CentralUI.Tests/ScadaLink.CentralUI.Tests.csproj` — all green incl. new tests.
3. Existing Playwright NavigationTests pass with the updated label/URL.
4. Browser smoke (after `bash docker/deploy.sh`):
- `/admin/data-connections` (legacy bookmark) loads the same page as `/admin/connections`.
- + Connection disabled until a site is selected; then navigates with `?siteId=N`; Site field is locked in the form.
- Right-click on an empty site → "Add Connection here" works.
- Search "OPC" dims non-matching connections (label-based search, case-insensitive).
- Expand / Collapse buttons work; Refresh re-fetches from repos.
- Form sections "Primary Endpoint" / "Backup Endpoint" render with the SiteForm-style headers; Failover Retry Count appears inside the Backup section only when backup is enabled.
## Critical files
- `src/ScadaLink.CentralUI/Components/Pages/Admin/DataConnections.razor`
- `src/ScadaLink.CentralUI/Components/Pages/Admin/DataConnectionForm.razor`
- `src/ScadaLink.CentralUI/Components/Layout/NavMenu.razor`
- `tests/ScadaLink.CentralUI.PlaywrightTests/NavigationTests.cs`
- `tests/ScadaLink.CentralUI.Tests/DataConnectionsPageTests.cs` (new)
## Reference patterns
- TreeView usage with toolbar/search: `src/ScadaLink.CentralUI/Components/Pages/Deployment/Topology.razor`
- Form layout convention: `src/ScadaLink.CentralUI/Components/Pages/Admin/SiteForm.razor`
- bUnit harness for tree page: `tests/ScadaLink.CentralUI.Tests/TopologyPageTests.cs`

View File

@@ -21,7 +21,7 @@
<NavLink class="nav-link" href="/admin/sites">Sites</NavLink> <NavLink class="nav-link" href="/admin/sites">Sites</NavLink>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<NavLink class="nav-link" href="/admin/data-connections">Data Connections</NavLink> <NavLink class="nav-link" href="/admin/connections">Connections</NavLink>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<NavLink class="nav-link" href="/admin/api-keys">API Keys</NavLink> <NavLink class="nav-link" href="/admin/api-keys">API Keys</NavLink>

View File

@@ -1,3 +1,5 @@
@page "/admin/connections/create"
@page "/admin/connections/{Id:int}/edit"
@page "/admin/data-connections/create" @page "/admin/data-connections/create"
@page "/admin/data-connections/{Id:int}/edit" @page "/admin/data-connections/{Id:int}/edit"
@using ScadaLink.Security @using ScadaLink.Security
@@ -21,17 +23,14 @@
{ {
<div class="card mb-3"> <div class="card mb-3">
<div class="card-body"> <div class="card-body">
@if (Id.HasValue) <div class="mb-2">
{ <label class="form-label small">Site</label>
<div class="mb-2"> @if (_siteLocked)
<label class="form-label small">Site</label> {
<input type="text" class="form-control form-control-sm" value="@(_siteName)" disabled /> <input type="text" class="form-control form-control-sm" value="@_siteName" disabled />
</div> }
} else
else {
{
<div class="mb-2">
<label class="form-label small">Site</label>
<select class="form-select form-select-sm" @bind="_formSiteId"> <select class="form-select form-select-sm" @bind="_formSiteId">
<option value="0">Select site...</option> <option value="0">Select site...</option>
@foreach (var site in _sites) @foreach (var site in _sites)
@@ -39,13 +38,13 @@
<option value="@site.Id">@site.Name</option> <option value="@site.Id">@site.Name</option>
} }
</select> </select>
</div> }
} </div>
<div class="mb-2"> <div class="mb-2">
<label class="form-label small">Name</label> <label class="form-label small">Name</label>
<input type="text" class="form-control form-control-sm" @bind="_formName" /> <input type="text" class="form-control form-control-sm" @bind="_formName" />
</div> </div>
<div class="mb-2"> <div class="mb-3">
<label class="form-label small">Protocol</label> <label class="form-label small">Protocol</label>
<select class="form-select form-select-sm" @bind="_formProtocol"> <select class="form-select form-select-sm" @bind="_formProtocol">
<option value="">Select...</option> <option value="">Select...</option>
@@ -53,12 +52,15 @@
<option value="Custom">Custom</option> <option value="Custom">Custom</option>
</select> </select>
</div> </div>
<div class="mb-2">
<label class="form-label small">Primary Endpoint Configuration</label> <h6 class="text-muted border-bottom pb-1">Primary Endpoint</h6>
<div class="mb-3">
<label class="form-label small">Configuration</label>
<input type="text" class="form-control form-control-sm" @bind="_formConfiguration" <input type="text" class="form-control form-control-sm" @bind="_formConfiguration"
placeholder='e.g. {"endpoint":"opc.tcp://..."}' /> placeholder='e.g. {"endpoint":"opc.tcp://..."}' />
</div> </div>
<h6 class="text-muted border-bottom pb-1">Backup Endpoint</h6>
@if (!_showBackup) @if (!_showBackup)
{ {
<div class="mb-3"> <div class="mb-3">
@@ -70,27 +72,27 @@
} }
else else
{ {
<div class="mb-3"> <div class="mb-2">
<div class="d-flex justify-content-between align-items-center mb-1"> <label class="form-label small">Configuration</label>
<label class="form-label small mb-0">Backup Endpoint Configuration</label>
<button type="button" class="btn btn-outline-danger btn-sm"
@onclick="RemoveBackup">
Remove Backup
</button>
</div>
<textarea class="form-control form-control-sm" rows="4" <textarea class="form-control form-control-sm" rows="4"
@bind="_formBackupConfiguration" @bind="_formBackupConfiguration"
placeholder='{"Host": "backup-host", "Port": 50101}' /> placeholder='{"Host": "backup-host", "Port": 50101}' />
</div> </div>
<div class="mb-2">
<div class="mb-3">
<label class="form-label small">Failover Retry Count</label> <label class="form-label small">Failover Retry Count</label>
<input type="number" class="form-control form-control-sm" style="max-width: 120px;" <input type="number" class="form-control form-control-sm" style="max-width: 120px;"
min="1" max="20" min="1" max="20"
@bind="_formFailoverRetryCount" /> @bind="_formFailoverRetryCount" />
<div class="form-text">Retries on active endpoint before switching to backup (default: 3)</div> <div class="form-text">Retries on active endpoint before switching to backup (default: 3)</div>
</div> </div>
<div class="mb-3">
<button type="button" class="btn btn-outline-danger btn-sm"
@onclick="RemoveBackup">
Remove Backup
</button>
</div>
} }
@if (_formError != null) @if (_formError != null)
{ {
<div class="text-danger small mt-2">@_formError</div> <div class="text-danger small mt-2">@_formError</div>
@@ -106,12 +108,14 @@
@code { @code {
[Parameter] public int? Id { get; set; } [Parameter] public int? Id { get; set; }
[SupplyParameterFromQuery] public int? SiteId { get; set; }
private bool _loading = true; private bool _loading = true;
private DataConnection? _editingConnection; private DataConnection? _editingConnection;
private List<Site> _sites = new(); private List<Site> _sites = new();
private int _formSiteId; private int _formSiteId;
private string _siteName = string.Empty; private string _siteName = string.Empty;
private bool _siteLocked;
private string _formName = string.Empty; private string _formName = string.Empty;
private string _formProtocol = string.Empty; private string _formProtocol = string.Empty;
private string? _formConfiguration; private string? _formConfiguration;
@@ -133,6 +137,7 @@
{ {
_formSiteId = _editingConnection.SiteId; _formSiteId = _editingConnection.SiteId;
_siteName = _sites.FirstOrDefault(s => s.Id == _formSiteId)?.Name ?? $"Site {_formSiteId}"; _siteName = _sites.FirstOrDefault(s => s.Id == _formSiteId)?.Name ?? $"Site {_formSiteId}";
_siteLocked = true;
_formName = _editingConnection.Name; _formName = _editingConnection.Name;
_formProtocol = _editingConnection.Protocol; _formProtocol = _editingConnection.Protocol;
_formConfiguration = _editingConnection.PrimaryConfiguration; _formConfiguration = _editingConnection.PrimaryConfiguration;
@@ -146,6 +151,16 @@
_formError = $"Failed to load connection: {ex.Message}"; _formError = $"Failed to load connection: {ex.Message}";
} }
} }
else if (SiteId.HasValue)
{
var site = _sites.FirstOrDefault(s => s.Id == SiteId.Value);
if (site != null)
{
_formSiteId = site.Id;
_siteName = site.Name;
_siteLocked = true;
}
}
_loading = false; _loading = false;
} }
@@ -178,7 +193,7 @@
await SiteRepository.AddDataConnectionAsync(conn); await SiteRepository.AddDataConnectionAsync(conn);
} }
await SiteRepository.SaveChangesAsync(); await SiteRepository.SaveChangesAsync();
NavigationManager.NavigateTo("/admin/data-connections"); NavigationManager.NavigateTo("/admin/connections");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -195,6 +210,6 @@
private void GoBack() private void GoBack()
{ {
NavigationManager.NavigateTo("/admin/data-connections"); NavigationManager.NavigateTo("/admin/connections");
} }
} }

View File

@@ -1,3 +1,4 @@
@page "/admin/connections"
@page "/admin/data-connections" @page "/admin/data-connections"
@using ScadaLink.Security @using ScadaLink.Security
@using ScadaLink.Commons.Entities.Sites @using ScadaLink.Commons.Entities.Sites
@@ -7,11 +8,6 @@
@inject NavigationManager NavigationManager @inject NavigationManager NavigationManager
<div class="container-fluid mt-3"> <div class="container-fluid mt-3">
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="mb-0">Data Connections</h4>
<button class="btn btn-primary btn-sm" @onclick='() => NavigationManager.NavigateTo("/admin/data-connections/create")'>Add Connection</button>
</div>
<ToastNotification @ref="_toast" /> <ToastNotification @ref="_toast" />
<ConfirmDialog @ref="_confirmDialog" /> <ConfirmDialog @ref="_confirmDialog" />
@@ -25,28 +21,56 @@
} }
else else
{ {
<TreeView TItem="DcTreeNode" Items="_treeRoots" <h6 class="mb-2">Connections</h6>
<div class="d-flex align-items-center mb-2 gap-2">
<input type="text" class="form-control form-control-sm" style="max-width: 320px;"
placeholder="Search sites or connections..."
@bind="_searchText" @bind:event="oninput" @bind:after="OnSearchChanged" />
<div class="btn-group btn-group-sm">
<button class="btn btn-outline-secondary"
disabled="@(!HasSiteSelected)"
@onclick="OnAddConnectionClicked">+ Connection</button>
<button class="btn btn-outline-secondary" @onclick="LoadDataAsync">Refresh</button>
<button class="btn btn-outline-secondary" @onclick="() => _tree?.ExpandAll()">Expand</button>
<button class="btn btn-outline-secondary" @onclick="() => _tree?.CollapseAll()">Collapse</button>
</div>
</div>
<TreeView @ref="_tree" TItem="DcTreeNode" Items="_treeRoots"
ChildrenSelector="n => n.Children" ChildrenSelector="n => n.Children"
HasChildrenSelector="n => n.Children.Count > 0" HasChildrenSelector="n => n.Children.Count > 0"
KeySelector="n => n.Key" KeySelector="n => (object)n.Key"
StorageKey="data-connections-tree"> StorageKey="data-connections-tree"
Selectable="true"
SelectedKey="_selectedKey"
SelectedKeyChanged="OnTreeNodeSelected">
<NodeContent Context="node"> <NodeContent Context="node">
@{
var labelStyle = IsDimmed(node) ? "opacity: 0.4;" : "";
}
@if (node.Kind == DcNodeKind.Site) @if (node.Kind == DcNodeKind.Site)
{ {
<span class="fw-semibold">@node.Label</span> <span class="tv-label fw-semibold" style="@labelStyle">@node.Label</span>
<span class="badge bg-secondary ms-1">@node.Children.Count</span> <span class="badge bg-secondary ms-1">@node.Children.Count</span>
} }
else else
{ {
<span>@node.Label</span> <span class="tv-label" style="@labelStyle">@node.Label</span>
<span class="badge bg-info ms-2">@node.Connection!.Protocol</span> <span class="badge bg-info ms-2">@node.Connection!.Protocol</span>
} }
</NodeContent> </NodeContent>
<ContextMenu Context="node"> <ContextMenu Context="node">
@if (node.Kind == DcNodeKind.DataConnection) @if (node.Kind == DcNodeKind.Site)
{ {
<button class="dropdown-item" <button class="dropdown-item"
@onclick='() => NavigationManager.NavigateTo($"/admin/data-connections/{node.Connection!.Id}/edit")'> @onclick="() => AddConnectionForSite(node.SiteId!.Value)">
Add Connection here
</button>
}
else
{
<button class="dropdown-item"
@onclick='() => NavigationManager.NavigateTo($"/admin/connections/{node.Connection!.Id}/edit")'>
Edit Edit
</button> </button>
<div class="dropdown-divider"></div> <div class="dropdown-divider"></div>
@@ -57,15 +81,19 @@
} }
</ContextMenu> </ContextMenu>
<EmptyContent> <EmptyContent>
<span class="text-muted fst-italic">No data connections configured.</span> <span class="text-muted fst-italic">No sites configured. Add sites under Admin → Sites.</span>
</EmptyContent> </EmptyContent>
</TreeView> </TreeView>
<div class="text-muted small mt-2">
@_connections.Count connection(s) across @_treeRoots.Count site(s).
</div>
} }
</div> </div>
@code { @code {
record DcTreeNode(string Key, string Label, DcNodeKind Kind, List<DcTreeNode> Children, record DcTreeNode(string Key, string Label, DcNodeKind Kind, List<DcTreeNode> Children,
DataConnection? Connection = null); int? SiteId = null, DataConnection? Connection = null);
enum DcNodeKind { Site, DataConnection } enum DcNodeKind { Site, DataConnection }
private List<DcTreeNode> _treeRoots = new(); private List<DcTreeNode> _treeRoots = new();
@@ -73,9 +101,16 @@
private bool _loading = true; private bool _loading = true;
private string? _errorMessage; private string? _errorMessage;
private TreeView<DcTreeNode>? _tree;
private object? _selectedKey;
private string _searchText = string.Empty;
private HashSet<string> _matchKeys = new();
private ToastNotification _toast = default!; private ToastNotification _toast = default!;
private ConfirmDialog _confirmDialog = default!; private ConfirmDialog _confirmDialog = default!;
private bool HasSiteSelected => ResolveSelectedSiteId() != null;
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
await LoadDataAsync(); await LoadDataAsync();
@@ -101,9 +136,12 @@
Label: c.Name, Label: c.Name,
Kind: DcNodeKind.DataConnection, Kind: DcNodeKind.DataConnection,
Children: new(), Children: new(),
SiteId: c.SiteId,
Connection: c)) Connection: c))
.ToList() .ToList(),
SiteId: site.Id
)).ToList(); )).ToList();
RebuildMatchKeys();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -112,6 +150,71 @@
_loading = false; _loading = false;
} }
private void OnTreeNodeSelected(object? key)
{
_selectedKey = key;
}
private int? ResolveSelectedSiteId()
{
if (_selectedKey is not string keyStr) return null;
foreach (var site in _treeRoots)
{
if (site.Key == keyStr) return site.SiteId;
foreach (var child in site.Children)
{
if (child.Key == keyStr) return site.SiteId;
}
}
return null;
}
private void OnAddConnectionClicked()
{
var sid = ResolveSelectedSiteId();
if (sid == null) return;
AddConnectionForSite(sid.Value);
}
private void AddConnectionForSite(int siteId)
{
NavigationManager.NavigateTo($"/admin/connections/create?siteId={siteId}");
}
private void OnSearchChanged()
{
RebuildMatchKeys();
}
private void RebuildMatchKeys()
{
_matchKeys.Clear();
if (string.IsNullOrWhiteSpace(_searchText)) return;
var q = _searchText.Trim();
foreach (var root in _treeRoots)
{
SubtreeContainsMatch(root, q);
}
}
private bool SubtreeContainsMatch(DcTreeNode node, string query)
{
var selfMatch = node.Label.Contains(query, StringComparison.OrdinalIgnoreCase);
var childMatch = false;
foreach (var child in node.Children)
{
if (SubtreeContainsMatch(child, query)) childMatch = true;
}
if (selfMatch || childMatch) _matchKeys.Add(node.Key);
return selfMatch || childMatch;
}
private bool IsDimmed(DcTreeNode node)
{
if (string.IsNullOrWhiteSpace(_searchText)) return false;
return !_matchKeys.Contains(node.Key);
}
private async Task DeleteConnection(DataConnection conn) private async Task DeleteConnection(DataConnection conn)
{ {
var confirmed = await _confirmDialog.ShowAsync( var confirmed = await _confirmDialog.ShowAsync(

View File

@@ -25,7 +25,7 @@ public class NavigationTests
[Theory] [Theory]
[InlineData("Sites", "/admin/sites")] [InlineData("Sites", "/admin/sites")]
[InlineData("Data Connections", "/admin/data-connections")] [InlineData("Connections", "/admin/connections")]
[InlineData("API Keys", "/admin/api-keys")] [InlineData("API Keys", "/admin/api-keys")]
[InlineData("LDAP Mappings", "/admin/ldap-mappings")] [InlineData("LDAP Mappings", "/admin/ldap-mappings")]
public async Task AdminNavLinks_NavigateCorrectly(string linkText, string expectedPath) public async Task AdminNavLinks_NavigateCorrectly(string linkText, string expectedPath)

View File

@@ -0,0 +1,158 @@
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ScadaLink.Commons.Entities.Sites;
using ScadaLink.Commons.Interfaces.Repositories;
using DataConnectionsPage = ScadaLink.CentralUI.Components.Pages.Admin.DataConnections;
namespace ScadaLink.CentralUI.Tests;
/// <summary>
/// bUnit rendering tests for the Connections page (Site → DataConnection tree).
/// Focuses on the Topology-style behaviors layered onto this page: always-show-empty
/// sites, search dimming, toolbar gating, and dual-route declaration.
/// </summary>
public class DataConnectionsPageTests : BunitContext
{
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
public DataConnectionsPageTests()
{
Services.AddSingleton(_siteRepo);
AddTestAuth();
JSInterop.Setup<string?>("treeviewStorage.load", _ => true).SetResult(null);
JSInterop.SetupVoid("treeviewStorage.save", _ => true);
}
private void AddTestAuth()
{
var claims = new[]
{
new Claim("Username", "tester"),
new Claim(ClaimTypes.Role, "Admin")
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
}
private void SeedRepos(
IEnumerable<Site>? sites = null,
IEnumerable<DataConnection>? connections = null)
{
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(sites?.ToList() ?? new List<Site>()));
_siteRepo.GetAllDataConnectionsAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<DataConnection>>(connections?.ToList() ?? new List<DataConnection>()));
}
private static AngleSharp.Dom.IElement? FindToggleForLabel(IRenderedComponent<DataConnectionsPage> cut, string label) =>
cut.FindAll(".tv-row")
.FirstOrDefault(row => row.QuerySelector(".tv-label")?.TextContent == label)
?.QuerySelector(".tv-toggle");
[Fact]
public void Renders_EmptyState_WhenNoSites()
{
SeedRepos();
var cut = Render<DataConnectionsPage>();
Assert.Contains("No sites configured", cut.Markup);
}
[Fact]
public void Renders_EmptySite_AsTopLevelNode()
{
// A site with no connections must still appear so it can be right-clicked
// to "Add Connection here".
SeedRepos(sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } });
var cut = Render<DataConnectionsPage>();
Assert.Contains("Plant-A", cut.Markup);
}
[Fact]
public void Renders_SiteConnection_Nesting()
{
SeedRepos(
sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } },
connections: new[]
{
new DataConnection("PLC-1", "OpcUa", 1) { Id = 100 }
});
var cut = Render<DataConnectionsPage>();
FindToggleForLabel(cut, "Plant-A")!.Click();
Assert.Contains("PLC-1", cut.Markup);
Assert.Contains("OpcUa", cut.Markup);
}
[Fact]
public void Search_DimsNonMatches_PreservesShape()
{
SeedRepos(
sites: new[]
{
new Site("Plant-A", "plant-a") { Id = 1 },
new Site("Plant-B", "plant-b") { Id = 2 }
},
connections: new[]
{
new DataConnection("PLC-1", "OpcUa", 1) { Id = 100 },
new DataConnection("RTU-9", "Custom", 2) { Id = 200 }
});
var cut = Render<DataConnectionsPage>();
var search = cut.Find("input[type='text']");
search.Input("Plant-A");
// Both sites remain in the DOM (shape preserved). Plant-B gets the dim style.
Assert.Contains("Plant-A", cut.Markup);
Assert.Contains("Plant-B", cut.Markup);
var dimmedNodes = cut.FindAll("span.tv-label[style*='opacity']");
Assert.Contains(dimmedNodes, n => n.TextContent.Contains("Plant-B"));
}
[Fact]
public void AddConnectionButton_DisabledUntilSiteSelected()
{
SeedRepos(sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } });
var cut = Render<DataConnectionsPage>();
var addBtn = cut.FindAll("button")
.First(b => b.TextContent.Contains("+ Connection"));
Assert.True(addBtn.HasAttribute("disabled"));
// Click the site content (TreeView wires selection on .tv-content).
var siteContent = cut.FindAll(".tv-row")
.First(r => r.QuerySelector(".tv-label")?.TextContent == "Plant-A")
.QuerySelector(".tv-content")!;
siteContent.Click();
var addBtnAfter = cut.FindAll("button")
.First(b => b.TextContent.Contains("+ Connection"));
Assert.False(addBtnAfter.HasAttribute("disabled"));
}
[Fact]
public void LegacyDataConnectionsRoute_IsDeclaredOnListPage()
{
// Old bookmarks to /admin/data-connections must still resolve.
var routes = typeof(DataConnectionsPage).GetCustomAttributes(
typeof(Microsoft.AspNetCore.Components.RouteAttribute), inherit: false)
.Cast<Microsoft.AspNetCore.Components.RouteAttribute>()
.Select(a => a.Template)
.ToList();
Assert.Contains("/admin/connections", routes);
Assert.Contains("/admin/data-connections", routes);
}
}