Release NeitzelLib 1.0.1 with declarative DataGrid controls and saved setups

This commit is contained in:
2026-11-18 08:31:03 +01:00
parent 91d9cdccaa
commit 257e0edb28
66 changed files with 6378 additions and 273 deletions
@@ -18,10 +18,13 @@ public final class IntegerSpinners {
* @return an editable spinner
*/
public static Spinner<Integer> nonNegative(int min, int max, int value) {
return new NonNegativeIntegerSpinner(min, max, value);
}
static void configure(Spinner<Integer> spinner, int min, int max, int value) {
if (min < 0 || max < min || value < min || value > max) {
throw new IllegalArgumentException("Invalid nonnegative spinner bounds or value");
}
Spinner<Integer> spinner = new Spinner<>(min, max, value);
spinner.setEditable(true);
spinner.getEditor().setTextFormatter(new TextFormatter<String>(change -> {
String text = change.getControlNewText();
@@ -46,6 +49,5 @@ public final class IntegerSpinners {
spinner.getEditor().setText(spinner.getValue().toString());
}
});
return spinner;
}
}
@@ -0,0 +1,29 @@
package de.neitzel.fx.control;
import javafx.beans.NamedArg;
import javafx.beans.property.ObjectProperty;
import javafx.scene.control.Spinner;
/** Bounded integer input available directly in FXML, including immediate valid typing. */
public final class NonNegativeIntegerSpinner extends Spinner<Integer> {
public NonNegativeIntegerSpinner(
@NamedArg(value = "minimum", defaultValue = "0") int minimum,
@NamedArg(value = "maximum", defaultValue = "2147483647") int maximum,
@NamedArg(value = "initialValue", defaultValue = "0") int initialValue) {
super(minimum, maximum, initialValue);
IntegerSpinners.configure(this, minimum, maximum, initialValue);
}
/** Writable property for DirectBinding; Spinner.valueProperty itself is read-only. */
public ObjectProperty<Integer> numberProperty() {
return getValueFactory().valueProperty();
}
public Integer getNumber() {
return numberProperty().get();
}
public void setNumber(Integer value) {
numberProperty().set(value);
}
}
+647 -63
View File
@@ -4,9 +4,12 @@ import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.DefaultProperty;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.shape.SVGPath;
import java.util.*;
import java.util.concurrent.*;
@@ -18,22 +21,23 @@ import java.util.function.*;
* load. The application owns the source and executor. Closing releases only this grid's requests
* and rows.
*/
@DefaultProperty("columns")
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final Table table = new Table();
private final TableResults<K, T> renderer;
private final GridCoordinator<K, T> coordinator;
private TableResults<K, T> renderer;
private GridCoordinator<K, T> coordinator;
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
new ReadOnlyObjectWrapper<>();
private final Label status = new Label("Not loaded");
private final Button first = new Button("First"),
previous = new Button("Previous"),
next = new Button("Next"),
last = new Button("Last"),
private final Button first = pagingButton("First page", "M0 0 H2 V14 H0 Z M4 7 L16 0 V14 Z"),
previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"),
next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"),
last = pagingButton("Last page", "M0 0 L12 7 L0 14 Z M14 0 H16 V14 H14 Z"),
retry = new Button("Retry"),
refresh = new Button("Refresh");
private final ComboBox<String> pageSize = new ComboBox<>();
private final GridQuery initial;
private final List<ResultColumn> columnDefinitions;
private GridQuery initial;
private List<ResultColumn> columnDefinitions;
private GridDefinition setupDefinition;
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
@@ -50,11 +54,201 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private Alert pendingAlert;
private long alertGeneration;
private final HBox groupingBar = new HBox(8);
private final HBox filterSummary = new HBox(8);
private final Label activeFilters = new Label();
private final Label interactionStatus = new Label();
private final MenuButton setupMenu = new MenuButton("Grid setup");
private final ReadOnlyLongWrapper committedRevision = new ReadOnlyLongWrapper();
private List<String> defaultGrouping = List.of();
private GridSetup developerDefaults;
private boolean hasPublished, restoredPublication;
private GridQuery lastPublishedQuery;
private long restoreSerial, lastRestoredSerial;
private GridPersistenceAttachment<K, T> attachment;
private GridColumnSettings<K, T> columnSettings;
private static Button pagingButton(String name, String path) {
var button = new Button();
var icon = new SVGPath();
icon.setContent(path);
icon.fillProperty().bind(button.textFillProperty());
var graphic = new StackPane(icon);
graphic.setMinSize(18, 16);
graphic.setPrefSize(18, 16);
graphic.setMaxSize(18, 16);
graphic.setMouseTransparent(true);
button.setGraphic(graphic);
button.setMinSize(36, 30);
button.setAccessibleText(name);
button.setTooltip(new Tooltip(name));
return button;
}
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
public DataGrid() {
requireFx();
getStyleClass().add("data-grid");
setSpacing(8);
getChildren().addAll(declaration.preview(), status);
}
public ObservableList<DataGridColumn> getColumns() {
return declaration.columns();
}
public ObjectProperty<ObservableList<T>> itemsProperty() {
return declaration.itemsProperty();
}
public ObservableList<T> getItems() {
return itemsProperty().get();
}
public void setItems(ObservableList<T> items) {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
if (getSource() != null) throw new IllegalStateException("Choose items or source");
itemsProperty().set(items);
}
public GridSource<K, T> getSource() {
return declaration.sourceProperty().get();
}
public ObjectProperty<GridSource<K, T>> sourceProperty() {
return declaration.sourceProperty();
}
public Function<T, ResultRow> getRowFactory() {
return declaration.rowFactory;
}
public void setRowFactory(Function<T, ResultRow> factory) {
declaration.beforeOpen();
declaration.rowFactory = factory;
}
public Function<T, K> getKeyFactory() {
return declaration.keyFactory;
}
public void setKeyFactory(Function<T, K> factory) {
declaration.beforeOpen();
declaration.keyFactory = factory;
}
public Comparator<K> getKeyComparator() {
return declaration.keyComparator;
}
public void setKeyComparator(Comparator<K> comparator) {
declaration.beforeOpen();
declaration.keyComparator = comparator;
}
public String getKeyAttribute() {
return declaration.keyAttribute;
}
public void setKeyAttribute(String attribute) {
declaration.beforeOpen();
declaration.keyAttribute = attribute;
}
public String getSetupId() {
return declaration.setupId;
}
public void setSetupId(String id) {
declaration.beforeOpen();
declaration.setupId = id;
}
public int getSetupVersion() {
return declaration.setupVersion;
}
public void setSetupVersion(int version) {
declaration.beforeOpen();
declaration.setupVersion = version;
}
public int getMaximumPageSize() {
return declaration.maximumPageSize;
}
public void setMaximumPageSize(int size) {
declaration.beforeOpen();
if (size < 1) throw new IllegalArgumentException("Positive maximum page size required");
declaration.maximumPageSize = size;
}
public String getGroupBy() {
return declaration.groupBy;
}
public void setGroupBy(String columns) {
declaration.beforeOpen();
declaration.groupBy = columns;
}
public boolean isGroupsCollapsed() {
return declaration.groupsCollapsed;
}
public void setGroupsCollapsed(boolean collapsed) {
declaration.beforeOpen();
declaration.groupsCollapsed = collapsed;
}
public int getInactiveGroupHistoryLimit() {
return declaration.inactiveGroupHistoryLimit;
}
public void setInactiveGroupHistoryLimit(int limit) {
declaration.beforeOpen();
if (limit < 0) throw new IllegalArgumentException("Negative group history limit");
declaration.inactiveGroupHistoryLimit = limit;
}
/** Completes declarative configuration without executing a query. */
public void initialize() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
if (coordinator == null) {
try {
declaration.open();
} catch (RuntimeException failure) {
try {
close();
} catch (RuntimeException cleanup) {
failure.addSuppressed(cleanup);
}
throw failure;
}
}
}
public DataGrid(
List<ResultColumn> columns,
Function<T, ResultRow> rowFactory,
GridSource<K, T> source) {
this();
declaration.setInitialSource(source);
initialize(columns, rowFactory, source);
}
void initialize(
List<ResultColumn> columns,
Function<T, ResultRow> rowFactory,
GridSource<K, T> source) {
requireFx();
getChildren().clear();
columnDefinitions = List.copyOf(columns);
Objects.requireNonNull(source);
initial =
@@ -64,40 +258,37 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
new PageRequest.Paged(
0, Math.min(50, source.capabilities().maximumPageSize())));
renderer = table.openResults(columns, rowFactory);
renderer.enableColumnSeparators();
selectedKey.bind(renderer.selectedKeyProperty());
selectedElement.bind(renderer.selectedElementProperty());
coordinator =
new GridCoordinator<>(
source,
Platform::runLater,
this::changed,
result -> renderer.show(result.rows()));
source, Platform::runLater, this::changed, result -> publishRows(result));
coordinator.setConfirmation(this::confirmAll);
renderer.setOnSortRequest(
id -> {
var q = query();
SortKey.Direction direction =
q.sort().size() == 1
&& q.sort().getFirst().columnId().equals(id)
&& q.sort().getFirst().direction()
== SortKey.Direction.ASCENDING
? SortKey.Direction.DESCENDING
: SortKey.Direction.ASCENDING;
setSort(new SortKey(id, direction));
});
renderer.setOnSortRequest(id -> {
var q = query();
SortKey.Direction direction =
q.sort().size() == 1
&& q.sort().getFirst().columnId().equals(id)
&& q.sort().getFirst().direction()
== SortKey.Direction.ASCENDING
? SortKey.Direction.DESCENDING
: SortKey.Direction.ASCENDING;
setSort(new SortKey(id, direction));
});
first.setOnAction(e -> first());
previous.setOnAction(e -> previous());
next.setOnAction(e -> next());
last.setOnAction(e -> last());
retry.setOnAction(e -> coordinator.retry());
refresh.setOnAction(e -> refresh());
pageSize.setOnAction(
e -> {
if (updating || pageSize.getValue() == null) return;
setPageRequest(
pageSize.getValue().equals("All")
? new PageRequest.All()
: new PageRequest.Paged(
0, Integer.parseInt(pageSize.getValue())));
});
pageSize.setOnAction(e -> {
if (updating || pageSize.getValue() == null) return;
setPageRequest(
pageSize.getValue().equals("All")
? new PageRequest.All()
: new PageRequest.Paged(0, Integer.parseInt(pageSize.getValue())));
});
status.setWrapText(true);
status.getStyleClass().add("data-grid-status");
HBox controls =
@@ -112,9 +303,37 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
refresh,
retry);
controls.getStyleClass().add("data-grid-paging");
getStyleClass().add("data-grid");
setSpacing(8);
getChildren().addAll(table, controls, status);
renderer.setOnLayoutCommitted(this::layoutCommitted);
renderer.setOnInteractionMessage(interactionStatus::setText);
groupingBar.getStyleClass().add("data-grid-grouping");
groupingBar.setAccessibleText("Grouping columns");
groupingBar.setFocusTraversable(true);
groupingBar.setVisible(false);
groupingBar.setManaged(false);
renderer.gestures().groupTarget(groupingBar);
MenuItem columnsItem = new MenuItem("Column settings…");
columnsItem.setOnAction(e -> {
if (columnSettings != null) columnSettings.close();
columnSettings = new GridColumnSettings<>(this, renderer);
columnSettings.show();
});
MenuItem resetExpansion = new MenuItem("Reset expansion");
resetExpansion.setOnAction(e -> resetExpansion());
MenuItem clearFilters = new MenuItem("Clear filters");
clearFilters.setOnAction(e -> setFilters(List.of()));
setupMenu.getItems().addAll(columnsItem, resetExpansion, clearFilters);
controls.getChildren().add(setupMenu);
interactionStatus.setWrapText(true);
interactionStatus.getStyleClass().add("data-grid-interaction-status");
var css = DataGrid.class.getResource("data-grid.css");
if (css != null) getStylesheets().add(css.toExternalForm());
Button clearActiveFilters = new Button("Clear filters");
clearActiveFilters.setOnAction(e -> setFilters(List.of()));
filterSummary.getChildren().addAll(activeFilters, clearActiveFilters);
filterSummary.setVisible(false);
filterSummary.setManaged(false);
getChildren()
.addAll(groupingBar, table, filterSummary, controls, status, interactionStatus);
VBox.setVgrow(table, Priority.ALWAYS);
state.set(coordinator.state());
updateControls(coordinator.state());
@@ -125,11 +344,11 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
return renderer.selectedKeyProperty();
return selectedKey.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<T> selectedElementProperty() {
return renderer.selectedElementProperty();
return selectedElement.getReadOnlyProperty();
}
public void select(K key) {
@@ -191,6 +410,15 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
}
public void setSource(GridSource<K, T> source) {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
if (getItems() != null) throw new IllegalStateException("Choose items or source");
Objects.requireNonNull(source);
if (coordinator != null && source == getSource()) replaceSource(source);
else sourceProperty().set(source);
}
void replaceSource(GridSource<K, T> source) {
check();
closeFilter();
var q = query();
@@ -220,15 +448,14 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
id,
version,
columnDefinitions.stream()
.map(
c ->
new GridDefinition.Column(
c.id(),
types.get(c.id()),
c.defaultWidth(),
c.minimumWidth(),
c.maximumWidth(),
c.fixedPosition()))
.map(c ->
new GridDefinition.Column(
c.id(),
types.get(c.id()),
c.defaultWidth(),
c.minimumWidth(),
c.maximumWidth(),
c.fixedPosition()))
.toList());
Map<Integer, java.util.function.UnaryOperator<GridSetup>> next = Map.copyOf(migrations);
if (coordinator.isRestoring())
@@ -247,18 +474,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
Map<String, String> types = new HashMap<>();
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
return new GridSetup(
1,
2,
setupDefinition.id(),
setupDefinition.version(),
renderer.columnOrder().stream()
.map(
id ->
new GridSetup.ColumnState(
id, types.get(id), renderer.columnWidths().get(id)))
.map(id ->
new GridSetup.ColumnState(
id, types.get(id), renderer.columnWidths().get(id)))
.toList(),
committed.sort(),
committed.filters(),
firstPage(committed.page()));
firstPage(committed.page()),
renderer.groupingSetup());
}
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
@@ -287,6 +514,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
coordinator.capabilities(),
condition -> coordinator.validateFilters(List.of(condition)));
var setup = prepared.setup();
var grouping =
setup.grouping() == null
? new GroupingSetup(defaultGrouping, List.of())
: setup.grouping();
renderer.validateGrouping(grouping);
long serial = restoreSerial;
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
coordinator.restoreSetup(
@@ -296,7 +529,11 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
renderer.show(
result.rows(),
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
widths);
widths,
grouping);
lastRestoredSerial = serial;
restoredPublication = true;
drawGroupingBar();
restorationAdjustments.set(prepared.adjustments());
});
} catch (RuntimeException error) {
@@ -431,10 +668,29 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
firstPage(q.page())));
}
public int getPageSize() {
return coordinator == null
? declaration.pageSize
: query().page() instanceof PageRequest.Paged page ? page.pageSize() : 0;
}
public void setPageSize(int size) {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
if (size < 1) throw new IllegalArgumentException("Positive page size required");
if (coordinator == null) {
declaration.pageSize = size;
return;
}
setPageRequest(new PageRequest.Paged(0, size));
}
void setInitialPageSize(int size) {
coordinator.capabilities().validate(new PageRequest.Paged(0, size));
initial = new GridQuery(initial.filters(), initial.sort(), new PageRequest.Paged(0, size));
updateControls(coordinator.state());
}
public void showAll() {
setPageRequest(new PageRequest.All());
}
@@ -502,11 +758,13 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("error"),
value.phase() == GridCoordinator.Phase.ERROR);
if (value.displayed() != null)
if (value.displayed() != null) {
renderer.setFilteredColumns(
value.displayed().filters().stream()
.map(FilterCondition::columnId)
.collect(java.util.stream.Collectors.toSet()));
renderer.setSortKeys(value.displayed().sort());
}
if (visibleSourceVersion != value.sourceVersion()) {
visibleSourceVersion = value.sourceVersion();
renderer.select(null);
@@ -515,6 +773,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
updateControls(value);
}
state.set(value);
if (!closed && value.phase() == GridCoordinator.Phase.READY) {
GridQuery published =
new GridQuery(
value.displayed().filters(),
value.displayed().sort(),
firstPage(value.displayed().page()));
boolean changedQuery = hasPublished && !Objects.equals(published, lastPublishedQuery);
hasPublished = true;
lastPublishedQuery = published;
if (changedQuery && !restoredPublication) fireCommitted();
restoredPublication = false;
}
}
private void updateControls(GridCoordinator.State<K, T> s) {
@@ -592,7 +862,27 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
yield pageLabel(requested.page()) + " — total unknown";
}
};
status.setText(message);
List<String> filtered =
s.displayed() == null
? List.of()
: s.displayed().filters().stream()
.map(f ->
columnDefinitions.stream()
.filter(c -> c.id().equals(f.columnId()))
.findFirst()
.orElseThrow()
.header())
.toList();
activeFilters.setText("Active filters: " + String.join(", ", filtered));
filterSummary.setVisible(!filtered.isEmpty());
filterSummary.setManaged(!filtered.isEmpty());
status.setText(
message
+ (renderer.groupingEnabled() && !renderer.groupingColumns().isEmpty()
? (requested.page() instanceof PageRequest.All
? " · Grouping loaded result"
: " · Grouping current page")
: ""));
}
private static String pageLabel(PageRequest page) {
@@ -617,15 +907,279 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
alert.initOwner(getScene().getWindow());
pendingAlert = alert;
alertGeneration = coordinator.state().generation();
alert.setOnHidden(
e -> {
if (pendingAlert == alert) pendingAlert = null;
answer.complete(alert.getResult() == proceed);
});
alert.setOnHidden(e -> {
if (pendingAlert == alert) pendingAlert = null;
answer.complete(alert.getResult() == proceed);
});
alert.show();
return answer;
}
public CompletionStage<Void> loadAsync() {
return awaitOperation(this::load, -1);
}
public CompletionStage<Void> restoreSetupAsync(GridSetup setup) {
long serial = ++restoreSerial;
return awaitOperation(() -> restoreSetup(setup), serial);
}
private CompletionStage<Void> awaitOperation(Runnable action, long serial) {
check();
action.run();
long generation = coordinator.state().generation();
CompletableFuture<Void> future = new CompletableFuture<>();
javafx.beans.value.ChangeListener<GridCoordinator.State<K, T>> listener =
(observable, before, value) -> {
if (value.generation() != generation
|| value.phase() == GridCoordinator.Phase.CLOSED)
future.completeExceptionally(
new CancellationException("Grid operation superseded"));
else if (value.phase() == GridCoordinator.Phase.ERROR)
future.completeExceptionally(value.error());
else if (value.phase() == GridCoordinator.Phase.READY) {
if (serial < 0 || lastRestoredSerial == serial) future.complete(null);
else
future.completeExceptionally(
new CancellationException("Restore declined"));
}
};
state.addListener(listener);
future.whenComplete((ok, error) -> state.removeListener(listener));
listener.changed(state, state.get(), state.get());
return future;
}
GridSetup developerDefaults() {
return developerDefaults == null ? snapshotSetup() : developerDefaults;
}
void cancelOwnedRestore(long generation) {
if (!closed && state.get().generation() == generation) coordinator.cancelRestore();
}
public ReadOnlyLongProperty committedRevisionProperty() {
return committedRevision.getReadOnlyProperty();
}
public List<String> groupingColumns() {
return renderer.groupingColumns();
}
public boolean groupingEnabled() {
return renderer.groupingEnabled();
}
public void configureGrouping(
List<GroupColumn<T>> columns,
boolean enabled,
List<String> defaults,
boolean collapsed,
int inactiveHistoryLimit) {
check();
renderer.configureGrouping(columns, enabled, defaults, collapsed, inactiveHistoryLimit);
defaultGrouping = List.copyOf(defaults);
developerDefaults = null;
drawGroupingBar();
}
public void setGroupingColumns(List<String> columns) {
check();
closeFilter();
coordinator.cancelRestore();
try {
renderer.setGroupingColumns(columns);
} catch (RuntimeException failure) {
interactionStatus.setText("Cannot change grouping: " + failure.getMessage());
throw failure;
}
}
public boolean isGroupingEnabled() {
return coordinator == null ? declaration.groupingEnabled : groupingEnabled();
}
public void setGroupingEnabled(boolean enabled) {
requireFx();
if (coordinator == null) {
declaration.groupingEnabled = enabled;
return;
}
check();
coordinator.cancelRestore();
renderer.setGroupingEnabled(enabled);
drawGroupingBar();
updateControls(coordinator.state());
}
public void resetExpansion() {
check();
coordinator.cancelRestore();
renderer.resetExpansion();
}
public void setExpanded(GroupPath path, boolean expanded) {
check();
coordinator.cancelRestore();
renderer.setExpanded(path, expanded);
}
public void regroup() {
check();
coordinator.cancelRestore();
try {
renderer.regroup();
interactionStatus.setText("");
} catch (RuntimeException failure) {
interactionStatus.setText("Cannot update grouping: " + failure.getMessage());
throw failure;
}
}
private void publishRows(PageResult<K, T> result) {
renderer.show(result.rows());
drawGroupingBar();
}
private void layoutCommitted() {
if (closed) return;
coordinator.cancelRestore();
drawGroupingBar();
updateControls(coordinator.state());
fireCommitted();
}
private void fireCommitted() {
committedRevision.set(committedRevision.get() + 1);
}
private void drawGroupingBar() {
groupingBar.setVisible(renderer.groupingEnabled());
groupingBar.setManaged(renderer.groupingEnabled());
NodeFocus focus = new NodeFocus(groupingBar);
groupingBar.getChildren().clear();
if (renderer.groupingColumns().isEmpty())
groupingBar
.getChildren()
.add(new Label("Drag a column here to group the current page"));
for (String id : renderer.groupingColumns()) {
String label =
columnDefinitions.stream()
.filter(c -> c.id().equals(id))
.findFirst()
.orElseThrow()
.header();
Label text = new Label(label);
Button remove = new Button("×");
remove.setAccessibleText("Remove grouping by " + label);
remove.setOnAction(e ->
setGroupingColumns(
renderer.groupingColumns().stream()
.filter(c -> !c.equals(id))
.toList()));
remove.addEventHandler(
javafx.scene.input.MouseEvent.DRAG_DETECTED, javafx.event.Event::consume);
HBox chip = new HBox(6, text, remove);
chip.getStyleClass().add("grouping-chip");
chip.setAccessibleText(
"Grouping level " + (groupingBar.getChildren().size() + 1) + ": " + label);
chip.setFocusTraversable(true);
renderer.gestures().chip(chip, id);
groupingBar.getChildren().add(chip);
}
focus.restore(groupingBar);
}
private static final class NodeFocus {
private final boolean inside;
NodeFocus(javafx.scene.Parent parent) {
javafx.scene.Node focus =
parent.getScene() == null ? null : parent.getScene().getFocusOwner();
boolean found = false;
for (var node = focus; node != null; node = node.getParent())
if (node == parent) found = true;
inside = found;
}
void restore(javafx.scene.Parent parent) {
if (inside) parent.requestFocus();
}
}
/**
* Configure defaults without fetching. Call after column/group definitions, before
* attachment/load.
*/
public void configureDefaults(GridSetup defaults) {
check();
if (hasPublished || attachment != null || state.get().phase() != GridCoordinator.Phase.IDLE)
throw new IllegalStateException("Configure defaults before attachment or loading");
if (setupDefinition == null)
throw new IllegalStateException("Configure the grid definition first");
var prepared =
setupDefinition
.prepare(
defaults,
setupMigrations,
coordinator.capabilities(),
condition -> coordinator.validateFilters(List.of(condition)))
.setup();
var groups =
prepared.grouping() == null
? new GroupingSetup(defaultGrouping, List.of())
: prepared.grouping();
renderer.validateGrouping(groups);
var widths = new LinkedHashMap<String, ColumnWidth>();
prepared.columns().forEach(c -> widths.put(c.id(), c.width()));
renderer.show(
List.of(),
prepared.columns().stream().map(GridSetup.ColumnState::id).toList(),
widths,
groups);
initial = new GridQuery(prepared.filters(), prepared.sort(), firstPage(prepared.page()));
defaultGrouping = groups.columns();
developerDefaults = snapshotSetup();
drawGroupingBar();
updateControls(coordinator.state());
}
public GridSetup defaultSetup() {
check();
if (developerDefaults == null) developerDefaults = snapshotSetup();
return developerDefaults;
}
public GridPersistenceAttachment<K, T> attachPersistence(
GridApplicationConfiguration config, String gridId) {
return attachPersistence(config, gridId, null);
}
public GridPersistenceAttachment<K, T> attachPersistence(
GridApplicationConfiguration config, String gridId, String context) {
check();
if (attachment != null) throw new IllegalStateException("Persistence already attached");
if (developerDefaults == null) developerDefaults = snapshotSetup();
attachment =
new GridPersistenceAttachment<>(
this, config, new GridSetupStore.Key(gridId, context));
return attachment;
}
void addPersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
getChildren().add(feedback);
setupMenu.getItems().addAll(items);
}
void removePersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
getChildren().remove(feedback);
setupMenu.getItems().removeAll(items);
}
void detached(GridPersistenceAttachment<K, T> handle) {
if (attachment == handle) attachment = null;
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
@@ -634,19 +1188,49 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private void check() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
initialize();
}
void refreshItems() {
if (coordinator == null
|| closed
|| coordinator.state().phase() == GridCoordinator.Phase.IDLE) return;
if (attachment != null) {
var ready = attachment.ready().toCompletableFuture();
if (!ready.isDone() || ready.isCompletedExceptionally()) return;
}
refresh();
}
boolean isInitialized() {
return coordinator != null;
}
boolean isClosed() {
return closed;
}
public void close() {
requireFx();
if (closed) return;
if (columnSettings != null) {
columnSettings.close();
columnSettings = null;
}
if (attachment != null) attachment.close();
closed = true;
closeFilter();
coordinator.close();
declaration.close();
if (coordinator != null) coordinator.close();
if (pendingAlert != null) {
pendingAlert.close();
pendingAlert = null;
}
renderer.close();
if (renderer != null) renderer.close();
selectedKey.unbind();
selectedElement.unbind();
selectedKey.set(null);
selectedElement.set(null);
getChildren().clear();
}
}
@@ -0,0 +1,96 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.FilterColumn;
import de.neitzel.grid.*;
import lombok.Getter;
import lombok.Setter;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
/** Declarative column shared by rendering, local queries, filters, grouping and saved setups. */
@Getter
@Setter
public final class DataGridColumn {
private String id;
private String header;
private String attribute;
private String groupAttribute;
@Setter(lombok.AccessLevel.NONE)
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>();
private double width = 150;
private double minimumWidth = 80;
private double maximumWidth = 1200;
private int fixedPosition = -1;
private MemoryColumn.Kind kind = MemoryColumn.Kind.TEXT;
private boolean filterable = true;
private FilterColumn.Checklist checklist = FilterColumn.Checklist.DISABLED;
private FilterCandidates.Provider candidates;
private String type;
ResultColumn definition() {
if (kind == null || checklist == null)
throw new IllegalArgumentException("Column kind and checklist are required");
return new ResultColumn(id, header, width, minimumWidth, maximumWidth, fixedPosition);
}
public Object getValue(Object row) {
return read(row, attribute == null ? id : attribute);
}
static Object read(Object row, String attribute) {
if (row == null) return null;
if (attribute == null || attribute.isBlank())
throw new IllegalArgumentException("Missing row attribute");
String suffix = Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1);
for (String name : new String[] {"get" + suffix, "is" + suffix, attribute}) {
try {
return row.getClass().getMethod(name).invoke(row);
} catch (NoSuchMethodException absent) {
// JavaBeans and record-style scalar accessors are both supported.
} catch (IllegalAccessException | InvocationTargetException error) {
throw new IllegalArgumentException(
"Could not read row attribute " + attribute, error);
}
}
throw new IllegalArgumentException(
"No row attribute " + attribute + " on " + row.getClass().getName());
}
FilterValue groupValue(Object row) {
return scalar(groupAttribute == null ? getValue(row) : read(row, groupAttribute));
}
String groupLabel(FilterValue value) {
String display = GroupColumn.display(value);
return groupLabels.getOrDefault(display, display);
}
FilterValue value(Object row) {
return scalar(getValue(row));
}
private FilterValue scalar(Object value) {
if (value == null) return null;
return switch (kind) {
case TEXT -> new FilterValue.Text(value.toString());
case INTEGER ->
new FilterValue.IntegerValue(new BigDecimal(value.toString()).longValueExact());
case DECIMAL -> new FilterValue.Decimal(new BigDecimal(value.toString()));
case BOOLEAN -> {
if (!(value instanceof Boolean bool))
throw new IllegalArgumentException("Boolean value required for " + id);
yield new FilterValue.BooleanValue(bool);
}
};
}
String schemaType() {
return type == null
? "neitzel." + kind.name().toLowerCase(java.util.Locale.ROOT) + ".v1"
: type;
}
}
@@ -0,0 +1,227 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.FilterColumn;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/** FXML construction and owned local-source lifetime, separate from query coordination. */
final class DataGridDeclaration<K, T> implements AutoCloseable {
private final DataGrid<K, T> grid;
private final ObservableList<DataGridColumn> columns = FXCollections.observableArrayList();
private final ObjectProperty<ObservableList<T>> items = new SimpleObjectProperty<>();
private final ObjectProperty<GridSource<K, T>> source = new SimpleObjectProperty<>();
private final HBox preview = new HBox();
private final ListChangeListener<T> itemsChanged = change -> changedItems();
private ExecutorService executor;
private boolean external;
private boolean assigningInitialSource;
Function<T, ResultRow> rowFactory;
Function<T, K> keyFactory;
Comparator<K> keyComparator;
String keyAttribute;
String setupId;
int setupVersion = 1;
int pageSize = 50;
int maximumPageSize = 250;
boolean groupingEnabled;
String groupBy = "";
boolean groupsCollapsed;
int inactiveGroupHistoryLimit = 1000;
DataGridDeclaration(DataGrid<K, T> grid) {
this.grid = grid;
preview.getStyleClass().add("data-grid-preview-header");
columns.addListener(
(ListChangeListener<DataGridColumn>)
change -> {
beforeOpen();
preview.getChildren().clear();
for (var column : columns) {
var label = new Label(column.getHeader());
label.setPrefWidth(column.getWidth());
label.getStyleClass().add("column-header");
preview.getChildren().add(label);
}
});
items.addListener((observable, previous, current) -> {
requireFx();
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
if (external && grid.isInitialized())
throw new IllegalStateException("External sources cannot use items");
if (previous != null) previous.removeListener(itemsChanged);
if (current != null) current.addListener(itemsChanged);
changedItems();
});
source.addListener((observable, previous, current) -> {
requireFx();
if (assigningInitialSource) return;
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
Objects.requireNonNull(current, "Missing source");
if (items.get() != null) throw new IllegalStateException("Choose items or source");
if (grid.isInitialized()) {
external = true;
grid.replaceSource(current);
}
});
}
void setInitialSource(GridSource<K, T> value) {
assigningInitialSource = true;
try {
source.set(Objects.requireNonNull(value));
external = true;
} finally {
assigningInitialSource = false;
}
}
ObservableList<DataGridColumn> columns() {
return columns;
}
ObjectProperty<ObservableList<T>> itemsProperty() {
return items;
}
ObjectProperty<GridSource<K, T>> sourceProperty() {
return source;
}
HBox preview() {
return preview;
}
void beforeOpen() {
requireFx();
if (grid.isClosed() || grid.isInitialized())
throw new IllegalStateException("Configure before initializing the grid");
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
}
private void changedItems() {
requireFx();
grid.refreshItems();
}
@SuppressWarnings("unchecked")
void open() {
var definitions = columns.stream().map(DataGridColumn::definition).toList();
if (definitions.isEmpty())
throw new IllegalArgumentException("Declare DataGrid columns before loading");
if (definitions.stream().map(ResultColumn::id).distinct().count() != definitions.size())
throw new IllegalArgumentException("Duplicate DataGrid column ID");
GridSource<K, T> configured = source.get();
MemoryGridSource<K, T> memory = null;
if (configured == null) {
if (keyFactory == null && (keyAttribute == null || keyAttribute.isBlank()))
throw new IllegalArgumentException(
"Local DataGrid requires keyAttribute or keyFactory");
Function<T, K> key =
keyFactory != null
? keyFactory
: row -> (K) DataGridColumn.read(row, keyAttribute);
Comparator<K> order =
keyComparator != null
? keyComparator
: (a, b) -> {
if (!(a instanceof Comparable<?>))
throw new IllegalArgumentException(
"Row keys require a comparator");
return ((Comparable<Object>) a).compareTo(b);
};
executor = Executors.newVirtualThreadPerTaskExecutor();
memory =
new MemoryGridSource<>(
() -> items.get() == null ? List.of() : items.get(),
key,
order,
columns.stream()
.map(c -> new MemoryColumn<T>(c.getId(), c.getKind(), c::value))
.toList(),
executor,
maximumPageSize);
configured = memory;
} else {
if (items.get() != null) throw new IllegalArgumentException("Choose items or source");
external = true;
}
configured.capabilities().validate(new PageRequest.Paged(0, pageSize));
grid.initialize(definitions, rowFactory == null ? this::render : rowFactory, configured);
grid.setInitialPageSize(pageSize);
for (var column : columns) {
if (!column.isFilterable()) continue;
FilterColumn filter =
switch (column.getKind()) {
case TEXT -> FilterColumn.text();
case INTEGER, DECIMAL ->
FilterColumn.number(
Locale.getDefault(),
column.getKind() == MemoryColumn.Kind.INTEGER,
null,
null);
case BOOLEAN -> null;
};
if (filter == null) {
if (column.getChecklist() != FilterColumn.Checklist.DISABLED)
throw new IllegalArgumentException(
"Boolean filter editor is not available; set filterable=false");
continue;
}
var candidates = column.getCandidates();
if (candidates == null && memory != null)
candidates = memory.candidateProvider(GroupColumn::display);
grid.configureFilter(
column.getId(), filter.withChecklist(column.getChecklist(), candidates));
}
grid.configureGrouping(
columns.stream()
.map(c ->
new GroupColumn<T>(
c.getId(), c.getKind(), c::groupValue, c::groupLabel))
.toList(),
groupingEnabled,
groupBy.isBlank()
? List.of()
: Arrays.stream(groupBy.split(",")).map(String::trim).toList(),
groupsCollapsed,
inactiveGroupHistoryLimit);
if (setupId != null && !setupId.isBlank()) {
Map<String, String> types = new LinkedHashMap<>();
columns.forEach(c -> types.put(c.getId(), c.schemaType()));
grid.configureSetups(setupId, setupVersion, types, Map.of());
}
}
private ResultRow render(T row) {
HBox root = new HBox();
root.setUserData(row);
Map<String, Region> cells = new LinkedHashMap<>();
for (var column : columns) {
Label label = new Label(Objects.toString(column.getValue(row), ""));
root.getChildren().add(label);
cells.put(column.getId(), label);
}
return new ResultRow(root, cells, () -> {});
}
@Override
public void close() {
if (items.get() != null) items.get().removeListener(itemsChanged);
items.unbind();
source.unbind();
if (executor != null) executor.shutdownNow();
}
}
@@ -0,0 +1,164 @@
package de.neitzel.fx.view;
import de.neitzel.grid.ColumnWidth;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.util.StringConverter;
import java.util.*;
/** Keyboard-operable equivalents of header resizing, reordering and grouping. */
final class GridColumnSettings<K, T> {
private final Dialog<Void> dialog = new Dialog<>();
GridColumnSettings(DataGrid<K, T> grid, TableResults<K, T> renderer) {
dialog.setTitle("Column settings");
if (grid.getScene() != null) dialog.initOwner(grid.getScene().getWindow());
dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
ComboBox<ResultColumn> column = new ComboBox<>();
column.getItems().setAll(renderer.definitions());
column.setConverter(
new StringConverter<>() {
public String toString(ResultColumn c) {
return c == null ? "" : c.header();
}
public ResultColumn fromString(String text) {
throw new UnsupportedOperationException();
}
});
column.setAccessibleText("Column");
column.setId("gridSettingsColumn");
Spinner<Double> width = new Spinner<>();
width.setEditable(true);
width.setAccessibleText("Column width");
Button apply = new Button("Apply width"),
left = new Button("Move left"),
right = new Button("Move right"),
group = new Button("Group by column"),
earlier = new Button("Earlier grouping level"),
later = new Button("Later grouping level"),
remove = new Button("Remove grouping");
Label description = new Label(), message = new Label();
message.setWrapText(true);
Runnable update =
() -> {
var c = column.getValue();
if (c == null) return;
width.setValueFactory(
new SpinnerValueFactory.DoubleSpinnerValueFactory(
c.minimumWidth(),
c.maximumWidth(),
renderer.width(c.id()),
10));
int index = renderer.columnOrder().indexOf(c.id()),
level = renderer.groupingColumns().indexOf(c.id());
description.setText(
"Position "
+ (index + 1)
+ (c.fixedPosition() >= 0 ? " (fixed)" : "")
+ " · "
+ c.minimumWidth()
+ "–"
+ c.maximumWidth()
+ " px");
left.setDisable(!canMove(renderer, c.id(), index - 1));
right.setDisable(!canMove(renderer, c.id(), index + 1));
group.setDisable(!renderer.canGroup(c.id()) || level >= 0);
earlier.setDisable(!renderer.groupingEnabled() || level <= 0);
later.setDisable(
!renderer.groupingEnabled()
|| level < 0
|| level == renderer.groupingColumns().size() - 1);
remove.setDisable(!renderer.groupingEnabled() || level < 0);
};
java.util.function.Consumer<Runnable> perform =
action -> {
try {
action.run();
message.setText("Applied.");
} catch (RuntimeException failure) {
message.setText(failure.getMessage());
}
update.run();
};
left.setOnAction(
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), -1)));
right.setOnAction(
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), 1)));
apply.setOnAction(e ->
perform.accept(() ->
grid.setColumnWidth(
column.getValue().id(),
new ColumnWidth.Explicit(
Double.parseDouble(width.getEditor().getText())))));
group.setOnAction(e ->
perform.accept(() -> {
var ids = new ArrayList<>(renderer.groupingColumns());
ids.add(column.getValue().id());
grid.setGroupingColumns(ids);
}));
remove.setOnAction(e ->
perform.accept(() ->
grid.setGroupingColumns(
renderer.groupingColumns().stream()
.filter(id -> !id.equals(column.getValue().id()))
.toList())));
earlier.setOnAction(
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), -1)));
later.setOnAction(
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), 1)));
VBox content =
new VBox(
10,
new Label("Column"),
column,
description,
new HBox(8, left, right),
new Label("Width in pixels"),
new HBox(8, width, apply),
new HBox(8, group, remove),
new HBox(8, earlier, later),
message);
dialog.getDialogPane().setContent(content);
column.valueProperty().addListener((o, b, a) -> update.run());
column.getSelectionModel().selectFirst();
}
void show() {
dialog.show();
}
void close() {
dialog.close();
}
private static boolean canMove(TableResults<?, ?> renderer, String id, int index) {
var order = new ArrayList<>(renderer.columnOrder());
if (index < 0 || index >= order.size()) return false;
order.remove(id);
order.add(index, id);
return renderer.definitions().stream()
.allMatch(
c -> c.fixedPosition() < 0 || order.get(c.fixedPosition()).equals(c.id()));
}
private static <K, T> void move(
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
var order = new ArrayList<>(renderer.columnOrder());
int index = order.indexOf(id);
order.remove(id);
order.add(index + delta, id);
grid.setColumnOrder(order);
}
private static <K, T> void moveGroup(
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
var order = new ArrayList<>(renderer.groupingColumns());
int index = order.indexOf(id);
order.remove(id);
order.add(index + delta, id);
grid.setGroupingColumns(order);
}
}
@@ -0,0 +1,259 @@
package de.neitzel.fx.view;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.util.*;
import java.util.concurrent.*;
/** One FX view's opt-in storage adapter. Closing it never discards accepted application saves. */
public final class GridPersistenceAttachment<K, T> implements AutoCloseable {
private final DataGrid<K, T> grid;
private final GridApplicationConfiguration application;
private final GridSetupStore.Key key;
private final Label status = new Label("Grid settings not loaded");
private final Button retry = new Button("Retry settings"),
reload = new Button("Reload saved setup"),
reset = new Button("Reset setup"),
overwrite = new Button("Overwrite saved setup");
private final VBox feedback = new VBox(4);
private final HBox recovery = new HBox(8);
private final List<MenuItem> menu;
private final ChangeListener<Number> commits;
private final AutoCloseable observation;
private final CompletableFuture<Void> ready = new CompletableFuture<>();
private boolean initialized, closed, restoreFailed;
private long generation, ownSave = -1, operationGeneration = -1;
private Throwable restoreError;
GridPersistenceAttachment(
DataGrid<K, T> grid, GridApplicationConfiguration application, GridSetupStore.Key key) {
this.grid = grid;
this.application = application;
this.key = key;
status.setWrapText(true);
status.getStyleClass().add("grid-persistence-status");
status.setAccessibleText("Grid settings status");
recovery.getChildren().addAll(retry, reload, reset, overwrite);
recovery.setVisible(false);
recovery.setManaged(false);
feedback.getChildren().addAll(status, recovery);
MenuItem reloadItem = new MenuItem("Reload saved setup"),
resetItem = new MenuItem("Reset setup");
reloadItem.setOnAction(e -> loadAsync());
resetItem.setOnAction(e -> resetAsync());
menu = List.of(reloadItem, resetItem);
grid.addPersistenceControls(feedback, menu);
retry.setOnAction(e -> {
if (!initialized || restoreFailed) loadAsync();
else application.retryAsync(key);
});
reload.setOnAction(e -> loadAsync());
reset.setOnAction(e -> resetAsync());
overwrite.setOnAction(e -> overwriteAsync());
commits =
(o, b, a) -> {
if (initialized && !closed) {
try {
ownSave = application.accept(key, grid.snapshotSetup(), this);
} catch (RuntimeException failure) {
fail(new CompletableFuture<>(), failure);
}
}
};
grid.committedRevisionProperty().addListener(commits);
observation =
application.observe(
key,
state ->
Platform.runLater(() -> {
if (!closed) show(state);
}));
}
public CompletionStage<Void> ready() {
return ready;
}
public CompletionStage<Void> loadAsync() {
requireFx();
check();
long token = ++generation;
long discarded = ownSave;
restoreFailed = false;
restoreError = null;
CompletableFuture<Void> answer = new CompletableFuture<>();
CompletionStage<GridApplicationConfiguration.Loaded> loading;
try {
loading = application.loadAsync(key);
} catch (RuntimeException failure) {
fail(answer, failure);
return answer;
}
loading.whenComplete((loaded, error) ->
Platform.runLater(() -> {
if (!live(token)) {
answer.completeExceptionally(
new CancellationException("Attachment closed or superseded"));
return;
}
if (error != null) {
fail(answer, error);
return;
}
GridSetup setup =
loaded.stored().setup() == null
? grid.developerDefaults()
: loaded.stored().setup();
CompletionStage<Void> restore = grid.restoreSetupAsync(setup);
operationGeneration = grid.stateProperty().get().generation();
restore.whenComplete((ok, failure) ->
Platform.runLater(() -> {
if (!live(token)) {
answer.completeExceptionally(
new CancellationException(
"Attachment closed or superseded"));
return;
}
if (failure != null) {
fail(answer, failure);
return;
}
try {
application.adopt(loaded, discarded);
} catch (RuntimeException adoptionFailure) {
fail(answer, adoptionFailure);
return;
}
initialized = true;
restoreFailed = false;
restoreError = null;
show(application.state(key));
ready.complete(null);
answer.complete(null);
}));
}));
return answer;
}
public CompletionStage<Void> resetAsync() {
requireFx();
check();
long token = ++generation;
boolean recover = !initialized || restoreFailed;
CompletableFuture<Void> answer = new CompletableFuture<>();
CompletionStage<Void> restore = grid.restoreSetupAsync(grid.developerDefaults());
operationGeneration = grid.stateProperty().get().generation();
restore.whenComplete((ok, error) ->
Platform.runLater(() -> {
if (!live(token)) {
answer.completeExceptionally(
new CancellationException("Attachment closed or superseded"));
return;
}
if (error != null) {
fail(answer, error);
return;
}
initialized = true;
restoreFailed = false;
restoreError = null;
try {
ownSave =
recover
? application.acceptOverwrite(
key, grid.snapshotSetup(), this)
: application.accept(key, grid.snapshotSetup(), this);
} catch (RuntimeException failure) {
fail(answer, failure);
return;
}
ready.complete(null);
answer.complete(null);
}));
return answer;
}
public CompletionStage<Void> overwriteAsync() {
requireFx();
check();
if (!initialized)
throw new IllegalStateException("Initialize or reset the view before saving");
ownSave = application.acceptOverwrite(key, grid.snapshotSetup(), this);
return application.retryAsync(key);
}
private void fail(CompletableFuture<Void> future, Throwable failure) {
restoreFailed = true;
restoreError = unwrap(failure);
status.setText("Grid settings unavailable: " + restoreError.getMessage());
recovery.setVisible(true);
recovery.setManaged(true);
overwrite.setDisable(!initialized);
future.completeExceptionally(restoreError);
}
private void show(GridApplicationConfiguration.State state) {
if (restoreFailed) {
status.setText("Grid settings unavailable: " + restoreError.getMessage());
return;
}
status.setText(
switch (state.phase()) {
case IDLE -> "Grid settings not loaded";
case LOADING -> "Loading grid settings…";
case PENDING -> "Grid settings have unsaved changes";
case SAVING -> "Saving grid settings…";
case SAVED -> "Grid settings saved";
case CLOSED -> "Grid settings closed";
case ERROR, CONFLICT -> "Grid settings: " + state.error().getMessage();
});
boolean failed =
state.phase() == GridApplicationConfiguration.Phase.ERROR
|| state.phase() == GridApplicationConfiguration.Phase.CONFLICT;
recovery.setVisible(failed);
recovery.setManaged(failed);
overwrite.setDisable(!initialized);
}
private boolean live(long token) {
return !closed && generation == token;
}
private void check() {
if (closed) throw new IllegalStateException("Attachment is closed");
}
private static void requireFx() {
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("Use FX thread");
}
private static Throwable unwrap(Throwable failure) {
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
&& failure.getCause() != null) failure = failure.getCause();
return failure;
}
@Override
public void close() {
requireFx();
if (closed) return;
closed = true;
generation++;
grid.committedRevisionProperty().removeListener(commits);
try {
observation.close();
} catch (Exception failure) {
throw new IllegalStateException(failure);
}
grid.cancelOwnedRestore(operationGeneration);
grid.removePersistenceControls(feedback, menu);
grid.detached(this);
if (!ready.isDone())
ready.completeExceptionally(new CancellationException("Attachment closed"));
}
}
@@ -0,0 +1,37 @@
package de.neitzel.fx.view;
import javafx.scene.Group;
import javafx.scene.layout.HBox;
import javafx.scene.shape.Line;
/** Row decoration that preserves field borders, component identity and hit testing. */
final class ResultColumnSeparators extends Group {
ResultColumnSeparators(HBox row, int columns) {
setManaged(false);
setMouseTransparent(true);
for (int i = 1; i < columns; i++) {
var line = new Line();
line.getStyleClass().add("column-separator-line");
line.endYProperty().bind(row.heightProperty());
getChildren().add(line);
}
}
static ResultColumnSeparators forHeader(HBox cell) {
var decoration = new ResultColumnSeparators(cell, 2);
var line = (Line) decoration.getChildren().getFirst();
line.startXProperty().bind(cell.widthProperty().subtract(.5));
line.endXProperty().bind(line.startXProperty());
return decoration;
}
void position(double[] widths) {
double x = 0;
for (int i = 0; i < getChildren().size(); i++) {
x += widths[i];
var line = (Line) getChildren().get(i);
line.setStartX(x - .5);
line.setEndX(x - .5);
}
}
}
@@ -0,0 +1,376 @@
package de.neitzel.fx.view;
import de.neitzel.grid.ColumnWidth;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import java.util.*;
/** Native gesture routing for result-mode headers only. No source/query or storage ownership. */
final class ResultHeaderGestures implements AutoCloseable {
private static final DataFormat FORMAT = new DataFormat("application/x-neitzel-grid-header");
private final String owner = UUID.randomUUID().toString();
private final TableResults<?, ?> renderer;
private final HBox header;
private final VBox body;
private Runnable cancelResize;
private double pointerX, pointerY;
private AnimationTimer scrolling;
private Runnable finishDrag;
private long dragGeneration;
ResultHeaderGestures(TableResults<?, ?> renderer, HBox header, VBox body) {
this.renderer = renderer;
this.header = header;
this.body = body;
}
void header(HBox cell, Label label, Region handle, String id, Runnable sort) {
boolean[] dragged = {false};
cell.setOnMousePressed(e -> {
if (e.getButton() == MouseButton.PRIMARY) dragged[0] = false;
});
cell.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY && !dragged[0]) sort.run();
});
label.setOnDragDetected(e -> {
if (!e.isPrimaryButtonDown() && e.getButton() != MouseButton.PRIMARY) return;
dragged[0] = true;
start(label, "column", id);
e.consume();
});
cell.setOnDragOver(e -> {
var payload = payload(e.getDragboard());
if (payload == null) return;
pointerX = e.getSceneX();
pointerY = e.getSceneY();
clearTargets();
int index =
insertion(
renderer.columnOrder(), payload[1], id, e.getX() > cell.getWidth() / 2);
var order = move(renderer.columnOrder(), payload[1], index);
boolean valid = payload[0].equals("column") && valid(order);
cell.getStyleClass()
.add(
valid
? (e.getX() > cell.getWidth() / 2
? "drop-after"
: "drop-before")
: "drop-invalid");
if (valid) e.acceptTransferModes(TransferMode.MOVE);
e.consume();
});
cell.setOnDragDropped(e -> {
var payload = payload(e.getDragboard());
boolean success = false;
if (payload != null && payload[0].equals("column")) {
int index =
insertion(
renderer.columnOrder(),
payload[1],
id,
e.getX() > cell.getWidth() / 2);
var order = move(renderer.columnOrder(), payload[1], index);
if (valid(order)) {
renderer.setColumnOrder(order);
success = true;
} else renderer.message("Fixed column cannot be displaced.");
}
clearTargets();
e.setDropCompleted(success);
e.consume();
});
handle.setOnMouseClicked(MouseEvent::consume);
handle.setOnDragDetected(MouseEvent::consume);
handle.setOnMousePressed(e -> {
if (e.getButton() != MouseButton.PRIMARY) return;
dragged[0] = true;
if (cancelResize != null) cancelResize.run();
ColumnWidth original = renderer.columnWidths().get(id);
double start = e.getScreenX(), width = renderer.width(id);
var definition =
renderer.definitions().stream()
.filter(c -> c.id().equals(id))
.findFirst()
.orElseThrow();
Scene scene = handle.getScene();
EventHandler<KeyEvent> escape =
key -> {
if (key.getCode() == KeyCode.ESCAPE && cancelResize != null) {
cancelResize.run();
key.consume();
}
};
double[] preview = {width};
boolean[] active = {true};
javafx.beans.value.ChangeListener<Boolean> focus =
(o, b, focused) -> {
if (!focused && cancelResize != null) cancelResize.run();
};
var window = scene.getWindow();
Runnable cleanup =
() -> {
active[0] = false;
scene.removeEventFilter(KeyEvent.KEY_PRESSED, escape);
if (window != null) window.focusedProperty().removeListener(focus);
handle.setOnMouseDragged(null);
handle.setOnMouseReleased(null);
cancelResize = null;
};
cancelResize =
() -> {
renderer.previewWidth(id, original);
cleanup.run();
renderer.message("Resize cancelled.");
};
scene.addEventFilter(KeyEvent.KEY_PRESSED, escape);
if (window != null) window.focusedProperty().addListener(focus);
handle.setOnMouseDragged(event -> {
if (active[0]) {
preview[0] =
Math.clamp(
width + event.getScreenX() - start,
definition.minimumWidth(),
definition.maximumWidth());
renderer.previewWidth(id, new ColumnWidth.Explicit(preview[0]));
}
event.consume();
});
handle.setOnMouseReleased(event -> {
if (active[0]) {
cleanup.run();
renderer.setColumnWidth(id, new ColumnWidth.Explicit(preview[0]));
renderer.message("Width applied to " + definition.header() + ".");
}
event.consume();
});
e.consume();
});
}
void groupTarget(HBox bar) {
bar.setOnDragOver(e -> {
var payload = payload(e.getDragboard());
if (payload == null) return;
clearTargets();
boolean valid =
renderer.canGroup(payload[1])
&& (payload[0].equals("group")
|| !renderer.groupingColumns().contains(payload[1]));
bar.getStyleClass().add(valid ? "drop-before" : "drop-invalid");
if (valid) {
e.acceptTransferModes(TransferMode.MOVE);
markGroupInsertion(bar, payload[1], e.getSceneX());
}
e.consume();
});
bar.setOnDragDropped(e -> {
var payload = payload(e.getDragboard());
boolean success = false;
if (payload != null
&& renderer.canGroup(payload[1])
&& (payload[0].equals("group")
|| !renderer.groupingColumns().contains(payload[1]))) {
var order = new ArrayList<>(renderer.groupingColumns());
order.remove(payload[1]);
int index = groupIndex(bar, payload[1], e.getSceneX());
order.add(Math.min(index, order.size()), payload[1]);
try {
renderer.setGroupingColumns(order);
success = true;
} catch (RuntimeException failure) {
renderer.message("Grouping failed: " + failure.getMessage());
}
}
if (!success && payload == null)
renderer.message("Column is already grouped or has no enabled grouping mapping.");
clearTargets();
e.setDropCompleted(success);
e.consume();
});
bar.setOnDragExited(e -> {
clearTargets();
e.consume();
});
}
void chip(Region chip, String id) {
chip.setUserData(id);
chip.setOnDragDetected(e -> {
if (e.isPrimaryButtonDown() || e.getButton() == MouseButton.PRIMARY) {
start(chip, "group", id);
e.consume();
}
});
}
private void start(Node node, String kind, String id) {
// Capture before entering native drag setup; snapshot uses the rendering pipeline.
var ghost = node.snapshot(null, null);
var board = node.startDragAndDrop(TransferMode.MOVE);
var content = new ClipboardContent();
content.put(FORMAT, owner + "\n" + kind + "\n" + id);
board.setContent(content);
board.setDragView(ghost);
if (finishDrag != null) finishDrag.run();
long generation = ++dragGeneration;
Scene scene = node.getScene();
// Header-only tracking leaves a stale edge x when the pointer exits
// vertically. Follow the whole scene and qualify its current y as well.
EventHandler<DragEvent> position =
event -> {
if (payload(event.getDragboard()) != null) {
pointerX = event.getSceneX();
pointerY = event.getSceneY();
}
};
EventHandler<DragEvent> exited =
event -> {
if (event.getTarget() == scene || event.getTarget() == scene.getRoot()) {
pointerX = pointerY = Double.NaN;
clearTargets();
}
};
scene.addEventFilter(DragEvent.DRAG_OVER, position);
scene.addEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
finishDrag =
() -> {
scene.removeEventFilter(DragEvent.DRAG_OVER, position);
scene.removeEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
pointerX = pointerY = Double.NaN;
clearTargets();
stopScroll();
finishDrag = null;
};
node.setOnDragDone(e -> {
if (generation != dragGeneration) return;
if (finishDrag != null) finishDrag.run();
renderer.message(
e.getTransferMode() == null
? "Drag cancelled; layout retained."
: "Layout applied.");
});
startScroll();
}
private String[] payload(Dragboard board) {
if (!board.hasContent(FORMAT)) return null;
Object content = board.getContent(FORMAT);
if (!(content instanceof String text)) return null;
var parts = text.split("\n", 3);
return parts.length == 3 && parts[0].equals(owner)
? new String[] {parts[1], parts[2]}
: null;
}
private static List<String> move(List<String> current, String id, int index) {
var result = new ArrayList<>(current);
result.remove(id);
result.add(Math.clamp(index, 0, result.size()), id);
return result;
}
private static int insertion(List<String> current, String id, String target, boolean after) {
if (id.equals(target)) return current.indexOf(id);
var others = new ArrayList<>(current);
others.remove(id);
return others.indexOf(target) + (after ? 1 : 0);
}
private boolean valid(List<String> order) {
if (!new HashSet<>(order).equals(new HashSet<>(renderer.columnOrder()))
|| order.size() != renderer.columnOrder().size()) return false;
for (var c : renderer.definitions())
if (c.fixedPosition() >= 0 && !order.get(c.fixedPosition()).equals(c.id()))
return false;
return true;
}
private int groupIndex(HBox bar, String dragged, double sceneX) {
int index = 0;
for (Node node : bar.getChildren())
if (node.getUserData() instanceof String id && !id.equals(dragged)) {
var bounds = node.localToScene(node.getBoundsInLocal());
if (sceneX < bounds.getMinX() + bounds.getWidth() / 2) return index;
index++;
}
return index;
}
private void markGroupInsertion(HBox bar, String dragged, double x) {
var chips =
bar.getChildren().stream()
.filter(n -> n.getUserData() instanceof String id && !id.equals(dragged))
.toList();
int index = groupIndex(bar, dragged, x);
if (!chips.isEmpty())
chips.get(Math.min(index, chips.size() - 1))
.getStyleClass()
.add(index < chips.size() ? "drop-before" : "drop-after");
}
private void clearTargets() {
Parent root = header.getScene() == null ? header : header.getScene().getRoot();
for (String style : List.of("drop-before", "drop-after", "drop-invalid"))
root.lookupAll("." + style).forEach(n -> n.getStyleClass().remove(style));
}
private void startScroll() {
stopScroll();
pointerX = pointerY = Double.NaN;
scrolling =
new AnimationTimer() {
long last;
@Override
public void handle(long now) {
if (now - last < 35_000_000) return;
last = now;
ScrollPane scroll = null;
for (Node node = body.getParent(); node != null; node = node.getParent())
if (node instanceof ScrollPane pane) {
scroll = pane;
break;
}
ScrollPane headerViewport = null;
for (Node node = header.getParent(); node != null; node = node.getParent())
if (node instanceof ScrollPane pane) {
headerViewport = pane;
break;
}
if (scroll == null
|| headerViewport == null
|| Double.isNaN(pointerX)
|| !headerViewport
.localToScene(headerViewport.getBoundsInLocal())
.contains(pointerX, pointerY)) return;
var bounds = scroll.localToScene(scroll.getViewportBounds());
double delta =
pointerX < bounds.getMinX() + 30
? -.012
: pointerX > bounds.getMaxX() - 30 ? .012 : 0;
scroll.setHvalue(Math.clamp(scroll.getHvalue() + delta, 0, 1));
}
};
scrolling.start();
}
private void stopScroll() {
if (scrolling != null) {
scrolling.stop();
scrolling = null;
}
}
@Override
public void close() {
if (cancelResize != null) cancelResize.run();
if (finishDrag != null) finishDrag.run();
stopScroll();
}
}
@@ -0,0 +1,44 @@
package de.neitzel.fx.view;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/** Makes equal normalized scroll values represent equal pixel offsets in queried results. */
final class ResultScrollAlignment implements AutoCloseable {
private final HBox header;
private final double originalMinimum;
private final DoubleBinding minimum;
ResultScrollAlignment(HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll) {
this.header = header;
originalMinimum = header.getMinWidth();
// A vertical body scrollbar narrows its viewport. Trailing row actions can also
// make its content wider than the column headings. Reserve blank header space
// so both scrollable extents match; the existing two-way hvalue binding then
// moves every mapped field and heading by the same number of pixels.
minimum =
Bindings.createDoubleBinding(
() ->
body.getLayoutBounds().getWidth()
+ Math.max(
0,
headerScroll.getViewportBounds().getWidth()
- bodyScroll
.getViewportBounds()
.getWidth()),
body.layoutBoundsProperty(),
headerScroll.viewportBoundsProperty(),
bodyScroll.viewportBoundsProperty());
header.minWidthProperty().bind(minimum);
}
@Override
public void close() {
header.minWidthProperty().unbind();
header.setMinWidth(originalMinimum);
minimum.dispose();
}
}
@@ -244,7 +244,9 @@ public class Table extends VBox {
if (opened || resultMode) {
throw new IllegalStateException("Table is already open");
}
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory);
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory, headerScroll, scroll);
// DataGrid grows this Table; let its viewport consume that height as well.
VBox.setVgrow(scroll, Priority.ALWAYS);
resultMode = true;
return renderer;
}
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.grid.ColumnWidth;
import de.neitzel.grid.GridRow;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
@@ -40,19 +39,40 @@ public final class TableResults<K, T> implements AutoCloseable {
new ReadOnlyObjectWrapper<>();
private boolean closed;
private boolean rowsInteractive = true;
private boolean columnSeparators;
private Set<String> filterColumns = Set.of();
private Set<String> filteredColumns = Set.of();
private List<SortKey> sortKeys = List.of();
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
private java.util.function.Consumer<String> sortRequest = id -> {};
private List<GroupColumn<T>> groupColumns = List.of();
private List<String> grouping = List.of();
private boolean groupingEnabled, defaultCollapsed = true;
private int inactiveHistoryLimit = 1000;
private GroupExpansion expansion = new GroupExpansion(true, 1000);
private GroupProjection.Snapshot<K, T> captured = GroupProjection.capture(List.of(), List.of());
private List<GroupProjection.Node<K, T>> groupTree = List.of();
private final Map<GroupPath, Button> disclosure = new HashMap<>();
private Runnable layoutCommitted = () -> {};
private java.util.function.Consumer<String> interactionMessage = ignored -> {};
private final ResultHeaderGestures gestures;
private final ResultScrollAlignment scrollAlignment;
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
TableResults(
HBox header, VBox body, List<ResultColumn> columns, Function<T, ResultRow> factory) {
HBox header,
VBox body,
List<ResultColumn> columns,
Function<T, ResultRow> factory,
javafx.scene.control.ScrollPane headerScroll,
javafx.scene.control.ScrollPane bodyScroll) {
requireFx();
this.header = header;
this.body = body;
this.factory = Objects.requireNonNull(factory);
gestures = new ResultHeaderGestures(this, header, body);
if (columns.isEmpty())
throw new IllegalArgumentException("At least one column is required");
for (var c : columns) {
@@ -62,11 +82,18 @@ public final class TableResults<K, T> implements AutoCloseable {
}
order = List.copyOf(definitions.keySet());
validateOrder(order);
scrollAlignment = new ResultScrollAlignment(header, body, headerScroll, bodyScroll);
drawHeader();
body.setOnMouseClicked(
e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
});
body.setOnMouseClicked(e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
});
}
void enableColumnSeparators() {
checkOpen();
columnSeparators = true;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
@@ -130,6 +157,28 @@ public final class TableResults<K, T> implements AutoCloseable {
markFilter(button, (String) cell.getUserData());
}
public void setSortKeys(List<SortKey> keys) {
checkOpen();
if (keys.size() > 1 || keys.stream().anyMatch(k -> !definitions.containsKey(k.columnId())))
throw new IllegalArgumentException("Unknown sort column");
sortKeys = List.copyOf(keys);
for (Node node : header.getChildren()) {
HBox cell = (HBox) node;
Label label = (Label) cell.getChildren().getFirst();
label.setText(headerText((String) cell.getUserData()));
label.setAccessibleText("Sort " + headerText((String) cell.getUserData()));
}
}
private String headerText(String id) {
return definitions.get(id).header()
+ sortKeys.stream()
.filter(k -> k.columnId().equals(id))
.map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓")
.findFirst()
.orElse("");
}
private void markFilter(Button button, String id) {
boolean active = filteredColumns.contains(id);
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
@@ -153,7 +202,7 @@ public final class TableResults<K, T> implements AutoCloseable {
* page.
*/
public void show(List<GridRow<K, T>> result) {
show(result, order, widths);
show(result, order, widths, groupingSetup());
}
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
@@ -161,7 +210,21 @@ public final class TableResults<K, T> implements AutoCloseable {
List<GridRow<K, T>> result,
List<String> nextOrder,
Map<String, ColumnWidth> nextWidths) {
show(result, nextOrder, nextWidths, groupingSetup());
}
public void show(
List<GridRow<K, T>> result,
List<String> nextOrder,
Map<String, ColumnWidth> nextWidths,
GroupingSetup nextGrouping) {
checkOpen();
validateGrouping(nextGrouping);
var nextCaptured = GroupProjection.capture(result, groupColumns);
var nextTree = GroupProjection.project(nextCaptured, nextGrouping.columns());
var nextExpansion = new GroupExpansion(defaultCollapsed, inactiveHistoryLimit);
nextExpansion.current(GroupProjection.paths(nextTree));
nextExpansion.restore(nextGrouping.choices());
nextOrder = List.copyOf(nextOrder);
validateOrder(nextOrder);
nextWidths = Map.copyOf(nextWidths);
@@ -213,8 +276,12 @@ public final class TableResults<K, T> implements AutoCloseable {
widths.clear();
widths.putAll(preparedWidths);
header.getChildren().setAll(nextHeader);
body.getChildren().setAll(entries.stream().map(e -> e.view().root()).toList());
markSelection();
captured = nextCaptured;
groupTree = nextTree;
grouping = nextGrouping.columns();
expansion = nextExpansion;
disclosure.clear();
drawGroups();
release(old);
}
@@ -226,6 +293,8 @@ public final class TableResults<K, T> implements AutoCloseable {
order = ids;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
resizeGroupHeadings();
layoutCommitted.run();
}
/**
@@ -243,8 +312,8 @@ public final class TableResults<K, T> implements AutoCloseable {
widths.put(
id,
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
applyWidths(widths);
layoutCommitted.run();
return applied;
}
@@ -271,7 +340,7 @@ public final class TableResults<K, T> implements AutoCloseable {
"Mapped fields must be distinct direct children");
}
private double width(String id) {
double width(String id) {
return width(id, widths);
}
@@ -288,15 +357,23 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
List<Node> nodes = new ArrayList<>();
for (String id : ordering) {
Label label = new Label(definitions.get(id).header());
Label label = new Label(headerText(id));
label.getStyleClass().add("column-header");
HBox cell = new HBox(label);
cell.getStyleClass().add("column-cell");
cell.setUserData(id);
cell.setOnMouseClicked(
event -> {
if (event.getButton() == MouseButton.PRIMARY) sortRequest.accept(id);
});
HBox.setHgrow(label, javafx.scene.layout.Priority.ALWAYS);
label.setMaxWidth(Double.MAX_VALUE);
label.setFocusTraversable(true);
label.setAccessibleRole(javafx.scene.AccessibleRole.BUTTON);
label.setAccessibleText("Sort " + definitions.get(id).header());
label.setOnKeyPressed(event -> {
if (event.getCode() == javafx.scene.input.KeyCode.ENTER
|| event.getCode() == javafx.scene.input.KeyCode.SPACE) {
sortRequest.accept(id);
event.consume();
}
});
if (filterColumns.contains(id)) {
SVGPath icon = new SVGPath();
icon.setContent("M0 0 H14 L9 6 V12 L5 14 V6 Z");
@@ -310,6 +387,16 @@ public final class TableResults<K, T> implements AutoCloseable {
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
cell.getChildren().add(button);
}
Region handle = new Region();
handle.getStyleClass().add("column-resize");
handle.setMinWidth(9);
handle.setPrefWidth(9);
handle.setMaxWidth(9);
handle.setCursor(javafx.scene.Cursor.E_RESIZE);
cell.getChildren().add(handle);
if (columnSeparators && !id.equals(ordering.getLast()))
cell.getChildren().add(ResultColumnSeparators.forHeader(cell));
gestures.header(cell, label, handle, id, () -> sortRequest.accept(id));
size(cell, width(id, sizes));
nodes.add(cell);
}
@@ -335,10 +422,25 @@ public final class TableResults<K, T> implements AutoCloseable {
size(field, width(id, sizes));
children.add(field);
}
for (Node child : view.root().getChildren())
if (!fields.contains(child)) children.add(child);
ResultColumnSeparators separators = null;
for (Node child : view.root().getChildren()) {
if (child instanceof ResultColumnSeparators existing) separators = existing;
else if (!fields.contains(child)) children.add(child);
}
if (columnSeparators) {
if (separators == null)
separators = new ResultColumnSeparators(view.root(), ordering.size());
separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray());
children.add(separators);
}
view.root().setSpacing(0);
view.root().getChildren().setAll(children);
if (!view.root().getChildren().equals(children)) {
Node focus =
view.root().getScene() == null ? null : view.root().getScene().getFocusOwner();
boolean restore = focus != null && descendant(view.root(), focus);
view.root().getChildren().setAll(children);
if (restore) focus.requestFocus();
}
}
private void markSelection() {
@@ -352,12 +454,322 @@ public final class TableResults<K, T> implements AutoCloseable {
e.view().root().getStyleClass().remove("selected");
if (selected) {
e.view().root().getStyleClass().add("selected");
loaded = e.row().model();
if (e.view().root().getParent() == body) loaded = e.row().model();
}
}
selectedElement.set(rowsInteractive ? loaded : null);
}
public void setOnLayoutCommitted(Runnable handler) {
layoutCommitted = Objects.requireNonNull(handler);
}
public void setOnInteractionMessage(java.util.function.Consumer<String> handler) {
interactionMessage = Objects.requireNonNull(handler);
}
void message(String text) {
interactionMessage.accept(text);
}
List<ResultColumn> definitions() {
return List.copyOf(definitions.values());
}
ResultHeaderGestures gestures() {
return gestures;
}
boolean canGroup(String id) {
return groupingEnabled && groupColumns.stream().anyMatch(c -> c.id().equals(id));
}
public List<String> groupingColumns() {
return grouping;
}
public boolean groupingEnabled() {
return groupingEnabled;
}
public GroupingSetup groupingSetup() {
return new GroupingSetup(grouping, expansion.snapshot());
}
public void configureGrouping(
List<GroupColumn<T>> columns,
boolean enabled,
List<String> defaults,
boolean collapsed,
int historyLimit) {
checkOpen();
if (!entries.isEmpty())
throw new IllegalStateException("Configure grouping before first publication");
if (historyLimit < 0
|| !definitions
.keySet()
.containsAll(columns.stream().map(GroupColumn::id).toList()))
throw new IllegalArgumentException("Unknown group column or invalid history limit");
var snapshot = GroupProjection.<K, T>capture(List.of(), columns);
GroupProjection.project(snapshot, defaults);
groupColumns = List.copyOf(columns);
captured = snapshot;
groupingEnabled = enabled;
grouping = List.copyOf(defaults);
defaultCollapsed = collapsed;
inactiveHistoryLimit = historyLimit;
expansion = new GroupExpansion(collapsed, historyLimit);
drawGroups();
}
public void validateGrouping(GroupingSetup setup) {
Set<String> ids =
groupColumns.stream()
.map(GroupColumn::id)
.collect(java.util.stream.Collectors.toSet());
if (!ids.containsAll(setup.columns()))
throw new IllegalArgumentException("Column has no grouping mapping");
for (var choice : setup.choices())
for (var part : choice.path().segments()) {
var column =
groupColumns.stream()
.filter(c -> c.id().equals(part.columnId()))
.findFirst()
.orElseThrow(() ->
new IllegalArgumentException(
"Unknown group path column; provide migration"));
column.validate(part.value());
}
}
public void setGroupingColumns(List<String> ids) {
checkOpen();
var setup = new GroupingSetup(ids, expansion.snapshot());
validateGrouping(setup);
var next = GroupProjection.project(captured, ids);
grouping = setup.columns();
groupTree = next;
expansion.current(GroupProjection.paths(next));
drawGroups();
layoutCommitted.run();
}
/** Refresh mapping snapshots only after an explicit application data-update signal. */
public void regroup() {
checkOpen();
var next = GroupProjection.capture(entries.stream().map(Entry::row).toList(), groupColumns);
var tree = GroupProjection.project(next, grouping);
captured = next;
groupTree = tree;
expansion.current(GroupProjection.paths(tree));
drawGroups();
}
public void setGroupingEnabled(boolean enabled) {
checkOpen();
groupingEnabled = enabled;
drawGroups();
}
public void resetExpansion() {
checkOpen();
expansion.reset();
drawGroups();
layoutCommitted.run();
}
public void setExpanded(GroupPath path, boolean expanded) {
checkOpen();
if (!GroupProjection.paths(groupTree).contains(path))
throw new IllegalArgumentException("Group is not on current page");
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
boolean hidesFocus = !expanded && focus != null && descendantContainsFocus(path, focus);
expansion.set(path, expanded);
drawGroups();
if (hidesFocus) disclosure.get(path).requestFocus();
layoutCommitted.run();
}
private boolean descendantContainsFocus(GroupPath path, Node focus) {
for (var row : entries) {
if (!descendant(row.view().root(), focus)) continue;
var values =
captured.rows().stream()
.filter(r -> Objects.equals(r.row().key(), row.row().key()))
.findFirst()
.orElseThrow()
.values();
return path.segments().stream()
.allMatch(p -> Objects.equals(values.get(p.columnId()).key(), p.value()));
}
return disclosure.entrySet().stream()
.anyMatch(e ->
descendant(e.getValue(), focus)
&& e.getKey().segments().size() > path.segments().size()
&& e.getKey()
.segments()
.subList(0, path.segments().size())
.equals(path.segments()));
}
private static boolean descendant(Node ancestor, Node node) {
for (Node current = node; current != null; current = current.getParent())
if (current == ancestor) return true;
return false;
}
private void drawGroups() {
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
boolean restoreFocus = focus != null && descendant(body, focus);
GroupPath focusedPath = restoreFocus ? focusPath(focus) : null;
disclosure.keySet().retainAll(new HashSet<>(GroupProjection.paths(groupTree)));
List<Node> nodes = new ArrayList<>();
Map<K, Node> rows = new HashMap<>();
entries.forEach(e -> rows.put(e.row().key(), e.view().root()));
if (!groupingEnabled || grouping.isEmpty())
entries.forEach(e -> nodes.add(e.view().root()));
else appendGroups(nodes, groupTree, rows);
if (!body.getChildren().equals(nodes)) body.getChildren().setAll(nodes);
if (restoreFocus) {
if (descendant(body, focus)) focus.requestFocus();
else {
Button destination = null;
if (focusedPath != null)
for (int level = 1; level <= focusedPath.segments().size(); level++) {
var candidate =
disclosure.get(
new GroupPath(focusedPath.segments().subList(0, level)));
if (candidate != null && candidate.getParent() == body)
destination = candidate;
if (candidate != null
&& !expansion.expanded(
new GroupPath(focusedPath.segments().subList(0, level))))
break;
}
if (destination != null) destination.requestFocus();
else if (!header.getChildren().isEmpty())
((HBox) header.getChildren().getFirst())
.getChildren()
.getFirst()
.requestFocus();
}
}
resizeGroupHeadings();
markSelection();
}
private GroupPath focusPath(Node focus) {
for (var entry : entries)
if (descendant(entry.view().root(), focus) && !grouping.isEmpty()) {
var values =
captured.rows().stream()
.filter(r -> Objects.equals(r.row().key(), entry.row().key()))
.findFirst()
.orElseThrow()
.values();
return new GroupPath(
grouping.stream()
.map(id -> new GroupPath.Segment(id, values.get(id).key()))
.toList());
}
return disclosure.entrySet().stream()
.filter(e -> descendant(e.getValue(), focus))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
private void appendGroups(
List<Node> nodes, List<GroupProjection.Node<K, T>> groups, Map<K, Node> rows) {
for (var group : groups) {
Button button =
disclosure.computeIfAbsent(
group.path(),
path -> {
Button control =
new Button() {
@Override
public Object queryAccessibleAttribute(
javafx.scene.AccessibleAttribute attribute,
Object... parameters) {
if (attribute
== javafx.scene.AccessibleAttribute
.EXPANDED)
return expansion.expanded(path);
if (attribute
== javafx.scene.AccessibleAttribute.LEAF)
return false;
return super.queryAccessibleAttribute(
attribute, parameters);
}
};
control.setAccessibleRole(javafx.scene.AccessibleRole.TREE_ITEM);
control.getStyleClass().add("group-heading");
control.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
control.setOnAction(
e -> setExpanded(path, !expansion.expanded(path)));
control.setOnKeyPressed(e -> {
if (e.getCode() == javafx.scene.input.KeyCode.LEFT) {
setExpanded(path, false);
e.consume();
}
if (e.getCode() == javafx.scene.input.KeyCode.RIGHT) {
setExpanded(path, true);
e.consume();
}
});
return control;
});
String id = group.path().segments().getLast().columnId();
boolean open = expansion.expanded(group.path());
button.setText(
(open ? "▾ " : "▸ ")
+ definitions.get(id).header()
+ ": "
+ group.label()
+ " — "
+ group.count()
+ " records");
button.setAccessibleText(
definitions.get(id).header()
+ ": "
+ group.label()
+ ", "
+ group.count()
+ " records, "
+ (open ? "expanded" : "collapsed"));
button.setPadding(
new javafx.geometry.Insets(
6, 8, 6, 8 + 24 * (group.path().segments().size() - 1)));
button.notifyAccessibleAttributeChanged(javafx.scene.AccessibleAttribute.EXPANDED);
nodes.add(button);
if (open) {
if (group.children().isEmpty())
group.rows().forEach(row -> nodes.add(rows.get(row.key())));
else appendGroups(nodes, group.children(), rows);
}
}
}
private void resizeGroupHeadings() {
double total = order.stream().mapToDouble(this::width).sum();
disclosure.values().forEach(button -> size(button, total));
}
void previewWidth(String id, ColumnWidth value) {
var next = new LinkedHashMap<>(widths);
next.put(id, value);
applyWidths(next);
}
private void applyWidths(Map<String, ColumnWidth> sizes) {
for (Node node : header.getChildren())
size((Region) node, width((String) node.getUserData(), sizes));
entries.forEach(e -> layoutRow(e.view(), order, sizes));
double total = order.stream().mapToDouble(id -> width(id, sizes)).sum();
disclosure.values().forEach(button -> size(button, total));
}
private void release(List<Entry<K, T>> retired) {
RuntimeException aggregate = null;
for (var e : retired) {
@@ -394,6 +806,12 @@ public final class TableResults<K, T> implements AutoCloseable {
body.setOnMouseClicked(null);
selectedKey.set(null);
selectedElement.set(null);
captured = GroupProjection.capture(List.of(), List.of());
groupTree = List.of();
disclosure.clear();
expansion.reset();
gestures.close();
scrollAlignment.close();
release(old);
}
}
@@ -835,7 +835,7 @@ public class ViewModel {
* @return {@code true} when the element is a simple value
*/
private static boolean isSimpleValue(Class<?> type) {
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum()) {
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum() || type.isRecord()) {
return true;
}
if (type.isPrimitive()) {