fix(admin-ui): scope UNS modal lifecycles and script identity

This commit is contained in:
Joseph Doherty
2026-11-14 00:14:30 -05:00
parent 071148e9b8
commit a0aa4f023c
69 changed files with 8332 additions and 437 deletions
@@ -7,17 +7,15 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
@inject IUnsTreeService 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">Add tag references</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CancelAsync"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{
var presentation = _generation;
var completedAction = OnCommitted;
var cancelAction = OnCancel;
}
<ModalFrame DialogClass="modal-lg modal-dialog-scrollable" Visible="@Visible" Title='Add tag references' Target="@presentation" Busy="@Pending" OnClose="() => CancelAsync(presentation, cancelAction)">
<ChildContent>
<fieldset disabled="@Pending">
<p class="text-muted small mb-2">
Pick raw tags to reference under this equipment. The tree is scoped to the
equipment's cluster. Tick individual tags, or use a device / tag-group's
@@ -26,7 +24,7 @@
@if (_loading)
{
<p class="text-muted"><span class="spinner-border spinner-border-sm me-1"></span>Loading…</p>
<p class="text-muted"><span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>Loading…</p>
}
else if (_roots.Count == 0)
{
@@ -36,31 +34,41 @@
{
<div class="border rounded p-2" style="max-height:50vh; overflow:auto">
<RawTree Roots="_roots" PickerMode="true" SelectedTagIds="_selected"
OnSelectionChanged="OnSelectionChanged"
ResolveDescendantTagIds="ResolveDescendantsAsync" />
@key="presentation" OnSelectionChanged="() => OnSelectionChanged(presentation)"
ResolveDescendantTagIds="node => ResolveDescendantsAsync(presentation, node)" />
</div>
}
@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="CancelAsync" disabled="@_busy">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="CommitAsync" disabled="@(_busy || _selected.Count == 0)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
</fieldset>
</ChildContent>
<Footer>
<div id='@FieldId("service-error")' role="alert" hidden="@string.IsNullOrWhiteSpace(_error)" class="text-danger small w-100">@_error</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => CancelAsync(presentation, cancelAction)" disabled="@Pending">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="() => CommitAsync(presentation, completedAction)" disabled="@(Pending || _loading || _selected.Count == 0)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
Add @_selected.Count reference@(_selected.Count == 1 ? "" : "s")
</button>
</div>
</div>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Optional nonconfidential identity for successive presentations.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-uns-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _disposed, _closing;
private long _generation;
private object? _lastTarget;
private bool _lastVisible;
private bool Current(long generation) => !_disposed && Visible && generation == _generation;
private bool Pending => _busy || _closing;
/// <summary>Retires UI continuations without cancelling a dispatched operation.</summary>
public void Dispose() { _disposed = true; ++_generation; }
/// <summary>Whether the modal is shown. The host owns this flag.</summary>
[Parameter] public bool Visible { get; set; }
@@ -74,64 +82,66 @@
[Parameter] public EventCallback OnCancel { get; set; }
private IReadOnlyList<RawNode> _roots = Array.Empty<RawNode>();
private readonly HashSet<string> _selected = new(StringComparer.Ordinal);
private HashSet<string> _selected = new(StringComparer.Ordinal);
private bool _busy;
private bool _loading;
private string? _error;
private bool _wasVisible;
// Bumped on every open and close so a superseded picker-root load can't install its tree under a
// different equipment's (or a re-opened) modal (RawBrowseModal idiom).
private int _openGeneration;
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
protected override async Task OnParametersSetAsync()
{
// Reset + reload only on the false→true transition so re-renders while open don't wipe state.
if (!Visible && _wasVisible) { _openGeneration++; }
if (Visible && !_wasVisible)
object identity = (Target, EquipmentId);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_generation;
if (!Visible) return;
_selected = new(StringComparer.Ordinal);
_error = null; _roots = Array.Empty<RawNode>(); _loading = true;
var equipmentId = EquipmentId;
try
{
_wasVisible = true;
var generation = ++_openGeneration;
_selected.Clear();
_error = null;
_roots = Array.Empty<RawNode>();
_loading = true;
StateHasChanged();
var root = string.IsNullOrEmpty(EquipmentId)
? null
: await Svc.LoadReferencePickerRootAsync(EquipmentId);
if (IsStale(generation)) { return; }
var root = string.IsNullOrEmpty(equipmentId) ? null : await Svc.LoadReferencePickerRootAsync(equipmentId);
if (!Current(generation)) return;
_roots = root is null ? Array.Empty<RawNode>() : new[] { root };
_loading = false;
}
_wasVisible = Visible;
catch when (!Current(generation)) { /* A superseded root load cannot fault the replacement. */ }
}
private Task<IReadOnlyList<string>> ResolveDescendantsAsync(RawNode node) =>
Svc.LoadDescendantTagIdsAsync(node);
// RawTree mutates _selected in place; this just re-renders the footer count.
private void OnSelectionChanged() => StateHasChanged();
private async Task CommitAsync()
private async Task<IReadOnlyList<string>> ResolveDescendantsAsync(long generation, RawNode node)
{
if (_selected.Count == 0) { return; }
_busy = true;
_error = null;
if (!Current(generation) || Pending) return Array.Empty<string>();
try
{
var res = await Svc.AddReferencesAsync(EquipmentId!, _selected.ToList());
if (res.Ok) { await OnCommitted.InvokeAsync(); }
else { _error = res.Error; }
}
finally
{
_busy = false;
var ids = await Svc.LoadDescendantTagIdsAsync(node);
return Current(generation) && !Pending ? ids : Array.Empty<string>();
}
catch when (!Current(generation)) { return Array.Empty<string>(); }
}
private Task CancelAsync() => OnCancel.InvokeAsync();
// Each presentation owns its set: a retired child can never mutate its replacement's selection.
private void OnSelectionChanged(long generation) { if (Current(generation)) StateHasChanged(); }
private async Task CommitAsync(long generation, EventCallback completedAction)
{
if (!Current(generation) || Pending || _loading || _selected.Count == 0) return;
var equipmentId = EquipmentId!;
var selected = _selected.ToList();
_busy = true; _error = null;
try
{
var result = await Svc.AddReferencesAsync(equipmentId, selected);
if (!Current(generation)) return;
if (result.Ok) await completedAction.InvokeAsync();
else _error = result.Error;
}
catch when (!Current(generation)) { /* A retired operation cannot surface an error in its replacement. */ }
finally { _busy = false; }
}
private async Task CancelAsync(long generation, EventCallback cancelAction)
{
if (!Current(generation) || Pending) return;
_closing = true;
try { await cancelAction.InvokeAsync(); }
finally { _closing = false; }
}
}
@@ -9,17 +9,15 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns
@inject IUnsTreeService 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">Import equipment CSV</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{
var presentation = _generation;
var completedAction = OnImported;
var cancelAction = OnCancel;
}
<ModalFrame DialogClass="modal-lg modal-dialog-scrollable" Visible="@Visible" Title='Import equipment CSV' Target="@presentation" Busy="@Pending" OnClose="() => CloseAsync(presentation, cancelAction, completedAction)">
<ChildContent>
<fieldset disabled="@Pending">
<p class="text-muted small mb-2">
Paste CSV below. Required header columns (in order):
<span class="mono">Name, MachineCode, UnsLineId</span>.
@@ -28,15 +26,13 @@
are detected by MachineCode and skipped (additive-only — no updates).
</p>
<textarea class="form-control form-control-sm mono" rows="12"
@bind="_csv" @bind:event="oninput" disabled="@_busy"
<label class="form-label" for='@FieldId("csv")'>Equipment CSV</label>
<textarea @ref="_csvInput" id='@FieldId("csv")' aria-describedby='@FieldIds("csv-hint", "csv-error")' aria-invalid="@(!string.IsNullOrEmpty(_parseError) ? "true" : null)" class="form-control form-control-sm mono" rows="12"
value="@_csv" @oninput="args => OnCsvInput(presentation, args)" disabled="@_busy"
placeholder="Name,MachineCode,UnsLineId,ZTag,SAPID,Manufacturer,Model&#10;mixer-01,MX_001,LINE-1,ZT-12345,SAP-9876,Siemens,SIMATIC-1500"></textarea>
<div class="form-text">RFC 4180 CSV: wrap a field containing commas, quotes or line breaks in double quotes (a quote inside is doubled: <span class="mono">""</span>). The opening quote must come straight after the comma — <span class="mono">a, "b"</span> is rejected.</div>
<div id='@FieldId("csv-hint")' class="form-text">RFC 4180 CSV: wrap a field containing commas, quotes or line breaks in double quotes (a quote inside is doubled: <span class="mono">""</span>). The opening quote must come straight after the comma — <span class="mono">a, "b"</span> is rejected.</div>
@if (!string.IsNullOrWhiteSpace(_parseError))
{
<div class="text-danger small mt-2">@_parseError</div>
}
@if (_result is not null)
{
@@ -57,24 +53,37 @@
}
</div>
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">
@(_result is null ? "Cancel" : "Close")
</fieldset>
</ChildContent>
<Footer>
<div id='@FieldId("csv-error")' role="alert" hidden="@string.IsNullOrWhiteSpace(_parseError)" class="text-danger small w-100">@_parseError</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => CloseAsync(presentation, cancelAction, completedAction)" disabled="@Pending">
@(_hasImportOutcome ? "Close" : "Cancel")
</button>
<button type="button" class="btn btn-primary" @onclick="ImportAsync" disabled="@_busy">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
<button type="button" class="btn btn-primary" @onclick="() => ImportAsync(presentation, completedAction)" disabled="@Pending">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
Import
</button>
</div>
</div>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Optional nonconfidential identity for successive presentations.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-uns-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _disposed, _closing;
private long _generation;
private object? _lastTarget;
private bool _lastVisible;
private bool Current(long generation) => !_disposed && Visible && generation == _generation;
private bool Pending => _busy || _closing;
/// <summary>Retires UI continuations without cancelling a dispatched operation.</summary>
public void Dispose() { _disposed = true; ++_generation; }
/// <summary>Whether the modal is shown. The host owns this flag.</summary>
[Parameter] public bool Visible { get; set; }
@@ -89,48 +98,59 @@
/// <summary>Raised when the user cancels before importing so the host can close.</summary>
[Parameter] public EventCallback OnCancel { get; set; }
private void OnCsvInput(long generation, ChangeEventArgs args)
{
if (Current(generation) && !Pending) _csv = args.Value?.ToString() ?? "";
}
private ElementReference _csvInput;
private string _csv = "";
private bool _busy;
private string? _parseError;
private EquipmentImportResult? _result;
private bool _wasVisible;
private bool _hasImportOutcome;
protected override void OnParametersSet()
{
// Reset only on the false→true transition so that re-renders while open don't wipe state.
if (Visible && !_wasVisible)
{
_csv = "";
_parseError = null;
_result = null;
}
_wasVisible = Visible;
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, Target))) return;
_lastVisible = Visible; _lastTarget = Target; ++_generation;
if (!Visible) return;
_csv = ""; _parseError = null; _result = null; _hasImportOutcome = false;
}
private async Task ImportAsync()
private async Task ImportAsync(long generation, EventCallback completedAction)
{
if (!Current(generation) || Pending) return;
var csv = _csv;
_parseError = null; _result = null;
var rows = ParseCsv(csv);
if (rows is null)
{
StateHasChanged();
await _csvInput.FocusAsync();
return;
}
_busy = true;
_parseError = null;
_result = null;
try
{
var rows = ParseCsv(_csv);
if (rows is null) { return; }
_result = await Svc.ImportEquipmentAsync(rows);
}
finally
{
_busy = false;
var result = await Svc.ImportEquipmentAsync(rows);
if (!Current(generation)) return;
_result = result;
_hasImportOutcome = true;
}
catch when (!Current(generation)) { /* A retired operation cannot surface an error in its replacement. */ }
finally { _busy = false; }
}
/// <summary>
/// Closes the modal. Once an import has run (the user has seen the summary), closing raises
/// OnImported so the host reloads the tree; before any import it raises OnCancel.
/// </summary>
private Task CloseAsync() =>
_result is not null ? OnImported.InvokeAsync() : OnCancel.InvokeAsync();
// A later parse error cannot erase an earlier landed import's refresh obligation.
private async Task CloseAsync(long generation, EventCallback cancelAction, EventCallback completedAction)
{
if (!Current(generation) || Pending) return;
var action = _hasImportOutcome ? completedAction : cancelAction;
_closing = true;
try { await action.InvokeAsync(); }
finally { _closing = false; }
}
/// <summary>Parses the pasted CSV via <see cref="EquipmentCsvParser"/> (RFC 4180, R04 S6); sets
/// <see cref="_parseError"/> and returns null on an empty/malformed CSV or a wrong header.</summary>
@@ -8,112 +8,121 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns
@inject IUnsTreeService 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="scriptedAlarmModal">
<DataAnnotationsValidator />
<div class="modal-header">
<h5 class="modal-title">@(IsNew ? "New scripted alarm" : "Edit scripted alarm")</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CancelAsync"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{
var presentation = _generation;
var form = _form;
var completedAction = OnSaved;
var cancelAction = OnCancel;
}
<ModalFrame DialogClass="modal-lg modal-dialog-scrollable" Visible="@Visible" Title='@(IsNew ? "New scripted alarm" : "Edit scripted alarm")' Target="@presentation" Busy="@Pending" OnClose="() => CancelAsync(presentation, cancelAction)">
<ChildContent>
<EditForm id='@FieldId("form")' Model="form" OnValidSubmit="() => SaveAsync(presentation, completedAction)" OnInvalidSubmit="context => FocusInvalidAsync(presentation, context)" FormName="scriptedAlarmModal" aria-describedby='@FieldId("service-error")'>
<DataAnnotationsValidator />
<fieldset disabled="@Pending">
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="alarm-id">ScriptedAlarmId</label>
<InputText id="alarm-id" @bind-Value="_form.ScriptedAlarmId" disabled="@(!IsNew)"
<label class="form-label" for='@FieldId("alarm-id")'>ScriptedAlarmId</label>
<InputText id='@FieldId("alarm-id")' @ref="_input0" aria-describedby='@FieldIds("alarm-id-error")' @bind-Value="form.ScriptedAlarmId" disabled="@(!IsNew)"
class="form-control form-control-sm mono" />
<ValidationMessage For="@(() => _form.ScriptedAlarmId)" />
<div id='@FieldId("alarm-id-error")' tabindex="-1" @ref="_error0"><ValidationMessage For="@(() => form.ScriptedAlarmId)" /></div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="alarm-name">Name</label>
<InputText id="alarm-name" @bind-Value="_form.Name" class="form-control form-control-sm" />
<ValidationMessage For="@(() => _form.Name)" />
<label class="form-label" for='@FieldId("alarm-name")'>Name</label>
<InputText id='@FieldId("alarm-name")' @ref="_input1" aria-describedby='@FieldIds("alarm-name-error")' @bind-Value="form.Name" class="form-control form-control-sm" />
<div id='@FieldId("alarm-name-error")' tabindex="-1" @ref="_error1"><ValidationMessage For="@(() => form.Name)" /></div>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="alarm-type">AlarmType</label>
<InputSelect id="alarm-type" @bind-Value="_form.AlarmType" class="form-select form-select-sm">
<label class="form-label" for='@FieldId("alarm-type")'>AlarmType</label>
<InputSelect id='@FieldId("alarm-type")' @ref="_input2" aria-describedby='@FieldIds("alarm-type-error")' @bind-Value="form.AlarmType" class="form-select form-select-sm">
<option value="LimitAlarm">LimitAlarm</option>
<option value="DiscreteAlarm">DiscreteAlarm</option>
<option value="OffNormalAlarm">OffNormalAlarm</option>
<option value="AlarmCondition">AlarmCondition</option>
</InputSelect>
<ValidationMessage For="@(() => _form.AlarmType)" />
<div id='@FieldId("alarm-type-error")' tabindex="-1" @ref="_error2"><ValidationMessage For="@(() => form.AlarmType)" /></div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="alarm-severity">Severity (1-1000)</label>
<InputNumber id="alarm-severity" @bind-Value="_form.Severity" class="form-control form-control-sm" />
<ValidationMessage For="@(() => _form.Severity)" />
<label class="form-label" for='@FieldId("alarm-severity")'>Severity (1-1000)</label>
<InputNumber DisplayName="Severity" id='@FieldId("alarm-severity")' @ref="_input3" aria-describedby='@FieldIds("alarm-severity-error")' @bind-Value="form.Severity" class="form-control form-control-sm" />
<div id='@FieldId("alarm-severity-error")' tabindex="-1" @ref="_error3"><ValidationMessage For="@(() => form.Severity)" /></div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="alarm-script">Predicate script</label>
<InputSelect id="alarm-script" @bind-Value="_form.PredicateScriptId" class="form-select form-select-sm">
<label class="form-label" for='@FieldId("alarm-script")'>Predicate script</label>
<InputSelect id='@FieldId("alarm-script")' @ref="_input4" aria-describedby='@FieldIds("alarm-script-error")' @bind-Value="form.PredicateScriptId" class="form-select form-select-sm">
<option value="">— pick script —</option>
@foreach (var (id, display) in Scripts)
{
<option value="@id">@display</option>
}
</InputSelect>
<ValidationMessage For="@(() => _form.PredicateScriptId)" />
<div id='@FieldId("alarm-script-error")' tabindex="-1" @ref="_error4"><ValidationMessage For="@(() => form.PredicateScriptId)" /></div>
</div>
<div class="mb-3">
<label class="form-label" for="alarm-message">Message template</label>
<InputTextArea id="alarm-message" @bind-Value="_form.MessageTemplate" rows="3"
<label class="form-label" for='@FieldId("alarm-message")'>Message template</label>
<InputTextArea id='@FieldId("alarm-message")' @ref="_input5" aria-describedby='@FieldIds("alarm-message-error")' @bind-Value="form.MessageTemplate" rows="3"
class="form-control form-control-sm"
placeholder="{equipment.MachineCode} temperature out of range: {value}°C" />
<ValidationMessage For="@(() => _form.MessageTemplate)" />
<div id='@FieldId("alarm-message-error")' tabindex="-1" @ref="_error5"><ValidationMessage For="@(() => form.MessageTemplate)" /></div>
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label">HistorizeToAveva</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.HistorizeToAveva" class="form-check-input" />
<label class="form-check-label">Route to HistorianGateway</label>
<InputCheckbox id='@FieldId("alarm-historize")' @bind-Value="form.HistorizeToAveva" class="form-check-input" />
<label class="form-check-label" for='@FieldId("alarm-historize")'>Route to HistorianGateway</label>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Retain</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.Retain" class="form-check-input" />
<label class="form-check-label">Retain active alarms on restart</label>
<InputCheckbox id='@FieldId("alarm-retain")' @bind-Value="form.Retain" class="form-check-input" />
<label class="form-check-label" for='@FieldId("alarm-retain")'>Retain active alarms on restart</label>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Enabled</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.Enabled" class="form-check-input" />
<label class="form-check-label">Spawn this alarm in deployments</label>
<InputCheckbox id='@FieldId("enabled")' @bind-Value="form.Enabled" class="form-check-input" />
<label class="form-check-label" for='@FieldId("enabled")'>Spawn this alarm in deployments</label>
</div>
</div>
</div>
@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="CancelAsync" disabled="@_busy">Cancel</button>
<button type="submit" class="btn btn-primary" disabled="@_busy">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
</fieldset>
</EditForm>
</ChildContent>
<Footer>
<div id='@FieldId("service-error")' role="alert" hidden="@string.IsNullOrWhiteSpace(_error)" class="text-danger small w-100">@_error</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => CancelAsync(presentation, cancelAction)" disabled="@Pending">Cancel</button>
<button type="submit" form='@FieldId("form")' class="btn btn-primary" disabled="@Pending">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
@(IsNew ? "Create" : "Save changes")
</button>
</div>
</div>
</EditForm>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Optional nonconfidential identity for successive presentations.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-uns-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _disposed, _closing;
private long _generation;
private object? _lastTarget;
private bool _lastVisible;
private bool Current(long generation) => !_disposed && Visible && generation == _generation;
private bool Pending => _busy || _closing;
/// <summary>Retires UI continuations without cancelling a dispatched operation.</summary>
public void Dispose() { _disposed = true; ++_generation; }
/// <summary>Whether the modal is shown. The host owns this flag.</summary>
[Parameter] public bool Visible { get; set; }
@@ -135,30 +144,46 @@
/// <summary>Raised when the user cancels so the host can close.</summary>
[Parameter] public EventCallback OnCancel { get; set; }
private InputText? _input0;
private InputText? _input1;
private InputSelect<string>? _input2;
private InputNumber<int>? _input3;
private InputSelect<string>? _input4;
private InputTextArea? _input5;
private ElementReference _error0;
private ElementReference _error1;
private ElementReference _error2;
private ElementReference _error3;
private ElementReference _error4;
private ElementReference _error5;
private async Task FocusErrorAsync(long generation, ElementReference error, ElementReference input)
{
// Focusing the input alone can clip its following message at a scroll-body boundary.
await error.FocusAsync();
if (Current(generation) && !Pending) await input.FocusAsync(preventScroll: true);
}
private async Task FocusInvalidAsync(long generation, EditContext context)
{
if (!Current(generation) || Pending) return;
if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.ScriptedAlarmId))).Any() && _input0?.Element is { } element0) await FocusErrorAsync(generation, _error0, element0);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.Name))).Any() && _input1?.Element is { } element1) await FocusErrorAsync(generation, _error1, element1);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.AlarmType))).Any() && _input2?.Element is { } element2) await FocusErrorAsync(generation, _error2, element2);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.Severity))).Any() && _input3?.Element is { } element3) await FocusErrorAsync(generation, _error3, element3);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.PredicateScriptId))).Any() && _input4?.Element is { } element4) await FocusErrorAsync(generation, _error4, element4);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.MessageTemplate))).Any() && _input5?.Element is { } element5) await FocusErrorAsync(generation, _error5, element5);
}
private FormModel _form = new();
private bool _busy;
private string? _error;
// Tracks which open this modal last loaded for, so unrelated Blazor Server re-renders don't
// rebuild _form and clobber in-progress edits. Null while closed.
private string? _loadedKey;
protected override void OnParametersSet()
{
if (!Visible)
{
_loadedKey = null; // closed → next open reloads fresh
return;
}
// Guard against unrelated re-renders. In Blazor Server any live-status push re-invokes
// OnParametersSet; without this the rebuild below would silently discard whatever the
// operator has typed. Only rebuild when the modal OPENS or the target entity CHANGES.
var key = IsNew ? "<new>" : Existing?.ScriptedAlarmId;
if (key == _loadedKey) return; // same open, re-render → preserve in-progress form edits
_loadedKey = key;
// Rebuild the working form whenever the host (re)opens the modal for a fresh target.
object identity = (Target, IsNew, EquipmentId, Existing);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity; ++_generation;
if (!Visible) return;
_form = new FormModel();
if (IsNew)
{
_form = new FormModel();
@@ -181,35 +206,36 @@
_error = null;
}
private async Task SaveAsync()
private async Task SaveAsync(long generation, EventCallback completedAction)
{
_busy = true;
_error = null;
if (!Current(generation) || Pending || (!IsNew && Existing is null)) return;
var isNew = IsNew;
var equipmentId = EquipmentId!;
var existingId = Existing?.ScriptedAlarmId;
var rowVersion = Existing?.RowVersion.ToArray() ?? Array.Empty<byte>();
var input = new ScriptedAlarmInput(_form.ScriptedAlarmId, _form.Name, _form.AlarmType, _form.Severity,
_form.MessageTemplate, _form.PredicateScriptId, _form.HistorizeToAveva, _form.Retain, _form.Enabled);
_busy = true; _error = null;
try
{
var input = new ScriptedAlarmInput(_form.ScriptedAlarmId, _form.Name, _form.AlarmType, _form.Severity,
_form.MessageTemplate, _form.PredicateScriptId, _form.HistorizeToAveva, _form.Retain, _form.Enabled);
var result = IsNew
? await Svc.CreateScriptedAlarmAsync(EquipmentId!, input)
: await Svc.UpdateScriptedAlarmAsync(Existing!.ScriptedAlarmId, input, Existing.RowVersion);
if (result.Ok)
{
await OnSaved.InvokeAsync();
}
else
{
_error = result.Error;
}
}
finally
{
_busy = false;
var result = isNew
? await Svc.CreateScriptedAlarmAsync(equipmentId, input)
: await Svc.UpdateScriptedAlarmAsync(existingId!, input, rowVersion);
if (!Current(generation)) return;
if (result.Ok) await completedAction.InvokeAsync();
else _error = result.Error;
}
catch when (!Current(generation)) { /* A retired operation cannot surface an error in its replacement. */ }
finally { _busy = false; }
}
private Task CancelAsync() => OnCancel.InvokeAsync();
private async Task CancelAsync(long generation, EventCallback cancelAction)
{
if (!Current(generation) || Pending) return;
_closing = true;
try { await cancelAction.InvokeAsync(); }
finally { _closing = false; }
}
private sealed class FormModel
{
@@ -10,36 +10,36 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis
@inject IUnsTreeService 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="virtualTagModal">
<DataAnnotationsValidator />
<div class="modal-header">
<h5 class="modal-title">@(IsNew ? "New virtual tag" : "Edit virtual tag")</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CancelAsync"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{
var presentation = _generation;
var form = _form;
var completedAction = OnSaved;
var cancelAction = OnCancel;
var scriptEpoch = _scriptEpoch;
}
<ModalFrame DialogClass="modal-lg modal-dialog-scrollable" Visible="@Visible" Title='@(IsNew ? "New virtual tag" : "Edit virtual tag")' Target="@presentation" Busy="@Pending" OnClose="() => CancelAsync(presentation, cancelAction)">
<ChildContent>
<EditForm id='@FieldId("form")' Model="form" OnValidSubmit="() => SaveAsync(presentation, completedAction)" OnInvalidSubmit="context => FocusInvalidAsync(presentation, context)" FormName="virtualTagModal" aria-describedby='@FieldId("service-error")'>
<DataAnnotationsValidator />
<fieldset disabled="@Pending">
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="vtag-id">VirtualTagId</label>
<InputText id="vtag-id" @bind-Value="_form.VirtualTagId" disabled="@(!IsNew)"
<label class="form-label" for='@FieldId("vtag-id")'>VirtualTagId</label>
<InputText id='@FieldId("vtag-id")' @ref="_input0" aria-describedby='@FieldIds("vtag-id-error")' @bind-Value="form.VirtualTagId" disabled="@(!IsNew)"
class="form-control form-control-sm mono" />
<ValidationMessage For="@(() => _form.VirtualTagId)" />
<div id='@FieldId("vtag-id-error")' tabindex="-1" @ref="_error0"><ValidationMessage For="@(() => form.VirtualTagId)" /></div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="vtag-name">Name</label>
<InputText id="vtag-name" @bind-Value="_form.Name" class="form-control form-control-sm" />
<ValidationMessage For="@(() => _form.Name)" />
<label class="form-label" for='@FieldId("vtag-name")'>Name</label>
<InputText id='@FieldId("vtag-name")' @ref="_input1" aria-describedby='@FieldIds("vtag-name-error")' @bind-Value="form.Name" class="form-control form-control-sm" />
<div id='@FieldId("vtag-name-error")' tabindex="-1" @ref="_error1"><ValidationMessage For="@(() => form.Name)" /></div>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="vtag-dtype">DataType</label>
<InputSelect id="vtag-dtype" @bind-Value="_form.DataType" class="form-select form-select-sm">
<label class="form-label" for='@FieldId("vtag-dtype")'>DataType</label>
<InputSelect id='@FieldId("vtag-dtype")' @bind-Value="form.DataType" class="form-select form-select-sm">
@foreach (var dt in DataTypes)
{
<option value="@dt">@dt</option>
@@ -47,28 +47,28 @@
</InputSelect>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="vtag-script">Script</label>
<InputSelect id="vtag-script" @bind-Value="_form.ScriptId"
@bind-Value:after="OnScriptChangedAsync" class="form-select form-select-sm">
<label class="form-label" for='@FieldId("vtag-script")'>Script</label>
<InputSelect TValue="string" id='@FieldId("vtag-script")' @ref="_input2" aria-describedby='@FieldIds("vtag-script-error")' Value="@form.ScriptId" ValueChanged="value => OnScriptChangedAsync(presentation, form, value)"
ValueExpression="() => form.ScriptId" class="form-select form-select-sm">
<option value="">— pick script —</option>
@foreach (var (id, display) in _scripts)
{
<option value="@id">@display</option>
}
</InputSelect>
<ValidationMessage For="@(() => _form.ScriptId)" />
<div id='@FieldId("vtag-script-error")' tabindex="-1" @ref="_error2"><ValidationMessage For="@(() => form.ScriptId)" /></div>
</div>
</div>
@* No script bound yet → offer a one-click "New script" action that creates a
fresh (blank) Script row, binds this virtual tag to it, and expands the inline
editor below so the operator can author the body without leaving the modal. *@
@if (string.IsNullOrEmpty(_form.ScriptId))
@if (string.IsNullOrEmpty(form.ScriptId))
{
<div class="mb-3">
<button type="button" class="btn btn-outline-primary btn-sm"
@onclick="CreateNewScriptAsync" disabled="@_scriptCreating">
@if (_scriptCreating) { <span class="spinner-border spinner-border-sm me-1"></span> }
@onclick="() => CreateNewScriptAsync(presentation)" disabled="@Pending">
@if (_scriptCreating) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
New script
</button>
<span class="form-text ms-2">Creates a blank script bound to this virtual tag.</span>
@@ -83,26 +83,26 @@
the SHARED Script row on its OWN concurrency-guarded button — it is deliberately
separate from the virtual-tag Create/Save below and never touches _form or closes
the modal. *@
@if (!string.IsNullOrEmpty(_form.ScriptId) && _scriptLoaded)
@if (!string.IsNullOrEmpty(form.ScriptId) && _scriptLoaded)
{
<div class="card mb-3">
<div class="card-header py-2 d-flex justify-content-between align-items-center">
<span class="fw-semibold">Script source</span>
<button type="button" class="btn btn-link btn-sm p-0 text-decoration-none"
@onclick="ToggleScriptPanel">
@onclick="() => ToggleScriptPanel(presentation, scriptEpoch)" disabled="@Pending" aria-expanded="@_scriptExpanded" aria-controls='@FieldId("script-panel")'>
@(_scriptExpanded ? "Hide" : "Edit source")
</button>
</div>
@if (_scriptExpanded)
{
<div class="card-body">
<div class="card-body" id='@FieldId("script-panel")'>
<div class="alert alert-warning py-2 small mb-2">
Editing shared script "<span class="mono">@_scriptName</span>" — used by
@_scriptUsageCount virtual tag(s). Changes affect all of them.
</div>
<MonacoEditor @ref="_scriptEditor" @bind-Value="_scriptSource" Height="300px" EquipmentId="@EquipmentId"
MarkersChanged="OnScriptMarkersChanged" />
<ScriptProblemsList Report="_scriptMarkers" OnSelect="RevealScriptProblemAsync" />
<MonacoEditor @key="(presentation, scriptEpoch)" @ref="_scriptEditor" Value="@_scriptSource" ValueChanged="value => OnScriptValueChanged(presentation, scriptEpoch, value)" ReadOnly="@Pending" AriaLabel="Shared virtual tag script source" Height="300px" EquipmentId="@EquipmentId"
MarkersChanged="report => OnScriptMarkersChanged(presentation, scriptEpoch, report)" />
<ScriptProblemsList Report="_scriptMarkers" OnSelect="marker => RevealScriptProblemAsync(presentation, scriptEpoch, marker)" />
@if (!string.IsNullOrWhiteSpace(_scriptError))
{
<div class="text-danger small mt-2">@_scriptError</div>
@@ -113,8 +113,8 @@
}
<div class="mt-2">
<button type="button" class="btn btn-outline-primary btn-sm"
@onclick="SaveScriptAsync" disabled="@_scriptSaving">
@if (_scriptSaving) { <span class="spinner-border spinner-border-sm me-1"></span> }
@onclick="() => SaveScriptAsync(presentation, scriptEpoch)" disabled="@Pending">
@if (_scriptSaving) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
Save script
</button>
</div>
@@ -126,52 +126,63 @@
<div class="col-md-4 mb-3">
<label class="form-label">Change-triggered</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.ChangeTriggered" class="form-check-input" />
<label class="form-check-label">Re-evaluate on dependency change</label>
<InputCheckbox id='@FieldId("vtag-change")' @bind-Value="form.ChangeTriggered" class="form-check-input" />
<label class="form-check-label" for='@FieldId("vtag-change")'>Re-evaluate on dependency change</label>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="form-label" for="vtag-timer">TimerIntervalMs (optional)</label>
<InputNumber id="vtag-timer" @bind-Value="_form.TimerIntervalMs" class="form-control form-control-sm" />
<div class="form-text">Periodic re-evaluation. Null = change-trigger only.</div>
<label class="form-label" for='@FieldId("vtag-timer")'>TimerIntervalMs (optional)</label>
<InputNumber DisplayName="Timer interval" id='@FieldId("vtag-timer")' @ref="_input3" aria-describedby='@FieldIds("vtag-timer-error", "vtag-timer-hint")' @bind-Value="form.TimerIntervalMs" class="form-control form-control-sm" />
<div id='@FieldId("vtag-timer-error")' tabindex="-1" @ref="_error3"><ValidationMessage For="@(() => form.TimerIntervalMs)" /></div>
<div id='@FieldId("vtag-timer-hint")' class="form-text">Periodic re-evaluation. Null = change-trigger only.</div>
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Historize</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.Historize" class="form-check-input" />
<label class="form-check-label">Send to HistorianGateway</label>
<InputCheckbox id='@FieldId("vtag-historize")' @bind-Value="form.Historize" class="form-check-input" />
<label class="form-check-label" for='@FieldId("vtag-historize")'>Send to HistorianGateway</label>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Enabled</label>
<div class="form-check form-switch">
<InputCheckbox @bind-Value="_form.Enabled" class="form-check-input" />
<label class="form-check-label">Spawn this virtual tag in deployments</label>
<InputCheckbox id='@FieldId("enabled")' @bind-Value="form.Enabled" class="form-check-input" />
<label class="form-check-label" for='@FieldId("enabled")'>Spawn this virtual tag in deployments</label>
</div>
</div>
@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="CancelAsync" disabled="@(_busy || _scriptSaving)">Cancel</button>
<button type="submit" class="btn btn-primary" disabled="@(_busy || _scriptSaving)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
</fieldset>
</EditForm>
</ChildContent>
<Footer>
<div id='@FieldId("service-error")' role="alert" hidden="@string.IsNullOrWhiteSpace(_error)" class="text-danger small w-100">@_error</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => CancelAsync(presentation, cancelAction)" disabled="@Pending">Cancel</button>
<button type="submit" form='@FieldId("form")' class="btn btn-primary" disabled="@Pending">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
@(IsNew ? "Create" : "Save changes")
</button>
</div>
</div>
</EditForm>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Optional nonconfidential identity for successive presentations.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fieldScope = "ot-uns-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private string FieldIds(params string[] suffixes) => string.Join(" ", suffixes.Select(FieldId));
private bool _disposed, _closing;
private long _generation;
private object? _lastTarget;
private bool _lastVisible;
private bool Current(long generation) => !_disposed && Visible && generation == _generation;
private bool Pending => _busy || _closing || _scriptSaving || _scriptCreating || _scriptToggling;
/// <summary>Retires UI continuations without cancelling a dispatched operation.</summary>
public void Dispose() { _disposed = true; ++_generation; }
/// <summary>The OPC UA data types offered for a virtual tag — the same set the TagModal uses.</summary>
private static readonly string[] DataTypes =
["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
@@ -198,6 +209,29 @@
/// <summary>Raised when the user cancels so the host can close.</summary>
[Parameter] public EventCallback OnCancel { get; set; }
private InputText? _input0;
private InputText? _input1;
private InputSelect<string>? _input2;
private InputNumber<int?>? _input3;
private ElementReference _error0;
private ElementReference _error1;
private ElementReference _error2;
private ElementReference _error3;
private async Task FocusErrorAsync(long generation, ElementReference error, ElementReference input)
{
// Focusing the input alone can clip its following message at a scroll-body boundary.
await error.FocusAsync();
if (Current(generation) && !Pending) await input.FocusAsync(preventScroll: true);
}
private async Task FocusInvalidAsync(long generation, EditContext context)
{
if (!Current(generation) || Pending) return;
if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.VirtualTagId))).Any() && _input0?.Element is { } element0) await FocusErrorAsync(generation, _error0, element0);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.Name))).Any() && _input1?.Element is { } element1) await FocusErrorAsync(generation, _error1, element1);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.ScriptId))).Any() && _input2?.Element is { } element2) await FocusErrorAsync(generation, _error2, element2);
else if (context.GetValidationMessages(new FieldIdentifier(_form, nameof(_form.TimerIntervalMs))).Any() && _input3?.Element is { } element3) await FocusErrorAsync(generation, _error3, element3);
}
private FormModel _form = new();
private bool _busy;
private string? _error;
@@ -206,10 +240,6 @@
// "New script", so the freshly-created (and now-bound) script is a real option in the dropdown.
private List<(string Id, string Display)> _scripts = new();
// Tracks which open this modal last loaded for, so unrelated Blazor Server re-renders don't
// rebuild _form / reload the script source and clobber in-progress edits. Null while closed.
private string? _loadedKey;
// Inline script-source editor state. Independent of _form and the virtual-tag save.
private string _scriptSource = "";
private bool _scriptLoaded;
@@ -223,17 +253,25 @@
private MonacoEditor? _scriptEditor;
private ScriptProblemReport _scriptMarkers = ScriptProblemReport.Empty;
private void OnScriptMarkersChanged(ScriptProblemReport report) => _scriptMarkers = report;
private bool _scriptToggling;
private long _scriptEpoch;
private bool ScriptCurrent(long generation, long epoch) => Current(generation) && epoch == _scriptEpoch;
private void OnScriptMarkersChanged(long generation, long epoch, ScriptProblemReport report)
{ if (ScriptCurrent(generation, epoch)) _scriptMarkers = report; }
private void OnScriptValueChanged(long generation, long epoch, string value)
{ if (ScriptCurrent(generation, epoch)) _scriptSource = value; }
private Task RevealScriptProblemAsync(DiagnosticMarker m)
=> _scriptEditor is null ? Task.CompletedTask : _scriptEditor.RevealLineAsync(m.StartLineNumber, m.StartColumn);
private Task RevealScriptProblemAsync(long generation, long epoch, DiagnosticMarker marker)
=> !ScriptCurrent(generation, epoch) || _scriptEditor is null ? Task.CompletedTask : _scriptEditor.RevealLineAsync(marker.StartLineNumber, marker.StartColumn);
// The inline editor reports its text only at blur; pull the authoritative current value before acting on it.
// Returns false (with _scriptError set) when the text could not be read, so nothing stale is saved.
private async Task<bool> PullScriptSourceAsync()
// Pull the authoritative editor text before a script write or collapse; never retarget an old read.
private async Task<bool> PullScriptSourceAsync(long generation, long epoch)
{
if (_scriptEditor is null) return true;
var read = await _scriptEditor.GetValueAsync();
var editor = _scriptEditor;
if (!ScriptCurrent(generation, epoch)) return false;
if (editor is null) return true;
var read = await editor.GetValueAsync();
if (!ScriptCurrent(generation, epoch)) return false;
if (!read.Ok) { _scriptError = $"Not saved: {read.Error}"; return false; }
_scriptSource = read.Value!;
return true;
@@ -245,28 +283,15 @@
protected override async Task OnParametersSetAsync()
{
if (!Visible)
{
_loadedKey = null; // closed → next open reloads fresh
// Closing removes the editor component: drop its reference and its problems.
_scriptEditor = null;
_scriptMarkers = ScriptProblemReport.Empty;
return;
}
// Guard against unrelated re-renders. In Blazor Server any live-status push re-invokes
// OnParametersSetAsync; without this the rebuild + script reload below would silently
// discard whatever the operator has typed. Only rebuild when the modal OPENS or the
// target entity CHANGES.
var key = IsNew ? "<new>" : Existing?.VirtualTagId;
if (key == _loadedKey) return; // same open, re-render → preserve in-progress form + script edits
_loadedKey = key;
// Snapshot the host-supplied script options; "New script" appends to this working copy so the
// newly-created script is selectable without mutating the parent's parameter.
object identity = (Target, IsNew, EquipmentId, Existing);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_generation;
++_scriptEpoch;
_scriptEditor = null; _scriptMarkers = ScriptProblemReport.Empty;
if (!Visible) return;
_scripts = Scripts.Select(s => (s.Id, s.Display)).ToList();
// Rebuild the working form whenever the host (re)opens the modal for a fresh target.
_form = new FormModel();
if (IsNew)
{
_form = new FormModel();
@@ -285,57 +310,43 @@
Enabled = Existing.Enabled,
};
}
_error = null;
_scriptCreateError = null;
_scriptExpanded = false;
// Load the bound script's source for the inline panel when editing an existing tag that
// already has a script (the open-load path; selection changes go through OnScriptChangedAsync).
await LoadScriptSourceAsync();
_error = null; _scriptCreateError = null; _scriptExpanded = false;
await LoadScriptSourceAsync(generation);
}
/// <summary>
/// Reloads the inline-editor state from the currently selected script. Clears it when no script is
/// bound. This drives both the open-load and the post-selection refresh, and never touches _form.
/// </summary>
private async Task LoadScriptSourceAsync()
private async Task LoadScriptSourceAsync(long generation)
{
_scriptSaved = false;
_scriptError = null;
// A different script (or a reload) — drop the previous script's problems. The editor instance itself stays:
// while the panel is open the same MonacoEditor component receives the new source via its Value.
_scriptMarkers = ScriptProblemReport.Empty;
if (string.IsNullOrEmpty(_form.ScriptId))
if (!Current(generation)) return;
var epoch = ++_scriptEpoch;
var scriptId = _form.ScriptId;
_scriptSaved = false; _scriptError = null; _scriptMarkers = ScriptProblemReport.Empty;
_scriptEditor = null; _scriptLoaded = false;
_scriptSource = ""; _scriptRowVersion = Array.Empty<byte>(); _scriptName = null; _scriptUsageCount = 0;
if (string.IsNullOrEmpty(scriptId)) return;
try
{
_scriptSource = "";
_scriptLoaded = false;
_scriptRowVersion = Array.Empty<byte>();
_scriptName = null;
_scriptUsageCount = 0;
return;
var loaded = await Svc.GetScriptSourceAsync(scriptId);
if (!ScriptCurrent(generation, epoch) || loaded is null) return;
var count = await Svc.CountVirtualTagsUsingScriptAsync(scriptId);
if (!ScriptCurrent(generation, epoch)) return;
_scriptSource = loaded.Value.SourceCode;
_scriptRowVersion = loaded.Value.RowVersion.ToArray();
_scriptName = loaded.Value.Name; _scriptUsageCount = count; _scriptLoaded = true;
}
var loaded = await Svc.GetScriptSourceAsync(_form.ScriptId);
if (loaded is null)
{
_scriptSource = "";
_scriptLoaded = false;
_scriptRowVersion = Array.Empty<byte>();
_scriptName = null;
_scriptUsageCount = 0;
return;
}
_scriptSource = loaded.Value.SourceCode;
_scriptLoaded = true;
_scriptRowVersion = loaded.Value.RowVersion;
_scriptName = loaded.Value.Name;
_scriptUsageCount = await Svc.CountVirtualTagsUsingScriptAsync(_form.ScriptId);
catch when (!ScriptCurrent(generation, epoch)) { /* A superseded read has no current UI outcome. */ }
}
/// <summary>Refreshes the inline script panel when the operator picks a different script.</summary>
private Task OnScriptChangedAsync() => LoadScriptSourceAsync();
private async Task OnScriptChangedAsync(long generation, FormModel form, string value)
{
// Disabled DOM cannot revoke an already queued child event: guard before changing script identity.
if (!Current(generation) || Pending || !ReferenceEquals(form, _form)) return;
form.ScriptId = value;
await LoadScriptSourceAsync(generation);
}
/// <summary>
/// Creates a brand-new (blank) script, binds this virtual tag to it, and expands the inline editor
@@ -344,8 +355,9 @@
/// the operator clicks Create/Save below; only the new Script row is persisted here. On failure the
/// inline error is surfaced and the binding is left untouched.
/// </summary>
private async Task CreateNewScriptAsync()
private async Task CreateNewScriptAsync(long generation)
{
if (!Current(generation) || Pending) return;
_scriptCreating = true;
_scriptCreateError = null;
try
@@ -355,6 +367,7 @@
// from every later modal open.
var seedName = string.IsNullOrWhiteSpace(_form.Name) ? "New script" : $"{_form.Name.Trim()} script";
var result = await Svc.CreateScriptAsync(seedName);
if (!Current(generation)) return;
if (!result.Ok || string.IsNullOrEmpty(result.CreatedId))
{
_scriptCreateError = result.Error ?? "Could not create the script.";
@@ -372,114 +385,97 @@
}
// Bind the new script and load its (blank) source so the inline editor renders + expands.
_form.ScriptId = result.CreatedId;
await LoadScriptSourceAsync();
_scriptExpanded = true;
}
finally
{
_scriptCreating = false;
await LoadScriptSourceAsync(generation);
if (Current(generation)) _scriptExpanded = true;
}
catch when (!Current(generation)) { /* Preserve a replacement presentation after an old create fails. */ }
finally { _scriptCreating = false; }
}
/// <summary>
/// Toggles the inline script-source panel. Clears the stale "Script saved." banner when
/// (re)expanding so a collapse/expand cycle doesn't re-show a confirmation from an earlier save.
/// </summary>
private async Task ToggleScriptPanel()
private async Task ToggleScriptPanel(long generation, long epoch)
{
if (_scriptExpanded)
{
// Collapsing disposes the editor: keep its unsaved text in _scriptSource so re-opening shows it.
// A failed read keeps the panel open (with the error) rather than discarding the edits.
if (!await PullScriptSourceAsync()) return;
_scriptEditor = null;
_scriptMarkers = ScriptProblemReport.Empty;
}
_scriptExpanded = !_scriptExpanded;
if (_scriptExpanded)
{
_scriptSaved = false;
}
}
/// <summary>
/// Saves the edited script body via its own RowVersion-guarded service call. This is wholly
/// separate from the virtual-tag save: it does not touch _form, does not raise OnSaved, and does
/// not close the modal. On success it re-fetches the source so the panel holds a fresh token.
/// </summary>
private async Task SaveScriptAsync()
{
if (string.IsNullOrEmpty(_form.ScriptId) || !_scriptLoaded)
{
return;
}
_scriptSaving = true;
_scriptSaved = false;
_scriptError = null;
if (!ScriptCurrent(generation, epoch) || Pending) return;
_scriptToggling = true;
try
{
if (!await PullScriptSourceAsync()) return;
var result = await Svc.UpdateScriptSourceAsync(_form.ScriptId, _scriptSource, _scriptRowVersion);
if (_scriptExpanded)
{
if (!await PullScriptSourceAsync(generation, epoch)) return;
_scriptEditor = null; _scriptMarkers = ScriptProblemReport.Empty;
}
if (!ScriptCurrent(generation, epoch)) return;
_scriptExpanded = !_scriptExpanded;
if (_scriptExpanded) _scriptSaved = false;
}
finally { _scriptToggling = false; }
}
// Script writes remain independent of the virtual tag save and keep their original rowversion.
private async Task SaveScriptAsync(long generation, long epoch)
{
if (!ScriptCurrent(generation, epoch) || Pending || string.IsNullOrEmpty(_form.ScriptId) || !_scriptLoaded) return;
var scriptId = _form.ScriptId;
var rowVersion = _scriptRowVersion.ToArray();
_scriptSaving = true; _scriptSaved = false; _scriptError = null;
try
{
if (!await PullScriptSourceAsync(generation, epoch)) return;
var source = _scriptSource;
var result = await Svc.UpdateScriptSourceAsync(scriptId, source, rowVersion);
if (!ScriptCurrent(generation, epoch)) return;
if (result.Ok)
{
// Re-fetch to refresh the concurrency token for any subsequent save.
var reloaded = await Svc.GetScriptSourceAsync(_form.ScriptId);
var reloaded = await Svc.GetScriptSourceAsync(scriptId);
if (!ScriptCurrent(generation, epoch)) return;
if (reloaded is not null)
{
_scriptSource = reloaded.Value.SourceCode;
_scriptRowVersion = reloaded.Value.RowVersion;
_scriptRowVersion = reloaded.Value.RowVersion.ToArray();
_scriptName = reloaded.Value.Name;
}
_scriptSaved = true;
}
else
{
_scriptError = result.Error;
}
}
finally
{
_scriptSaving = false;
else _scriptError = result.Error;
}
catch when (!ScriptCurrent(generation, epoch)) { /* Current script failures still use the existing boundary. */ }
finally { _scriptSaving = false; }
}
private async Task SaveAsync()
private async Task SaveAsync(long generation, EventCallback completedAction)
{
_busy = true;
_error = null;
if (!Current(generation) || Pending || (!IsNew && Existing is null)) return;
var isNew = IsNew;
var equipmentId = EquipmentId!;
var existingId = Existing?.VirtualTagId;
var rowVersion = Existing?.RowVersion.ToArray() ?? Array.Empty<byte>();
var input = new VirtualTagInput(
_form.VirtualTagId, _form.Name, _form.DataType, _form.ScriptId,
_form.ChangeTriggered, _form.TimerIntervalMs, _form.Historize, _form.Enabled);
_busy = true; _error = null;
try
{
var input = new VirtualTagInput(
_form.VirtualTagId,
_form.Name,
_form.DataType,
_form.ScriptId,
_form.ChangeTriggered,
_form.TimerIntervalMs,
_form.Historize,
_form.Enabled);
var result = IsNew
? await Svc.CreateVirtualTagAsync(EquipmentId!, input)
: await Svc.UpdateVirtualTagAsync(Existing!.VirtualTagId, input, Existing.RowVersion);
if (result.Ok)
{
await OnSaved.InvokeAsync();
}
else
{
_error = result.Error;
}
}
finally
{
_busy = false;
var result = isNew
? await Svc.CreateVirtualTagAsync(equipmentId, input)
: await Svc.UpdateVirtualTagAsync(existingId!, input, rowVersion);
if (!Current(generation)) return;
if (result.Ok) await completedAction.InvokeAsync();
else _error = result.Error;
}
catch when (!Current(generation)) { /* A retired operation cannot surface an error in its replacement. */ }
finally { _busy = false; }
}
private Task CancelAsync() => OnCancel.InvokeAsync();
private async Task CancelAsync(long generation, EventCallback cancelAction)
{
if (!Current(generation) || Pending) return;
_closing = true;
try { await cancelAction.InvokeAsync(); }
finally { _closing = false; }
}
private sealed class FormModel
{