Isolate staged CSV imports in named managed dialogs

This commit is contained in:
Joseph Doherty
2026-11-13 23:54:11 -05:00
parent 784dc7aeca
commit c9f191d5fa
70 changed files with 17947 additions and 131 deletions
@@ -19,20 +19,22 @@
@inject IRawTreeService Svc
@inject RawTagCsvExportReader ExportReader
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Import tags — CSV</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="Close"></button>
</div>
<div class="modal-body">
@implements IDisposable
@{ var presentation = _openGeneration; var savedAction = OnSaved; var closeAction = VisibleChanged; }
<ModalFrame Visible="@Visible" Title="Import tags — CSV" DialogClass="modal-xl" Target="@presentation" Busy="@Pending" OnClose="() => ClosePresentation(presentation, closeAction)">
<ChildContent>
@if (_resolving) { <p role="status">Resolving import target…</p> }
@if (_targetError is not null)
{
<p role="alert">The import target could not be read. Retry before selecting a file.</p>
<DiagnosticDetails Summary="Import target details" Text="@_targetError" />
<button type="button" class="btn btn-outline-secondary mb-2" disabled="@Pending" @onclick="() => RetryTarget(presentation)">Retry target</button>
}
<fieldset disabled="@(Pending || _parsing || _resolving || _targetError is not null)" @key="_openGeneration">
@if (!string.IsNullOrEmpty(_fatal))
{
<div class="alert alert-danger">@_fatal</div>
<div class="alert alert-danger" role="alert">@_fatal</div>
}
@if (_result is null)
@@ -42,10 +44,12 @@
<span class="mono">@DriverType</span> device.
Target: <span class="mono">@TargetLabel</span>.
</p>
<InputFile OnChange="OnFileSelected" accept=".csv,text/csv" class="form-control" />
<label class="form-label" for="@_fileId">CSV file</label>
<InputFile id="@_fileId" @key="_openGeneration" OnChange="e => OnFileSelectedPresentation(e, presentation)" aria-describedby="@(_fileId + "-hint")" accept=".csv,text/csv" class="form-control" />
<p id="@(_fileId + "-hint")" class="form-text">CSV with a header row; maximum 16 MiB. Review every row before committing. Nothing is imported during upload.</p>
@if (_parsing)
{
<p class="text-muted mt-2"><span class="spinner-border spinner-border-sm"></span> Parsing…</p>
<p class="text-muted mt-2" role="status"><span class="spinner-border spinner-border-sm" aria-hidden="true"></span> Parsing…</p>
}
}
else
@@ -59,7 +63,7 @@
<span class="badge bg-danger">@ErrorCount invalid</span>
}
</div>
<button type="button" class="btn btn-sm btn-outline-secondary" @onclick="Reset">Choose another file</button>
<button type="button" class="btn btn-sm btn-outline-secondary" @onclick="() => ResetPresentation(presentation)">Choose another file</button>
</div>
@if (ErrorCount > 0)
@@ -69,17 +73,17 @@
</div>
}
<div class="table-responsive" style="max-height:50vh;overflow:auto">
<table class="table table-sm table-hover align-middle">
<thead class="sticky-top bg-body">
<div class="table-wrap" style="max-height:50vh;overflow:auto" role="region" aria-label="CSV import review" tabindex="0">
<table class="data-table" aria-label="Staged CSV tags">
<thead>
<tr>
<th style="width:2.5rem"></th>
<th title="Data-row number in the file (the header is row 0)">Row</th>
<th>Name</th>
<th>Group</th>
<th>Verdict</th>
<th>Provenance</th>
<th style="width:2.5rem"></th>
<th scope="col" style="width:2.5rem">Status</th>
<th scope="col" title="Data-row number in the file (the header is row 0)">Row</th>
<th scope="col">Name</th>
<th scope="col">Group</th>
<th scope="col">Verdict</th>
<th scope="col">Provenance</th>
<th scope="col" style="width:2.5rem">Actions</th>
</tr>
</thead>
<tbody>
@@ -88,7 +92,7 @@
SpacerElement="tr" Context="row">
<tr @key="row.RowNumber" class="@(row.Ok ? "" : "table-danger")">
<td>@(row.Ok ? "✓" : "✕")</td>
<td class="mono">@row.RowNumber</td>
<th scope="row" class="mono">@row.RowNumber</th>
<td class="mono">
@if (row.Name.Length == 0)
{
@@ -130,8 +134,8 @@
</td>
<td>
<button type="button" class="btn btn-sm btn-outline-danger"
title="Remove this row from the import"
@onclick="() => RemoveRow(row.RowNumber)">✕</button>
aria-label="@($"Remove row {row.RowNumber}: {(row.Name.Length == 0 ? "blank name" : row.Name)}")" title="Remove this row from the import"
@onclick="() => RemoveRowPresentation(row.RowNumber, presentation)">✕</button>
</td>
</tr>
</Virtualize>
@@ -141,7 +145,7 @@
@if (_commitErrors.Count > 0)
{
<div class="alert alert-danger mt-2">
<div class="alert alert-danger mt-2" role="alert">
<strong>Commit rejected:</strong>
<ul class="mb-0">
@foreach (var e in _commitErrors)
@@ -152,25 +156,18 @@
</div>
}
}
</div>
<div class="modal-footer">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="Close">Cancel</button>
<button type="button" class="btn btn-primary"
disabled="@(!CanCommit || _committing)"
@onclick="Commit">
@if (_committing)
{
<span class="spinner-border spinner-border-sm"></span>
}
Commit @RemainingCount tag@(RemainingCount == 1 ? "" : "s")
</button>
</div>
</div>
</div>
</fieldset>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" disabled="@Pending" @onclick="() => ClosePresentation(presentation, closeAction)">Cancel</button>
<button type="button" class="btn btn-primary" disabled="@(!CanCommit || Pending || _parsing || _resolving)" @onclick="() => CommitPresentation(presentation, savedAction, closeAction)">
@if (_committing) { <span class="spinner-border spinner-border-sm" aria-hidden="true"></span> }
@(_committing ? "Committing…" : $"Commit {RemainingCount} tag{(RemainingCount == 1 ? "" : "s")}")
</button>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Whether the modal is shown (two-way bound).</summary>
@@ -200,7 +197,6 @@
private string? _fatal;
private bool _parsing;
private bool _committing;
private bool _resolved;
// Bumped on every open and every close; an async continuation compares its captured value after each
// await so a superseded open can never write its target under a different device's displayed modal
@@ -221,132 +217,123 @@
private bool CanCommit =>
_result is not null && _fatal is null && RemainingCount > 0 && ErrorCount == 0;
/// <summary>Optional nonconfidential identity for otherwise identical import contexts.</summary>
[Parameter] public object? Target { get; set; }
private readonly string _fileId = "raw-csv-file-" + Guid.NewGuid().ToString("N");
private object? _lastTarget;
private bool _lastVisible, _closing, _disposed, _resolving;
private string? _targetError;
private bool Pending => _committing || _closing;
protected override async Task OnParametersSetAsync()
{
if (Visible && !_resolved)
{
_resolved = true;
var generation = ++_openGeneration;
await ResolveTargetAsync(generation);
}
else if (!Visible)
{
_resolved = false;
_openGeneration++;
}
object identity = (Target, DeviceId, TagGroupId, DriverType);
if (_disposed || (_lastVisible == Visible && Equals(_lastTarget, identity))) return;
_lastVisible = Visible; _lastTarget = identity;
var generation = ++_openGeneration;
Reset(); _parsing = false; _targetError = null;
if (Visible) await ResolveTargetAsync(generation);
}
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
private bool IsStale(int generation) => _disposed || generation != _openGeneration || !Visible;
// Resolve the effective device id + the group-path prefix once per open.
// Keep the original group resolution and device-id precedence, but bind every await to this presentation.
private async Task ResolveTargetAsync(int generation)
{
_effectiveDeviceId = DeviceId;
_groupPrefix = null;
if (!string.IsNullOrEmpty(TagGroupId))
var deviceId = DeviceId;
var tagGroupId = TagGroupId;
_resolving = true; _targetError = null;
_effectiveDeviceId = deviceId; _groupPrefix = null;
try
{
var ctx = await ExportReader.ResolveGroupContextAsync(TagGroupId!);
if (IsStale(generation)) { return; }
if (ctx is { } c)
if (!string.IsNullOrEmpty(tagGroupId))
{
_groupPrefix = c.GroupPath;
if (string.IsNullOrEmpty(_effectiveDeviceId))
var context = await ExportReader.ResolveGroupContextAsync(tagGroupId);
if (IsStale(generation)) return;
if (context is { } value)
{
_effectiveDeviceId = c.DeviceId;
_groupPrefix = value.GroupPath;
if (string.IsNullOrEmpty(deviceId)) _effectiveDeviceId = value.DeviceId;
}
}
}
catch (Exception ex) { if (!IsStale(generation)) _targetError = ex.Message; }
finally { if (!IsStale(generation)) _resolving = false; }
}
private async Task OnFileSelected(InputFileChangeEventArgs e)
{
_fatal = null;
_commitErrors = new();
_view.Set(null);
_parsing = true;
var generation = _openGeneration;
private Task RetryTarget(int generation) => IsStale(generation) || Pending || _resolving
? Task.CompletedTask : ResolveTargetAsync(generation);
private Task OnFileSelected(InputFileChangeEventArgs e) => OnFileSelectedPresentation(e, _openGeneration);
private async Task OnFileSelectedPresentation(InputFileChangeEventArgs e, int generation)
{
if (IsStale(generation) || Pending || _parsing || _resolving || _targetError is not null) return;
var driverType = DriverType;
var groupPrefix = _groupPrefix;
_fatal = null; _commitErrors = new(); _result = null; _view.Set(null); _parsing = true;
try
{
using var stream = e.File.OpenReadStream(maxAllowedSize: 16 * 1024 * 1024);
using var reader = new StreamReader(stream);
var text = await reader.ReadToEndAsync();
if (IsStale(generation)) { return; }
_result = RawTagCsvMapper.Parse(DriverType, text, _groupPrefix);
_view.Set(_result);
_fatal = _result.FatalError;
if (IsStale(generation)) return;
_result = RawTagCsvMapper.Parse(driverType, text, groupPrefix);
_view.Set(_result); _fatal = _result.FatalError;
}
catch (Exception ex)
{
_fatal = $"Could not read the file: {ex.Message}";
_result = null;
_view.Set(null);
}
finally
{
_parsing = false;
if (!IsStale(generation)) { _fatal = $"Could not read the file: {ex.Message}"; _result = null; _view.Set(null); }
}
finally { if (!IsStale(generation)) _parsing = false; }
}
private void RemoveRow(int rowNumber) => _view.Remove(rowNumber);
private void RemoveRowPresentation(int rowNumber, int generation)
{
if (!IsStale(generation) && !Pending && !_parsing && !_resolving) _view.Remove(rowNumber);
}
private void ResetPresentation(int generation)
{
if (!IsStale(generation) && !Pending && !_parsing && !_resolving) Reset();
}
private void Reset()
{
_result = null;
_fatal = null;
_commitErrors = new();
_view.Set(null);
_result = null; _fatal = null; _commitErrors = new(); _view.Set(null);
}
private async Task Commit()
private Task Commit() => CommitPresentation(_openGeneration, OnSaved, VisibleChanged);
private async Task CommitPresentation(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
if (_result is null || !CanCommit)
{
return;
}
_committing = true;
_commitErrors = new();
var generation = _openGeneration;
if (IsStale(generation) || Pending || _parsing || _resolving || _targetError is not null || !CanCommit) return;
var targetDeviceId = _effectiveDeviceId;
var rows = _view.CommitRows().ToArray();
_committing = true; _commitErrors = new();
try
{
var rows = _view.CommitRows();
var outcome = await Svc.ImportTagsAsync(targetDeviceId, rows);
// The write has landed whether or not the modal was closed/reopened meanwhile, so the parent must
// still refresh its tree; only the modal-local state writes are skipped when stale.
if (IsStale(generation))
{
if (outcome.Errors.Count == 0) { await OnSaved.InvokeAsync(); }
return;
}
if (_disposed) return;
if (outcome.Errors.Count > 0)
{
_commitErrors = outcome.Errors.ToList();
if (!IsStale(generation)) _commitErrors = outcome.Errors.ToList();
return;
}
await OnSaved.InvokeAsync();
await Close();
}
catch (Exception ex)
{
_commitErrors = new() { ex.Message };
}
finally
{
_committing = false;
// Preserve the existing committed-write refresh contract using only the originating callback.
await savedAction.InvokeAsync();
if (!IsStale(generation)) await ClosePresentation(generation, closeAction, true);
}
catch (Exception ex) { if (!IsStale(generation)) _commitErrors = new() { ex.Message }; }
finally { _committing = false; }
}
private async Task Close()
private Task Close() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> action, bool afterCommit = false)
{
Reset();
Visible = false;
_resolved = false;
_openGeneration++;
await VisibleChanged.InvokeAsync(false);
if (IsStale(generation) || _closing || (_committing && !afterCommit)) return;
_closing = true;
Reset(); Visible = false; _lastVisible = false; ++_openGeneration;
try { await action.InvokeAsync(false); }
finally { _closing = false; }
}
/// <summary>Retires uploads, reads and callbacks without cancelling a dispatched all-or-nothing import.</summary>
public void Dispose() { _disposed = true; ++_openGeneration; }
}