Bind script editing and deletion to captured route intent
This commit is contained in:
@@ -15,6 +15,13 @@
|
||||
@using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis
|
||||
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
|
||||
@inject NavigationManager Nav
|
||||
@implements IDisposable
|
||||
|
||||
@{
|
||||
var presentation = _generation;
|
||||
var form = _form;
|
||||
var confirmation = _confirmationEpoch;
|
||||
}
|
||||
|
||||
<PageErrorBoundary>
|
||||
<PageTitle>Script editor · OtOpcUa</PageTitle>
|
||||
@@ -26,7 +33,11 @@
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p>Loading…</p>
|
||||
<p role="status">Loading script…</p>
|
||||
}
|
||||
else if (_loadError is not null)
|
||||
{
|
||||
<section class="panel notice notice-alert" role="alert">@_loadError</section>
|
||||
}
|
||||
else if (!IsNew && _existing is null)
|
||||
{
|
||||
@@ -36,7 +47,8 @@ else
|
||||
{
|
||||
@* OnSubmit (not OnValidSubmit): the editor text is pulled from Monaco FIRST, then validated — the bound
|
||||
SourceCode is only refreshed at blur, so validating before the pull could judge stale text. *@
|
||||
<EditForm Model="_form" OnSubmit="SubmitAsync" FormName="scriptEdit">
|
||||
<EditForm @key="presentation" Model="_form" OnSubmit="context => SubmitAsync(context, presentation, form)" FormName="scriptEdit">
|
||||
<fieldset disabled="@_busy" aria-busy="@_busy.ToString().ToLowerInvariant()">
|
||||
<DataAnnotationsValidator />
|
||||
<ValidationSummary class="alert alert-danger py-2 px-3" />
|
||||
<section class="panel rise">
|
||||
@@ -48,13 +60,13 @@ else
|
||||
@if (!IsNew)
|
||||
{
|
||||
<div class="col-md-5 mb-3">
|
||||
<label class="form-label">ScriptId</label>
|
||||
<input value="@_form.ScriptId" disabled class="form-control form-control-sm mono" />
|
||||
<label class="form-label" for="@(_fieldId + "-id")">ScriptId</label>
|
||||
<input id="@(_fieldId + "-id")" value="@_form.ScriptId" disabled class="form-control form-control-sm mono" />
|
||||
</div>
|
||||
}
|
||||
<div class="@(IsNew ? "col-md-12" : "col-md-7") mb-3">
|
||||
<label class="form-label">Name</label>
|
||||
<InputText @bind-Value="_form.Name" class="form-control form-control-sm" />
|
||||
<label class="form-label" for="@(_fieldId + "-name")">Name</label>
|
||||
<InputText id="@(_fieldId + "-name")" Value="@_form.Name" ValueChanged="value => ChangeName(value, presentation, form)" ValueExpression="() => _form.Name" class="form-control form-control-sm" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -63,133 +75,177 @@ else
|
||||
<section class="panel rise mt-3">
|
||||
<h2 class="panel-head">Source</h2>
|
||||
<div style="padding:1rem">
|
||||
<MonacoEditor @ref="_editor" @bind-Value="_form.SourceCode" Height="420px"
|
||||
MarkersChanged="OnMarkersChanged" />
|
||||
<ScriptProblemsList Report="_markers" OnSelect="RevealProblemAsync" />
|
||||
<MonacoEditor @key="presentation" @ref="_editor" Value="@_form.SourceCode" ValueChanged="value => ChangeSource(value, presentation, form)" Height="420px"
|
||||
AriaLabel="Script source code" ReadOnly="@_busy" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
||||
<ScriptProblemsList Report="_markers" OnSelect="marker => RevealProblemAsync(marker, presentation)" />
|
||||
<div class="form-text">SHA-256 hash is computed automatically on save.</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(_error)) { <div class="panel notice notice-alert mt-3">@_error</div> }
|
||||
@if (!string.IsNullOrWhiteSpace(_error)) { <div class="panel notice notice-alert mt-3" role="alert">@_error</div> }
|
||||
|
||||
<div class="mt-3 d-flex gap-2">
|
||||
<div class="btn-group" role="group">
|
||||
<button type="submit" class="btn btn-primary" disabled="@_busy">@(IsNew ? "Create" : "Save changes")</button>
|
||||
<button type="submit" class="btn btn-primary" disabled="@_busy">@(_busy ? "Saving…" : IsNew ? "Create" : "Save changes")</button>
|
||||
<a href="/scripts" class="btn btn-outline-secondary">Cancel</a>
|
||||
</div>
|
||||
@if (!IsNew) { <button type="button" class="btn btn-outline-danger ms-auto" @onclick="() => _confirmDeleteVisible = true" disabled="@_busy">Delete</button> }
|
||||
@if (!IsNew) { <button type="button" class="btn btn-outline-danger ms-auto" @onclick="() => OpenDelete(presentation, form)" disabled="@_busy">Delete</button> }
|
||||
</div>
|
||||
</fieldset>
|
||||
</EditForm>
|
||||
|
||||
@* R04 H1: the delete used to run on the first click. *@
|
||||
<RawConfirmDialog @bind-Visible="_confirmDeleteVisible" Title="Delete script"
|
||||
Message="@($"Delete the script '{_existing?.Name ?? _form.Name}'? This cannot be undone.")"
|
||||
OnConfirm="DeleteAsync" />
|
||||
<RawConfirmDialog Visible="@_confirmDeleteVisible" VisibleChanged="visible => ChangeDeleteVisibility(visible, presentation, confirmation)" Title="Delete script"
|
||||
Target="@confirmation" Message="@_deleteMessage"
|
||||
OnConfirm="() => DeleteAsync(presentation, confirmation)" />
|
||||
}
|
||||
</PageErrorBoundary>
|
||||
|
||||
@code {
|
||||
[Parameter] public string? ScriptId { get; set; }
|
||||
private bool IsNew => string.IsNullOrEmpty(ScriptId);
|
||||
|
||||
private readonly string _fieldId = "script-" + Guid.NewGuid().ToString("N");
|
||||
private FormModel _form = new();
|
||||
private Script? _existing;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private string? _error;
|
||||
private bool _loaded, _busy, _disposed, _hasTarget;
|
||||
private string? _target, _error, _loadError;
|
||||
private long _generation, _confirmationEpoch;
|
||||
private bool _confirmDeleteVisible;
|
||||
private string _deleteMessage = "";
|
||||
private DeleteIntent? _deleteIntent;
|
||||
private MonacoEditor? _editor;
|
||||
private ScriptProblemReport _markers = ScriptProblemReport.Empty;
|
||||
private sealed record DeleteIntent(string Id, byte[] RowVersion);
|
||||
|
||||
private void OnMarkersChanged(ScriptProblemReport report) => _markers = report;
|
||||
|
||||
private Task RevealProblemAsync(DiagnosticMarker m)
|
||||
=> _editor is null ? Task.CompletedTask : _editor.RevealLineAsync(m.StartLineNumber, m.StartColumn);
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
private bool Current(long generation) => !_disposed && generation == _generation;
|
||||
private void ChangeName(string value, long generation, FormModel form)
|
||||
{
|
||||
if (!IsNew)
|
||||
if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.Name = value;
|
||||
}
|
||||
private void ChangeSource(string value, long generation, FormModel form)
|
||||
{
|
||||
if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value;
|
||||
}
|
||||
private void OnMarkersChanged(ScriptProblemReport report, long generation)
|
||||
{
|
||||
if (Current(generation)) _markers = report;
|
||||
}
|
||||
private Task RevealProblemAsync(DiagnosticMarker marker, long generation)
|
||||
=> !Current(generation) || _editor is null ? Task.CompletedTask : _editor.RevealLineAsync(marker.StartLineNumber, marker.StartColumn);
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
if (_disposed || (_hasTarget && string.Equals(_target, ScriptId, StringComparison.Ordinal))) return;
|
||||
_hasTarget = true;
|
||||
_target = ScriptId;
|
||||
var id = ScriptId;
|
||||
var generation = ++_generation;
|
||||
++_confirmationEpoch;
|
||||
_loaded = _busy = _confirmDeleteVisible = false;
|
||||
_existing = null; _editor = null; _deleteIntent = null;
|
||||
_form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null;
|
||||
try
|
||||
{
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
_existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
|
||||
if (_existing is not null)
|
||||
if (!string.IsNullOrEmpty(id))
|
||||
{
|
||||
_form = new FormModel
|
||||
{
|
||||
ScriptId = _existing.ScriptId,
|
||||
Name = _existing.Name,
|
||||
SourceCode = _existing.SourceCode,
|
||||
RowVersion = _existing.RowVersion,
|
||||
};
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
if (!Current(generation)) return;
|
||||
var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id);
|
||||
if (!Current(generation)) return;
|
||||
_existing = existing;
|
||||
if (existing is not null)
|
||||
_form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name,
|
||||
SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() };
|
||||
}
|
||||
}
|
||||
_loaded = true;
|
||||
catch (Exception ex) { if (Current(generation)) _loadError = $"The script could not be loaded: {ex.Message}"; }
|
||||
finally { if (Current(generation)) _loaded = true; }
|
||||
}
|
||||
|
||||
private async Task SubmitAsync(EditContext editContext)
|
||||
private async Task SubmitAsync(EditContext editContext, long generation, FormModel form)
|
||||
{
|
||||
if (!Current(generation) || _busy || !_loaded || !ReferenceEquals(form, _form) || _confirmDeleteVisible) return;
|
||||
var id = _target;
|
||||
var name = form.Name;
|
||||
var version = form.RowVersion.ToArray();
|
||||
var editor = _editor;
|
||||
_busy = true; _error = null;
|
||||
try
|
||||
{
|
||||
// The editor reports its text only at blur, so read the authoritative current value now. A read
|
||||
// failure (e.g. the script is too large to send) aborts the save rather than persisting stale source.
|
||||
if (_editor is not null)
|
||||
// Monaco is authoritative at Save. Capture the editor/context before awaiting its current text.
|
||||
var source = form.SourceCode;
|
||||
if (editor is not null)
|
||||
{
|
||||
var read = await _editor.GetValueAsync();
|
||||
var read = await editor.GetValueAsync();
|
||||
if (!Current(generation)) return;
|
||||
if (!read.Ok) { _error = $"Not saved: {read.Error}"; return; }
|
||||
_form.SourceCode = read.Value!;
|
||||
source = read.Value!;
|
||||
}
|
||||
if (!Current(generation)) return;
|
||||
form.SourceCode = source;
|
||||
if (!editContext.Validate()) return;
|
||||
|
||||
var sourceHash = HashSource(_form.SourceCode);
|
||||
var sourceHash = HashSource(source);
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
if (IsNew)
|
||||
if (!Current(generation)) return;
|
||||
if (string.IsNullOrEmpty(id))
|
||||
{
|
||||
// ScriptId is system-generated (mirrors EquipmentId's "EQ-{12 hex}" convention);
|
||||
// Language is always CSharp.
|
||||
db.Scripts.Add(new Script
|
||||
{
|
||||
ScriptId = $"SC-{Guid.NewGuid().ToString("N")[..12]}",
|
||||
Name = _form.Name,
|
||||
Language = "CSharp",
|
||||
SourceCode = _form.SourceCode,
|
||||
SourceHash = sourceHash,
|
||||
});
|
||||
// Preserve system-generated SC- identity and the CSharp language contract.
|
||||
db.Scripts.Add(new Script { ScriptId = $"SC-{Guid.NewGuid().ToString("N")[..12]}",
|
||||
Name = name, Language = "CSharp", SourceCode = source, SourceHash = sourceHash });
|
||||
}
|
||||
else
|
||||
{
|
||||
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
|
||||
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == id);
|
||||
if (!Current(generation)) return;
|
||||
if (entity is null) { _error = "Row no longer exists."; return; }
|
||||
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
|
||||
entity.Name = _form.Name;
|
||||
entity.SourceCode = _form.SourceCode;
|
||||
entity.SourceHash = sourceHash;
|
||||
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = version;
|
||||
entity.Name = name; entity.SourceCode = source; entity.SourceHash = sourceHash;
|
||||
}
|
||||
await db.SaveChangesAsync();
|
||||
Nav.NavigateTo("/scripts");
|
||||
await db.SaveChangesAsync(); // Already-dispatched writes finish independently of route lifetime.
|
||||
if (Current(generation)) Nav.NavigateTo("/scripts");
|
||||
}
|
||||
catch (DbUpdateConcurrencyException) { _error = "Another user changed this script while you were editing."; }
|
||||
catch (Exception ex) { _error = ex.Message; }
|
||||
finally { _busy = false; }
|
||||
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were editing."; }
|
||||
catch (Exception ex) { if (Current(generation)) _error = ex.Message; }
|
||||
finally { if (Current(generation)) _busy = false; }
|
||||
}
|
||||
|
||||
private async Task DeleteAsync()
|
||||
private void OpenDelete(long generation, FormModel form)
|
||||
{
|
||||
if (IsNew) return;
|
||||
if (!Current(generation) || _busy || _confirmDeleteVisible || string.IsNullOrEmpty(_target) || !ReferenceEquals(form, _form)) return;
|
||||
_deleteIntent = new(_target, form.RowVersion.ToArray());
|
||||
_deleteMessage = $"Delete the script '{_existing?.Name ?? form.Name}'? This cannot be undone.";
|
||||
++_confirmationEpoch;
|
||||
_confirmDeleteVisible = true;
|
||||
}
|
||||
private void ChangeDeleteVisibility(bool visible, long generation, long confirmation)
|
||||
{
|
||||
if (!Current(generation) || confirmation != _confirmationEpoch || _busy || visible) return;
|
||||
_confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch;
|
||||
}
|
||||
private async Task DeleteAsync(long generation, long confirmation)
|
||||
{
|
||||
if (!Current(generation) || _busy || !_confirmDeleteVisible || confirmation != _confirmationEpoch || _deleteIntent is not { } intent) return;
|
||||
_busy = true; _error = null;
|
||||
try
|
||||
{
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
|
||||
if (!Current(generation)) return;
|
||||
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
|
||||
if (!Current(generation)) return;
|
||||
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
|
||||
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
|
||||
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = intent.RowVersion;
|
||||
db.Scripts.Remove(entity);
|
||||
await db.SaveChangesAsync();
|
||||
Nav.NavigateTo("/scripts");
|
||||
if (Current(generation)) Nav.NavigateTo("/scripts");
|
||||
}
|
||||
catch (DbUpdateConcurrencyException) { _error = "Another user changed this script while you were viewing it."; }
|
||||
catch (Exception ex) { _error = $"Delete failed: {ex.Message}. Likely because virtual tags or scripted alarms still reference this script — remove them first."; }
|
||||
finally { _busy = false; }
|
||||
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
|
||||
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}. Likely because virtual tags or scripted alarms still reference this script — remove them first."; }
|
||||
finally { if (Current(generation)) _busy = false; }
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true; ++_generation; ++_confirmationEpoch;
|
||||
}
|
||||
|
||||
private static string HashSource(string source) =>
|
||||
|
||||
Reference in New Issue
Block a user