From ad5b901bbec47f0e28337cec16f5ba0c3a3e2d40 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Mon, 23 Nov 2026 18:28:05 +0100 Subject: [PATCH] Expose coherent DataGrid selection snapshots for view bindings --- fx/docs/data-grid.md | 21 +++ .../java/de/neitzel/fx/view/DataGrid.java | 16 ++ .../de/neitzel/fx/view/DataGridSelection.java | 58 +++++++ .../de/neitzel/fx/view/GridSelection.java | 45 ++++++ .../java/de/neitzel/fx/view/TableResults.java | 11 ++ .../fx/view/ObserveGridSelectionTest.java | 144 ++++++++++++++++++ .../selection/SelectionSummaryController.java | 25 +++ .../fx/view/grid-selection-summary.fxml | 15 ++ 8 files changed, 335 insertions(+) create mode 100644 fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java create mode 100644 fx/src/main/java/de/neitzel/fx/view/GridSelection.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java create mode 100644 fx/src/test/resources/de/neitzel/fx/view/grid-selection-summary.fxml diff --git a/fx/docs/data-grid.md b/fx/docs/data-grid.md index 46fac83..2dd89c9 100644 --- a/fx/docs/data-grid.md +++ b/fx/docs/data-grid.md @@ -36,6 +36,27 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo - A successfully replaced source clears all selection. `confirmedDeleted(key)` removes only that key and refreshes; absence from a page alone does not imply deletion. Collapsed groups retain their keys but expose no actionable elements for hidden rows. - Empty results disable navigation. Unknown totals are displayed as unknown and disable Last. A disappeared page receives one bounded correction; subsequent invalidation becomes an error with Retry. +## Selection in a ViewModel + +Use `grid.observeSelection()` for a single read-only property containing both selected keys and available elements. The initial snapshot reflects the current grid. Each subsequent snapshot captures both lists after selection or row availability changes. Keys follow selection order and elements follow display order. A selected key can remain present while its row is unavailable. An action that needs every selected row can compare the two list sizes in one snapshot before capturing that snapshot for confirmation. + +For example, a ViewModel can derive a label from the adapter. + +```java +var selection = grid.observeSelection(); +var summary = selection.selectionProperty().map(state -> + state.selectedKeys().size() + " selected, " + + state.selectedElements().size() + " visible"); +``` + +Expose the result through a public `ObservableValue summaryProperty()` on the ViewModel and declare the label binding. + +```xml + +``` + +Restore keys explicitly with `selection.selectKeys(savedKeys)` or restore one with `selection.select(key)`. The adapter delegates to the grid and respects its selection mode. The owner closes the adapter on the JavaFX thread when the ViewModel stops observing. Closing detaches the adapter and freezes its last snapshot while the grid and other observers continue to work independently. See the [FXML integration test](../src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java). + ## Guards, warnings and supersession `setEditGuard(query -> CompletionStage)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage)` can replace the default nonblocking Continue/Cancel alert. Neither dialog handling nor guard completion runs inside a source transaction. Superseded answers cannot publish or restart old requests. diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java index c9ac51c..38aa664 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java +++ b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java @@ -94,6 +94,8 @@ public final class DataGrid extends VBox implements AutoCloseable { } private final DataGridDeclaration declaration = new DataGridDeclaration<>(this); + private final ReadOnlyObjectWrapper> selection = + new ReadOnlyObjectWrapper<>(GridSelection.empty()); private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper selectedElement = new ReadOnlyObjectWrapper<>(); private final ReadOnlyListWrapper selectedKeys = new ReadOnlyListWrapper<>( @@ -292,6 +294,7 @@ public final class DataGrid extends VBox implements AutoCloseable { renderer.enableColumnSeparators(); selectedKey.bind(renderer.selectedKeyProperty()); selectedElement.bind(renderer.selectedElementProperty()); + selection.bind(renderer.selectionProperty()); coordinator = new GridCoordinator<>( source, Platform::runLater, this::changed, result -> publishRows(result)); @@ -395,6 +398,18 @@ public final class DataGrid extends VBox implements AutoCloseable { public ReadOnlyListProperty selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); } + /** + * Observes selection as one snapshot from the current state, including before the first load. + * The caller owns the adapter and closes it when the observing ViewModel stops using it. + * + * @return an independently closeable selection adapter for this grid + */ + public DataGridSelection observeSelection() { + requireFx(); + if (closed) throw new IllegalStateException("Grid is closed"); + return new DataGridSelection<>(this, selection.getReadOnlyProperty()); + } + public void selectKeys(Collection keys) { check(); renderer.selectKeys(keys); @@ -1339,6 +1354,7 @@ public final class DataGrid extends VBox implements AutoCloseable { if (renderer != null) renderer.close(); selectedKey.unbind(); selectedElement.unbind(); + selection.unbind(); selectedKeys.unbind(); selectedElements.unbind(); selectedKeys.set(FXCollections.emptyObservableList()); diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java b/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java new file mode 100644 index 0000000..c1ce825 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java @@ -0,0 +1,58 @@ +package de.neitzel.fx.view; + +import java.util.Collection; +import javafx.application.Platform; +import javafx.beans.property.ReadOnlyObjectProperty; +import javafx.beans.property.ReadOnlyObjectWrapper; + +/** + * An observable selection for a ViewModel to read, with explicit methods for selection changes. + * Create it through {@link DataGrid#observeSelection()} and use it on the JavaFX application thread. + * Closing the adapter detaches it without changing the grid's selection or closing the grid. + * + * @param row key type + * @param row model type + */ +public final class DataGridSelection implements AutoCloseable { + private final ReadOnlyObjectWrapper> selection = new ReadOnlyObjectWrapper<>(); + private DataGrid grid; + + DataGridSelection(DataGrid grid, ReadOnlyObjectProperty> source) { + this.grid = grid; + selection.bind(source); + } + + /** Returns one read-only observable containing the selected keys and available elements. */ + public ReadOnlyObjectProperty> selectionProperty() { + return selection.getReadOnlyProperty(); + } + + /** Returns the current snapshot, or the last snapshot when the adapter is closed. */ + public GridSelection getSelection() { + return selection.get(); + } + + /** Replaces the selection with one key, or clears it for a null key. */ + public void select(K key) { + requireOpen().select(key); + } + + /** Restores the selection by key, respecting the grid's current selection mode. */ + public void selectKeys(Collection keys) { + requireOpen().selectKeys(keys); + } + + private DataGrid requireOpen() { + if (grid == null) throw new IllegalStateException("Selection adapter is closed"); + return grid; + } + + /** Detaches the adapter and preserves its last published snapshot. */ + @Override + public void close() { + if (!Platform.isFxApplicationThread()) + throw new IllegalStateException("Use the JavaFX application thread"); + selection.unbind(); + grid = null; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/GridSelection.java b/fx/src/main/java/de/neitzel/fx/view/GridSelection.java new file mode 100644 index 0000000..8934556 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/GridSelection.java @@ -0,0 +1,45 @@ +package de.neitzel.fx.view; + +import java.util.List; +import java.util.Objects; + +/** + * One published selection of a grid. Keys retain their selection order and can include keys outside + * the current page. Elements follow the grid's display order and contain only available selected + * rows. The lead element is null when the lead key has no available row. + * + * @param selectedKeys selected keys, including retained off-page keys + * @param selectedElements selected models of visible and interactive rows + * @param leadKey lead key, or null for an empty selection + * @param leadElement lead model, or null when unavailable + * @param row key type + * @param row model type + */ +public record GridSelection( + List selectedKeys, List selectedElements, K leadKey, T leadElement) { + + /** Copies both lists so a published selection remains stable as the grid changes. */ + public GridSelection { + selectedKeys = List.copyOf(selectedKeys); + selectedElements = List.copyOf(selectedElements); + } + + static GridSelection empty() { + return new GridSelection<>(List.of(), List.of(), null, null); + } + + /** A refreshed row can replace an equal model with a different instance. */ + boolean sameSelection(GridSelection previous) { + if (!selectedKeys.equals(previous.selectedKeys) || !Objects.equals(leadKey, previous.leadKey) + || leadElement != previous.leadElement + || selectedElements.size() != previous.selectedElements.size()) { + return false; + } + for (int index = 0; index < selectedElements.size(); index++) { + if (selectedElements.get(index) != previous.selectedElements.get(index)) { + return false; + } + } + return true; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/TableResults.java b/fx/src/main/java/de/neitzel/fx/view/TableResults.java index ff8646f..50b5853 100644 --- a/fx/src/main/java/de/neitzel/fx/view/TableResults.java +++ b/fx/src/main/java/de/neitzel/fx/view/TableResults.java @@ -41,6 +41,8 @@ public final class TableResults implements AutoCloseable { private List order; private final Set hiddenColumns = new HashSet<>(); private List> entries = List.of(); + private final ReadOnlyObjectWrapper> selection = + new ReadOnlyObjectWrapper<>(GridSelection.empty()); private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper selectedElement = new ReadOnlyObjectWrapper<>(); private final ObservableList selectedKeys = FXCollections.observableArrayList(); @@ -131,6 +133,10 @@ public final class TableResults implements AutoCloseable { /** Only selected models currently visible and interactive are actionable. */ public ReadOnlyListProperty selectedElementsProperty() { return elementsView.getReadOnlyProperty(); } + ReadOnlyObjectProperty> selectionProperty() { + return selection.getReadOnlyProperty(); + } + public RowSelectionMode getSelectionMode() { return selectionMode; } public void setSelectionMode(RowSelectionMode mode) { @@ -623,6 +629,10 @@ public final class TableResults implements AutoCloseable { } selectedElement.set(rowsInteractive ? loaded : null); selectedElements.setAll(actionable); + + GridSelection snapshot = new GridSelection<>( + selectedKeys, selectedElements, selectedKey.get(), selectedElement.get()); + if (!snapshot.sameSelection(selection.get())) selection.set(snapshot); } public void setOnLayoutCommitted(Runnable handler) { @@ -980,6 +990,7 @@ public final class TableResults implements AutoCloseable { selectedElement.set(null); selectedKeys.clear(); selectedElements.clear(); + selection.set(GridSelection.empty()); anchor = null; captured = GroupProjection.capture(List.of(), List.of()); groupTree = List.of(); diff --git a/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java b/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java new file mode 100644 index 0000000..ef94a00 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java @@ -0,0 +1,144 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.view.DataGridTest.Item; +import de.neitzel.grid.TextFilter; +import de.neitzel.injection.ApplicationContext; +import javafx.scene.control.Label; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ObserveGridSelectionTest { + + @BeforeAll + static void startJavaFx() throws Exception { + FxThread.start(); + } + + @Test + void publishesOneCoherentChangeToTheViewAndStopsAfterClose() throws Exception { + var first = new Item(1, "Alpha"); + var second = new Item(2, "Beta"); + var grid = new AtomicReference>(); + FxThread.onFx(() -> { + grid.set(DataGridTest.grid(List.of(first, second), new AtomicInteger())); + grid.get().refresh(); + }); + try { + DataGridTest.drain(); + FxThread.onFx(() -> { + var control = grid.get(); + control.select(1L); + var document = getClass().getResource("grid-selection-summary.fxml"); + var context = new ApplicationContext("de.neitzel.fx.view.selection"); + try (var selection = control.observeSelection(); + var models = new ViewModelContext(); + var view = ViewLoader.load(document, selection, context, models)) { + var initial = selection.getSelection(); + var summary = (Label) view.getRoot().lookup("#summary"); + assertEquals(List.of(1L), initial.selectedKeys()); + assertEquals(List.of(first), initial.selectedElements()); + assertEquals("[1] · 1 visible", summary.getText()); + assertThrows(UnsupportedOperationException.class, () -> initial.selectedKeys().clear()); + assertThrows(UnsupportedOperationException.class, () -> initial.selectedElements().clear()); + + var changes = new ArrayList>(); + selection.selectionProperty().addListener((observable, before, after) -> { + changes.add(after); + selection.selectKeys(after.selectedKeys()); + }); + + var liveKeys = control.selectedKeysProperty().get(); + selection.select(2L); + assertSame(liveKeys, control.selectedKeysProperty().get()); + assertEquals(List.of(new GridSelection<>(List.of(2L), List.of(second), 2L, second)), changes); + assertEquals("[2] · 1 visible", summary.getText()); + assertEquals(List.of(first), initial.selectedElements()); + + selection.close(); + selection.close(); + control.select(1L); + assertEquals("[2] · 1 visible", summary.getText()); + assertEquals(1, changes.size()); + assertEquals(List.of(1L), control.selectedKeysProperty()); + assertThrows(IllegalStateException.class, () -> selection.select(2L)); + } + }); + } finally { + FxThread.onFx(() -> grid.get().close()); + } + } + + @Test + void keepsUnloadedKeysThroughPagingFiltersDeletionAndRestoration() throws Exception { + var first = new Item(1, "Alpha"); + var second = new Item(2, "Beta"); + var items = new ArrayList<>(List.of(first, second)); + var grid = new AtomicReference>(); + var selected = new AtomicReference>(); + FxThread.onFx(() -> { + var control = DataGridTest.grid(items, new AtomicInteger()); + grid.set(control); + control.setSelectionMode(RowSelectionMode.MULTIPLE); + selected.set(control.observeSelection()); + assertEquals(GridSelection.empty(), selected.get().getSelection()); + control.setPageSize(1); + }); + try { + DataGridTest.drain(); + FxThread.onFx(() -> { + var adapter = selected.get(); + adapter.selectKeys(List.of(1L, 2L)); + var current = adapter.getSelection(); + assertEquals(List.of(1L, 2L), current.selectedKeys()); + assertEquals(List.of(first), current.selectedElements()); + assertEquals(2L, current.leadKey()); + assertNull(current.leadElement()); + grid.get().next(); + assertEquals(List.of(), adapter.getSelection().selectedElements()); + }); + DataGridTest.drain(); + FxThread.onFx(() -> { + var current = selected.get().getSelection(); + assertEquals(List.of(1L, 2L), current.selectedKeys()); + assertEquals(List.of(second), current.selectedElements()); + assertSame(second, current.leadElement()); + grid.get().setFilters(List.of(new TextFilter("text", TextFilter.Operator.EQUALS, "Alpha", false))); + }); + DataGridTest.drain(); + FxThread.onFx(() -> { + assertEquals(List.of(1L, 2L), selected.get().getSelection().selectedKeys()); + assertEquals(List.of(first), selected.get().getSelection().selectedElements()); + items.remove(first); + grid.get().confirmedDeleted(1L); + assertEquals(List.of(2L), selected.get().getSelection().selectedKeys()); + grid.get().setFilters(List.of()); + }); + DataGridTest.drain(); + FxThread.onFx(() -> { + var adapter = selected.get(); + assertEquals(List.of(second), adapter.getSelection().selectedElements()); + adapter.select(null); + assertEquals(GridSelection.empty(), adapter.getSelection()); + adapter.selectKeys(List.of(2L)); + assertSame(second, adapter.getSelection().leadElement()); + grid.get().close(); + assertEquals(GridSelection.empty(), adapter.getSelection()); + }); + } finally { + FxThread.onFx(() -> { + selected.get().close(); + grid.get().close(); + }); + } + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java b/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java new file mode 100644 index 0000000..b1a39c9 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java @@ -0,0 +1,25 @@ +package de.neitzel.fx.view.selection; + +import de.neitzel.fx.view.DataGridSelection; +import de.neitzel.fx.view.ViewModelClass; +import jakarta.inject.Singleton; +import javafx.beans.value.ObservableValue; + +/** Supplies a read-only summary of the selected keys and available rows. */ +@Singleton +@ViewModelClass(SelectionSummaryController.Summary.class) +public class SelectionSummaryController { + + public static class Summary { + private final ObservableValue summary; + + public Summary(DataGridSelection selection) { + summary = selection.selectionProperty().map(state -> + state.selectedKeys() + " · " + state.selectedElements().size() + " visible"); + } + + public ObservableValue summaryProperty() { + return summary; + } + } +} diff --git a/fx/src/test/resources/de/neitzel/fx/view/grid-selection-summary.fxml b/fx/src/test/resources/de/neitzel/fx/view/grid-selection-summary.fxml new file mode 100644 index 0000000..8b91b8f --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/grid-selection-summary.fxml @@ -0,0 +1,15 @@ + + + + + + + + + + + + +