fix(reorganize): Apply on the first click, one offer per toast, no open dialog replaced

Review of owner review 2, phase 4a (R7): the Reorganize dialogs of the desktop and the web panel.

Desktop
- Clicking Apply first takes the focus from the template field, which committed it and started
  a dry run identical to the one on screen: Apply turned off under the click. A commit now plans
  only when the templates differ from the shown plan (or the last dry run failed).
- The Settings toast's Reorganize… disposed whatever dialog the Archive screen had open, so a
  running Delete stopped without being asked. An open dialog now stays and its archive is not
  switched; Reorganize says it waits and opens once that dialog closes, with the archive's
  templates read again and every part the toasts offered meanwhile.
- Each Settings toast takes its own archive's offer (one pending offer per archive), and a toast
  gone early (dismissed, pushed out) lets the next change of that archive raise its own toast:
  Toast.Closed now says when a toast leaves the screen.

Web panel
- The Library sends the selected ids up to a thousand. all:true is used only above that, when
  the selection is exactly what Select all fetched without a filter and the archive has not grown
  since, so a sequence unticked or added later is never reorganized; otherwise the toast asks to
  select again.
- The preview's "before" of an untitled sequence is its old name, not the new title twice.
- A dry run of the same request answering during the confirmation no longer drops the confirmed
  apply; a plan that really changed is shown and said (Admin.Reorganize.PlanChanged).
- Enter in a template plans at once (the form never submitted on Enter).
- The confirm tooltip and the module header no longer say the moves are verified: moves and
  renames are not hashed.

Strings in en and it; the reworded key exists in no other culture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit bed718fb5af2ef69943fd348690c689259872a34)
This commit is contained in:
Alby96 committed 2026-10-27 16:30:01 +01:00
1 parent 9ae773aa5a
commit 59ee982e4d
14 files changed
+301 -49

No files matched your search

+2 -2
View File
@@ -71,7 +71,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files) |
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary; `ReorganizeOffer`: per archive, the templates Settings › Archive's toast offers, joined while that archive's toast is up), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); the schedules of Jobs › Scheduled (`DesktopScheduleHost`: the desktop's `IScheduleHost` and its system schedules `archive-scan`, `index-backup`, `housekeeping`; `CacheTrimStep`, the host's clean-up step; `SchedulesViewModel`, `ScheduleRowViewModel`, `ScheduleEditorViewModel` and `ScheduleDialogs.xaml`, the in-window editor; `ScheduleText`); settings rows (`LogSettingsRows`: Advanced's log rows), encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppLogging` (Settings › Advanced › Logs applied to the log files from their first line, a launch that only hands over included, and at every save), `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
@@ -82,7 +82,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| Folder | Content |
|---|---|
| `Ui/Themes`, `Ui/Theming` | DESIGN tokens (light, dark), typography, control styles, `ThemeManager` |
| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost` (`Toast.Closed` once a toast leaves the screen), `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, with `ReorganizePlanCache`: a dry run's plan kept a few minutes while the index's stamp stays, for the same dry run and its confirmation), API errors, the WebSocket `EventHub` |
+2 -1
View File
@@ -443,7 +443,7 @@
<data name="Admin.Reorganize.Column.Folder" xml:space="preserve"><value>Folder</value></data>
<data name="Admin.Reorganize.Column.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Reorganize.Confirm" xml:space="preserve"><value>Reorganize</value></data>
<data name="Admin.Reorganize.Confirm.Tip" xml:space="preserve"><value>Queue the job that moves and renames the originals, each one verified; nothing is overwritten or deleted</value></data>
<data name="Admin.Reorganize.Confirm.Tip" xml:space="preserve"><value>Queue the job that moves and renames the originals; nothing is overwritten or deleted</value></data>
<data name="Admin.Reorganize.ConfirmFiles.one" xml:space="preserve"><value>{0} photo gets a new name.</value><comment>long</comment></data>
<data name="Admin.Reorganize.ConfirmFiles.other" xml:space="preserve"><value>{0} photos get new names.</value><comment>long</comment></data>
<data name="Admin.Reorganize.ConfirmFolders.one" xml:space="preserve"><value>{0} folder moves.</value><comment>long</comment></data>
@@ -467,6 +467,7 @@
<data name="Admin.Reorganize.Offer.Tip" xml:space="preserve"><value>Apply the new templates to the sequences already in the archive; a preview shows every change first</value></data>
<data name="Admin.Reorganize.OpenJob" xml:space="preserve"><value>Open job</value></data>
<data name="Admin.Reorganize.OpenJob.Tip" xml:space="preserve"><value>Show the job and its log on the Jobs page</value></data>
<data name="Admin.Reorganize.PlanChanged" xml:space="preserve"><value>The archive changed during the confirmation; check the new preview and apply again.</value><comment>long</comment></data>
<data name="Admin.Reorganize.Planning" xml:space="preserve"><value>Planning…</value></data>
<data name="Admin.Reorganize.Preview" xml:space="preserve"><value>Preview</value></data>
<data name="Admin.Reorganize.Preview.Tip" xml:space="preserve"><value>What each sequence becomes, in the order the changes apply; nothing has changed yet</value></data>
+1
View File
@@ -240,6 +240,7 @@
<data name="Archive.Reorganize.Renamed.other" xml:space="preserve"><value>{0:N0} files renamed</value></data>
<data name="Archive.Reorganize.Title" xml:space="preserve"><value>Title</value></data>
<data name="Archive.Reorganize.Titles" xml:space="preserve"><value>Titles</value></data>
<data name="Archive.Reorganize.Waiting" xml:space="preserve"><value>Reorganize opens when the open dialog closes</value><comment>long: toast when the Settings toast's Reorganize… finds another Archive dialog open</comment></data>
<data name="Archive.Retag.Add" xml:space="preserve"><value>Add tags</value></data>
<data name="Archive.Retag.Apply" xml:space="preserve"><value>Apply</value></data>
<data name="Archive.Retag.Heading.one" xml:space="preserve"><value>Tags of {0:N0} sequence</value></data>
+2 -1
View File
@@ -442,7 +442,7 @@
<data name="Admin.Reorganize.Column.Folder" xml:space="preserve"><value>Cartella</value></data>
<data name="Admin.Reorganize.Column.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Reorganize.Confirm" xml:space="preserve"><value>Riorganizza</value></data>
<data name="Admin.Reorganize.Confirm.Tip" xml:space="preserve"><value>Metti in coda il job che sposta e rinomina gli originali, verificandoli uno per uno; niente viene sovrascritto o eliminato</value></data>
<data name="Admin.Reorganize.Confirm.Tip" xml:space="preserve"><value>Metti in coda il job che sposta e rinomina gli originali; niente viene sovrascritto o eliminato</value></data>
<data name="Admin.Reorganize.ConfirmFiles.one" xml:space="preserve"><value>{0} foto riceve un nuovo nome.</value></data>
<data name="Admin.Reorganize.ConfirmFiles.other" xml:space="preserve"><value>{0} foto ricevono un nuovo nome.</value></data>
<data name="Admin.Reorganize.ConfirmFolders.one" xml:space="preserve"><value>Si sposta {0} cartella.</value></data>
@@ -466,6 +466,7 @@
<data name="Admin.Reorganize.Offer.Tip" xml:space="preserve"><value>Applica i nuovi modelli alle sequenze già nell'archivio; un'anteprima mostra prima ogni modifica</value></data>
<data name="Admin.Reorganize.OpenJob" xml:space="preserve"><value>Apri job</value></data>
<data name="Admin.Reorganize.OpenJob.Tip" xml:space="preserve"><value>Mostra il job e il suo log nella pagina Job</value></data>
<data name="Admin.Reorganize.PlanChanged" xml:space="preserve"><value>L'archivio è cambiato durante la conferma; controlla la nuova anteprima e applica di nuovo.</value></data>
<data name="Admin.Reorganize.Planning" xml:space="preserve"><value>Pianificazione…</value></data>
<data name="Admin.Reorganize.Preview" xml:space="preserve"><value>Anteprima</value></data>
<data name="Admin.Reorganize.Preview.Tip" xml:space="preserve"><value>Cosa diventa ogni sequenza, nell'ordine in cui si applicano le modifiche; ancora non è cambiato niente</value></data>
+1
View File
@@ -234,6 +234,7 @@
<data name="Archive.Reorganize.Renamed.other" xml:space="preserve"><value>{0:N0} file rinominati</value></data>
<data name="Archive.Reorganize.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Archive.Reorganize.Titles" xml:space="preserve"><value>Titoli</value></data>
<data name="Archive.Reorganize.Waiting" xml:space="preserve"><value>Riorganizza si apre quando si chiude la finestra aperta</value></data>
<data name="Archive.Retag.Add" xml:space="preserve"><value>Aggiungi tag</value></data>
<data name="Archive.Retag.Apply" xml:space="preserve"><value>Applica</value></data>
<data name="Archive.Retag.Heading.one" xml:space="preserve"><value>Tag di {0:N0} sequenza</value></data>
@@ -98,7 +98,7 @@ public sealed class ReorganizeDialogViewModel : ArchiveDialogViewModel
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
ReorganizeTemplate Template(ReorganizeParts part, string text, string toolTip) =>
new(part, text, enabled.HasFlag(part), toolTip, OnTyped, () => _ = PlanAsync(), () => _ = PlanAsync());
new(part, text, enabled.HasFlag(part), toolTip, OnTyped, () => _ = PlanAsync(), OnCommitted);
}
public ReorganizeTemplate Folders { get; }
@@ -182,6 +182,23 @@ public sealed class ReorganizeDialogViewModel : ArchiveDialogViewModel
_delay.Start();
}
/// <summary>
/// Enter, or the focus leaving a field, plans at once, unless the dry run on screen or the one under way is already of
/// these templates: a click on Apply takes the focus from the field first, and an identical dry run started then
/// would turn Apply off under the click.
/// </summary>
private void OnCommitted()
{
if (IsPlanned()) _delay.Stop();
else _ = PlanAsync();
}
/// <summary>The templates on screen have their plan, or a dry run of them is under way; false after a failed one.</summary>
private bool IsPlanned()
{
lock (_gate) return _run.For is { } templates && templates == Current() && (_run.Plan is not null || _planning is not null);
}
private async Task DryRunAsync()
{
var templates = Current();
+29 -17
View File
@@ -112,33 +112,45 @@ public static class ReorganizePlans
}
/// <summary>
/// What Settings › Archive offers to reorganize after its templates changed (owner review 2, R7): the archive and every
/// template changed since the offer was last taken. A change while the toast is still up joins the offer on screen
/// instead of raising another toast; a change in another archive raises its own.
/// What Settings › Archive offers to reorganize after its templates changed (owner review 2, R7): per archive, every
/// template changed since its offer was last taken. A change while that archive's toast is still up joins the offer on
/// screen instead of raising another toast; a change in another archive raises its own, and each toast takes only its
/// archive's offer.
/// </summary>
/// <param name="toastTime">How long a toast stays up.</param>
public sealed class ReorganizeOffer(TimeSpan toastTime)
{
private (Core.Model.Archive Archive, ReorganizeParts Parts)? _pending;
private DateTime _raised;
private readonly Dictionary<Guid, Pending> _pending = [];
/// <summary>Records that <paramref name="part"/> of <paramref name="archive"/> changed at <paramref name="now"/>; true when a toast should offer it.</summary>
/// <summary>
/// Records that <paramref name="part"/> of <paramref name="archive"/> changed at <paramref name="now"/>; true when a
/// toast should offer it (none of that archive is up), raised at <paramref name="now"/>.
/// </summary>
public bool Add(Core.Model.Archive archive, ReorganizeParts part, DateTime now)
{
ArgumentNullException.ThrowIfNull(archive);
var same = _pending is { } pending && pending.Archive.Id == archive.Id;
_pending = same ? (archive, _pending!.Value.Parts | part) : (archive, part);
if (same && now - _raised < toastTime) return false;
_raised = now;
return true;
var known = _pending.TryGetValue(archive.Id, out var pending);
var shown = known && pending!.Raised is { } raised && now - raised < toastTime;
_pending[archive.Id] = new Pending(archive, (known ? pending!.Parts : ReorganizeParts.None) | part, shown ? pending!.Raised : now);
return !shown;
}
/// <summary>The offer when a toast's action runs: the archive as it was last saved and every template changed; null when taken already.</summary>
public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take()
/// <summary>
/// The toast of <paramref name="archiveId"/> raised at <paramref name="raised"/> left the screen (dismissed, timed out,
/// pushed out by newer ones): the next change raises a new one. A toast older than the one up now changes nothing.
/// </summary>
public void Closed(Guid archiveId, DateTime raised)
{
var pending = _pending;
_pending = null;
_raised = default;
return pending;
if (_pending.TryGetValue(archiveId, out var pending) && pending.Raised == raised) _pending[archiveId] = pending with { Raised = null };
}
/// <summary>
/// The offer of <paramref name="archiveId"/> when its toast's action runs: the archive as it was last saved and every
/// template changed; null when taken already. Other archives' offers stay.
/// </summary>
public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take(Guid archiveId) =>
_pending.Remove(archiveId, out var pending) ? (pending.Archive, pending.Parts) : null;
/// <param name="Raised">When the toast on screen was raised; null once it left.</param>
private sealed record Pending(Core.Model.Archive Archive, ReorganizeParts Parts, DateTime? Raised);
}
+27 -2
View File
@@ -61,6 +61,10 @@ public sealed class ArchiveViewModel : SectionViewModel
private bool _jobEvents;
private string _lastScanText = string.Empty;
private ArchiveDialogViewModel? _dialog;
/// <summary>A Reorganize the Settings toast asked for while a dialog was open: it opens once that one closes.</summary>
private (Core.Model.Archive Archive, ReorganizeParts Parts)? _waitingReorganize;
private IReadOnlyList<ArchiveTile> _tiles = [];
private IReadOnlyList<ChartRow> _months = [];
private IReadOnlyList<ChartItem> _storage = [];
@@ -516,6 +520,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_reloadDelay.Stop();
_search?.Cancel();
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
_waitingReorganize = null;
_dialog?.Dispose();
base.Dispose();
}
@@ -772,11 +777,19 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>
/// Opens Reorganize on every sequence of <paramref name="archive"/> (Settings › Archive offers it after its templates
/// changed), with <paramref name="parts"/> switched on; the screen shows that archive.
/// changed), with <paramref name="parts"/> switched on; the screen shows that archive. The toast is reached from
/// another screen, so a dialog may be open here, a Delete moving sequences say: it is never replaced nor its archive
/// switched under it; Reorganize waits, says so, and opens once that dialog closes.
/// </summary>
public async Task OpenReorganizeAllAsync(Core.Model.Archive archive, ReorganizeParts parts)
{
ArgumentNullException.ThrowIfNull(archive);
if (_dialog is not null)
{
_waitingReorganize = _waitingReorganize is { } waiting && waiting.Archive.Id == archive.Id ? (archive, waiting.Parts | parts) : (archive, parts);
Shell.Notify(Loc.L("Archive.Reorganize.Waiting"));
return;
}
if (Services.Archives is not { } archives || Services.Engine is not { } engine) return;
if (_archive != archive) SelectedArchive = archive;
var dialog = new ReorganizeDialogViewModel(archives, archive, null, parts, r => EnqueueAsync(engine, r), CloseDialog);
@@ -784,6 +797,14 @@ public sealed class ArchiveViewModel : SectionViewModel
await dialog.PlanAsync();
}
/// <summary>The Reorganize that waited for the dialog that just closed, with the archive's templates as they are now.</summary>
private async Task OpenWaitingReorganizeAsync()
{
if (_waitingReorganize is not { } waiting) return;
_waitingReorganize = null;
await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
}
/// <summary>The archive's record as the index holds it now; <paramref name="archive"/> when it cannot be read.</summary>
private async Task<Core.Model.Archive> FreshAsync(Core.Model.Archive archive)
{
@@ -853,12 +874,16 @@ public sealed class ArchiveViewModel : SectionViewModel
await Shell.Library.RefreshAsync();
}
/// <summary>Closes <paramref name="dialog"/> if it is still the open one (an apply that finishes late closes nothing else).</summary>
/// <summary>
/// Closes <paramref name="dialog"/> if it is still the open one (an apply that finishes late closes nothing else); a
/// Reorganize asked for meanwhile opens then.
/// </summary>
private void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
_ = OpenWaitingReorganizeAsync();
}
private async Task AdoptAsync()
+16 -6
View File
@@ -1074,15 +1074,25 @@ public sealed class SettingsViewModel : SectionViewModel
Log.Warning("settings", "The sequences of the archive were not counted", ex);
return;
}
if (!_reorganize.Add(archive, part, DateTime.UtcNow)) return;
Shell.Notify(Loc.L("Settings.Archive.TemplatesSaved"), Loc.L("Settings.Archive.ExistingKept"), Loc.L("Settings.Archive.Reorganize"),
Loc.L("Tooltips.Settings.Reorganize"), () =>
var raised = DateTime.UtcNow;
if (!_reorganize.Add(archive, part, raised)) return;
var toast = new Toast
{
Title = Loc.L("Settings.Archive.TemplatesSaved"),
Message = Loc.L("Settings.Archive.ExistingKept"),
ActionText = Loc.L("Settings.Archive.Reorganize"),
ActionToolTip = Loc.L("Tooltips.Settings.Reorganize"),
ActionCommand = new RelayCommand(() =>
{
// Every template changed since; what this toast offered when another one was used since.
var (target, parts) = _reorganize.Take() ?? (archive, part);
// Every template of this archive changed since; what this toast offered when another toast of it took them.
var (target, parts) = _reorganize.Take(archive.Id) ?? (archive, part);
Shell.Navigate(SectionKey.Archive);
_ = Shell.Archive.OpenReorganizeAllAsync(target, parts);
});
}),
};
// Gone from the screen early (dismissed, pushed out), the next change of this archive raises a toast of its own.
toast.Closed += (_, _) => _reorganize.Closed(archive.Id, raised);
Shell.ShowToast(toast);
}
/// <summary>
@@ -425,17 +425,20 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
}
/**
* Reorganize (owner review 2, R7) of the selected sequences: every sequence of the archive after Select all without a
* filter, else their ids, at most a bulk request's thousand (one plan, one job).
* Reorganize (owner review 2, R7) of the selected sequences: their ids, at most a bulk request's thousand (one plan,
* one job). Beyond that, every sequence of the archive, but only while the selection is exactly what Select all
* fetched without a filter and the archive has not grown since: a sequence unticked or added later is never included.
*/
async function reorganize() {
const everything = matching !== null && !isFiltered() && selection.size === matching.length;
if (!everything && selection.size > BULK_LIMIT) {
const ids = [...selection.ids];
const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&
ids.length === matching.length && matching.every((s) => selection.has(s.id));
if (!everything && ids.length > BULK_LIMIT) {
toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true);
return;
}
const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }, names });
await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }, names });
}
async function retag() {
+21 -6
View File
@@ -2,7 +2,7 @@
// to sequences already in the archive, the Library's selection or every sequence. Each change of a template asks the
// server for a dry run (nothing is touched) and the table shows what every sequence becomes, in the order the changes
// apply. Apply confirms that very plan by its fingerprint, and the server runs it as a job (kind "move") that moves and
// renames the originals, verified, never overwriting or deleting one.
// renames the originals, never overwriting or deleting one (only photos whose SHA-256 is known get new names).
import { t, plural, applyStrings } from "./i18n.js";
import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js";
@@ -104,11 +104,14 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
schedule(PLAN_DELAY);
});
}
// Enter in a field plans at once; only the Apply button changes anything.
form.addEventListener("submit", (e) => {
// Enter in a template plans at once (a form of several fields without a submit button never submits on Enter);
// only the Apply button changes anything.
form.addEventListener("keydown", (e) => {
if (e.key !== "Enter" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === "checkbox") return;
e.preventDefault();
if (loaded && !busy) schedule(0);
});
form.addEventListener("submit", (e) => e.preventDefault());
closeButton.addEventListener("click", () => {
if (!busy) dialog.close();
});
@@ -257,7 +260,10 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
const fromTitle = s.fromTitle ?? null;
const toTitle = s.toTitle ?? null;
const name = names.get(s.sequenceId) ?? toTitle ?? fromTitle ?? folderName(s.fromFolder);
const sequence = fromTitle !== toTitle ? change(fromTitle ?? name, toTitle ?? name, "auto")
// Before reads the old state only: an untitled sequence goes by the page's name for it or its folder, never by the
// title it is about to get.
const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);
const sequence = fromTitle !== toTitle ? change(before, toTitle ?? before, "auto")
: `<span class="ellipsis" dir="auto" title="${attr(name)}">${escapeHtml(name)}</span>`;
const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path")
: `<span class="path muted" dir="ltr" title="${attr(t("Admin.Reorganize.SameFolder.Tip"))}">${escapeHtml(s.fromFolder || "/")}</span>`;
@@ -285,7 +291,11 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
closeButton.disabled = busy;
}
/** The confirmation names what moves; the plan sent back is the one the table shows (the fields cannot change meanwhile). */
/**
* The confirmation names what moves; the plan sent back is the one the table showed. The fields cannot change
* meanwhile, but a dry run scheduled before may answer during it: the same plan again (same request and fingerprint)
* is applied all the same; a different one is shown instead, and Apply waits for the user.
*/
async function apply() {
if (applyButton.disabled) return;
const chosen = plan;
@@ -301,7 +311,12 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed || !dialog.open || plan !== chosen) return;
if (!confirmed || !dialog.open) return;
if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {
// A failed dry run already says why; a new plan is on screen to be checked.
if (plan) showError(t("Admin.Reorganize.PlanChanged"));
return;
}
busy = true;
showError("");
drawButtons();
+7 -1
View File
@@ -29,6 +29,11 @@ public sealed class Toast : ObservableObject
/// before they have read why.
/// </summary>
public bool RunsFromNotification { get; init; }
/// <summary>The toast left the screen: dismissed, timed out, pushed out by newer ones or closed by its action.</summary>
public event EventHandler? Closed;
internal void OnClosed() => Closed?.Invoke(this, EventArgs.Empty);
}
/// <summary>
@@ -78,8 +83,9 @@ public class ToastHost : ItemsControl
{
if (_timers.Remove(toast, out var timer)) timer.Stop();
var hadFocus = IsKeyboardFocusWithin;
Toasts.Remove(toast);
var removed = Toasts.Remove(toast);
if (hadFocus && !IsKeyboardFocusWithin && _returnFocus is UIElement { IsVisible: true } previous) previous.Focus();
if (removed) toast.OnClosed();
}
/// <summary>Moves the keyboard to the newest toast's first control; false when no toast is shown.</summary>
@@ -3,7 +3,12 @@ using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.App.Archiving;
using Chronos.App.DesignTime;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Import;
using Chronos.App.Tests.Uploader;
using Chronos.App.Tests.Windows;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
@@ -12,6 +17,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Archiving;
@@ -110,16 +116,73 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(offer.Add(main, ReorganizeParts.Folders, now), "the first change raises the toast");
var saved = main with { FileTemplate = "{date}_{n:000}" };
Assert.False(offer.Add(saved, ReorganizeParts.Files, now.AddSeconds(5)), "a change while it is up joins it");
Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(), "both templates, the archive as saved last");
Assert.Null(offer.Take(), "a second toast of the same offer finds it taken");
Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(main.Id), "both templates, the archive as saved last");
Assert.Null(offer.Take(main.Id), "a second toast of the same offer finds it taken");
Assert.True(offer.Add(main, ReorganizeParts.Folders, now.AddSeconds(6)), "once taken, the next change raises a toast again");
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(7)), "another archive has its own toast");
Assert.Equal((other, ReorganizeParts.Files), offer.Take());
Assert.Equal((other, ReorganizeParts.Files), offer.Take(other.Id));
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(8)));
Assert.True(offer.Add(other, ReorganizeParts.Folders, now.AddSeconds(17)), "the toast is gone: a new one");
// Each toast takes its own archive's offer: the older toast of Main opens Main, not the Other changed since.
Assert.Equal((main, ReorganizeParts.Folders), offer.Take(main.Id));
Assert.Equal((other, ReorganizeParts.Files | ReorganizeParts.Folders), offer.Take(other.Id), "Other's offer stayed for its own toast");
Assert.Null(offer.Take(main.Id));
}
[Test]
public void AToastGoneEarlyLetsTheNextChangeRaiseItsOwn()
{
var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
var offer = new ReorganizeOffer(TimeSpan.FromSeconds(8));
var now = new DateTime(2026, 10, 27, 9, 0, 0, DateTimeKind.Utc);
Assert.True(offer.Add(main, ReorganizeParts.Folders, now));
offer.Closed(main.Id, now);
Assert.True(offer.Add(main, ReorganizeParts.Files, now.AddSeconds(2)), "dismissed after a second: the next change has a toast of its own");
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(3)), "and joins it while it is up");
offer.Closed(main.Id, now);
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(4)), "an older toast leaving changes nothing for the one up");
Assert.Equal((main, ReorganizeParts.Folders | ReorganizeParts.Files | ReorganizeParts.Titles), offer.Take(main.Id),
"the toast up offers every change since the last one taken");
offer.Closed(main.Id, now.AddSeconds(2));
Assert.Null(offer.Take(main.Id), "the toast closing after its action finds nothing to keep");
}
/// <summary>
/// The toasts' host says when a toast leaves the screen, as Settings › Archive needs to know whether its offer is still
/// up: dismissed, pushed out by three newer ones, timed out or closed by its action, once each.
/// </summary>
[Test]
[WindowsOnly]
public void AToastLeavingTheScreenSaysSoOnce() => WpfApplication.Dispatcher.Invoke(() =>
{
var host = new ToastHost();
var closed = new List<string>();
Toast Show(string title)
{
var toast = new Toast { Title = title };
toast.Closed += (_, _) => closed.Add(title);
host.Show(toast);
return toast;
}
var first = Show("first");
var second = Show("second");
host.Dismiss(second);
host.Dismiss(second);
Assert.SequenceEqual(["second"], closed, "dismissed, once");
Show("third");
Show("fourth");
Assert.Empty(closed.Skip(1), "three on screen");
Show("fifth");
Assert.SequenceEqual(["second", "first"], closed, "the oldest pushed out by a fourth");
host.Dismiss(first);
Assert.Count(2, closed, "a toast gone already says nothing");
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
});
[Test]
public async Task SwitchesChooseTheTemplatesAndApplyQueuesExactlyThatPlan()
{
@@ -182,14 +245,24 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.Null(plan.FileTemplate);
Assert.True(dialog.ApplyCommand.CanExecute(null));
// Typing again: Apply waits for the dry run of what is on screen.
// Typing again: Apply waits for the dry run of what is on screen; Enter plans it at once.
dialog.Folders.Field.Text = "{year}/{date} {title}";
Assert.Null(dialog.Plan);
Assert.False(dialog.ApplyCommand.CanExecute(null));
Assert.True(dialog.Folders.Field.Commit());
Assert.Equal(Loc.L("Archive.Reorganize.Planning"), dialog.BusyText, "a template changed since its dry run plans without waiting for the typing to pause");
dialog.Folders.Field.Text = "{year}/{date}";
await dialog.PlanAsync();
plan = Assert.NotNull(dialog.Plan);
// A click on Apply takes the focus from the field first, which commits it: the dry run on screen is of that text
// already, so no other one starts and Apply stays on under the click.
Assert.True(dialog.Folders.Field.IsDirty, "typed, not committed");
Assert.True(dialog.Folders.Field.Commit());
Assert.Same(plan, dialog.Plan);
Assert.Null(dialog.BusyText);
Assert.True(dialog.ApplyCommand.CanExecute(null));
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
@@ -218,6 +291,76 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(Directory.Exists(Path.Combine(archive.RootPath, "2026", "2026-09-28")));
}
/// <summary>
/// The Settings toast's Reorganize… is reached from another screen while the Archive screen may have a dialog open (a
/// Delete moving sequences, the trash): that dialog is neither replaced nor stopped. Reorganize says it waits, and
/// opens once that dialog closes, on every sequence with every part the toasts offered meanwhile.
/// </summary>
[Test]
[WindowsOnly]
public void TheToastsReorganizeWaitsForTheDialogOpenOnTheArchiveScreen()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
await sample.OpenEmptyAsync();
await sample.FillAsync();
var shell = new ShellViewModel(services);
try
{
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
var screen = shell.Archive;
await screen.LoadAsync();
var archive = Assert.NotNull(screen.SelectedArchive);
await screen.OpenTrashAsync();
var trash = Assert.NotNull(screen.Dialog as TrashDialogViewModel);
await screen.OpenReorganizeAllAsync(archive with { FileTemplate = "{date}_{n:0000}" }, ReorganizeParts.Files);
await screen.OpenReorganizeAllAsync(archive, ReorganizeParts.Folders);
Assert.Same(trash, screen.Dialog);
Assert.Equal(Loc.L("Archive.Reorganize.Waiting"), toasts[^1].Title);
trash.CloseCommand.Execute(null);
await UntilAsync(() => screen.Dialog is ReorganizeDialogViewModel);
var reorganize = (ReorganizeDialogViewModel)screen.Dialog!;
await UntilAsync(() => reorganize.BusyText is null);
Assert.Null(reorganize.ErrorText);
Assert.Equal(Loc.L("Archive.Reorganize.HeadingAll", archive.Name), reorganize.Heading);
Assert.True(reorganize.Folders.IsEnabled, "the parts of both toasts");
Assert.True(reorganize.Files.IsEnabled);
Assert.False(reorganize.Titles.IsEnabled);
Assert.Equal(archive.FileTemplate, reorganize.Files.Field.Text, "the archive's templates as the index holds them when it opens");
reorganize.CloseCommand.Execute(null);
Assert.Null(screen.Dialog);
}
finally
{
shell.Dispose();
await services.DisposeAsync();
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
/// <summary>Uploads two photos ten seconds apart into a new sequence filed with the archive's templates; returns its id.</summary>
private async Task<Guid> UploadAsync(ArchiveService archives, Core.Model.Archive archive, string key, DateTime start, int seed)
{
@@ -32,9 +32,12 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains(@"from ""../reorganize.js""", library);
Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library);
Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library);
// The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand).
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }", library);
Assert.Contains("selection.size > BULK_LIMIT", library);
// The selection: its ids up to a thousand (one request); beyond, every sequence only while the selection is exactly
// what Select all fetched without a filter, the archive no larger since; a sequence unticked or added is never in it.
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }", library);
Assert.Contains("const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&", library);
Assert.Contains("ids.length === matching.length && matching.every((s) => selection.has(s.id));", library);
Assert.Contains("if (!everything && ids.length > BULK_LIMIT) {", library);
var archive = await server.Client.GetStringAsync("/admin/pages/archive.js");
Assert.Contains(@"from ""../reorganize.js""", archive);
Assert.Contains("target: { all: true }", archive);
@@ -56,6 +59,16 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog);
Assert.Contains("#/jobs?job=", dialog);
Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler");
// Enter in a template plans at once: a form of three fields and no submit button never submits on Enter.
Assert.Contains(@"form.addEventListener(""keydown"", (e) => {", dialog);
Assert.Contains(@"if (e.key !== ""Enter"" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === ""checkbox"") return;", dialog);
// An untitled sequence that gets a title reads by its old name before, never by the new title twice.
Assert.Contains("const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);", dialog);
Assert.Contains(@"change(before, toTitle ?? before, ""auto"")", dialog);
// A dry run answering during the confirmation: the same plan is applied, a different one is shown and said.
Assert.Contains("if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {", dialog);
Assert.Contains(@"showError(t(""Admin.Reorganize.PlanChanged""))", dialog);
Assert.True(!dialog.Contains("plan !== chosen) return;", StringComparison.Ordinal), "a confirmed apply is dropped when the same plan is answered again");
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
@@ -65,6 +78,10 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
}
Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]);
// The job renames and moves; nothing in it hashes a file again, so nothing says it verifies them.
Assert.False(en["Admin.Reorganize.Confirm.Tip"].Contains("verif", StringComparison.OrdinalIgnoreCase), en["Admin.Reorganize.Confirm.Tip"]);
Assert.False(it["Admin.Reorganize.Confirm.Tip"].Contains("verific", StringComparison.OrdinalIgnoreCase), it["Admin.Reorganize.Confirm.Tip"]);
Assert.False(Regex.IsMatch(dialog, @"^//.*\bverified\b", RegexOptions.Multiline), "the header says the moves are verified");
}
[Test]