Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/+kraefte-keeps-selection.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Kräfte: a change saved anywhere in the Einsatz no longer clears the selected row or takes keyboard focus out of its STATUS box (#294).
91 changes: 82 additions & 9 deletions src/LageBuch.AppLogic/ViewModels/ForcesViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public ForceRow(
_onStrengthEdited = onStrengthEdited;
_onRemoved = onRemoved;
Edits = unit.Edits;
_syncedStrength = StrengthOf(unit);
_zugfuehrerCount = unit.ZugfuehrerCount;
_officerCount = unit.OfficerCount;
_mannschaftCount = unit.MannschaftCount;
Expand All @@ -59,6 +60,72 @@ public ForceRow(
_notes = unit.Notes;
}

// Set while Update() writes the incident's values into the row, so the Status/Notes setters do
// not push what was only just pulled back to the session as a new edit (#294).
private bool _pulling;

// The Stärke the row last read from the incident. The four count fields double as the strength
// editor's input, so Update() overwrites them only when the incident's Stärke actually moved:
// a correction half-typed into the editor survives a change made elsewhere in the Einsatz.
private (int Zugfuehrer, int Officer, int Mannschaft, int Scba) _syncedStrength;

private static (int Zugfuehrer, int Officer, int Mannschaft, int Scba) StrengthOf(Domain.ForceUnit unit) =>
(unit.ZugfuehrerCount, unit.OfficerCount, unit.MannschaftCount, unit.ScbaCount);

/// <summary>
/// Brings a kept row in line with its unit after a change anywhere in the incident (#294),
/// instead of the row being thrown away and rebuilt.
/// </summary>
/// <remarks>
/// <paramref name="unit"/> may be a different instance than the one the row was built from: a
/// joined device rebuilds its whole aggregate from each snapshot. Brigade and Funkrufname are
/// not touched -- no session operation changes them.
/// </remarks>
public void Update(Domain.ForceUnit unit, IReadOnlyList<string> statusOptions)
{
ArgumentNullException.ThrowIfNull(unit);
ArgumentNullException.ThrowIfNull(statusOptions);

// Options first, so a status set elsewhere that the Stammdaten do not list already has an
// entry to select when Status changes. Replaced only when the list really differs: swapping
// a ComboBox's ItemsSource under it is what froze the Atemschutz picker in #408.
var options = StammdatenCatalogue.Including(statusOptions, unit.Status);
if (!options.SequenceEqual(StatusOptions, StringComparer.Ordinal))
{
StatusOptions = options;
OnPropertyChanged(nameof(StatusOptions));
}

_pulling = true;
try
{
Status = unit.Status;
Notes = unit.Notes;
}
finally
{
_pulling = false;
}

var strength = StrengthOf(unit);
if (strength != _syncedStrength)
{
_syncedStrength = strength;
ZugfuehrerCount = strength.Zugfuehrer;
OfficerCount = strength.Officer;
MannschaftCount = strength.Mannschaft;
ScbaCount = strength.Scba;
}

if (!ReferenceEquals(Edits, unit.Edits))
{
Edits = unit.Edits;
OnPropertyChanged(nameof(Edits));
OnPropertyChanged(nameof(HasHistory));
OnPropertyChanged(nameof(EditLines));
}
}

public Guid Id { get; }

public string Brigade { get; }
Expand All @@ -68,7 +135,7 @@ public ForceRow(
public bool IsReadOnly { get; }

/// <summary>Wert-Historie der Stärke (#76), für die Verlauf-Anzeige.</summary>
public IReadOnlyList<Domain.ForceUnitStrengthEdit> Edits { get; }
public IReadOnlyList<Domain.ForceUnitStrengthEdit> Edits { get; private set; }

/// <summary>The Verlauf affordance only makes sense once something was corrected.</summary>
public bool HasHistory => Edits.Count > 0;
Expand Down Expand Up @@ -118,7 +185,7 @@ public ForceRow(
/// the row, and reaching back up to the ForcesViewModel from inside it is a brittle
/// $parent expression for no gain.
/// </summary>
public IReadOnlyList<string> StatusOptions { get; }
public IReadOnlyList<string> StatusOptions { get; private set; }

[ObservableProperty]
private string? _status;
Expand All @@ -137,7 +204,7 @@ public ForceRow(
/// </summary>
private void PushStatusNotes()
{
if (IsReadOnly)
if (IsReadOnly || _pulling)
{
return;
}
Expand Down Expand Up @@ -239,14 +306,18 @@ public ForcesViewModel(

public void Dispose() => _session.Changed -= RefreshForces;

// Rebuild from the incident on any change — this device's edit, or (when joined) another's.
// Brings the rows in line with the incident on any change -- this device's edit, or (when
// joined) another's -- by id and in place rather than Clear()+re-add, which dropped the
// selected row and the STATUS combo's focus on every change (#294).
private void RefreshForces()
{
Forces.Clear();
foreach (var f in _session.Incident.Forces)
{
Forces.Add(ToRow(f));
}
RowReconciler.Reconcile(
Forces,
_session.Incident.Forces,
r => r.Id,
f => f.Id,
ToRow,
(row, f) => row.Update(f, StatusOptions));

TotalPersonnel = _session.Incident.TotalPersonnel;
TotalOfficer = _session.Incident.TotalOfficer;
Expand Down Expand Up @@ -610,6 +681,8 @@ private void ShowErrors(bool shown)
OnPropertyChanged(nameof(ErrorSummary));
}

// A kept row keeps the callbacks it was built with. They read only f.Id, f.Brigade and
// f.CallSign, which no session operation changes, so a stale f is harmless here.
private ForceRow ToRow(Domain.ForceUnit f) =>
new(
f,
Expand Down
76 changes: 76 additions & 0 deletions src/LageBuch.AppLogic/ViewModels/RowReconciler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System.Collections.ObjectModel;

namespace LageBuch.AppLogic.ViewModels;

/// <summary>
/// Brings a bound row collection in line with the incident by id instead of Clear()+re-add (#294).
/// <c>Clear()</c> raises a Reset, which makes Avalonia tear down and re-realise every row container
/// and takes the selected row, the scroll offset and keyboard focus with it -- on every change made
/// anywhere in the incident. Here a row whose item is gone is removed, a new item is inserted where
/// it belongs, a row out of place is moved, and every kept row is updated in place.
/// </summary>
internal static class RowReconciler
{
/// <summary>
/// Makes <paramref name="rows"/> mirror <paramref name="items"/>, in order. Never raises a Reset
/// and never replaces a row by index. O(n²) through <c>IndexOf</c>, which costs nothing at the
/// tens of rows an Einsatz holds.
/// </summary>
public static void Reconcile<TRow, TItem>(
ObservableCollection<TRow> rows,
IReadOnlyList<TItem> items,
Func<TRow, Guid> rowId,
Func<TItem, Guid> itemId,
Func<TItem, TRow> create,
Action<TRow, TItem> update)
{
ArgumentNullException.ThrowIfNull(rows);
ArgumentNullException.ThrowIfNull(items);
ArgumentNullException.ThrowIfNull(rowId);
ArgumentNullException.ThrowIfNull(itemId);
ArgumentNullException.ThrowIfNull(create);
ArgumentNullException.ThrowIfNull(update);

var wanted = items.Select(itemId).ToHashSet();
for (var i = rows.Count - 1; i >= 0; i--)
{
if (!wanted.Contains(rowId(rows[i])))
{
rows.RemoveAt(i);
}
}

for (var i = 0; i < items.Count; i++)
{
var item = items[i];
var id = itemId(item);
var at = IndexOf(rows, rowId, id, from: i);
if (at < 0)
{
rows.Insert(i, create(item));
continue;
}

if (at != i)
{
rows.Move(at, i);
}

update(rows[i], item);
}
}

// Rows before 'from' are already placed, so the search starts there.
private static int IndexOf<TRow>(ObservableCollection<TRow> rows, Func<TRow, Guid> rowId, Guid id, int from)
{
for (var i = from; i < rows.Count; i++)
{
if (rowId(rows[i]) == id)
{
return i;
}
}

return -1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using LageBuch.App.Shared.Views;
using LageBuch.AppLogic.ViewModels;
using LageBuch.Domain;
using LageBuch.Domain.Etb;
using LageBuch.Persistence.MasterData;

namespace LageBuch.Acceptance.Tests;

// #294: every change anywhere in the Einsatz rebuilt the Kräfte grid with Clear()+re-add, so the
// selected row lost its highlight (and the STATUS combo its focus) after any save.
public class ForcesSelectionSurvivesChangeTests
{
private static MasterDataSet Md() => MasterDataSet.Empty with
{
UnitStatus = new[] { "Alarmiert", "Im Einsatz" },
};

[AvaloniaFact]
public void The_selected_row_stays_selected_when_the_incident_changes_elsewhere()
{
var session = TestSession.StartNew(
new FakeStore(),
new FixedClock(),
new SessionOperator("Müller", "FFB 12/1"),
"/x.fwincident",
Array.Empty<(string, bool)>(),
Array.Empty<(string, bool)>());
session.AddForceUnit("FFB Wache 1", 9, "FFB 11/1", "Alarmiert", null);
session.AddForceUnit("Emmering", 6, "FFB 12/1", "Alarmiert", null);
var vm = new ForcesViewModel(session, new FixedClock(), Md(), () => { });
var view = new ForcesView { DataContext = vm };
var window = new Window { Content = view, Width = 1200, Height = 600 };
window.Show();
Dispatcher.UIThread.RunJobs();

var grid = Assert.IsType<DataGrid>(view.FindControl<DataGrid>("ForcesGrid"));
var second = vm.Forces[1];
grid.SelectedItem = second;
Dispatcher.UIThread.RunJobs();

session.AddJournalEntry(EtbDirection.Outgoing, "Lagemeldung");
Dispatcher.UIThread.RunJobs();

Assert.Same(second, grid.SelectedItem);

// A status change on the selected row itself is the case the operator actually hit.
second.Status = "Im Einsatz";
Dispatcher.UIThread.RunJobs();

Assert.Same(second, grid.SelectedItem);
Assert.Equal("Im Einsatz", session.Incident.Forces[1].Status);
}
}
Loading
Loading