fix(secrets-ui): align fields, confirmation lifecycle and list recovery

This commit is contained in:
Joseph Doherty
2026-11-13 17:02:22 -05:00
parent cb424a0ce7
commit 510d15d546
64 changed files with 4376 additions and 97 deletions
@@ -1,5 +1,7 @@
@namespace ZB.MOM.WW.Secrets.Ui.Components
@implements IDisposable
@implements IAsyncDisposable
@using Microsoft.JSInterop
@inject IJSRuntime JS
@inject ISecretStore Store
@inject IAuditWriter Audit
@inject IServiceProvider Services
@@ -16,49 +18,71 @@
every Bootstrap host. Theme tokens with fallbacks keep it legible even without the kit. *@
<style>
.zb-secrets-modal-backdrop {
position: fixed; inset: 0; z-index: 1080;
background: rgba(15, 18, 20, 0.45);
position: fixed; inset: 0; z-index: -1;
background: transparent; pointer-events: none;
}
.zb-secrets-modal {
position: fixed; inset: 0; z-index: 1081;
position: fixed; inset: 0; z-index: 1081; margin: 0; box-sizing: border-box;
width: 100vw; height: 100dvh; max-width: none; max-height: none;
border: 0; padding: 0; background: transparent;
display: flex; align-items: center; justify-content: center;
font-family: var(--sans, system-ui, sans-serif);
}
.zb-secrets-modal:not([open]) { display: none; }
.zb-secrets-modal::backdrop { background: rgba(15, 18, 20, 0.45); }
.zb-secrets-modal-card {
box-sizing: border-box;
background: var(--card, #ffffff); color: var(--ink, #1a1d1f);
border: 1px solid var(--rule-strong, #c9ced2);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.25);
padding: 1.25rem 1.5rem; max-width: 30rem; width: calc(100% - 2rem);
max-height: calc(100dvh - 2rem); overflow: auto; overflow-wrap: anywhere;
}
.zb-secrets-modal-title { margin: 0 0 0.5rem; font-size: 1.05rem; }
.zb-secrets-modal-card .btn-row { display: flex; gap: 0.5rem; margin-top: 1rem; }
</style>
<div class="zb-secrets-modal-backdrop" data-testid="delete-modal-backdrop"></div>
<div class="zb-secrets-modal" role="dialog" aria-modal="true" data-testid="delete-modal">
<dialog @ref="_dialog" class="zb-secrets-modal" role="dialog" aria-modal="true"
aria-labelledby="@TitleId" aria-describedby="@DescriptionId" aria-busy="@(_busy ? "true" : "false")"
tabindex="-1" data-testid="delete-modal">
<div class="zb-secrets-modal-backdrop" aria-hidden="true" data-testid="delete-modal-backdrop"></div>
<div class="zb-secrets-modal-card">
<h3 class="zb-secrets-modal-title">Delete secret '@Name.Value'?</h3>
<p>This tombstones the secret so the removal can propagate. The action is audited.</p>
<h3 id="@TitleId" class="zb-secrets-modal-title">Delete secret '@Name.Value'?</h3>
<p id="@DescriptionId">This tombstones the secret so the removal can propagate. The action is audited.</p>
@if (_error is not null)
{
<p class="field-error s-bad" data-testid="delete-error">@_error</p>
<p class="field-error s-bad" role="status" data-testid="delete-error">@_error</p>
}
<div class="btn-row">
<TechButton Variant="ButtonVariant.Danger" Busy="_busy"
<TechButton Variant="ButtonVariant.Danger" Busy="_busy" BusyText="Deleting…"
data-testid="confirm-delete" @onclick="ConfirmAsync">
Delete
</TechButton>
<TechButton Variant="ButtonVariant.Secondary"
data-testid="cancel-delete" @onclick="CancelAsync">
<TechButton Variant="ButtonVariant.Secondary" disabled="@_busy"
id="@CancelId" data-testid="cancel-delete" @onclick="CancelAsync">
Cancel
</TechButton>
</div>
</div>
</div>
</dialog>
}
@code {
private readonly string _id = $"secrets-delete-{Guid.NewGuid():N}";
private string TitleId => $"{_id}-title";
private string DescriptionId => $"{_id}-description";
private string CancelId => $"{_id}-cancel";
private ElementReference _dialog;
private IJSObjectReference? _module;
private DotNetObjectReference<ConfirmDeleteModal>? _reference;
private bool _opened;
private bool _activationAttempted;
private readonly SemaphoreSlim _dialogLifecycle = new(1, 1);
private bool _disposed;
private Task? _disposeTask;
private long _generation;
private SecretName? _identity;
private readonly CancellationTokenSource _cts = new();
private string? _error;
private bool _busy;
@@ -69,6 +93,12 @@
/// <summary>The secret the modal offers to delete.</summary>
[Parameter] public SecretName Name { get; set; }
/// <summary>Stable focus fallback when the originating row no longer exists.</summary>
[Parameter] public string? ReturnFocusId { get; set; }
/// <summary>Notifies a parent while deletion is pending so targets cannot be switched.</summary>
[Parameter] public EventCallback<bool> OnBusyChanged { get; set; }
/// <summary>Raised after the secret has been tombstoned and audited.</summary>
[Parameter] public EventCallback OnDeleted { get; set; }
@@ -78,60 +108,118 @@
/// <summary>The cascading authentication state, used as the fallback source of the audit actor.</summary>
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
private async Task ConfirmAsync()
{
_error = null;
private bool IsCurrent(long generation) => !_disposed && Visible && generation == _generation;
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, AuthState, SecretsAuthorization.ManagePolicy))
/// <inheritdoc />
protected override void OnParametersSet()
{
SecretName? identity = Visible ? Name : null;
if (identity != _identity)
{
_error = "You are not authorized to delete secrets.";
return;
_identity = identity;
++_generation;
_error = null;
}
_busy = true;
bool deleted = false;
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Blazor can start a newer render or disposal while import/open is awaiting JS.
// Serialize those continuations so an old activation cannot close a newer identity,
// and disposal always closes an attempted open before disposing its module/reference.
await _dialogLifecycle.WaitAsync();
try
{
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
if (_disposed) return;
if (Visible)
{
long generation = _generation;
_module ??= await JS.InvokeAsync<IJSObjectReference>("import", "./_content/ZB.MOM.WW.Secrets.Ui/js/secrets-dialog.js");
if (_disposed || !IsCurrent(generation)) return;
if (!_opened)
{
_reference ??= DotNetObjectReference.Create(this);
_activationAttempted = true;
await _module.InvokeVoidAsync("open", _dialog, CancelId, _reference, ReturnFocusId, _id);
_opened = true;
if (_disposed || !IsCurrent(generation))
{
await CloseDialogAsync();
return;
}
}
await _module.InvokeVoidAsync("setBusy", _id, _busy, ReturnFocusId);
}
else await CloseDialogAsync();
}
finally { _dialogLifecycle.Release(); }
}
private async Task CloseDialogAsync()
{
if (_module is not null && _activationAttempted)
{
await _module.InvokeVoidAsync("close", _id);
_activationAttempted = false;
_opened = false;
}
}
/// <summary>Handles the native dialog's safe Escape/cancel request.</summary>
[JSInvokable]
public Task RequestCancelAsync() => CancelAsync();
private async Task ConfirmAsync()
{
if (_disposed || _busy || !Visible) return;
long generation = _generation;
SecretName name = Name;
Task<AuthenticationState>? authState = AuthState;
CancellationToken ct = _cts.Token;
EventCallback deletedCallback = OnDeleted;
EventCallback<bool> busyCallback = OnBusyChanged;
_error = null;
_busy = true;
try
{
await busyCallback.InvokeAsync(true);
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, authState, SecretsAuthorization.ManagePolicy))
{
if (IsCurrent(generation)) _error = "You are not authorized to delete secrets.";
return;
}
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
string actor = await SecretActorResolver.ResolveAsync(Services, authState);
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
ISecretCacheInvalidator? cache = Services.GetService<ISecretCacheInvalidator>();
ILogger<ConfirmDeleteModal>? logger = Services.GetService<ILogger<ConfirmDeleteModal>>();
bool deleted = false;
try
{
await Store.DeleteAsync(Name, actor, _cts.Token);
// The tombstone is committed from here on.
await Store.DeleteAsync(name, actor, ct);
deleted = true;
}
catch (Exception)
{
// An unexpected store fault must still be audited as a Failure and surfaced to the
// operator instead of tearing down the circuit.
_error = "Unable to delete the secret.";
await WriteFailureAuditAsync(actor);
if (IsCurrent(generation)) _error = "Unable to delete the secret.";
await WriteFailureAuditAsync(actor, name, ct);
}
if (deleted)
{
// Outside the mutation try (scadaproj#34): a throwing audit sink must not turn a
// committed delete into a reported failure, nor skip the cache eviction below.
await WriteSuccessAuditAsync(actor);
await WriteSuccessAuditAsync(actor, name, ct, logger);
cache?.Invalidate(name);
if (IsCurrent(generation)) await deletedCallback.InvokeAsync();
}
}
finally
{
_busy = false;
}
if (deleted)
{
// Evict any cached plaintext so the ${secret:} / ISecretResolver path does not serve a
// stale value after this delete for the remainder of its TTL. Optional seam — a no-op
// when the host has not registered an invalidator.
Services.GetService<ISecretCacheInvalidator>()?.Invalidate(Name);
await OnDeleted.InvokeAsync();
await busyCallback.InvokeAsync(false);
}
}
private async Task WriteSuccessAuditAsync(string actor)
private async Task WriteSuccessAuditAsync(string actor, SecretName name, CancellationToken ct, ILogger<ConfirmDeleteModal>? logger)
{
try
{
@@ -144,22 +232,22 @@
Action = "secret.delete",
Outcome = AuditOutcome.Success,
Category = "Secrets",
Target = Name.Value,
Target = name.Value,
},
_cts.Token);
ct);
}
catch (Exception ex)
{
// Best-effort: the delete itself succeeded. Logged so the audit gap is visible.
Services.GetService<ILogger<ConfirmDeleteModal>>()?.LogWarning(
logger?.LogWarning(
ex,
"Secret delete of {SecretName} by {Actor} succeeded, but its audit event could not be written.",
Name.Value,
name.Value,
actor);
}
}
private async Task WriteFailureAuditAsync(string actor)
private async Task WriteFailureAuditAsync(string actor, SecretName name, CancellationToken ct)
{
try
{
@@ -172,10 +260,10 @@
Action = "secret.delete",
Outcome = AuditOutcome.Failure,
Category = "Secrets",
Target = Name.Value,
Target = name.Value,
DetailsJson = "{\"reason\":\"error\"}",
},
_cts.Token);
ct);
}
catch
{
@@ -183,12 +271,34 @@
}
}
private Task CancelAsync() => OnCancelled.InvokeAsync();
private Task CancelAsync() => _busy || _disposed ? Task.CompletedTask : OnCancelled.InvokeAsync();
/// <inheritdoc />
public void Dispose()
public ValueTask DisposeAsync() => new(_disposeTask ??= DisposeCoreAsync());
private async Task DisposeCoreAsync()
{
_disposed = true;
++_generation;
_cts.Cancel();
_cts.Dispose();
await _dialogLifecycle.WaitAsync();
try
{
if (_module is not null)
{
try
{
await CloseDialogAsync();
await _module.DisposeAsync();
}
catch (JSDisconnectedException) { }
}
}
finally
{
_reference?.Dispose();
_dialogLifecycle.Release();
}
}
}
@@ -9,25 +9,27 @@
The value is entered through a masked input and never rendered back or placed in any audit field. *@
<TechCard Title="@(IsRotate ? "Rotate secret" : "Add secret")">
<TechField Label="Name">
<TechField Label="Name" For="@NameId" Hint="@NameHint" HintId="@NameHintId"
Error="@_nameError" ErrorId="@NameErrorId">
@if (IsRotate)
{
<input class="form-control mono" type="text" readonly
<input id="@NameId" class="form-control mono" type="text" readonly aria-describedby="@NameHintId"
value="@_name" disabled="@_busy" data-testid="secret-name" />
}
else
{
<input class="form-control mono" type="text"
<input id="@NameId" @ref="_nameControl" class="form-control mono" type="text" required
aria-describedby="@NameDescriptionIds" aria-invalid="@(!string.IsNullOrEmpty(_nameError) ? "true" : null)"
@bind="_name" disabled="@_busy" data-testid="secret-name" />
}
</TechField>
<TechField Label="Description">
<input class="form-control" type="text" @bind="_description" disabled="@(_busy || _metadataLoading)" data-testid="secret-description" />
<TechField Label="Description" For="@DescriptionId" Hint="Optional metadata; do not include credentials." HintId="@DescriptionHintId">
<input id="@DescriptionId" aria-describedby="@DescriptionHintId" class="form-control" type="text" @bind="_description" disabled="@(_busy || _metadataLoading)" data-testid="secret-description" />
</TechField>
<TechField Label="Content type">
<select class="form-select" @bind="_contentType" disabled="@(_busy || _metadataLoading)" data-testid="secret-content-type">
<TechField Label="Content type" For="@ContentTypeId">
<select id="@ContentTypeId" class="form-select" @bind="_contentType" disabled="@(_busy || _metadataLoading)" data-testid="secret-content-type">
@foreach (SecretContentType ct in Enum.GetValues<SecretContentType>())
{
<option value="@ct">@ct</option>
@@ -35,14 +37,19 @@
</select>
</TechField>
<TechField Label="Value">
<input class="form-control mono" type="password" autocomplete="new-password"
<TechField Label="Value" For="@ValueId" Hint="Enter the new value. Stored values are never prefilled." HintId="@ValueHintId">
<input id="@ValueId" aria-describedby="@ValueHintId" class="form-control mono" type="password" autocomplete="new-password"
@bind="_value" disabled="@(_busy || _metadataLoading)" data-testid="secret-value" />
</TechField>
@if (_error is not null)
{
<p class="field-error s-bad" data-testid="editor-error">@_error</p>
<p class="field-error s-bad" role="status" data-testid="editor-error">@_error</p>
}
@if (!string.IsNullOrEmpty(_nameError))
{
<p class="visually-hidden" role="alert">Check the Name field.</p>
}
@if (_busy)
@@ -51,11 +58,11 @@
}
<div class="btn-row">
<TechButton Variant="ButtonVariant.Primary" Busy="@(_busy || _metadataLoading || !_metadataReady)"
<TechButton Variant="ButtonVariant.Primary" Busy="@(_busy || _metadataLoading)" BusyText="@(_metadataLoading ? "Loading…" : "Saving…")" disabled="@(!_metadataReady)"
data-testid="editor-submit" @onclick="SubmitAsync">
@(IsRotate ? "Rotate" : "Add")
</TechButton>
<TechButton Variant="ButtonVariant.Secondary" Busy="_busy"
<TechButton Variant="ButtonVariant.Secondary" disabled="@_busy"
data-testid="editor-cancel" @onclick="CancelAsync">
Cancel
</TechButton>
@@ -63,6 +70,20 @@
</TechCard>
@code {
private readonly string _fieldPrefix = $"secret-editor-{Guid.NewGuid():N}";
private ElementReference _nameControl;
private bool _focusNameError;
private string NameId => $"{_fieldPrefix}-name";
private string NameHintId => $"{_fieldPrefix}-name-hint";
private string NameErrorId => $"{_fieldPrefix}-name-error";
private string DescriptionId => $"{_fieldPrefix}-description";
private string DescriptionHintId => $"{_fieldPrefix}-description-hint";
private string ContentTypeId => $"{_fieldPrefix}-content-type";
private string ValueId => $"{_fieldPrefix}-value";
private string ValueHintId => $"{_fieldPrefix}-value-hint";
private string NameDescriptionIds => string.IsNullOrEmpty(_nameError) ? NameHintId : $"{NameHintId} {NameErrorId}";
private string NameHint => IsRotate ? "This name is fixed during rotation." : "Required. Up to 450 characters: letters, numbers, dot, underscore, hyphen and slash. No '..', leading/trailing slash or empty path segment. Letters normalize to lowercase.";
private string? _nameError;
private readonly CancellationTokenSource _cts = new();
private CancellationTokenSource? _metadataCts;
private SecretName? _identityName;
@@ -120,6 +141,8 @@
_contentType = SecretContentType.Text;
_value = string.Empty;
_error = null;
_nameError = null;
_focusNameError = false;
_restoreConfirmedFor = null;
_metadataLoading = false;
_metadataReady = !IsRotate;
@@ -171,6 +194,18 @@
}
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Wait until finally has unlocked the controls and the DOM reflects it. Focusing a
// disabled input during the submit handler fails in a real host even if markup tests pass.
if (_focusNameError && !_busy && !_disposed)
{
_focusNameError = false;
await _nameControl.FocusAsync();
}
}
private async Task SubmitAsync()
{
if (_disposed || _busy || _metadataLoading || !_metadataReady)
@@ -193,6 +228,7 @@
EventCallback savedCallback = OnSaved;
EventCallback<bool> busyCallback = OnBusyChanged;
_error = null;
_nameError = null;
_busy = true;
try
{
@@ -214,7 +250,11 @@
}
catch (ArgumentException ex)
{
if (IsCurrent(generation)) _error = ex.Message;
if (IsCurrent(generation))
{
_nameError = ex.Message;
_focusNameError = true;
}
return;
}
@@ -7,7 +7,7 @@
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
<div class="toolbar btn-row">
<TechButton Variant="ButtonVariant.Primary" Busy="_editorBusy" data-testid="add-secret" @onclick="ShowAdd">
<TechButton Variant="ButtonVariant.Primary" disabled="@OperationBusy" data-testid="add-secret" @onclick="ShowAdd">
Add secret
</TechButton>
</div>
@@ -22,14 +22,27 @@
OnCancelled="() => CloseEditor(editorGeneration)" />
}
<TechCard Title="Secrets">
@if (_secrets is null)
<TechCard>
<Header><h2 id="@HeadingId" tabindex="-1" style="margin:0;font:inherit">Secrets</h2></Header>
<ChildContent>
@if (_listError is not null)
{
<p class="mono">Loading…</p>
<div role="status" class="s-bad" data-testid="list-error">
<p>@_listError</p>
<TechButton Variant="ButtonVariant.Secondary" disabled="@_loading" data-testid="list-retry" @onclick="RetryAsync">Retry refresh</TechButton>
</div>
}
else
@if (_outcome is not null)
{
<div class="table-wrap">
<p role="status" data-testid="list-outcome">@_outcome</p>
}
@if (_loading)
{
<p role="status" data-testid="list-loading">@(_secrets is null ? "Loading secrets…" : "Refreshing secret metadata…")</p>
}
@if (_secrets is not null)
{
<div class="table-wrap" aria-busy="@(_loading ? "true" : "false")">
<table class="data-table">
<thead>
<tr>
@@ -68,12 +81,12 @@
</AuthorizeView>
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
<button type="button" class="btn btn-outline-secondary rotate-secret"
data-secret-name="@secret.Name.Value" disabled="@_editorBusy"
data-secret-name="@secret.Name.Value" disabled="@OperationBusy"
@onclick="() => ShowRotate(secret.Name)">
Rotate
</button>
<button type="button" class="btn btn-danger delete-secret"
data-secret-name="@secret.Name.Value" disabled="@_editorBusy"
id="@RowActionId(secret.Name)" data-secret-name="@secret.Name.Value" disabled="@OperationBusy"
@onclick="() => ShowDelete(secret.Name)">
Delete
</button>
@@ -86,16 +99,30 @@
</table>
</div>
}
</ChildContent>
</TechCard>
<ConfirmDeleteModal Visible="_deleteTarget.HasValue"
Name="_deleteTarget.GetValueOrDefault()"
OnDeleted="OnMutatedAsync"
OnCancelled="CloseDelete" />
@{ var deleteGeneration = _deleteGeneration; }
<ConfirmDeleteModal @key="_deleteTarget" Visible="_deleteTarget.HasValue"
Name="_deleteTarget.GetValueOrDefault()" ReturnFocusId="@DeleteReturnFocusId()"
OnBusyChanged="busy => OnDeleteBusyChanged(deleteGeneration, busy)"
OnDeleted="() => OnDeleteCommittedAsync(deleteGeneration)"
OnCancelled="() => CloseDelete(deleteGeneration)" />
@code {
private readonly string _id = $"secrets-list-{Guid.NewGuid():N}";
private string HeadingId => $"{_id}-heading";
private readonly Dictionary<SecretName, string> _rowIds = new();
private long _deleteGeneration;
private bool _deleteBusy;
private bool OperationBusy => _editorBusy || _deleteBusy;
private readonly CancellationTokenSource _cts = new();
private IReadOnlyList<SecretMetadata>? _secrets;
private CancellationTokenSource? _listCts;
private long _loadGeneration;
private bool _loading;
private string? _listError;
private string? _outcome;
private EditorMode _editorMode = EditorMode.None;
private SecretName? _rotateName;
@@ -114,12 +141,50 @@
/// <inheritdoc />
protected override async Task OnInitializedAsync() => await ReloadAsync();
private async Task ReloadAsync()
=> _secrets = await Store.ListAsync(includeDeleted: false, _cts.Token);
private Task RetryAsync() => ReloadAsync();
private async Task ReloadAsync(bool committed = false)
{
if (_disposed) return;
long generation = ++_loadGeneration;
_listCts?.Cancel();
_listCts?.Dispose();
var readCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token);
_listCts = readCts;
CancellationToken ct = readCts.Token;
_loading = true;
_listError = null;
if (committed) _outcome = null;
try
{
IReadOnlyList<SecretMetadata> rows = await Store.ListAsync(includeDeleted: false, ct);
if (!_disposed && generation == _loadGeneration)
{
_secrets = rows;
if (committed) _outcome = "Change saved.";
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
catch (Exception)
{
if (!_disposed && generation == _loadGeneration)
{
_listError = committed
? "Change saved; list refresh failed. Retry refresh only; the change will not be repeated."
: "Unable to load secret metadata. Retry refresh.";
}
}
finally
{
if (!_disposed && generation == _loadGeneration) _loading = false;
if (ReferenceEquals(_listCts, readCts)) _listCts = null;
readCts.Dispose();
}
}
private void ShowAdd()
{
if (_editorBusy || _disposed || _editorMode == EditorMode.Add) return;
if (OperationBusy || _disposed || _editorMode == EditorMode.Add) return;
++_editorGeneration;
_rotateName = null;
_editorMode = EditorMode.Add;
@@ -127,7 +192,7 @@
private void ShowRotate(SecretName name)
{
if (_editorBusy || _disposed || (_editorMode == EditorMode.Rotate && _rotateName == name)) return;
if (OperationBusy || _disposed || (_editorMode == EditorMode.Rotate && _rotateName == name)) return;
++_editorGeneration;
_rotateName = name;
_editorMode = EditorMode.Rotate;
@@ -135,7 +200,7 @@
private void CloseEditor(long generation)
{
if (_editorBusy || _disposed || generation != _editorGeneration) return;
if (OperationBusy || _disposed || generation != _editorGeneration) return;
ClearEditor();
}
@@ -152,32 +217,80 @@
if (!_disposed && generation == _editorGeneration)
{
_editorBusy = busy;
if (busy) _outcome = null;
}
}
private async Task OnEditorSavedAsync(long generation)
{
if (_disposed || generation != _editorGeneration) return;
await ReloadAsync();
await ReloadAsync(committed: true);
if (!_disposed && generation == _editorGeneration)
{
ClearEditor();
CloseDelete();
ClearDelete();
}
}
private string RowActionId(SecretName name)
{
if (!_rowIds.TryGetValue(name, out string? id))
{
id = $"{_id}-row-{_rowIds.Count}";
_rowIds.Add(name, id);
}
return id;
}
private string DeleteReturnFocusId()
{
if (_secrets is null || _deleteTarget is not { } target) return HeadingId;
var rows = _secrets.ToList();
int index = rows.FindIndex(row => row.Name == target);
if (index < 0) return HeadingId;
if (index + 1 < rows.Count) return RowActionId(rows[index + 1].Name);
if (index > 0) return RowActionId(rows[index - 1].Name);
return HeadingId;
}
private void ShowDelete(SecretName name)
{
if (!_editorBusy && !_disposed) _deleteTarget = name;
if (OperationBusy || _disposed || _deleteTarget == name) return;
++_deleteGeneration;
_deleteTarget = name;
}
private void CloseDelete() => _deleteTarget = null;
private async Task OnMutatedAsync()
private void OnDeleteBusyChanged(long generation, bool busy)
{
CloseEditor(_editorGeneration);
CloseDelete();
await ReloadAsync();
if (!_disposed && generation == _deleteGeneration)
{
_deleteBusy = busy;
if (busy) _outcome = null;
}
}
private void CloseDelete(long generation)
{
if (_deleteBusy || _disposed || generation != _deleteGeneration) return;
ClearDelete();
}
private void ClearDelete()
{
++_deleteGeneration;
_deleteTarget = null;
_deleteBusy = false;
}
private async Task OnDeleteCommittedAsync(long generation)
{
if (_disposed || generation != _deleteGeneration) return;
await ReloadAsync(committed: true);
if (!_disposed && generation == _deleteGeneration)
{
ClearEditor();
ClearDelete();
}
}
/// <inheritdoc />
@@ -185,6 +298,11 @@
{
_disposed = true;
++_editorGeneration;
++_deleteGeneration;
++_loadGeneration;
_listCts?.Cancel();
_listCts?.Dispose();
_listCts = null;
_cts.Cancel();
_cts.Dispose();
}
@@ -0,0 +1,101 @@
// Native top-layer dialog adapter. Each mounted instance owns its trigger and listeners.
const states = new Map();
let scrollLocks = 0;
let previousOverflow;
const visible = node => {
if (!node?.isConnected || !node.getClientRects().length) return false;
for (let ancestor = node; ancestor; ancestor = ancestor.parentElement) {
const style = getComputedStyle(ancestor);
if (ancestor.hidden || ancestor.inert || style.display === 'none' || ['hidden', 'collapse'].includes(style.visibility)) return false;
}
return true;
};
const usable = node => visible(node) && !node.disabled && node.getAttribute('aria-disabled') !== 'true';
const focusable = dialog => [...dialog.querySelectorAll('button, [href], input, select, textarea, [tabindex]')]
.filter(node => usable(node) && node.tabIndex >= 0);
export function open(dialog, safeActionId, dotnet, fallbackId, instanceId) {
if (states.has(instanceId)) return;
const state = { dialog, trigger: document.activeElement, busy: false, fallbackId };
const requestCancel = () => {
if (!state.busy) dotnet.invokeMethodAsync('RequestCancelAsync').catch(error => {
if (states.has(instanceId)) console.error('Unable to dismiss secrets confirmation.', error);
});
};
state.keydown = event => {
if (event.key === 'Escape') {
event.preventDefault();
requestCancel();
} else if (event.key === 'Tab') {
const items = focusable(dialog);
const first = items[0];
const last = items.at(-1);
if (!first) { event.preventDefault(); dialog.focus(); }
else if (event.shiftKey && (document.activeElement === first || !items.includes(document.activeElement))) {
event.preventDefault(); last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !items.includes(document.activeElement))) {
event.preventDefault(); first.focus();
}
}
};
state.cancel = event => { event.preventDefault(); requestCancel(); };
states.set(instanceId, state);
dialog.addEventListener('keydown', state.keydown);
dialog.addEventListener('cancel', state.cancel);
let locked = false;
try {
// showModal provides the top layer and native background inertness without mutating
// an ancestor's existing inert attribute or depending on the host's transform styles.
dialog.showModal();
if (scrollLocks++ === 0) {
previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
}
locked = true;
document.getElementById(safeActionId)?.focus({ preventScroll: true });
} catch (error) {
dialog.removeEventListener('keydown', state.keydown);
dialog.removeEventListener('cancel', state.cancel);
states.delete(instanceId);
if (dialog.open) dialog.close();
if (locked && --scrollLocks === 0) document.body.style.overflow = previousOverflow;
throw error;
}
}
export function setBusy(instanceId, busy, fallbackId) {
const state = states.get(instanceId);
if (state) { state.busy = busy; state.fallbackId = fallbackId; }
}
export function close(instanceId) {
const state = states.get(instanceId);
if (!state) return;
const dialog = state.dialog;
states.delete(instanceId);
dialog.removeEventListener('keydown', state.keydown);
dialog.removeEventListener('cancel', state.cancel);
if (dialog.open) dialog.close();
if (--scrollLocks === 0) document.body.style.overflow = previousOverflow;
// Blazor can dispose a child before its parent render batch removes the old row and
// re-enables adjacent actions. Restore after that actual DOM change, not during disposal.
// A bounded observer also handles a slow circuit round trip without a fixed timing guess.
let timer;
let frame;
const observer = new MutationObserver(restore);
const cleanup = () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); };
function restore() {
if (states.has(instanceId)) { cleanup(); return; }
for (const target of [state.trigger, document.getElementById(state.fallbackId)]) {
if (!usable(target)) continue;
const modal = document.querySelector('dialog:modal');
if (modal && !modal.contains(target)) { cleanup(); return; }
target.focus({ preventScroll: true });
// A connected node can still reject focus. Try the logical fallback too.
if (document.activeElement === target) { cleanup(); return; }
}
}
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled', 'aria-disabled', 'inert', 'hidden', 'style', 'class', 'tabindex'] });
timer = setTimeout(cleanup, 3000);
frame = requestAnimationFrame(restore);
}