fix(admin-ui): scope configuration modal lifecycles and validation

This commit is contained in:
Joseph Doherty
2026-11-13 23:24:56 -05:00
parent f7bc69e9c3
commit 79acb80da9
65 changed files with 17081 additions and 511 deletions
@@ -11,17 +11,12 @@
@using ZB.MOM.WW.OtOpcUa.Core.Authorization
@inject IAclScopeService Scopes
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Choose scope &middot; <span class="mono">@ClusterId</span></h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CancelAsync"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{ var presentation = _generation; var pickedAction = OnPicked; var cancelAction = OnCancel; }
<ModalFrame Visible="@Visible" Title="Choose scope" DialogClass="modal-xl" Target="@presentation" Busy="@_pending" OnClose="() => CancelPresentation(presentation, cancelAction)">
<TitleContent>Choose scope &middot; <span class="mono">@ClusterId</span></TitleContent>
<ChildContent><fieldset disabled="@_pending" @key="_generation">
<p class="text-muted small mb-3">
Pick the node this grant applies to. Permissions inherit <strong>downward</strong>,
so a grant on a device covers every tag beneath it. Both trees are scoped to this
@@ -30,15 +25,15 @@
@if (_loading)
{
<p class="text-muted"><span class="spinner-border spinner-border-sm me-1"></span>Loading…</p>
<p class="text-muted" role="status"><span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>Loading…</p>
}
else
{
<div class="row g-3">
<div class="col-md-6">
<div class="panel-head mb-1">Raw device tree</div>
<h3 class="panel-head mb-1">Raw device tree</h3>
<div class="border rounded p-2" style="max-height:50vh; overflow:auto">
<AclScopeTree Nodes="_rawHeader" SelectedKey="@_selected?.Key" OnSelect="Select" />
<AclScopeTree Nodes="_rawHeader" SelectedKey="@_selected?.Key" OnSelect="node => SelectPresentation(node, presentation)" />
@if (_roots.Raw.Count == 0)
{
<p class="text-muted small mb-0 mt-1">This cluster has no raw tree yet.</p>
@@ -46,21 +41,21 @@
else
{
<AclScopeTree Nodes="_roots.Raw" SelectedKey="@_selected?.Key"
OnSelect="Select" LoadChildren="LoadChildrenAsync" />
OnSelect="node => SelectPresentation(node, presentation)" LoadChildren="node => LoadChildrenPresentation(node, presentation)" />
}
</div>
</div>
<div class="col-md-6">
<div class="panel-head mb-1">UNS tree</div>
<h3 class="panel-head mb-1">UNS tree</h3>
<div class="border rounded p-2" style="max-height:50vh; overflow:auto">
<AclScopeTree Nodes="_unsHeader" SelectedKey="@_selected?.Key" OnSelect="Select" />
<AclScopeTree Nodes="_unsHeader" SelectedKey="@_selected?.Key" OnSelect="node => SelectPresentation(node, presentation)" />
@if (_roots.Uns.Count == 0)
{
<p class="text-muted small mb-0 mt-1">This cluster has no UNS areas yet.</p>
}
else
{
<AclScopeTree Nodes="_roots.Uns" SelectedKey="@_selected?.Key" OnSelect="Select" />
<AclScopeTree Nodes="_roots.Uns" SelectedKey="@_selected?.Key" OnSelect="node => SelectPresentation(node, presentation)" />
}
</div>
<p class="text-muted small mt-2 mb-0">
@@ -72,8 +67,9 @@
</div>
</div>
}
</div>
<div class="modal-footer d-flex justify-content-between">
</fieldset></ChildContent>
<Footer><div class="d-flex justify-content-between w-100 gap-2 flex-wrap">
<div class="small">
@if (_selected is null)
{
@@ -93,18 +89,17 @@
</div>
<div class="d-flex gap-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CancelAsync">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="ConfirmAsync"
disabled="@(_selected is null)">Use this scope</button>
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" disabled="@_pending" @onclick="() => CancelPresentation(presentation, cancelAction)">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="() => ConfirmPresentation(presentation, pickedAction)"
disabled="@(_selected is null || _pending || _loading)">Use this scope</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
</div></Footer>
</ModalFrame>
@code {
/// <summary>Whether the modal is shown. The host owns this flag.</summary>
[Parameter] public bool Visible { get; set; }
@@ -150,43 +145,67 @@
},
};
/// <summary>Optional nonconfidential identity when different grants use the same cluster.</summary>
[Parameter] public object? Target { get; set; }
private object? _lastTarget;
private bool _pending, _disposed;
private int _generation;
private bool IsStale(int generation) => _disposed || !Visible || generation != _generation;
protected override async Task OnParametersSetAsync()
{
// Reload only on the false→true transition, so a re-render while open does not wipe the
// expansion state the operator has built up.
if (Visible && !_wasVisible)
object identity = (Target, ClusterId);
if (_disposed || (_wasVisible == Visible && Equals(_lastTarget, identity))) return;
_wasVisible = Visible; _lastTarget = identity;
var generation = ++_generation;
if (!Visible) return;
var clusterId = ClusterId;
_selected = null; _loading = true;
_roots = new AclScopeRoots([], []);
try
{
_selected = null;
_loading = true;
_roots = new AclScopeRoots(Array.Empty<AclScopeNode>(), Array.Empty<AclScopeNode>());
StateHasChanged();
_roots = string.IsNullOrWhiteSpace(ClusterId)
? new AclScopeRoots(Array.Empty<AclScopeNode>(), Array.Empty<AclScopeNode>())
: await Scopes.LoadRootsAsync(ClusterId);
// The cluster root is the one node worth opening for the operator — everything else is a
// decision they should make deliberately.
foreach (var root in _roots.Raw) { root.Expanded = false; }
_loading = false;
var roots = string.IsNullOrWhiteSpace(clusterId) ? new AclScopeRoots([], []) : await Scopes.LoadRootsAsync(clusterId);
if (IsStale(generation)) return;
foreach (var root in roots.Raw) root.Expanded = false;
_roots = roots;
}
_wasVisible = Visible;
catch (Exception) when (IsStale(generation)) { }
finally { if (!IsStale(generation)) _loading = false; }
}
private Task<IReadOnlyList<AclScopeNode>> LoadChildrenAsync(AclScopeNode node) =>
Scopes.LoadChildrenAsync(node);
private void Select(AclScopeNode node)
private async Task<IReadOnlyList<AclScopeNode>> LoadChildrenPresentation(AclScopeNode node, int generation)
{
if (IsStale(generation) || _pending) return [];
try
{
var children = await Scopes.LoadChildrenAsync(node);
return IsStale(generation) ? [] : children;
}
catch (Exception) when (IsStale(generation)) { return []; }
}
private void SelectPresentation(AclScopeNode node, int generation)
{
if (IsStale(generation) || _pending || _loading) return;
_selected = node;
StateHasChanged();
}
private async Task ConfirmAsync()
private async Task ConfirmPresentation(int generation, EventCallback<AclScopeNode> action)
{
if (_selected is null) { return; }
await OnPicked.InvokeAsync(_selected);
if (IsStale(generation) || _pending || _loading || _selected is null) return;
var selected = _selected;
_pending = true;
try { await action.InvokeAsync(selected); }
finally { _pending = false; }
}
private Task CancelAsync() => OnCancel.InvokeAsync();
private async Task CancelPresentation(int generation, EventCallback action)
{
if (IsStale(generation) || _pending) return;
_pending = true;
try { await action.InvokeAsync(); }
finally { _pending = false; }
}
/// <summary>Discards old picker callbacks and late read results.</summary>
public void Dispose() { _disposed = true; ++_generation; }
}
@@ -8,18 +8,20 @@
@using ZB.MOM.WW.OtOpcUa.Core.Abstractions
@inject IRawTreeService Svc
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">@(_isNew ? "New device" : "Edit device") &middot; <span class="mono">@_driverType</span></h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
@if (_loadError is not null)
@implements IDisposable
@{
var presentation = _openGeneration;
var savedAction = OnSaved;
var closeAction = VisibleChanged;
}
<ModalFrame Visible="@Visible" Title="@(_isNew ? "New device" : "Edit device")" Target="@presentation" Busy="@Pending" DialogClass="modal-lg" OnClose="() => ClosePresentation(presentation, closeAction)">
<TitleContent>@(_isNew ? "New device" : "Edit device") &middot; <span class="mono">@_driverType</span></TitleContent>
<ChildContent>
<fieldset disabled="@(Pending || _loading)" @key="_openGeneration">
@if (_loading)
{ <p role="status">Loading…</p> }
else if (_loadError is not null)
{
<div class="panel notice notice-alert mb-3">@_loadError</div>
}
@@ -27,14 +29,14 @@
{
<div class="row g-3 mb-2">
<div class="col-md-6">
<label class="form-label">Device name</label>
<input class="form-control form-control-sm mono" @bind="_name" placeholder="e.g. plc1" />
<div class="form-text">A RawPath segment — letters, digits, dash, underscore.</div>
<label class="form-label" for='@FieldId("device-name")'>Device name</label>
<input id='@FieldId("device-name")' aria-describedby='@FieldIds("name-hint", "save-error")' class="form-control form-control-sm mono" @bind="_name" placeholder="e.g. plc1" />
<div id='@FieldId("name-hint")' class="form-text">A RawPath segment — letters, digits, dash, underscore.</div>
</div>
<div class="col-md-3">
<div class="form-check form-switch mt-4">
<input type="checkbox" class="form-check-input" id="devEnabled" @bind="_enabled" />
<label class="form-check-label" for="devEnabled">Enabled</label>
<input type="checkbox" class="form-check-input" id='@FieldId("enabled")' @bind="_enabled" />
<label class="form-check-label" for='@FieldId("enabled")'>Enabled</label>
</div>
</div>
</div>
@@ -44,7 +46,7 @@
have no per-device form; the parity test consults that set. *@
@if (DeviceFormMap.Resolve(_driverType) is { } deviceFormType)
{
<DynamicComponent Type="deviceFormType" Parameters="_deviceFormParameters" />
<DynamicComponent @key="_openGeneration" Type="deviceFormType" Parameters="_deviceFormParameters" />
}
else if (DeviceFormMap.IsSingleConnection(_driverType))
{
@@ -59,31 +61,30 @@
}
<div class="mt-3">
<DriverTestConnectButton DriverType="@_driverType" GetConfigJson="@BuildMergedProbeConfig" DriverInstanceId="@_resolvedDriverInstanceId" />
<DriverTestConnectButton DriverType="@_driverType" GetConfigJson="@ProbeConfigAccessor" DriverInstanceId="@_resolvedDriverInstanceId" />
</div>
<SaveRefusalNotice GateError="@DriverConfigSaveGate.Validate(_driverType, _deviceConfigJson)" SaveError="@_saveError" />
<div id='@FieldId("save-error")'><SaveRefusalNotice GateError="@DriverConfigSaveGate.Validate(_driverType, _deviceConfigJson)" SaveError="@_saveError" /></div>
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">Cancel</button>
@if (_loadError is null)
{
<button type="button" class="btn btn-primary" @onclick="SaveAsync"
disabled="@(_busy || DriverConfigSaveGate.Validate(_driverType, _deviceConfigJson) is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
@(_isNew ? "Create device" : "Save changes")
</button>
}
</div>
</div>
</div>
</fieldset>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => ClosePresentation(presentation, closeAction)" disabled="@Pending">Cancel</button>
@if (_loadError is null)
{
<button type="button" class="btn btn-primary" @onclick="() => SavePresentation(presentation, savedAction, closeAction)" disabled="@(Pending || _loading || DriverConfigSaveGate.Validate(_driverType, _deviceConfigJson) is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
@(_isNew ? "Create device" : "Save changes")
</button>
}
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Whether the modal is shown (supports @bind-Visible).</summary>
[Parameter] public bool Visible { get; set; }
/// <summary>Two-way visibility callback.</summary>
@@ -109,14 +110,20 @@
/// <summary>Parameters handed to the DynamicComponent-rendered device form. Cached on the value it
/// carries and rebuilt when that changes (never build-once: see DriverConfigModal), with the callback
/// created once (R04 H2).</summary>
private Dictionary<string, object> _deviceFormParameters => _deviceFormParameterCache.Get(
[_deviceConfigJson],
() => new()
private Dictionary<string, object> _deviceFormParameters {
get
{
["DeviceConfigJson"] = _deviceConfigJson,
["DeviceConfigJsonChanged"] = _deviceConfigJsonChanged ??=
EventCallback.Factory.Create<string>(this, v => { _deviceConfigJson = v; _saveError = null; }),
});
var generation = _openGeneration;
return _deviceFormParameterCache.Get(
[_deviceConfigJson, _openGeneration],
() => new()
{
["DeviceConfigJson"] = _deviceConfigJson,
["DeviceConfigJsonChanged"] = _deviceConfigJsonChanged ??=
EventCallback.Factory.Create<string>(this, GuardChange<string>(generation, v => { _deviceConfigJson = v; _saveError = null; })),
});
}
}
private readonly ParameterDictionaryCache _deviceFormParameterCache = new();
private EventCallback<string>? _deviceConfigJsonChanged;
private byte[] _rowVersion = [];
@@ -127,62 +134,90 @@
private string? _saveError;
private bool _openHandled;
// Bumped on every open and close; LoadAsync re-checks it after each await so a superseded open can't
// install one target's fields under another target's displayed modal (RawBrowseModal idiom).
private int _openGeneration;
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
/// <summary>Optional nonconfidential identity for otherwise identical editor contexts.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-config-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _loading, _closing, _disposed, _lastVisible;
private object? _lastTarget;
private int _openGeneration;
private bool Pending => _busy || _closing;
private bool IsStale(int generation) => _disposed || generation != _openGeneration || !Visible;
private Action<T> GuardChange<T>(int generation, Action<T> update) => value => { if (!IsStale(generation) && !Pending && !_loading) update(value); };
protected override async Task OnParametersSetAsync()
{
if (Visible && !_openHandled)
object identity = (Target, DeviceId, DriverInstanceId, DriverType);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
FreezeProbeConfig();
_lastVisible = Visible; _lastTarget = identity;
_probeConfig = new ProbeConfigState();
var generation = ++_openGeneration;
_openHandled = Visible;
if (Visible)
{
_openHandled = true;
await LoadAsync(++_openGeneration);
}
else if (!Visible)
{
_openHandled = false;
_openGeneration++;
_deviceConfigJsonChanged = null;
_probeConfigAccessor = null;
_deviceFormParameterCache.Reset();
await LoadAsync(generation);
}
}
private async Task LoadAsync(int generation)
{
_busy = false; _loadError = null; _saveError = null;
_isNew = string.IsNullOrEmpty(DeviceId);
var deviceId = DeviceId;
var driverInstanceId = DriverInstanceId;
var driverType = DriverType;
_loading = true;
_parentDriverConfig = "{}";
try
{
_loadError = null; _saveError = null;
_isNew = string.IsNullOrEmpty(deviceId);
if (_isNew)
{
_resolvedDriverInstanceId = DriverInstanceId;
_driverType = DriverType ?? "";
_name = ""; // placeholder only: a pre-filled value made typing append to it (#577); the name is validated on save
_enabled = true;
_deviceConfigJson = "{}";
_rowVersion = [];
}
else
{
var dto = await Svc.LoadDeviceForEditAsync(DeviceId!);
if (IsStale(generation)) { return; }
if (dto is null) { _loadError = $"Device '{DeviceId}' was not found."; return; }
_resolvedDriverInstanceId = dto.DriverInstanceId;
_driverType = dto.DriverType;
_name = dto.Name;
_enabled = dto.Enabled;
_deviceConfigJson = string.IsNullOrWhiteSpace(dto.DeviceConfig) ? "{}" : dto.DeviceConfig;
_rowVersion = dto.RowVersion;
}
if (_isNew)
{
_resolvedDriverInstanceId = driverInstanceId;
_driverType = driverType ?? "";
_name = ""; // placeholder only: a pre-filled value made typing append to it (#577); the name is validated on save
_enabled = true;
_deviceConfigJson = "{}";
_rowVersion = [];
}
else
{
var dto = await Svc.LoadDeviceForEditAsync(deviceId!);
if (IsStale(generation)) { return; }
if (dto is null) { _loadError = $"Device '{deviceId}' was not found."; return; }
_resolvedDriverInstanceId = dto.DriverInstanceId;
_driverType = dto.DriverType;
_name = dto.Name;
_enabled = dto.Enabled;
_deviceConfigJson = string.IsNullOrWhiteSpace(dto.DeviceConfig) ? "{}" : dto.DeviceConfig;
_rowVersion = dto.RowVersion;
}
// The parent driver's DriverConfig — folded with the (possibly unsaved) DeviceConfig for Test-connect.
if (!string.IsNullOrEmpty(_resolvedDriverInstanceId))
// The parent driver's DriverConfig — folded with the (possibly unsaved) DeviceConfig for Test-connect.
if (!string.IsNullOrEmpty(_resolvedDriverInstanceId))
{
var drv = await Svc.LoadDriverForEditAsync(_resolvedDriverInstanceId);
if (IsStale(generation)) { return; }
_parentDriverConfig = drv?.DriverConfig ?? "{}";
}
}
catch (Exception) when (IsStale(generation)) { }
finally
{
var drv = await Svc.LoadDriverForEditAsync(_resolvedDriverInstanceId);
if (IsStale(generation)) { return; }
_parentDriverConfig = drv?.DriverConfig ?? "{}";
if (!IsStale(generation))
{
_loading = false;
if (_loadError is null) _probeConfig.Value = BuildMergedProbeConfig();
}
}
}
/// <summary>Builds the merged Driver+Device probe config from the CURRENT (possibly unsaved) form —
/// same merge as <c>LoadMergedProbeConfigAsync</c>, so Test-connect works before the device is saved.</summary>
private string BuildMergedProbeConfig()
@@ -191,50 +226,71 @@
new[] { new DriverDeviceConfigMerger.DeviceRow(_name, _deviceConfigJson) },
Array.Empty<RawTagEntry>());
private async Task SaveAsync()
private Func<string>? _probeConfigAccessor;
private sealed class ProbeConfigState { public string Value = "{}"; }
private ProbeConfigState _probeConfig = new();
private void FreezeProbeConfig()
{
// A resubmit REPLACES the previous refusal; a gate refusal is already rendered live by
// SaveRefusalNotice, so it is not copied into _saveError (that stacked two boxes — lmxopcua#847).
if (!_loading && _loadError is null) _probeConfig.Value = BuildMergedProbeConfig();
}
private Func<string> ProbeConfigAccessor
{
get
{
var generation = _openGeneration;
var state = _probeConfig;
return _probeConfigAccessor ??= () =>
{
if (!IsStale(generation) && !_loading && _loadError is null) state.Value = BuildMergedProbeConfig();
return state.Value;
};
}
}
private Task SaveAsync() => SavePresentation(_openGeneration, OnSaved, VisibleChanged);
private async Task SavePresentation(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
if (IsStale(generation) || Pending || _loading || _loadError is not null) return;
_saveError = null;
if (DriverConfigSaveGate.Validate(_driverType, _deviceConfigJson) is not null) return;
var isNew = _isNew;
var name = _name;
var json = _deviceConfigJson;
var driverType = _driverType;
var rowVersion = _rowVersion.ToArray();
var parentId = _resolvedDriverInstanceId;
var deviceId = DeviceId;
var enabled = _enabled;
_busy = true;
try
{
UnsMutationResult result;
if (_isNew)
if (isNew)
{
if (string.IsNullOrEmpty(_resolvedDriverInstanceId))
{
_saveError = "No owning driver instance was supplied.";
return;
}
result = await Svc.CreateDeviceAsync(_resolvedDriverInstanceId, _name, _deviceConfigJson);
if (string.IsNullOrEmpty(parentId)) { _saveError = "No owning driver instance was supplied."; return; }
result = await Svc.CreateDeviceAsync(parentId, name, json);
}
else
{
result = await Svc.UpdateDeviceAsync(DeviceId!, _name, _deviceConfigJson, _enabled, _rowVersion);
}
if (!result.Ok)
{
_saveError = result.Error ?? "Save failed.";
return;
}
await OnSaved.InvokeAsync();
await SetVisibleAsync(false);
else result = await Svc.UpdateDeviceAsync(deviceId!, name, json, enabled, rowVersion);
if (IsStale(generation)) return;
if (!result.Ok) { _saveError = result.Error ?? "Save failed."; return; }
await savedAction.InvokeAsync();
if (!IsStale(generation)) await ClosePresentation(generation, closeAction, true);
}
catch (Exception ex) { _saveError = ex.Message; }
catch (Exception ex) { if (!IsStale(generation)) _saveError = ex.Message; }
finally { _busy = false; }
}
private Task CloseAsync() => SetVisibleAsync(false);
private async Task SetVisibleAsync(bool value)
private Task CloseAsync() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> action, bool afterSave = false)
{
Visible = value;
_openHandled = value;
_openGeneration++;
await VisibleChanged.InvokeAsync(value);
if (IsStale(generation) || _closing || (_busy && !afterSave)) return;
_closing = true;
FreezeProbeConfig();
Visible = false; _lastVisible = false; _openHandled = false; ++_openGeneration;
try { await action.InvokeAsync(false); }
finally { _closing = false; }
}
/// <summary>Invalidates UI callbacks and read results without cancelling dispatched mutations.</summary>
public void Dispose() { FreezeProbeConfig(); _disposed = true; ++_openGeneration; }
}
@@ -6,18 +6,20 @@
@using ZB.MOM.WW.OtOpcUa.Core.Abstractions
@inject IRawTreeService Svc
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">@(_isNew ? "New driver" : "Configure driver") &middot; <span class="mono">@_driverType</span></h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
@if (_loadError is not null)
@implements IDisposable
@{
var presentation = _openGeneration;
var savedAction = OnSaved;
var closeAction = VisibleChanged;
}
<ModalFrame Visible="@Visible" Title="@(_isNew ? "New driver" : "Configure driver")" Target="@presentation" Busy="@Pending" DialogClass="modal-xl" OnClose="() => ClosePresentation(presentation, closeAction)">
<TitleContent>@(_isNew ? "New driver" : "Configure driver") &middot; <span class="mono">@_driverType</span></TitleContent>
<ChildContent>
<fieldset disabled="@(Pending || _loading)" @key="_openGeneration">
@if (_loading)
{ <p role="status">Loading…</p> }
else if (_loadError is not null)
{
<div class="panel notice notice-alert mb-3">@_loadError</div>
}
@@ -26,7 +28,7 @@
<div class="row g-3 mb-2">
<div class="col-md-6">
<TechField Label="Driver name" For="@_nameId" Hint="A RawPath segment — letters, digits, dash, underscore." HintId="@(_nameId + "-hint")">
<input id="@_nameId" class="form-control form-control-sm mono" @bind="_name" placeholder="line3-modbus" aria-describedby="@(_nameId + "-hint")" />
<input id="@_nameId" class="form-control form-control-sm mono" @bind="_name" placeholder="line3-modbus" aria-describedby="@(_nameId + "-hint " + FieldId("save-error"))" />
</TechField>
</div>
</div>
@@ -37,7 +39,7 @@
green (deferment.md G-1/G-4). The map is guarded by DriverFormMapParityTests. *@
@if (DriverConfigFormMap.Resolve(_driverType) is { } formType)
{
<DynamicComponent Type="formType" Parameters="_formParameters" />
<DynamicComponent @key="_openGeneration" Type="formType" Parameters="_formParameters" />
}
else
{
@@ -63,28 +65,27 @@
</p>
}
<SaveRefusalNotice GateError="@DriverConfigSaveGate.Validate(_driverType, _driverConfigJson)" SaveError="@_saveError" />
<div id='@FieldId("save-error")'><SaveRefusalNotice GateError="@DriverConfigSaveGate.Validate(_driverType, _driverConfigJson)" SaveError="@_saveError" /></div>
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">Cancel</button>
@if (_loadError is null)
{
<button type="button" class="btn btn-primary" @onclick="SaveAsync"
disabled="@(_busy || DriverConfigSaveGate.Validate(_driverType, _driverConfigJson) is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
@(_isNew ? "Create driver" : "Save changes")
</button>
}
</div>
</div>
</div>
</fieldset>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => ClosePresentation(presentation, closeAction)" disabled="@Pending">Cancel</button>
@if (_loadError is null)
{
<button type="button" class="btn btn-primary" @onclick="() => SavePresentation(presentation, savedAction, closeAction)" disabled="@(Pending || _loading || DriverConfigSaveGate.Validate(_driverType, _driverConfigJson) is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
@(_isNew ? "Create driver" : "Save changes")
</button>
}
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Whether the modal is shown (supports @bind-Visible).</summary>
[Parameter] public bool Visible { get; set; }
/// <summary>Two-way visibility callback.</summary>
@@ -114,17 +115,23 @@
/// CURRENT json — a build-once dictionary would pin the value captured at first render and silently
/// strand every subsequent edit — so the cache is keyed on the values it carries and rebuilt only when
/// one changes; the callbacks are created once and reused (R04 H2).</summary>
private Dictionary<string, object> _formParameters => _formParameterCache.Get(
[_driverConfigJson, _resilienceConfig],
() => new()
private Dictionary<string, object> _formParameters {
get
{
["DriverConfigJson"] = _driverConfigJson,
["DriverConfigJsonChanged"] = _driverConfigJsonChanged ??=
EventCallback.Factory.Create<string>(this, v => { _driverConfigJson = v; _saveError = null; }),
["ResilienceConfig"] = _resilienceConfig!,
["ResilienceConfigChanged"] = _resilienceConfigChanged ??=
EventCallback.Factory.Create<string?>(this, v => _resilienceConfig = v),
});
var generation = _openGeneration;
return _formParameterCache.Get(
[_driverConfigJson, _resilienceConfig, _openGeneration],
() => new()
{
["DriverConfigJson"] = _driverConfigJson,
["DriverConfigJsonChanged"] = _driverConfigJsonChanged ??=
EventCallback.Factory.Create<string>(this, GuardChange<string>(generation, v => { _driverConfigJson = v; _saveError = null; })),
["ResilienceConfig"] = _resilienceConfig!,
["ResilienceConfigChanged"] = _resilienceConfigChanged ??=
EventCallback.Factory.Create<string?>(this, GuardChange<string?>(generation, v => _resilienceConfig = v)),
});
}
}
private readonly ParameterDictionaryCache _formParameterCache = new();
private EventCallback<string>? _driverConfigJsonChanged;
private EventCallback<string?>? _resilienceConfigChanged;
@@ -136,96 +143,115 @@
private string? _saveError;
private bool _openHandled;
// Bumped on every open and close; LoadAsync re-checks it after each await so a superseded open can't
// install one target's fields under another target's displayed modal (RawBrowseModal idiom).
private int _openGeneration;
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
/// <summary>Optional nonconfidential identity for otherwise identical editor contexts.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-config-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _loading, _closing, _disposed, _lastVisible;
private object? _lastTarget;
private int _openGeneration;
private bool Pending => _busy || _closing;
private bool IsStale(int generation) => _disposed || generation != _openGeneration || !Visible;
private Action<T> GuardChange<T>(int generation, Action<T> update) => value => { if (!IsStale(generation) && !Pending && !_loading) update(value); };
protected override async Task OnParametersSetAsync()
{
if (Visible && !_openHandled)
object identity = (Target, DriverInstanceId, ClusterId, FolderId, DriverType);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_openGeneration;
_openHandled = Visible;
if (Visible)
{
_openHandled = true;
await LoadAsync(++_openGeneration);
}
else if (!Visible)
{
_openHandled = false;
_openGeneration++;
_driverConfigJsonChanged = null;
_resilienceConfigChanged = null;
_formParameterCache.Reset();
await LoadAsync(generation);
}
}
private async Task LoadAsync(int generation)
{
_busy = false; _loadError = null; _saveError = null;
_isNew = string.IsNullOrEmpty(DriverInstanceId);
var driverInstanceId = DriverInstanceId;
var driverType = DriverType;
_loading = true;
if (_isNew)
try
{
_driverType = DriverType ?? "";
_name = "";
_driverConfigJson = "{}";
_resilienceConfig = null;
_rowVersion = [];
}
else
{
var dto = await Svc.LoadDriverForEditAsync(DriverInstanceId!);
if (IsStale(generation)) { return; }
if (dto is null) { _loadError = $"Driver '{DriverInstanceId}' was not found."; return; }
_driverType = dto.DriverType;
_name = dto.Name;
_driverConfigJson = string.IsNullOrWhiteSpace(dto.DriverConfig) ? "{}" : dto.DriverConfig;
_resilienceConfig = dto.ResilienceConfig;
_rowVersion = dto.RowVersion;
_loadError = null; _saveError = null;
_isNew = string.IsNullOrEmpty(driverInstanceId);
if (_isNew)
{
_driverType = driverType ?? "";
_name = "";
_driverConfigJson = "{}";
_resilienceConfig = null;
_rowVersion = [];
}
else
{
var dto = await Svc.LoadDriverForEditAsync(driverInstanceId!);
if (IsStale(generation)) { return; }
if (dto is null) { _loadError = $"Driver '{driverInstanceId}' was not found."; return; }
_driverType = dto.DriverType;
_name = dto.Name;
_driverConfigJson = string.IsNullOrWhiteSpace(dto.DriverConfig) ? "{}" : dto.DriverConfig;
_resilienceConfig = dto.ResilienceConfig;
_rowVersion = dto.RowVersion;
}
}
catch (Exception) when (IsStale(generation)) { }
finally { if (!IsStale(generation)) _loading = false; }
}
private async Task SaveAsync()
private Task SaveAsync() => SavePresentation(_openGeneration, OnSaved, VisibleChanged);
private async Task SavePresentation(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
// A resubmit REPLACES the previous refusal; a gate refusal is already rendered live by
// SaveRefusalNotice, so it is not copied into _saveError (that stacked two boxes — lmxopcua#847).
if (IsStale(generation) || Pending || _loading || _loadError is not null) return;
_saveError = null;
if (DriverConfigSaveGate.Validate(_driverType, _driverConfigJson) is not null) return;
var isNew = _isNew;
var name = _name;
var json = _driverConfigJson;
var driverType = _driverType;
var rowVersion = _rowVersion.ToArray();
var driverInstanceId = DriverInstanceId;
var clusterId = ClusterId;
var folderId = FolderId;
var resilience = _resilienceConfig;
_busy = true;
try
{
UnsMutationResult result;
if (_isNew)
if (isNew)
{
if (string.IsNullOrEmpty(ClusterId))
{
_saveError = "No owning cluster was supplied.";
return;
}
result = await Svc.CreateDriverAsync(ClusterId, FolderId, _name, _driverType, _driverConfigJson);
if (string.IsNullOrEmpty(clusterId)) { _saveError = "No owning cluster was supplied."; return; }
result = await Svc.CreateDriverAsync(clusterId, folderId, name, driverType, json);
}
else
{
result = await Svc.UpdateDriverAsync(DriverInstanceId!, _name, _driverConfigJson, _resilienceConfig, _rowVersion);
}
if (!result.Ok)
{
_saveError = result.Error ?? "Save failed.";
return;
}
await OnSaved.InvokeAsync();
await SetVisibleAsync(false);
else result = await Svc.UpdateDriverAsync(driverInstanceId!, name, json, resilience, rowVersion);
if (IsStale(generation)) return;
if (!result.Ok) { _saveError = result.Error ?? "Save failed."; return; }
await savedAction.InvokeAsync();
if (!IsStale(generation)) await ClosePresentation(generation, closeAction, true);
}
catch (Exception ex) { _saveError = ex.Message; }
catch (Exception ex) { if (!IsStale(generation)) _saveError = ex.Message; }
finally { _busy = false; }
}
private Task CloseAsync() => SetVisibleAsync(false);
private async Task SetVisibleAsync(bool value)
private Task CloseAsync() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> action, bool afterSave = false)
{
Visible = value;
_openHandled = value;
_openGeneration++;
await VisibleChanged.InvokeAsync(value);
if (IsStale(generation) || _closing || (_busy && !afterSave)) return;
_closing = true;
Visible = false; _lastVisible = false; _openHandled = false; ++_openGeneration;
try { await action.InvokeAsync(false); }
finally { _closing = false; }
}
/// <summary>Invalidates UI callbacks and read results without cancelling dispatched mutations.</summary>
public void Dispose() { _disposed = true; ++_openGeneration; }
}
@@ -14,24 +14,18 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns
@inject RawTagCsvExportReader ExportReader
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Export tags — CSV</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="Close"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{ var presentation = _openGeneration; var closeAction = VisibleChanged; }
<ModalFrame Visible="@Visible" Title="Export tags — CSV" DialogClass="modal-lg" Target="@presentation" Busy="@_closing" OnClose="() => ClosePresentation(presentation, closeAction)">
<ChildContent>
@if (_loading)
{
<p class="text-muted"><span class="spinner-border spinner-border-sm"></span> Reading tags…</p>
<p class="text-muted" role="status"><span class="spinner-border spinner-border-sm" aria-hidden="true"></span> Reading tags…</p>
}
else if (_error is not null)
{
<div class="alert alert-danger">@_error</div>
<div class="alert alert-danger" role="alert">@_error</div>
}
else
{
@@ -47,24 +41,22 @@
{
<p class="small text-muted mb-1">Preview — first @RawTagCsvExport.PreviewLines lines. Download for the full file.</p>
}
<textarea class="form-control mono small" rows="10" readonly>@_preview</textarea>
<label class="form-label" for="@_previewId">CSV preview</label>
<textarea id="@_previewId" class="form-control mono small" rows="10" readonly>@_preview</textarea>
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="Close">Close</button>
@if (!_loading && _error is null)
{
<a class="btn btn-primary" download="@_fileName" href="@_downloadUrl">Download CSV</a>
}
</div>
</div>
</div>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" disabled="@_closing" @onclick="() => ClosePresentation(presentation, closeAction)">Close</button>
@if (!_loading && _error is null)
{ <a class="btn btn-primary" download="@_fileName" href="@_downloadUrl">Download CSV</a> }
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Whether the modal is shown (two-way bound).</summary>
[Parameter] public bool Visible { get; set; }
@@ -90,27 +82,32 @@
private int _rowCount;
private string? _groupFilter;
// Bumped on every open and close so a superseded build can't install its CSV under another device's modal.
/// <summary>Optional nonconfidential export context identity.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _previewId = "csv-preview-" + Guid.NewGuid().ToString("N");
private bool _lastVisible, _closing, _disposed;
private object? _lastTarget;
private int _openGeneration;
protected override async Task OnParametersSetAsync()
{
if (Visible && !_built)
{
_built = true;
await BuildAsync(++_openGeneration);
}
else if (!Visible)
{
_built = false;
_openGeneration++;
}
object identity = (Target, DeviceId, TagGroupId, DriverType);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_openGeneration;
_built = Visible;
if (Visible) await BuildAsync(generation);
}
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
private bool IsStale(int generation) => _disposed || generation != _openGeneration || !Visible;
private async Task BuildAsync(int generation)
{
var deviceId = DeviceId;
var tagGroupId = TagGroupId;
var driverType = DriverType;
_preview = ""; _rowCount = 0; _downloadUrl = ""; _truncated = false;
_loading = true;
_error = null;
try
@@ -118,7 +115,7 @@
_groupFilter = null;
// The same builder the download endpoint runs, so the preview matches the file — but mapping only
// the preview's rows (the header takes the first line), never the whole export (review r0 M8).
var export = await RawTagCsvExport.BuildAsync(ExportReader, DeviceId, TagGroupId, DriverType,
var export = await RawTagCsvExport.BuildAsync(ExportReader, deviceId, tagGroupId, driverType,
maxRows: RawTagCsvExport.PreviewLines - 1);
if (IsStale(generation)) { return; }
if (export is null)
@@ -133,7 +130,7 @@
// Only the bounded preview is kept on the component; the full CSV is not held by the circuit.
(_preview, var cut) = RawTagCsvExport.Preview(export.Csv);
_truncated = cut || export.RowCount > RawTagCsvExport.PreviewLines - 1;
_downloadUrl = RawTagCsvExport.DownloadUrl(DeviceId, TagGroupId, DriverType);
_downloadUrl = RawTagCsvExport.DownloadUrl(deviceId, tagGroupId, driverType);
}
catch (Exception ex)
{
@@ -145,14 +142,17 @@
}
}
private async Task Close()
private Task Close() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> action)
{
_built = false;
_openGeneration++;
_preview = "";
_truncated = false;
_downloadUrl = "";
Visible = false;
await VisibleChanged.InvokeAsync(false);
if (IsStale(generation) || _closing) return;
_closing = true;
_built = false; _lastVisible = false; ++_openGeneration;
_preview = ""; _truncated = false; _downloadUrl = ""; Visible = false;
try { await action.InvokeAsync(false); }
finally { _closing = false; }
}
/// <summary>Discards late read results without changing the export/download contract.</summary>
public void Dispose() { _disposed = true; ++_openGeneration; }
}
@@ -14,20 +14,17 @@
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@inject IRawTreeService Svc
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<EditForm Model="_form" OnValidSubmit="SaveAsync" FormName="rawTagModal">
<DataAnnotationsValidator />
<div class="modal-header">
<h5 class="modal-title">Edit tag</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
@if (_loadError is not null)
@implements IDisposable
@{ var presentation = _openGeneration; var savedAction = OnSaved; var closeAction = VisibleChanged; }
<ModalFrame Visible="@Visible" Title="Edit tag" DialogClass="modal-lg" Target="@presentation" Busy="@Pending" OnClose="() => ClosePresentation(presentation, closeAction)">
<ChildContent>
<EditForm @ref="_editForm" id='@FieldId("form")' Model="_form" OnValidSubmit="() => SavePresentation(presentation, savedAction, closeAction)" OnInvalidSubmit="() => FocusInvalidOwnedField(presentation)" FormName="rawTagModal" aria-describedby='@FieldId("save-error")'>
<DataAnnotationsValidator />
<fieldset disabled="@(Pending || _loading)" @key="_openGeneration">
@if (_loading)
{ <p role="status">Loading…</p> }
else if (_loadError is not null)
{
<div class="alert alert-danger py-2">@_loadError</div>
}
@@ -35,26 +32,23 @@
{
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="raw-tag-name">Name</label>
<InputText id="raw-tag-name" @bind-Value="_form.Name" class="form-control form-control-sm"
<label class="form-label" for='@FieldId("raw-tag-name")'>Name</label>
<InputText @ref="_nameInput" id='@FieldId("raw-tag-name")' aria-describedby='@FieldId("name-error")' @bind-Value="_form.Name" class="form-control form-control-sm"
placeholder="Temperature" />
<ValidationMessage For="@(() => _form.Name)" />
@if (_nameError is not null)
{
<div class="text-danger small">@_nameError</div>
}
<div id='@FieldId("name-error")'><ValidationMessage For="@(() => _form.Name)" />
</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="raw-tag-dtype">Data type</label>
<label class="form-label" for='@FieldId("raw-tag-dtype")'>Data type</label>
@if (RawTagRowDefaults.DictatedDataType(DriverType, _form.TagConfig) is { } dictated)
{
@* lmxopcua#830: locked to what the driver publishes for this address. *@
<input id="raw-tag-dtype" class="form-control form-control-sm mono" value="@dictated" disabled readonly />
<input id='@FieldId("raw-tag-dtype")' class="form-control form-control-sm mono" value="@dictated" disabled readonly />
<div class="form-text">Set by the address.</div>
}
else
{
<InputSelect id="raw-tag-dtype" @bind-Value="_form.DataType" class="form-select form-select-sm">
<InputSelect id='@FieldId("raw-tag-dtype")' @bind-Value="_form.DataType" class="form-select form-select-sm">
@foreach (var dt in DataTypes)
{
<option value="@dt">@dt</option>
@@ -65,75 +59,74 @@
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="raw-tag-access">Access level</label>
<label class="form-label" for='@FieldId("raw-tag-access")'>Access level</label>
@if (IsReadOnlyDriver)
{
<input id="raw-tag-access" class="form-control form-control-sm" value="Read" disabled readonly />
<input id='@FieldId("raw-tag-access")' class="form-control form-control-sm" value="Read" disabled readonly />
<div class="form-text">This driver is read-only.</div>
}
else
{
<InputSelect id="raw-tag-access" @bind-Value="_form.AccessLevel" class="form-select form-select-sm">
<InputSelect id='@FieldId("raw-tag-access")' @bind-Value="_form.AccessLevel" class="form-select form-select-sm">
<option value="@TagAccessLevel.Read">Read</option>
<option value="@TagAccessLevel.ReadWrite">ReadWrite</option>
</InputSelect>
}
</div>
<div class="col-md-6 mb-3">
<label class="form-label">WriteIdempotent</label>
<span class="form-label">WriteIdempotent</span>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.WriteIdempotent" class="form-check-input" />
<label class="form-check-label">Safe to retry writes</label>
<InputCheckbox id='@FieldId("write-idempotent")' @bind-Value="_form.WriteIdempotent" class="form-check-input" />
<label class="form-check-label" for='@FieldId("write-idempotent")'>Safe to retry writes</label>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="raw-tag-pgroup">PollGroupId (optional)</label>
<InputText id="raw-tag-pgroup" @bind-Value="_form.PollGroupId" class="form-control form-control-sm mono" />
<label class="form-label" for='@FieldId("raw-tag-pgroup")'>PollGroupId (optional)</label>
<InputText id='@FieldId("raw-tag-pgroup")' @bind-Value="_form.PollGroupId" class="form-control form-control-sm mono" />
</div>
<div class="mb-3">
<label class="form-label">Tag config <span class="text-muted small">(@DriverType)</span></label>
@{
var editorType = TagConfigEditorMap.Resolve(DriverType);
}
@if (editorType is not null)
{
<DynamicComponent Type="editorType" Parameters="BuildEditorParameters()" />
<div class="form-label" id='@FieldId("config-label")'>Tag config <span class="text-muted small">(@DriverType)</span></div>
<DynamicComponent @key="_openGeneration" Type="editorType" Parameters="BuildEditorParameters()" />
}
else
{
<InputTextArea id="raw-tag-config" @bind-Value="_form.TagConfig" rows="6"
<label class="form-label" for='@FieldId("raw-tag-config")'>Tag config <span class="text-muted small">(@DriverType)</span></label>
<InputTextArea @ref="_configInput" id='@FieldId("raw-tag-config")' aria-describedby='@FieldIds("config-hint", "save-error")' @bind-Value="_form.TagConfig" rows="6"
class="form-control form-control-sm mono"
placeholder='{ "FullName": "tag_name.AttributeName" }' />
<div class="form-text">Schemaless per driver type. Validated server-side at deploy.</div>
<div id='@FieldId("config-hint")' class="form-text">Schemaless per driver type. Validated server-side at deploy.</div>
}
</div>
<NativeAlarmEditor ConfigJson="@_form.TagConfig"
ConfigJsonChanged="@(v => _form.TagConfig = v)"
ConfigJsonChanged="@(v => UpdateAlarmConfig(v, presentation))"
DriverType="@DriverType" />
}
@if (!string.IsNullOrWhiteSpace(_error))
{
<div class="text-danger small mt-2">@_error</div>
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">Cancel</button>
<button type="submit" class="btn btn-primary" disabled="@(_busy || _loadError is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
Save changes
</button>
</div>
</div>
</EditForm>
</div>
<div id='@FieldId("save-error")' role="alert" class="text-danger small"><ValidationMessage For="@(() => _form.TagConfig)" />@_error</div>
</fieldset>
</EditForm>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => ClosePresentation(presentation, closeAction)" disabled="@Pending">Cancel</button>
<button type="submit" form='@FieldId("form")' class="btn btn-primary" disabled="@(Pending || _loading || _loadError is not null)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
Save changes
</button>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
private static readonly string[] DataTypes =
["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
"Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid", "ByteString"];
@@ -157,7 +150,12 @@
private byte[] _rowVersion = Array.Empty<byte>();
private bool _busy;
private string? _error;
private string? _nameError;
private EditForm? _editForm;
private InputText? _nameInput;
private InputTextArea? _configInput;
private EditContext? _nameContext;
private ValidationMessageStore? _nameMessages;
private EventHandler<FieldChangedEventArgs>? _nameFieldChanged;
private string? _loadError;
// Tracks which (open, tag) this modal last loaded for, so unrelated Blazor Server re-renders don't
@@ -169,150 +167,186 @@
// browse then degrades to its graceful error chip.
private string? _mergedConfigJson;
/// <summary>Optional nonconfidential context identity for identical tag presentations.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-tag-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private object? _lastTarget;
private bool _lastVisible, _loading, _closing, _disposed;
private int _openGeneration;
private bool Pending => _busy || _closing;
private bool IsStale(int generation) => _disposed || !Visible || generation != _openGeneration;
protected override async Task OnParametersSetAsync()
{
if (!Visible)
{
_loadedKey = null; // closed → next open reloads fresh
_mergedConfigJson = null;
return;
}
var key = TagId;
if (key == _loadedKey) { return; } // same open, re-render → preserve in-progress edits
_loadedKey = key;
_error = null;
_nameError = null;
_loadError = null;
if (string.IsNullOrEmpty(TagId))
{
_loadError = "No tag selected.";
return;
}
var dto = await Svc.LoadTagForEditAsync(TagId);
// Two opens can overlap on one modal instance (the tree's Edit command is synchronous and does
// not disable while this resolves), so every post-await write is discarded unless this open is
// still the displayed one. Last-completion-wins would point the picker at another device.
if (_loadedKey != key || !Visible) { return; }
// RawTagEditDto is a record struct → a missing tag comes back as default (all-zero), not null.
if (dto is not { } d || string.IsNullOrEmpty(d.TagId))
{
_loadError = "This tag no longer exists.";
return;
}
_form = new FormModel
{
Name = d.Name,
DataType = string.IsNullOrEmpty(d.DataType) ? "Float" : d.DataType,
AccessLevel = d.AccessLevel,
WriteIdempotent = d.WriteIdempotent,
PollGroupId = d.PollGroupId,
TagConfig = string.IsNullOrWhiteSpace(d.TagConfig) ? "{}" : d.TagConfig,
};
_rowVersion = d.RowVersion;
object identity = (Target, TagId, DriverType);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
ResetNameValidation(); _nameInput = null; _configInput = null;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_openGeneration;
_probeConfig = new ProbeConfigState();
_mergedConfigJson = null;
_loadedKey = Visible ? TagId : null;
if (!Visible) return;
_configJsonChanged = null; _getDriverConfigJson = null; _editorParameterCache.Reset();
var key = TagId;
_error = null; _loadError = null; _loading = true;
try
{
var merged = await Svc.LoadMergedProbeConfigAsync(d.DeviceId);
if (_loadedKey != key || !Visible) { return; } // superseded open → never install its device
if (merged is { } m)
if (string.IsNullOrEmpty(key)) { _loadError = "No tag selected."; return; }
var dto = await Svc.LoadTagForEditAsync(key);
if (IsStale(generation) || _loadedKey != key) return;
if (dto is not { } d || string.IsNullOrEmpty(d.TagId)) { _loadError = "This tag no longer exists."; return; }
_form = new FormModel
{
_mergedConfigJson = m.MergedConfigJson;
Name = d.Name,
DataType = string.IsNullOrEmpty(d.DataType) ? "Float" : d.DataType,
AccessLevel = d.AccessLevel,
WriteIdempotent = d.WriteIdempotent,
PollGroupId = d.PollGroupId,
TagConfig = string.IsNullOrWhiteSpace(d.TagConfig) ? "{}" : d.TagConfig,
};
_rowVersion = d.RowVersion;
try
{
var merged = await Svc.LoadMergedProbeConfigAsync(d.DeviceId);
if (IsStale(generation) || _loadedKey != key) return;
if (merged is { } m)
{
_mergedConfigJson = m.MergedConfigJson;
_probeConfig.Value = m.MergedConfigJson;
}
}
catch
{
// Existing fail-soft probe resolution: tag editing/saving remains available.
}
}
catch
{
// Fail-soft: the modal must open and save regardless of the probe-config resolve. Only the
// browse affordance degrades, and it reports its own error when used.
}
catch (Exception) when (IsStale(generation)) { }
finally { if (!IsStale(generation)) _loading = false; }
}
/// <summary>Parameters handed to the typed TagConfig editor. Internal so tests can assert them. Cached
/// on the values it carries and rebuilt when one changes (never build-once, which would pin the first
/// render's TagConfig); the callback and accessor are created once (R04 H2).</summary>
internal IDictionary<string, object> BuildEditorParameters() => _editorParameterCache.Get(
[_form.TagConfig, DriverType ?? ""],
() => new Dictionary<string, object>
{
["ConfigJson"] = _form.TagConfig,
["ConfigJsonChanged"] = _configJsonChanged ??=
EventCallback.Factory.Create<string>(this, v =>
{
_form.TagConfig = v;
RawTagRowDefaults.Apply(DriverType, _form.TagConfig, a => _form.AccessLevel = a, d => _form.DataType = d);
}),
["DriverType"] = DriverType ?? "",
// Live accessor, not a snapshot: the picker reads it when the operator clicks Browse.
["GetDriverConfigJson"] = _getDriverConfigJson ??= () => _mergedConfigJson ?? "{}",
});
/// <summary>Caches live values and callbacks within one presentation; retired callbacks cannot retarget a newer editor.</summary>
internal IDictionary<string, object> BuildEditorParameters()
{
var generation = _openGeneration;
var driverType = DriverType;
var probeConfig = _probeConfig;
return _editorParameterCache.Get(
[_form.TagConfig, driverType ?? "", generation],
() => new Dictionary<string, object>
{
["ConfigJson"] = _form.TagConfig,
["ConfigJsonChanged"] = _configJsonChanged ??=
EventCallback.Factory.Create<string>(this, v =>
{
if (IsStale(generation) || Pending || _loading) return;
_form.TagConfig = v;
RawTagRowDefaults.Apply(driverType, _form.TagConfig, a => _form.AccessLevel = a, d => _form.DataType = d);
}),
["DriverType"] = driverType ?? "",
["GetDriverConfigJson"] = _getDriverConfigJson ??= () => probeConfig.Value,
});
}
private readonly ParameterDictionaryCache _editorParameterCache = new();
private EventCallback<string>? _configJsonChanged;
private Func<string>? _getDriverConfigJson;
private sealed class ProbeConfigState { public string Value = "{}"; }
private ProbeConfigState _probeConfig = new();
private async Task SaveAsync()
private void UpdateAlarmConfig(string value, int generation)
{
if (!IsStale(generation) && !Pending && !_loading) _form.TagConfig = value;
}
private Task SaveAsync() => SavePresentation(_openGeneration, OnSaved, VisibleChanged);
private async Task SavePresentation(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
if (IsStale(generation) || Pending || _loading || _loadError is not null) return;
_error = null; SetNameValidation(null, generation);
var driverType = DriverType;
var nameError = RawPaths.ValidateSegment(_form.Name);
if (nameError is not null) { SetNameValidation(nameError, generation); await FocusInvalidOwnedField(generation); return; }
var configError = TagConfigValidator.Validate(driverType, _form.TagConfig);
if (configError is not null) { _error = configError; return; }
RawTagRowDefaults.Apply(driverType, _form.TagConfig, a => _form.AccessLevel = a, d => _form.DataType = d);
var input = new RawTagInput(_form.Name, _form.DataType, _form.AccessLevel, _form.WriteIdempotent,
string.IsNullOrWhiteSpace(_form.PollGroupId) ? null : _form.PollGroupId,
string.IsNullOrWhiteSpace(_form.TagConfig) ? "{}" : _form.TagConfig);
var tagId = TagId!;
var rowVersion = _rowVersion.ToArray();
_busy = true;
_error = null;
_nameError = null;
try
{
// Client-side name validation (RawPath segment) so a bad name is caught before the round-trip.
var nameError = RawPaths.ValidateSegment(_form.Name);
if (nameError is not null)
{
_nameError = nameError;
return;
}
// Client-side per-driver config validation (the typed editor's Validate()).
var configError = TagConfigValidator.Validate(DriverType, _form.TagConfig);
if (configError is not null)
{
_error = configError;
return;
}
RawTagRowDefaults.Apply(DriverType, _form.TagConfig, a => _form.AccessLevel = a, d => _form.DataType = d);
var input = new RawTagInput(
_form.Name,
_form.DataType,
_form.AccessLevel,
_form.WriteIdempotent,
string.IsNullOrWhiteSpace(_form.PollGroupId) ? null : _form.PollGroupId,
string.IsNullOrWhiteSpace(_form.TagConfig) ? "{}" : _form.TagConfig);
var result = await Svc.UpdateTagAsync(TagId!, input, _rowVersion);
var result = await Svc.UpdateTagAsync(tagId, input, rowVersion);
if (IsStale(generation)) return;
if (result.Ok)
{
await OnSaved.InvokeAsync();
await CloseAsync();
}
else
{
_error = result.Error;
await savedAction.InvokeAsync();
if (!IsStale(generation)) await ClosePresentation(generation, closeAction, true);
}
else _error = result.Error;
}
finally
catch (Exception) when (IsStale(generation)) { }
finally { _busy = false; }
}
private void SetNameValidation(string? error, int generation)
{
if (_editForm?.EditContext is not { } context) return;
if (!ReferenceEquals(context, _nameContext))
{
_busy = false;
ResetNameValidation();
_nameContext = context;
var messages = new ValidationMessageStore(context);
var field = new FieldIdentifier(_form, nameof(FormModel.Name));
_nameMessages = messages;
_nameFieldChanged = (_, args) =>
{
if (IsStale(generation) || !args.FieldIdentifier.Equals(field)) return;
messages.Clear(field);
context.NotifyValidationStateChanged();
};
context.OnFieldChanged += _nameFieldChanged;
}
_nameMessages!.Clear();
if (error is not null) _nameMessages.Add(new FieldIdentifier(_form, nameof(FormModel.Name)), error);
context.NotifyValidationStateChanged();
}
private async Task FocusInvalidOwnedField(int generation)
{
if (IsStale(generation) || _loading || _closing || _editForm?.EditContext is not { } context) return;
ElementReference? element = null;
if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(FormModel.Name))).Any()) element = _nameInput?.Element;
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(FormModel.TagConfig))).Any()) element = _configInput?.Element;
if (element is not { } target) return;
try { await target.FocusAsync(); }
catch (JSDisconnectedException) { }
catch (JSException) { }
catch (InvalidOperationException) { } // Static SSR has no browser element runtime.
}
private void ResetNameValidation()
{
if (_nameContext is not null && _nameFieldChanged is not null) _nameContext.OnFieldChanged -= _nameFieldChanged;
_nameMessages?.Clear();
_nameContext = null; _nameMessages = null; _nameFieldChanged = null;
}
private bool IsReadOnlyDriver => RawTagRowDefaults.IsReadOnlyDriver(DriverType);
private async Task CloseAsync()
private Task CloseAsync() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> action, bool afterSave = false)
{
Visible = false;
_loadedKey = null;
await VisibleChanged.InvokeAsync(false);
if (IsStale(generation) || _closing || (_busy && !afterSave)) return;
_closing = true;
ResetNameValidation(); _editForm = null; _nameInput = null; _configInput = null;
Visible = false; _lastVisible = false; _loadedKey = null; ++_openGeneration;
try { await action.InvokeAsync(false); }
finally { _closing = false; }
}
/// <summary>Invalidates old callbacks and reads without cancelling a dispatched update.</summary>
public void Dispose() { ResetNameValidation(); _editForm = null; _nameInput = null; _configInput = null; _disposed = true; ++_openGeneration; }
private sealed class FormModel
{
@@ -323,4 +357,5 @@
public string? PollGroupId { get; set; }
[Required] public string TagConfig { get; set; } = "{}";
}
}