Expose coherent DataGrid selection snapshots for view bindings

This commit is contained in:
2026-11-23 18:28:05 +01:00
parent 1ff9753de8
commit ad5b901bbe
8 changed files with 335 additions and 0 deletions
+21
View File
@@ -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. - 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. - 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<String> summaryProperty()` on the ViewModel and declare the label binding.
```xml
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
```
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 ## Guards, warnings and supersession
`setEditGuard(query -> CompletionStage<Boolean>)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage<Boolean>)` 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. `setEditGuard(query -> CompletionStage<Boolean>)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage<Boolean>)` 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.
@@ -94,6 +94,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
} }
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this); private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>( private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
@@ -292,6 +294,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
renderer.enableColumnSeparators(); renderer.enableColumnSeparators();
selectedKey.bind(renderer.selectedKeyProperty()); selectedKey.bind(renderer.selectedKeyProperty());
selectedElement.bind(renderer.selectedElementProperty()); selectedElement.bind(renderer.selectedElementProperty());
selection.bind(renderer.selectionProperty());
coordinator = coordinator =
new GridCoordinator<>( new GridCoordinator<>(
source, Platform::runLater, this::changed, result -> publishRows(result)); source, Platform::runLater, this::changed, result -> publishRows(result));
@@ -395,6 +398,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
public ReadOnlyListProperty<T> selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); } public ReadOnlyListProperty<T> 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<K, T> observeSelection() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
return new DataGridSelection<>(this, selection.getReadOnlyProperty());
}
public void selectKeys(Collection<? extends K> keys) { public void selectKeys(Collection<? extends K> keys) {
check(); check();
renderer.selectKeys(keys); renderer.selectKeys(keys);
@@ -1339,6 +1354,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
if (renderer != null) renderer.close(); if (renderer != null) renderer.close();
selectedKey.unbind(); selectedKey.unbind();
selectedElement.unbind(); selectedElement.unbind();
selection.unbind();
selectedKeys.unbind(); selectedKeys.unbind();
selectedElements.unbind(); selectedElements.unbind();
selectedKeys.set(FXCollections.emptyObservableList()); selectedKeys.set(FXCollections.emptyObservableList());
@@ -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 <K> row key type
* @param <T> row model type
*/
public final class DataGridSelection<K, T> implements AutoCloseable {
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection = new ReadOnlyObjectWrapper<>();
private DataGrid<K, T> grid;
DataGridSelection(DataGrid<K, T> grid, ReadOnlyObjectProperty<GridSelection<K, T>> source) {
this.grid = grid;
selection.bind(source);
}
/** Returns one read-only observable containing the selected keys and available elements. */
public ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
/** Returns the current snapshot, or the last snapshot when the adapter is closed. */
public GridSelection<K, T> 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<? extends K> keys) {
requireOpen().selectKeys(keys);
}
private DataGrid<K, T> 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;
}
}
@@ -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 <K> row key type
* @param <T> row model type
*/
public record GridSelection<K, T>(
List<K> selectedKeys, List<T> 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 <K, T> GridSelection<K, T> 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<K, T> 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;
}
}
@@ -41,6 +41,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<String> order; private List<String> order;
private final Set<String> hiddenColumns = new HashSet<>(); private final Set<String> hiddenColumns = new HashSet<>();
private List<Entry<K, T>> entries = List.of(); private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList(); private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
@@ -131,6 +133,10 @@ public final class TableResults<K, T> implements AutoCloseable {
/** Only selected models currently visible and interactive are actionable. */ /** Only selected models currently visible and interactive are actionable. */
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); } public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
public RowSelectionMode getSelectionMode() { return selectionMode; } public RowSelectionMode getSelectionMode() { return selectionMode; }
public void setSelectionMode(RowSelectionMode mode) { public void setSelectionMode(RowSelectionMode mode) {
@@ -623,6 +629,10 @@ public final class TableResults<K, T> implements AutoCloseable {
} }
selectedElement.set(rowsInteractive ? loaded : null); selectedElement.set(rowsInteractive ? loaded : null);
selectedElements.setAll(actionable); selectedElements.setAll(actionable);
GridSelection<K, T> snapshot = new GridSelection<>(
selectedKeys, selectedElements, selectedKey.get(), selectedElement.get());
if (!snapshot.sameSelection(selection.get())) selection.set(snapshot);
} }
public void setOnLayoutCommitted(Runnable handler) { public void setOnLayoutCommitted(Runnable handler) {
@@ -980,6 +990,7 @@ public final class TableResults<K, T> implements AutoCloseable {
selectedElement.set(null); selectedElement.set(null);
selectedKeys.clear(); selectedKeys.clear();
selectedElements.clear(); selectedElements.clear();
selection.set(GridSelection.empty());
anchor = null; anchor = null;
captured = GroupProjection.capture(List.of(), List.of()); captured = GroupProjection.capture(List.of(), List.of());
groupTree = List.of(); groupTree = List.of();
@@ -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<DataGrid<Long, Item>>();
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<GridSelection<Long, Item>>();
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<DataGrid<Long, Item>>();
var selected = new AtomicReference<DataGridSelection<Long, Item>>();
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();
});
}
}
}
@@ -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<String> summary;
public Summary(DataGridSelection<?, ?> selection) {
summary = selection.selectionProperty().map(state ->
state.selectedKeys() + " · " + state.selectedElements().size() + " visible");
}
public ObservableValue<String> summaryProperty() {
return summary;
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1"
fx:controller="de.neitzel.fx.view.selection.SelectionSummaryController">
<fx:define>
<BindingList>
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="summary"/>
</VBox>