diff --git a/changelog.d/+kraefte-keeps-selection.fixed.md b/changelog.d/+kraefte-keeps-selection.fixed.md
new file mode 100644
index 00000000..4b693b8d
--- /dev/null
+++ b/changelog.d/+kraefte-keeps-selection.fixed.md
@@ -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).
diff --git a/src/LageBuch.AppLogic/ViewModels/ForcesViewModel.cs b/src/LageBuch.AppLogic/ViewModels/ForcesViewModel.cs
index 4b6697c7..353ae83d 100644
--- a/src/LageBuch.AppLogic/ViewModels/ForcesViewModel.cs
+++ b/src/LageBuch.AppLogic/ViewModels/ForcesViewModel.cs
@@ -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;
@@ -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);
+
+ ///
+ /// 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.
+ ///
+ ///
+ /// 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.
+ ///
+ public void Update(Domain.ForceUnit unit, IReadOnlyList 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; }
@@ -68,7 +135,7 @@ public ForceRow(
public bool IsReadOnly { get; }
/// Wert-Historie der Stärke (#76), für die Verlauf-Anzeige.
- public IReadOnlyList Edits { get; }
+ public IReadOnlyList Edits { get; private set; }
/// The Verlauf affordance only makes sense once something was corrected.
public bool HasHistory => Edits.Count > 0;
@@ -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.
///
- public IReadOnlyList StatusOptions { get; }
+ public IReadOnlyList StatusOptions { get; private set; }
[ObservableProperty]
private string? _status;
@@ -137,7 +204,7 @@ public ForceRow(
///
private void PushStatusNotes()
{
- if (IsReadOnly)
+ if (IsReadOnly || _pulling)
{
return;
}
@@ -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;
@@ -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,
diff --git a/src/LageBuch.AppLogic/ViewModels/RowReconciler.cs b/src/LageBuch.AppLogic/ViewModels/RowReconciler.cs
new file mode 100644
index 00000000..89d3189d
--- /dev/null
+++ b/src/LageBuch.AppLogic/ViewModels/RowReconciler.cs
@@ -0,0 +1,76 @@
+using System.Collections.ObjectModel;
+
+namespace LageBuch.AppLogic.ViewModels;
+
+///
+/// Brings a bound row collection in line with the incident by id instead of Clear()+re-add (#294).
+/// Clear() 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.
+///
+internal static class RowReconciler
+{
+ ///
+ /// Makes mirror , in order. Never raises a Reset
+ /// and never replaces a row by index. O(n²) through IndexOf, which costs nothing at the
+ /// tens of rows an Einsatz holds.
+ ///
+ public static void Reconcile(
+ ObservableCollection rows,
+ IReadOnlyList items,
+ Func rowId,
+ Func itemId,
+ Func create,
+ Action 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(ObservableCollection rows, Func rowId, Guid id, int from)
+ {
+ for (var i = from; i < rows.Count; i++)
+ {
+ if (rowId(rows[i]) == id)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/tests/LageBuch.Acceptance.Tests/ForcesSelectionSurvivesChangeTests.cs b/tests/LageBuch.Acceptance.Tests/ForcesSelectionSurvivesChangeTests.cs
new file mode 100644
index 00000000..46f0e14e
--- /dev/null
+++ b/tests/LageBuch.Acceptance.Tests/ForcesSelectionSurvivesChangeTests.cs
@@ -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(view.FindControl("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);
+ }
+}
diff --git a/tests/LageBuch.AppLogic.Tests/ForcesViewModelTests.cs b/tests/LageBuch.AppLogic.Tests/ForcesViewModelTests.cs
index 4fc3ce61..a11b9c0f 100644
--- a/tests/LageBuch.AppLogic.Tests/ForcesViewModelTests.cs
+++ b/tests/LageBuch.AppLogic.Tests/ForcesViewModelTests.cs
@@ -1,5 +1,7 @@
+using System.Collections.Specialized;
using LageBuch.AppLogic.ViewModels;
using LageBuch.Domain;
+using LageBuch.Domain.Etb;
using LageBuch.Persistence.MasterData;
namespace LageBuch.AppLogic.Tests;
@@ -986,4 +988,155 @@ public void A_row_whose_status_is_configured_gets_the_plain_vocabulary()
Assert.Equal(new[] { "Alarmiert", "Im Einsatz" }, vm.Forces[0].StatusOptions);
}
+
+ // #294: the grid is reconciled by id rather than rebuilt with Clear()+re-add.
+ private static LocalIncidentSession SessionWithTwoUnits()
+ {
+ var session = TestSession.StartNew(
+ new FakeStore(),
+ new FixedClock(T0),
+ new SessionOperator("Müller"),
+ "/x.fwincident",
+ Array.Empty<(string, bool)>(),
+ Array.Empty<(string, bool)>());
+ session.AddForceUnit("FFB Wache 1", 9, "FFB 11/1", "Alarmiert", "erste Meldung");
+ session.AddForceUnit("Emmering", 6, "FFB 12/1", "Alarmiert", null);
+ return session;
+ }
+
+ private static Func CountResets(ForcesViewModel vm)
+ {
+ var resets = 0;
+ vm.Forces.CollectionChanged += (_, e) =>
+ {
+ if (e.Action == NotifyCollectionChangedAction.Reset)
+ {
+ resets++;
+ }
+ };
+ return () => resets;
+ }
+
+ [Fact]
+ public void An_unrelated_change_keeps_the_rows_and_raises_no_reset()
+ {
+ var session = SessionWithTwoUnits();
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => { });
+ var rows = vm.Forces.ToArray();
+ var resets = CountResets(vm);
+
+ session.AddJournalEntry(EtbDirection.Outgoing, "Lagemeldung");
+
+ Assert.Equal(0, resets());
+ Assert.Equal(2, vm.Forces.Count);
+ Assert.Same(rows[0], vm.Forces[0]);
+ Assert.Same(rows[1], vm.Forces[1]);
+ }
+
+ [Fact]
+ public void Adding_and_removing_a_unit_still_shows_up_without_a_reset()
+ {
+ var session = SessionWithTwoUnits();
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => { });
+ var second = vm.Forces[1];
+ var resets = CountResets(vm);
+
+ session.AddForceUnit("Aich", 6, "FFB 13/1", null, null);
+ session.RemoveForceUnit(vm.Forces[0].Id);
+
+ Assert.Equal(0, resets());
+ Assert.Equal(new[] { "FFB 12/1", "FFB 13/1" }, vm.Forces.Select(r => r.CallSign));
+ Assert.Same(second, vm.Forces[0]);
+ }
+
+ [Fact]
+ public void A_status_change_made_elsewhere_updates_the_row_without_writing_back()
+ {
+ var session = SessionWithTwoUnits();
+ var changes = 0;
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => changes++);
+ var row = vm.Forces[0];
+ var sessionChanges = 0;
+ session.Changed += () => sessionChanges++;
+
+ session.UpdateForceUnit(row.Id, "Im Einsatz", "zweite Meldung");
+
+ Assert.Same(row, vm.Forces[0]);
+ Assert.Equal("Im Einsatz", row.Status);
+ Assert.Equal("zweite Meldung", row.Notes);
+
+ // A write-back would be a second mutation, and with it a second Changed and a save.
+ Assert.Equal(1, sessionChanges);
+ Assert.Equal(0, changes);
+ }
+
+ [Fact]
+ public void A_status_change_arriving_in_a_snapshot_updates_the_row_without_writing_back()
+ {
+ // A joined device rebuilds its whole Incident from every broadcast, so the unit the row is
+ // matched to is a new instance each time.
+ var local = SessionWithTwoUnits();
+ var remote = new SnapshotRoundTrippingSession(local);
+ var changes = 0;
+ var vm = new ForcesViewModel(remote, new FixedClock(T0), Md(), () => changes++);
+ var row = vm.Forces[0];
+ var resets = CountResets(vm);
+ var sessionChanges = 0;
+ remote.Changed += () => sessionChanges++;
+
+ local.UpdateForceUnit(row.Id, "Im Einsatz", null);
+
+ Assert.Same(row, vm.Forces[0]);
+ Assert.Equal("Im Einsatz", row.Status);
+ Assert.Equal(0, resets());
+ Assert.Equal(1, sessionChanges);
+ Assert.Equal(0, changes);
+ }
+
+ [Fact]
+ public void A_status_off_the_catalogue_set_elsewhere_becomes_selectable_on_the_kept_row()
+ {
+ var session = SessionWithTwoUnits();
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => { });
+ var row = vm.Forces[0];
+
+ session.UpdateForceUnit(row.Id, "Abgerückt", null);
+
+ Assert.Same(row, vm.Forces[0]);
+ Assert.Equal("Abgerückt", row.Status);
+ Assert.Contains("Abgerückt", row.StatusOptions);
+ }
+
+ [Fact]
+ public void A_half_typed_strength_survives_an_unrelated_change()
+ {
+ var session = SessionWithTwoUnits();
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => { });
+ var row = vm.Forces[0];
+
+ row.MannschaftCount = 12; // typed into the editor, not yet Übernehmen
+
+ session.AddJournalEntry(EtbDirection.Outgoing, "Lagemeldung");
+
+ Assert.Same(row, vm.Forces[0]);
+ Assert.Equal(12, row.MannschaftCount);
+ Assert.Equal(9, session.Incident.Forces[0].PersonnelCount);
+ }
+
+ [Fact]
+ public void A_strength_correction_made_elsewhere_reaches_the_kept_row()
+ {
+ var session = SessionWithTwoUnits();
+ var vm = new ForcesViewModel(session, new FixedClock(T0), Md(), () => { });
+ var row = vm.Forces[0];
+
+ session.UpdateForceStrength(row.Id, officerCount: 1, personnelCount: 8, scbaCount: 2);
+
+ Assert.Same(row, vm.Forces[0]);
+ Assert.Equal(1, row.OfficerCount);
+ Assert.Equal(7, row.MannschaftCount);
+ Assert.Equal(2, row.ScbaCount);
+ Assert.True(row.HasHistory);
+ Assert.Single(row.EditLines);
+ }
}