diff --git a/README.md b/README.md
index 9ca48ad..7ab8c52 100644
--- a/README.md
+++ b/README.md
@@ -87,7 +87,7 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
## Use a release from Maven
-The main branch builds `1.1-SNAPSHOT`. For the published `1.0` release,
+The main branch builds `1.0.1`. For the published `1.0.1` release,
add the Gitea registry to the consuming project's POM and use the release
version for the module you need:
@@ -103,7 +103,7 @@ version for the module you need:
de.neitzel.lib
fx
- 1.0
+ 1.0.1
```
diff --git a/core/pom.xml b/core/pom.xml
index 2159d05..faf5a71 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.lib
neitzellib
- 1.1-SNAPSHOT
+ 1.0.1
core
diff --git a/data-grid-jdbc/pom.xml b/data-grid-jdbc/pom.xml
index 01b0cf8..701d841 100644
--- a/data-grid-jdbc/pom.xml
+++ b/data-grid-jdbc/pom.xml
@@ -1,5 +1,5 @@
-4.0.0de.neitzel.libneitzellib1.1-SNAPSHOT
+4.0.0de.neitzel.libneitzellib1.0.1
data-grid-jdbcOptional mapped JDBC grid source
de.neitzel.libdata-grid${project.version}
com.h2databaseh22.5.252test
diff --git a/data-grid/README.md b/data-grid/README.md
index e536c5d..c32d38e 100644
--- a/data-grid/README.md
+++ b/data-grid/README.md
@@ -37,3 +37,16 @@ Collection changes do not automatically trigger requests in this slice. Call ref
## Saved setups
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
+
+## Page-local grouping and application configuration
+
+`GroupColumn`, `GroupProjection`, `GroupPath` and `GroupExpansion` capture typed
+values and project a returned page without fetching or mutating source order.
+GroupingSetup extends GridSetup v2 with ordered columns and explicit path choices;
+old constructors/version-one documents remain supported. Group expansion retains
+current choices plus a configurable inactive LRU history, never historical rows.
+
+`GridApplicationConfiguration` owns debounced immutable setup snapshots and queued
+saves after views detach. `GridSetupStore` requires revision-aware conditional
+writes. The default optional JSON/file implementation is in Gson; no toolkit or
+JSON dependency is introduced here. See the [integration guide](../fx/docs/data-grid-layout.md).
diff --git a/data-grid/pom.xml b/data-grid/pom.xml
index cc432ad..b212fb6 100644
--- a/data-grid/pom.xml
+++ b/data-grid/pom.xml
@@ -1,6 +1,6 @@
4.0.0
- de.neitzel.libneitzellib1.1-SNAPSHOT
+ de.neitzel.libneitzellib1.0.1
data-grid
Toolkit-independent filter, query and grid setup contracts
diff --git a/data-grid/src/main/java/de/neitzel/grid/GridApplicationConfiguration.java b/data-grid/src/main/java/de/neitzel/grid/GridApplicationConfiguration.java
new file mode 100644
index 0000000..cafe0af
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GridApplicationConfiguration.java
@@ -0,0 +1,378 @@
+package de.neitzel.grid;
+
+import java.time.Duration;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.function.Consumer;
+
+/**
+ * Application-owned, toolkit-independent save coordination. Accept immutable snapshots on the owner
+ * thread; this service serializes blocking store work on its scheduled worker. No I/O runs in
+ * construction. A detached view does not own or discard already accepted saves.
+ */
+public final class GridApplicationConfiguration {
+ public enum Phase {
+ IDLE,
+ LOADING,
+ PENDING,
+ SAVING,
+ SAVED,
+ ERROR,
+ CONFLICT,
+ CLOSED
+ }
+
+ public record State(Phase phase, long generation, boolean dirty, Throwable error) {}
+
+ public record Loaded(
+ GridSetupStore.Key key, GridSetupStore.Stored stored, long storageVersion) {}
+
+ private record Pending(long generation, GridSetup setup, boolean overwrite) {}
+
+ private static final class Slot {
+ final java.util.concurrent.locks.ReentrantLock io =
+ new java.util.concurrent.locks.ReentrantLock();
+ String revision;
+ long generation, storageVersion;
+ Pending pending;
+ ScheduledFuture> delay;
+ State state = new State(Phase.IDLE, 0, false, null);
+ final List> listeners = new ArrayList<>();
+ }
+
+ @lombok.Getter
+ @lombok.experimental.Accessors(fluent = true)
+ private final String applicationName;
+
+ private final GridSetupStore store;
+ private final ScheduledExecutorService worker;
+ private final boolean ownsWorker;
+ private final long debounceMillis;
+ private final Map slots = new LinkedHashMap<>();
+ private boolean closing, closed;
+
+ public GridApplicationConfiguration(String applicationName, GridSetupStore store) {
+ this(
+ applicationName,
+ store,
+ Duration.ofMillis(500),
+ Executors.newSingleThreadScheduledExecutor(r -> {
+ Thread thread = new Thread(r, "grid-setup-storage");
+ thread.setDaemon(true);
+ return thread;
+ }),
+ true);
+ }
+
+ public GridApplicationConfiguration(
+ String applicationName,
+ GridSetupStore store,
+ Duration debounce,
+ ScheduledExecutorService worker,
+ boolean ownsWorker) {
+ if (applicationName == null
+ || applicationName.isBlank()
+ || applicationName.equals(".")
+ || applicationName.equals("..")
+ || applicationName.contains("/")
+ || applicationName.contains("\\")
+ || applicationName.indexOf(0) >= 0)
+ throw new IllegalArgumentException("Application name must be a directory name");
+ this.applicationName = applicationName;
+ this.store = Objects.requireNonNull(store);
+ debounceMillis = Objects.requireNonNull(debounce).toMillis();
+ if (debounceMillis < 0) throw new IllegalArgumentException("Negative debounce");
+ this.worker = Objects.requireNonNull(worker);
+ this.ownsWorker = ownsWorker;
+ }
+
+ private Slot slot(GridSetupStore.Key key) {
+ return slots.computeIfAbsent(key, k -> new Slot());
+ }
+
+ private void requireOpen() {
+ if (closed || closing) throw new IllegalStateException("Configuration is closing/closed");
+ }
+
+ public synchronized State state(GridSetupStore.Key key) {
+ return slot(key).state;
+ }
+
+ /** Listener callbacks may run on the storage thread; an FX adapter must dispatch them. */
+ public synchronized AutoCloseable observe(GridSetupStore.Key key, Consumer listener) {
+ requireOpen();
+ var s = slot(key);
+ s.listeners.add(listener);
+ listener.accept(s.state);
+ return () -> {
+ synchronized (this) {
+ s.listeners.remove(listener);
+ }
+ };
+ }
+
+ private void emit(Slot slot, Phase phase, Throwable error) {
+ slot.state = new State(phase, slot.generation, slot.pending != null, error);
+ for (var listener : List.copyOf(slot.listeners)) listener.accept(slot.state);
+ }
+
+ public CompletionStage loadAsync(GridSetupStore.Key key) {
+ synchronized (this) {
+ requireOpen();
+ emit(slot(key), Phase.LOADING, null);
+ }
+ return submit(() -> {
+ Slot target;
+ synchronized (this) {
+ target = slot(key);
+ }
+ target.io.lock();
+ try {
+ GridSetupStore.Stored loaded = store.load(key);
+ synchronized (this) {
+ return new Loaded(key, loaded, target.storageVersion);
+ }
+ } catch (Exception failure) {
+ synchronized (this) {
+ emit(target, Phase.ERROR, failure);
+ }
+ throw failure;
+ } finally {
+ target.io.unlock();
+ }
+ });
+ }
+
+ /** Called only after the grid has successfully validated/published this loaded setup. */
+ public synchronized void adopt(Loaded loaded, long discardedOwnGeneration) {
+ requireOpen();
+ Slot s = slot(loaded.key());
+ if (s.storageVersion == loaded.storageVersion()) s.revision = loaded.stored().revision();
+ if (s.pending != null && s.pending.generation() == discardedOwnGeneration) {
+ s.pending = null;
+ if (s.delay != null) s.delay.cancel(false);
+ }
+ emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
+ }
+
+ public synchronized long accept(GridSetupStore.Key key, GridSetup setup, Object owner) {
+ return accept(key, setup, owner, false);
+ }
+
+ public synchronized long acceptOverwrite(
+ GridSetupStore.Key key, GridSetup setup, Object owner) {
+ return accept(key, setup, owner, true);
+ }
+
+ private long accept(GridSetupStore.Key key, GridSetup setup, Object owner, boolean overwrite) {
+ requireOpen();
+ Slot s = slot(key);
+ // Owner is an attribution token, never retained: it may be a closed UI view.
+ Objects.requireNonNull(owner);
+ s.pending = new Pending(++s.generation, Objects.requireNonNull(setup), overwrite);
+ if (s.delay != null) s.delay.cancel(false);
+ emit(s, Phase.PENDING, null);
+ long acceptedGeneration = s.generation;
+ s.delay =
+ worker.schedule(
+ () -> {
+ try {
+ write(key, acceptedGeneration);
+ } catch (Exception ignored) {
+ /* retained and exposed through state */
+ }
+ },
+ debounceMillis,
+ TimeUnit.MILLISECONDS);
+ return s.generation;
+ }
+
+ /** Explicit user recovery: still performs a conditional write against a fresh revision. */
+ public CompletionStage overwriteAsync(
+ GridSetupStore.Key key, GridSetup setup, Object owner) {
+ synchronized (this) {
+ accept(key, setup, owner, true);
+ }
+ return retryAsync(key);
+ }
+
+ public CompletionStage retryAsync(GridSetupStore.Key key) {
+ synchronized (this) {
+ requireOpen();
+ Slot s = slot(key);
+ if (s.delay != null) s.delay.cancel(false);
+ }
+ return submit(() -> {
+ write(key);
+ return null;
+ });
+ }
+
+ private void write(GridSetupStore.Key key) throws Exception {
+ write(key, -1);
+ }
+
+ private void write(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
+ Slot target;
+ synchronized (this) {
+ target = slot(key);
+ }
+ target.io.lock();
+ try {
+ writeLocked(key, scheduledGeneration);
+ } finally {
+ target.io.unlock();
+ }
+ }
+
+ private void writeLocked(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
+ Pending pending;
+ String expected;
+ synchronized (this) {
+ Slot s = slot(key);
+ pending = s.pending;
+ if (pending == null
+ || closed
+ || (scheduledGeneration >= 0 && pending.generation() != scheduledGeneration))
+ return;
+ expected = s.revision;
+ emit(s, Phase.SAVING, null);
+ }
+ try {
+ if (pending.overwrite()) expected = store.revision(key);
+ if (expected == null)
+ throw new IllegalStateException(
+ "Load or explicitly reset the saved setup before writing");
+ String revision = store.save(key, expected, pending.setup());
+ synchronized (this) {
+ Slot s = slot(key);
+ s.revision = revision;
+ s.storageVersion++;
+ if (s.pending != null && s.pending.generation() == pending.generation())
+ s.pending = null;
+ emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
+ }
+ } catch (Exception failure) {
+ synchronized (this) {
+ emit(
+ slot(key),
+ failure instanceof GridSetupStore.Conflict ? Phase.CONFLICT : Phase.ERROR,
+ failure);
+ }
+ throw failure;
+ }
+ }
+
+ public CompletionStage flushAsync() {
+ synchronized (this) {
+ if (closed) return CompletableFuture.completedFuture(null);
+ cancelDelays();
+ }
+ return submit(() -> {
+ flush();
+ return null;
+ });
+ }
+
+ private void cancelDelays() {
+ slots.values()
+ .forEach(s -> {
+ if (s.delay != null) s.delay.cancel(false);
+ });
+ }
+
+ private void flush() throws Exception {
+ while (true) {
+ List pending;
+ synchronized (this) {
+ pending =
+ slots.entrySet().stream()
+ .filter(e -> e.getValue().pending != null)
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+ if (pending.isEmpty()) return;
+ for (var key : pending) write(key);
+ }
+ }
+
+ public CompletionStage closeAsync() {
+ synchronized (this) {
+ if (closed) return CompletableFuture.completedFuture(null);
+ if (closing) throw new IllegalStateException("Close already pending");
+ closing = true;
+ cancelDelays();
+ }
+ return submit(() -> {
+ try {
+ flush();
+ finishClose();
+ return null;
+ } catch (Exception failure) {
+ synchronized (this) {
+ closing = false;
+ }
+ throw failure;
+ }
+ });
+ }
+
+ /** Explicit quit-without-saving path. It cannot undo a write already committed. */
+ public CompletionStage discardAndCloseAsync() {
+ synchronized (this) {
+ if (closed) return CompletableFuture.completedFuture(null);
+ closing = true;
+ cancelDelays();
+ slots.values().forEach(s -> s.pending = null);
+ }
+ return submit(() -> {
+ finishClose();
+ return null;
+ });
+ }
+
+ private void finishClose() {
+ // A supplied scheduler may have multiple workers. Drain all in-flight slot I/O
+ // before publishing CLOSED, including an already-committing discarded write.
+ List targets;
+ synchronized (this) {
+ targets = List.copyOf(slots.values());
+ }
+ targets.forEach(s -> s.io.lock());
+ try {
+ finishCloseLocked();
+ } finally {
+ for (int index = targets.size() - 1; index >= 0; index--)
+ targets.get(index).io.unlock();
+ }
+ }
+
+ private void finishCloseLocked() {
+ synchronized (this) {
+ closed = true;
+ closing = false;
+ slots.values()
+ .forEach(s -> {
+ emit(s, Phase.CLOSED, null);
+ s.listeners.clear();
+ });
+ }
+ if (ownsWorker) worker.shutdown();
+ }
+
+ private CompletionStage submit(Callable action) {
+ CompletableFuture future = new CompletableFuture<>();
+ try {
+ worker.execute(() -> {
+ try {
+ future.complete(action.call());
+ } catch (Exception failure) {
+ future.completeExceptionally(failure);
+ }
+ });
+ } catch (RejectedExecutionException failure) {
+ future.completeExceptionally(failure);
+ }
+ return future;
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java b/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java
index 593648c..63e8ad8 100644
--- a/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java
+++ b/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java
@@ -57,7 +57,7 @@ public record GridDefinition(String id, int version, List columns) {
Consumer validateFilter) {
Objects.requireNonNull(input);
Objects.requireNonNull(migrations);
- if (input.formatVersion() != 1)
+ if (input.formatVersion() != 1 && input.formatVersion() != 2)
throw new IllegalArgumentException(
"Unsupported setup format version: " + input.formatVersion());
if (!id.equals(input.definitionId()))
@@ -75,10 +75,10 @@ public record GridDefinition(String id, int version, List columns) {
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
if (!id.equals(setup.definitionId())
|| setup.definitionVersion() != old + 1
- || setup.formatVersion() != 1)
+ || setup.formatVersion() != input.formatVersion())
throw new IllegalArgumentException(
"Migration must preserve identity/format and advance one definition"
- + " version");
+ + " version");
}
Map definitions = new LinkedHashMap<>();
columns.forEach(c -> definitions.put(c.id(), c));
@@ -123,7 +123,15 @@ public record GridDefinition(String id, int version, List columns) {
source.validate(setup.page());
setup.filters().forEach(validateFilter);
return new Prepared(
- new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
+ new GridSetup(
+ setup.formatVersion(),
+ id,
+ version,
+ next,
+ setup.sort(),
+ setup.filters(),
+ setup.page(),
+ setup.grouping()),
adjustments);
}
}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GridSetup.java b/data-grid/src/main/java/de/neitzel/grid/GridSetup.java
index d9247ad..1c72614 100644
--- a/data-grid/src/main/java/de/neitzel/grid/GridSetup.java
+++ b/data-grid/src/main/java/de/neitzel/grid/GridSetup.java
@@ -10,7 +10,20 @@ public record GridSetup(
List columns,
List sort,
List filters,
- PageRequest page) {
+ PageRequest page,
+ GroupingSetup grouping) {
+ /** Source/binary-compatible constructor for version-one clients. */
+ public GridSetup(
+ int formatVersion,
+ String definitionId,
+ int definitionVersion,
+ List columns,
+ List sort,
+ List filters,
+ PageRequest page) {
+ this(formatVersion, definitionId, definitionVersion, columns, sort, filters, page, null);
+ }
+
public record ColumnState(String id, String type, ColumnWidth width) {
/** Older callers must supply a definition type before persistence/restoration. */
public ColumnState(String id, ColumnWidth width) {
@@ -43,6 +56,17 @@ public record GridSetup(
for (var f : filters)
if (!ids.contains(f.columnId()))
throw new IllegalArgumentException("Unknown filter column");
+ if (formatVersion == 2 && grouping == null)
+ throw new IllegalArgumentException("Version two requires grouping preferences");
+ if (grouping != null) {
+ for (String id : grouping.columns())
+ if (!ids.contains(id))
+ throw new IllegalArgumentException("Unknown grouping column");
+ for (var choice : grouping.choices())
+ for (var segment : choice.path().segments())
+ if (!ids.contains(segment.columnId()))
+ throw new IllegalArgumentException("Unknown group path column");
+ }
new GridQuery(filters, sort, page);
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
throw new IllegalArgumentException("Setups must start on the first page");
diff --git a/data-grid/src/main/java/de/neitzel/grid/GridSetupStore.java b/data-grid/src/main/java/de/neitzel/grid/GridSetupStore.java
new file mode 100644
index 0000000..f53c15d
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GridSetupStore.java
@@ -0,0 +1,38 @@
+package de.neitzel.grid;
+
+import java.io.IOException;
+import java.util.Objects;
+
+/** Blocking store port. The configuration service calls it off the UI thread. */
+public interface GridSetupStore {
+ record Key(String gridId, String context) {
+ public Key {
+ Checks.id(gridId);
+ if (context != null) Checks.id(context);
+ }
+ }
+
+ record Stored(GridSetup setup, String revision) {
+ public Stored {
+ Objects.requireNonNull(revision);
+ }
+ }
+
+ Stored load(Key key) throws IOException;
+
+ /**
+ * Revision alone must remain readable even when setup decoding fails, for explicit recovery.
+ */
+ String revision(Key key) throws IOException;
+
+ /** Atomically compare revision and replace the entire setup; never a blind overwrite. */
+ String save(Key key, String expectedRevision, GridSetup setup) throws IOException;
+
+ final class Conflict extends IOException {
+ public Conflict() {
+ super(
+ "Saved grid setup changed in another application instance. Reload or explicitly"
+ + " overwrite.");
+ }
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GroupColumn.java b/data-grid/src/main/java/de/neitzel/grid/GroupColumn.java
new file mode 100644
index 0000000..109f0ea
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GroupColumn.java
@@ -0,0 +1,104 @@
+package de.neitzel.grid;
+
+import java.util.*;
+import java.util.function.Function;
+
+/** Explicit owner-thread mapping. Labels never determine identity or ordering. */
+public record GroupColumn(
+ String id,
+ MemoryColumn.Kind kind,
+ Function read,
+ Function label) {
+ public GroupColumn {
+ Checks.id(id);
+ Objects.requireNonNull(kind);
+ Objects.requireNonNull(read);
+ Objects.requireNonNull(label);
+ }
+
+ public static GroupColumn text(String id, Function reader) {
+ return new GroupColumn<>(
+ id,
+ MemoryColumn.Kind.TEXT,
+ row -> {
+ String value = reader.apply(row);
+ return value == null ? null : new FilterValue.Text(value);
+ },
+ GroupColumn::display);
+ }
+
+ public static GroupColumn integer(String id, Function reader) {
+ return new GroupColumn<>(
+ id,
+ MemoryColumn.Kind.INTEGER,
+ row -> {
+ Long value = reader.apply(row);
+ return value == null ? null : new FilterValue.IntegerValue(value);
+ },
+ GroupColumn::display);
+ }
+
+ public static GroupColumn decimal(String id, Function reader) {
+ return new GroupColumn<>(
+ id,
+ MemoryColumn.Kind.DECIMAL,
+ row -> {
+ var value = reader.apply(row);
+ return value == null ? null : new FilterValue.Decimal(value);
+ },
+ GroupColumn::display);
+ }
+
+ public static GroupColumn bool(String id, Function reader) {
+ return new GroupColumn<>(
+ id,
+ MemoryColumn.Kind.BOOLEAN,
+ row -> {
+ Boolean value = reader.apply(row);
+ return value == null ? null : new FilterValue.BooleanValue(value);
+ },
+ GroupColumn::display);
+ }
+
+ public void validate(FilterValue value) {
+ if (value == null) return;
+ boolean valid =
+ switch (kind) {
+ case TEXT -> value instanceof FilterValue.Text;
+ case INTEGER -> value instanceof FilterValue.IntegerValue;
+ case DECIMAL -> value instanceof FilterValue.Decimal;
+ case BOOLEAN -> value instanceof FilterValue.BooleanValue;
+ };
+ if (!valid) throw new IllegalArgumentException("Grouping value type changed: " + id);
+ }
+
+ public static String display(FilterValue value) {
+ return switch (value) {
+ case null -> "(Missing)";
+ case FilterValue.Text t -> t.value().isEmpty() ? "(Empty)" : t.value();
+ case FilterValue.IntegerValue i -> Long.toString(i.value());
+ case FilterValue.Decimal d -> d.value().toPlainString();
+ case FilterValue.BooleanValue b -> Boolean.toString(b.value());
+ };
+ }
+
+ public static int compare(FilterValue a, FilterValue b) {
+ if (a == null) return b == null ? 0 : 1;
+ if (b == null) return -1;
+ return switch (a) {
+ case FilterValue.Text t -> {
+ String right = ((FilterValue.Text) b).value();
+ int order =
+ t.value()
+ .toLowerCase(Locale.ROOT)
+ .compareTo(right.toLowerCase(Locale.ROOT));
+ yield order == 0 ? t.value().compareTo(right) : order;
+ }
+ case FilterValue.IntegerValue i ->
+ Long.compare(i.value(), ((FilterValue.IntegerValue) b).value());
+ case FilterValue.Decimal d -> d.value().compareTo(((FilterValue.Decimal) b).value());
+ case FilterValue.BooleanValue v ->
+ Boolean.compare(v.value(), ((FilterValue.BooleanValue) b).value());
+ };
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GroupExpansion.java b/data-grid/src/main/java/de/neitzel/grid/GroupExpansion.java
new file mode 100644
index 0000000..5264d3c
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GroupExpansion.java
@@ -0,0 +1,69 @@
+package de.neitzel.grid;
+
+import java.util.*;
+
+/** Owner-thread expansion history retaining scalar paths, never rows/models. */
+public final class GroupExpansion {
+ private final LinkedHashMap choices = new LinkedHashMap<>();
+ private Set current = Set.of();
+ private boolean defaultCollapsed;
+ private int inactiveLimit;
+
+ public GroupExpansion(boolean defaultCollapsed, int inactiveLimit) {
+ configure(defaultCollapsed, inactiveLimit);
+ }
+
+ public void configure(boolean collapsed, int limit) {
+ if (limit < 0) throw new IllegalArgumentException("Negative expansion history capacity");
+ defaultCollapsed = collapsed;
+ inactiveLimit = limit;
+ trim();
+ }
+
+ public boolean expanded(GroupPath path) {
+ return choices.getOrDefault(path, !defaultCollapsed);
+ }
+
+ public void set(GroupPath path, boolean expanded) {
+ choices.remove(path);
+ choices.put(path, expanded);
+ trim();
+ }
+
+ public void current(Collection paths) {
+ current = Set.copyOf(paths);
+ for (var path : paths)
+ if (choices.containsKey(path)) {
+ boolean choice = choices.remove(path);
+ choices.put(path, choice);
+ }
+ trim();
+ }
+
+ public List snapshot() {
+ return choices.entrySet().stream()
+ .map(e -> new GroupingSetup.Choice(e.getKey(), e.getValue()))
+ .toList();
+ }
+
+ public void restore(List saved) {
+ choices.clear();
+ saved.forEach(c -> choices.put(c.path(), c.expanded()));
+ trim();
+ }
+
+ public void reset() {
+ choices.clear();
+ }
+
+ private void trim() {
+ int inactive = (int) choices.keySet().stream().filter(p -> !current.contains(p)).count();
+ for (var iterator = choices.keySet().iterator();
+ inactive > inactiveLimit && iterator.hasNext(); ) {
+ if (!current.contains(iterator.next())) {
+ iterator.remove();
+ inactive--;
+ }
+ }
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GroupPath.java b/data-grid/src/main/java/de/neitzel/grid/GroupPath.java
new file mode 100644
index 0000000..ce4ffee
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GroupPath.java
@@ -0,0 +1,27 @@
+package de.neitzel.grid;
+
+import java.util.*;
+
+/** Stable typed identity, independent of labels, page position and row identity. */
+public record GroupPath(List segments) {
+ public record Segment(String columnId, FilterValue value) {
+ public Segment {
+ Checks.id(columnId);
+ }
+ }
+
+ public GroupPath {
+ segments = List.copyOf(segments);
+ if (segments.isEmpty()) throw new IllegalArgumentException("Empty group path");
+ Set seen = new HashSet<>();
+ for (var segment : segments)
+ if (!seen.add(segment.columnId()))
+ throw new IllegalArgumentException("Repeated group column");
+ }
+
+ public GroupPath child(String column, FilterValue value) {
+ var next = new ArrayList<>(segments);
+ next.add(new Segment(column, value));
+ return new GroupPath(next);
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GroupProjection.java b/data-grid/src/main/java/de/neitzel/grid/GroupProjection.java
new file mode 100644
index 0000000..117ffc9
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GroupProjection.java
@@ -0,0 +1,105 @@
+package de.neitzel.grid;
+
+import java.util.*;
+
+/** Pure current-page projection. Capture all eligible scalar values before publishing a page. */
+public final class GroupProjection {
+ private GroupProjection() {}
+
+ public record Value(FilterValue key, String label) {
+ public Value {
+ Objects.requireNonNull(label);
+ }
+ }
+
+ public record Captured(GridRow row, Map values) {
+ public Captured {
+ Objects.requireNonNull(row);
+ values = Map.copyOf(values);
+ }
+ }
+
+ public record Snapshot(List> rows, Map> columns) {
+ public Snapshot {
+ rows = List.copyOf(rows);
+ columns = Map.copyOf(columns);
+ }
+ }
+
+ public record Node(
+ GroupPath path, String label, List> children, List> rows) {
+ public Node {
+ children = List.copyOf(children);
+ rows = List.copyOf(rows);
+ }
+
+ public int count() {
+ return rows.size();
+ }
+ }
+
+ public static Snapshot capture(
+ List> rows, Collection> columns) {
+ Map> mappings = new LinkedHashMap<>();
+ for (var c : columns)
+ if (mappings.putIfAbsent(c.id(), c) != null)
+ throw new IllegalArgumentException("Duplicate group mapping");
+ List> captured = new ArrayList<>();
+ for (var row : rows) {
+ Map values = new LinkedHashMap<>();
+ for (var c : columns) {
+ FilterValue key = c.read().apply(row.model());
+ c.validate(key);
+ values.put(c.id(), new Value(key, c.label().apply(key)));
+ }
+ captured.add(new Captured<>(row, values));
+ }
+ return new Snapshot<>(captured, mappings);
+ }
+
+ public static List> project(Snapshot snapshot, List order) {
+ if (new HashSet<>(order).size() != order.size()
+ || !snapshot.columns().keySet().containsAll(order))
+ throw new IllegalArgumentException("Unknown/repeated grouping column");
+ return build(snapshot.rows(), order, 0, null);
+ }
+
+ private static List> build(
+ List> rows, List order, int depth, GroupPath parent) {
+ if (depth == order.size()) return List.of();
+ String id = order.get(depth);
+ Map>> buckets = new LinkedHashMap<>();
+ for (var row : rows)
+ buckets.computeIfAbsent(row.values().get(id).key(), ignored -> new ArrayList<>())
+ .add(row);
+ List keys = new ArrayList<>(buckets.keySet());
+ keys.sort(GroupColumn::compare);
+ List> nodes = new ArrayList<>();
+ for (var key : keys) {
+ var bucket = buckets.get(key);
+ String label = bucket.getFirst().values().get(id).label();
+ if (bucket.stream().anyMatch(r -> !r.values().get(id).label().equals(label)))
+ throw new IllegalArgumentException("Inconsistent label for group value in " + id);
+ GroupPath path =
+ parent == null
+ ? new GroupPath(List.of(new GroupPath.Segment(id, key)))
+ : parent.child(id, key);
+ nodes.add(
+ new Node<>(
+ path,
+ label,
+ build(bucket, order, depth + 1, path),
+ bucket.stream().map(Captured::row).toList()));
+ }
+ return List.copyOf(nodes);
+ }
+
+ public static List paths(List> nodes) {
+ List paths = new ArrayList<>();
+ for (var node : nodes) {
+ paths.add(node.path());
+ paths.addAll(paths(node.children()));
+ }
+ return paths;
+ }
+}
diff --git a/data-grid/src/main/java/de/neitzel/grid/GroupingSetup.java b/data-grid/src/main/java/de/neitzel/grid/GroupingSetup.java
new file mode 100644
index 0000000..02a1ec8
--- /dev/null
+++ b/data-grid/src/main/java/de/neitzel/grid/GroupingSetup.java
@@ -0,0 +1,30 @@
+package de.neitzel.grid;
+
+import java.util.*;
+
+/** Committed grouping preferences. Choices are ordered least-recently to most-recently used. */
+public record GroupingSetup(List columns, List choices) {
+ public record Choice(GroupPath path, boolean expanded) {
+ public Choice {
+ Objects.requireNonNull(path);
+ }
+ }
+
+ public GroupingSetup {
+ columns = List.copyOf(columns);
+ choices = List.copyOf(choices);
+ Set ids = new HashSet<>();
+ for (String id : columns) {
+ Checks.id(id);
+ if (!ids.add(id)) throw new IllegalArgumentException("Repeated grouping column");
+ }
+ Set paths = new HashSet<>();
+ for (var choice : choices)
+ if (!paths.add(choice.path()))
+ throw new IllegalArgumentException("Repeated expansion choice");
+ }
+
+ public static GroupingSetup empty() {
+ return new GroupingSetup(List.of(), List.of());
+ }
+}
diff --git a/data-grid/src/test/java/de/neitzel/grid/GridConfigurationTest.java b/data-grid/src/test/java/de/neitzel/grid/GridConfigurationTest.java
new file mode 100644
index 0000000..8d34b5d
--- /dev/null
+++ b/data-grid/src/test/java/de/neitzel/grid/GridConfigurationTest.java
@@ -0,0 +1,294 @@
+package de.neitzel.grid;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.*;
+import java.util.concurrent.*;
+
+class GridConfigurationTest {
+ static GridSetup setup(double width) {
+ return new GridSetup(
+ 2,
+ "records",
+ 1,
+ List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Explicit(width))),
+ List.of(),
+ List.of(),
+ new PageRequest.Paged(0, 50),
+ new GroupingSetup(List.of("type"), List.of()));
+ }
+
+ static final GridSetupStore.Key KEY = new GridSetupStore.Key("records", null);
+
+ static final class MemoryStore implements GridSetupStore {
+ GridSetup value;
+ int revision, writes;
+ boolean fail;
+
+ public synchronized Stored load(Key key) {
+ return new Stored(value, Integer.toString(revision));
+ }
+
+ public synchronized String revision(Key key) {
+ return Integer.toString(revision);
+ }
+
+ public synchronized String save(Key key, String expected, GridSetup setup)
+ throws IOException {
+ if (fail) throw new IOException("disk unavailable");
+ if (!expected.equals(Integer.toString(revision))) throw new Conflict();
+ value = setup;
+ writes++;
+ return Integer.toString(++revision);
+ }
+ }
+
+ static GridApplicationConfiguration config(MemoryStore store) {
+ return new GridApplicationConfiguration(
+ "Example",
+ store,
+ Duration.ofHours(1),
+ Executors.newSingleThreadScheduledExecutor(),
+ true);
+ }
+
+ static void load(GridApplicationConfiguration config) throws Exception {
+ config.adopt(config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS), -1);
+ }
+
+ @Test
+ void coalescesWholeSnapshotsAndDoesNotSaveUnchangedLoadsOrClose() throws Exception {
+ var store = new MemoryStore();
+ var config = config(store);
+ load(config);
+ assertEquals(0, store.writes);
+ config.accept(KEY, setup(100), new Object());
+ config.accept(KEY, setup(200), new Object());
+ config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(setup(200), store.value);
+ assertEquals(1, store.writes);
+ config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(1, store.writes);
+ }
+
+ @Test
+ void failedCloseRetainsLatestUnsavedStateAndCanRetry() throws Exception {
+ var store = new MemoryStore();
+ var config = config(store);
+ load(config);
+ config.accept(KEY, setup(100), this);
+ config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ store.fail = true;
+ config.accept(KEY, setup(200), this);
+ assertThrows(
+ ExecutionException.class,
+ () -> config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(setup(100), store.value);
+ assertTrue(config.state(KEY).dirty());
+ store.fail = false;
+ config.retryAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(setup(200), store.value);
+ config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void reloadCannotDiscardAnotherViewsNewerGeneration() throws Exception {
+ var store = new MemoryStore();
+ var config = config(store);
+ load(config);
+ long old = config.accept(KEY, setup(100), this);
+ var read = config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
+ config.accept(KEY, setup(200), new Object());
+ config.adopt(read, old);
+ assertTrue(config.state(KEY).dirty());
+ config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(setup(200), store.value);
+ config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void crossInstanceConflictRequiresExplicitOverwriteAndDiscardCloseDoesNotWrite()
+ throws Exception {
+ var store = new MemoryStore();
+ var first = config(store);
+ var second = config(store);
+ load(first);
+ load(second);
+ first.accept(KEY, setup(100), first);
+ first.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ second.accept(KEY, setup(200), second);
+ assertThrows(
+ ExecutionException.class,
+ () -> second.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(GridApplicationConfiguration.Phase.CONFLICT, second.state(KEY).phase());
+ second.overwriteAsync(KEY, setup(200), second)
+ .toCompletableFuture()
+ .get(5, TimeUnit.SECONDS);
+ assertEquals(setup(200), store.value);
+ second.accept(KEY, setup(300), second);
+ second.discardAndCloseAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(setup(200), store.value);
+ first.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void debounceWaitsForQuietPeriodRatherThanSavingEveryChange() throws Exception {
+ var store = new MemoryStore();
+ var clock = new Clock();
+ var config =
+ new GridApplicationConfiguration(
+ "Example", store, Duration.ofMillis(500), clock, false);
+ load(config);
+ config.accept(KEY, setup(100), this);
+ clock.advance(499);
+ assertEquals(0, store.writes);
+ config.accept(KEY, setup(200), this);
+ clock.advance(1);
+ assertEquals(0, store.writes);
+ clock.advance(499);
+ assertEquals(1, store.writes);
+ assertEquals(setup(200), store.value);
+ config.closeAsync().toCompletableFuture().get();
+ }
+
+ @Test
+ void discardCloseWaitsForAnAlreadyCommittingWriteOnAParallelScheduler() throws Exception {
+ var entered = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var closed = new CountDownLatch(1);
+ var backing = new MemoryStore();
+ GridSetupStore store =
+ new GridSetupStore() {
+ public Stored load(Key key) {
+ return backing.load(key);
+ }
+
+ public String revision(Key key) {
+ return backing.revision(key);
+ }
+
+ public String save(Key key, String revision, GridSetup setup)
+ throws IOException {
+ entered.countDown();
+ try {
+ if (!release.await(5, TimeUnit.SECONDS))
+ throw new IOException("Timed out");
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ throw new IOException(failure);
+ }
+ return backing.save(key, revision, setup);
+ }
+ };
+ var worker = Executors.newScheduledThreadPool(2);
+ var config =
+ new GridApplicationConfiguration(
+ "Example", store, Duration.ofHours(1), worker, true);
+ load(config);
+ config.observe(
+ KEY,
+ state -> {
+ if (state.phase() == GridApplicationConfiguration.Phase.CLOSED)
+ closed.countDown();
+ });
+ config.accept(KEY, setup(100), this);
+ var write = config.retryAsync(KEY);
+ assertTrue(entered.await(5, TimeUnit.SECONDS));
+ var close = config.discardAndCloseAsync();
+ try {
+ assertFalse(closed.await(100, TimeUnit.MILLISECONDS));
+ } finally {
+ release.countDown();
+ }
+ close.toCompletableFuture().get(5, TimeUnit.SECONDS);
+ write.toCompletableFuture().get(5, TimeUnit.SECONDS);
+ assertEquals(GridApplicationConfiguration.Phase.CLOSED, config.state(KEY).phase());
+ assertFalse(config.state(KEY).dirty());
+ }
+
+ /** Deterministic scheduled worker: no wall-clock sleeps in debounce assertions. */
+ static final class Clock extends java.util.concurrent.AbstractExecutorService
+ implements java.util.concurrent.ScheduledExecutorService {
+ long now;
+ boolean shutdown;
+ final List jobs = new ArrayList<>();
+
+ static final class Job extends java.util.concurrent.FutureTask
+ implements java.util.concurrent.ScheduledFuture {
+ final long due;
+
+ Job(Runnable action, long due) {
+ super(action, null);
+ this.due = due;
+ }
+
+ public long getDelay(java.util.concurrent.TimeUnit unit) {
+ return unit.convert(due, java.util.concurrent.TimeUnit.MILLISECONDS);
+ }
+
+ public int compareTo(java.util.concurrent.Delayed other) {
+ return Long.compare(due, ((Job) other).due);
+ }
+ }
+
+ void advance(long millis) {
+ now += millis;
+ var ready = jobs.stream().filter(job -> job.due <= now).toList();
+ jobs.removeAll(ready);
+ ready.forEach(Job::run);
+ }
+
+ public java.util.concurrent.ScheduledFuture> schedule(
+ Runnable action, long delay, java.util.concurrent.TimeUnit unit) {
+ var job = new Job(action, now + unit.toMillis(delay));
+ jobs.add(job);
+ return job;
+ }
+
+ public java.util.concurrent.ScheduledFuture schedule(
+ java.util.concurrent.Callable action,
+ long delay,
+ java.util.concurrent.TimeUnit unit) {
+ throw new UnsupportedOperationException();
+ }
+
+ public java.util.concurrent.ScheduledFuture> scheduleAtFixedRate(
+ Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
+ throw new UnsupportedOperationException();
+ }
+
+ public java.util.concurrent.ScheduledFuture> scheduleWithFixedDelay(
+ Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void execute(Runnable command) {
+ command.run();
+ }
+
+ public void shutdown() {
+ shutdown = true;
+ }
+
+ public List shutdownNow() {
+ shutdown = true;
+ return List.of();
+ }
+
+ public boolean isShutdown() {
+ return shutdown;
+ }
+
+ public boolean isTerminated() {
+ return shutdown;
+ }
+
+ public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) {
+ return shutdown;
+ }
+ }
+}
diff --git a/data-grid/src/test/java/de/neitzel/grid/GroupingTest.java b/data-grid/src/test/java/de/neitzel/grid/GroupingTest.java
new file mode 100644
index 0000000..2062fa6
--- /dev/null
+++ b/data-grid/src/test/java/de/neitzel/grid/GroupingTest.java
@@ -0,0 +1,130 @@
+package de.neitzel.grid;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+
+class GroupingTest {
+ record Item(String type, String status) {}
+
+ static GroupPath path(String value) {
+ return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(value))));
+ }
+
+ @Test
+ void snapshotSeparatesExactIdentityAndLabelsFromOrderingAndRetainsLeafSourceOrder() {
+ AtomicInteger calls = new AtomicInteger();
+ var mapping =
+ new GroupColumn- (
+ "type",
+ MemoryColumn.Kind.TEXT,
+ i -> {
+ calls.incrementAndGet();
+ return i.type() == null ? null : new FilterValue.Text(i.type());
+ },
+ GroupColumn::display);
+ var rows =
+ List.of(
+ new GridRow<>(1, new Item("a", "one")),
+ new GridRow<>(2, new Item(null, "two")),
+ new GridRow<>(3, new Item("A", "three")),
+ new GridRow<>(4, new Item("a", "four")),
+ new GridRow<>(5, new Item("", "five")));
+ var snapshot = GroupProjection.capture(rows, List.of(mapping));
+ var groups = GroupProjection.project(snapshot, List.of("type"));
+ assertEquals(
+ List.of("(Empty)", "A", "a", "(Missing)"),
+ groups.stream().map(GroupProjection.Node::label).toList());
+ assertEquals(List.of(1, 4), groups.get(2).rows().stream().map(GridRow::key).toList());
+ assertEquals(5, calls.get());
+ GroupProjection.project(snapshot, List.of("type"));
+ assertEquals(5, calls.get(), "Regroup must use captured scalars, not reread models");
+ assertEquals(List.of(1, 2, 3, 4, 5), rows.stream().map(GridRow::key).toList());
+ }
+
+ @Test
+ void decimalScaleDoesNotCreateDifferentGroupsAndWrongTypesFailBeforePublication() {
+ var mapping =
+ new GroupColumn(
+ "amount",
+ MemoryColumn.Kind.DECIMAL,
+ FilterValue.Decimal::new,
+ GroupColumn::display);
+ var groups =
+ GroupProjection.project(
+ GroupProjection.capture(
+ List.of(
+ new GridRow<>(1, new BigDecimal("1.0")),
+ new GridRow<>(2, new BigDecimal("1.00"))),
+ List.of(mapping)),
+ List.of("amount"));
+ assertEquals(1, groups.size());
+ assertEquals(2, groups.getFirst().count());
+ var invalid =
+ new GroupColumn(
+ "type",
+ MemoryColumn.Kind.TEXT,
+ s -> new FilterValue.BooleanValue(true),
+ GroupColumn::display);
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GroupProjection.capture(List.of(new GridRow<>(1, "x")), List.of(invalid)));
+ }
+
+ @Test
+ void expansionPreservesCurrentChoicesAndBoundsOnlyInactiveHistory() {
+ var expansion = new GroupExpansion(true, 1);
+ expansion.current(List.of(path("A"), path("B")));
+ expansion.set(path("A"), true);
+ expansion.set(path("B"), false);
+ expansion.set(path("C"), true);
+ expansion.set(path("D"), true);
+ assertEquals(3, expansion.snapshot().size());
+ assertTrue(expansion.expanded(path("A")));
+ assertFalse(expansion.expanded(path("C")));
+ expansion.configure(false, 1);
+ assertFalse(
+ expansion.expanded(path("B")),
+ "Explicit choice equal to old default must survive default change");
+ expansion.reset();
+ assertTrue(expansion.expanded(path("B")));
+ }
+
+ @Test
+ void nestedCountsAndPathsDoNotConflateEqualLabelsOrParentCollapse() {
+ var cols =
+ List.of(
+ new GroupColumn
- (
+ "type",
+ MemoryColumn.Kind.TEXT,
+ i -> new FilterValue.Text(i.type()),
+ v -> "same"),
+ new GroupColumn
- (
+ "status",
+ MemoryColumn.Kind.TEXT,
+ i -> new FilterValue.Text(i.status()),
+ GroupColumn::display));
+ var tree =
+ GroupProjection.project(
+ GroupProjection.capture(
+ List.of(
+ new GridRow<>(1, new Item("A", "live")),
+ new GridRow<>(2, new Item("B", "live"))),
+ cols),
+ List.of("type", "status"));
+ assertEquals(2, tree.size());
+ assertNotEquals(tree.get(0).path(), tree.get(1).path());
+ var expansion = new GroupExpansion(true, 1000);
+ expansion.current(GroupProjection.paths(tree));
+ var parent = tree.get(0).path();
+ var child = tree.get(0).children().getFirst().path();
+ expansion.set(child, true);
+ expansion.set(parent, false);
+ expansion.set(parent, true);
+ assertTrue(expansion.expanded(child));
+ }
+}
diff --git a/encryption/pom.xml b/encryption/pom.xml
index afc0638..a772997 100644
--- a/encryption/pom.xml
+++ b/encryption/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.lib
neitzellib
- 1.1-SNAPSHOT
+ 1.0.1
encryption
diff --git a/fx-example/README.md b/fx-example/README.md
index 6ceb35a..f60eba6 100644
--- a/fx-example/README.md
+++ b/fx-example/README.md
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
./mvnw -f fx-example/pom.xml javafx:run
```
-The first command installs local `1.1-SNAPSHOT` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
+The first command installs local `1.0.1` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The packaged alternative, after `package` or `install`, is:
```bash
-java -jar fx-example/target/fx-example-1.1-SNAPSHOT.jar
+java -jar fx-example/target/fx-example-1.0.1.jar
```
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
diff --git a/fx-example/docs/product-grid.md b/fx-example/docs/product-grid.md
index e186f0f..67379d7 100644
--- a/fx-example/docs/product-grid.md
+++ b/fx-example/docs/product-grid.md
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
```sh
./mvnw -pl fx-example -am package -DskipTests
-java -cp 'fx-example/target/fx-example-1.1-SNAPSHOT.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
+java -cp 'fx-example/target/fx-example-1.0.1.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
diff --git a/fx-example/docs/theme-gallery.md b/fx-example/docs/theme-gallery.md
index d673875..6ddee6a 100644
--- a/fx-example/docs/theme-gallery.md
+++ b/fx-example/docs/theme-gallery.md
@@ -5,7 +5,7 @@
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
```sh
-java -cp 'fx-example/target/fx-example-1.1-SNAPSHOT.jar:fx-example/target/libs/*' \
+java -cp 'fx-example/target/fx-example-1.0.1.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
diff --git a/fx-example/pom.xml b/fx-example/pom.xml
index cdd56d7..53b042e 100644
--- a/fx-example/pom.xml
+++ b/fx-example/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.lib
neitzellib
- 1.1-SNAPSHOT
+ 1.0.1
fx-example
diff --git a/fx/README.md b/fx/README.md
index eb1b18e..795544a 100644
--- a/fx/README.md
+++ b/fx/README.md
@@ -2,6 +2,8 @@
## Documentation map
+- [FXML support for every public control](docs/fxml-controls.md).
+
- [Build a complete application from scratch](docs/quick-start.md).
- [Architecture, MVVM, identity, threading and lifetime](docs/architecture.md).
- [Walk through the person desk](../fx-example/README.md).
@@ -21,6 +23,7 @@
- [Dependency injection](../injection/README.md).
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
+- [Interactive layout, grouping and optional application persistence](docs/data-grid-layout.md).
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
@@ -51,7 +54,7 @@ These are the versions configured by this source snapshot, not a promise of comp
| --- | --- | --- |
| JDK | Java 25 | Select a matching JDK for compilation and launch |
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
-| Library | `de.neitzel.lib:fx:1.0` | Use the Gitea Maven registry or install the local reactor |
+| Library | `de.neitzel.lib:fx:1.0.1` | Use the Gitea Maven registry or install the local reactor |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
diff --git a/fx/docs/data-grid-layout.md b/fx/docs/data-grid-layout.md
new file mode 100644
index 0000000..92801c8
--- /dev/null
+++ b/fx/docs/data-grid-layout.md
@@ -0,0 +1,193 @@
+# DataGrid layout, grouping and saved application setups
+
+These features extend the opt-in queried DataGrid. Standalone collection/FXML
+Table behavior is unchanged. Use Java 25 and call grid operations on the JavaFX
+application thread.
+
+## Group a returned page
+
+Declare group values explicitly; never derive them from a rendered cell. A text
+mapping is convenient for labels, while the full constructor supports integers,
+exact decimals and booleans using `FilterValue` and `MemoryColumn.Kind`.
+
+```java
+// grid already has stable ResultColumn IDs and a source, as in data-grid.md.
+grid.configureGrouping(
+ List.of(GroupColumn.text("name", Person::name),
+ GroupColumn.text("type", Person::type)),
+ true, // developer enables grouping
+ List.of("type"), // outer-to-inner default grouping columns
+ true, // unseen groups start collapsed
+ 1000); // inactive expansion choices retained
+```
+
+`GroupColumn`, `GroupPath`, `GroupingSetup` and the projection/history models live
+in `de.neitzel.grid`. All eligible values/labels are captured when a page publishes,
+even for columns not currently grouped. `setGroupingColumns(List.of("type","name"))`
+rearranges existing page components using those snapshots and issues no query.
+`regroup()` explicitly recaptures group values after an application data update;
+it does not change page membership. `refresh()` instead queries the source.
+
+Text equality is exact, including case and whitespace; missing and empty text
+are distinct. Decimal 1.0 and 1.00 share identity. Groups sort ascending, text
+ignoring case with an exact tie-breaker, booleans false then true, missing last.
+Rows within a leaf group retain their source order. Custom domains must map to
+one declared scalar type; changing identity/normalization semantics requires a
+schema migration. Labels never define identity. Invalid mappings fail visibly
+without replacing the prior grouping.
+
+Grouping applies only to the loaded page. The same value may recur on another
+page; counts include collapsed data rows and exclude group headings. Explicit All
+mode still uses the existing guard/confirmation protocol and retains all returned
+row components. Collapsing it does not remove that memory cost.
+
+## Interactions and row ownership
+
+Drag a column's right boundary to preview a bounded width; release commits that
+column and Escape restores its previous sizing intent. Drag a header label to
+move a column, or into the grouping area to add a chip. Insertion feedback and
+fixed-position constraints apply; invalid/outside drops cancel without sorting.
+Grouped columns remain visible. Drag chips to reorder levels, and use × to remove
+a grouping level. A header click still sorts and the separate filter icon opens
+its editor. The Grid setup menu offers keyboard-operable Column settings.
+
+Each group has a disclosure triangle. Expansion follows the typed ordered path,
+not its label or page number. Parent collapse preserves child choices. Current
+paths are retained along with the configured LRU history of inactive explicit
+choices; evicted paths return to the default. `setExpanded(path, boolean)` and
+`resetExpansion()` provide programmatic equivalents. `setGroupingEnabled(false)`
+hides grouped presentation without erasing valid dormant choices.
+
+Reorder/regroup/collapse preserve current-page component identity and drafts.
+Actual page replacement keeps the existing guard/staging/disposal rules. A hidden
+selected record retains its key but has no actionable `selectedElement`. Expansion
+never re-enables stale rows. If collapse/reset hides focus, focus moves to a visible
+group heading. No historical rows are retained merely for expansion history.
+
+## Attach optional persistence
+
+`fx` does not depend on Gson. Add `de.neitzel.lib:gson` at the same library version
+when using the supplied JSON/file integration. The neutral custom-store contracts
+remain available without Gson.
+
+```java
+// Once per application, not per tab. No files/directories are created here.
+var configuration = GridSetupFiles.forApplication("MyApplication");
+
+// On each grid, after columns/grouping are configured, before the first query:
+grid.configureSetups("people.records", 1,
+ Map.of("name", "text.v1", "type", "text.v1"), Map.of());
+var attachment = grid.attachPersistence(configuration, "people.records");
+attachment.loadAsync(); // read -> validate/restore or defaults -> one initial query
+// attachment.ready() completes after initialization or explicit recovery succeeds.
+```
+
+Factory: `de.neitzel.gson.grid.GridSetupFiles`. Service/store:
+`de.neitzel.grid.GridApplicationConfiguration` and `GridSetupStore`. Attachment:
+`de.neitzel.fx.view.GridPersistenceAttachment`. An attachment overload accepts a
+context key. `GridSetupFiles.forApplication(name, path)` selects an explicit grid
+storage directory; another overload accepts pre-registered `GridSetupJson` codecs.
+Custom stores implement blocking load/revision/conditional-save; the service runs
+those operations off the FX thread.
+
+The default directory is `ApplicationDirectories.configurationDirectory(name)`
+plus `grids`. Grid/context keys map to opaque safe filenames, with identity checked
+inside each document. Existing application preferences are never migrated.
+Never-attached grids perform no persistence I/O. Attachments can be closed and
+replaced; the application service owns accepted saves after detachment.
+
+A stable grid ID/context shares one stored setup, not live displays. Newly opened
+grids restore the latest successfully saved snapshot. Open grids keep their own
+state until `attachment.loadAsync()` or Reload saved setup. The newest committed
+change replaces the whole saved snapshot; fields from different views are not
+merged. Closing an unchanged older tab cannot overwrite newer choices.
+
+## Defaults, formats and recovery
+
+The existing GridSetup format is extended with grouping and typed expansion
+choices. Version-one documents remain readable; absent new preferences inherit
+current developer grouping defaults. Current version-two documents require their
+complete schema. Definition/type migrations, fixed-position validation, width
+clamping and custom filter codecs retain their existing strict behavior.
+Unsupported or incompatible files fail visibly, never by silently dropping fields.
+
+`configureDefaults(GridSetup)` may configure the full default query/layout without
+fetching, after definitions/mappings and before attachment/load. Otherwise defaults
+are captured at attachment. Defaults stay separate from the restored display.
+
+Committed changes autosave after a configurable debounce (500 ms by default).
+`committedRevisionProperty()` is the FX notification seam; previews, cancelled
+operations, drafts and failed/pending queries do not become saves. Query preferences
+are saved only after successful publication. Saving/encoding failures retain the
+latest unsaved snapshot and last good file. The grid shows nonmodal settings
+feedback with Retry/Reload/Reset/Overwrite actions, separate from query status.
+
+If no saved file exists, developer defaults apply. An unreadable/incompatible file blocks startup restoration
+and initial query until retry or explicit reset succeeds. Full Reset setup uses
+current defaults and the existing edit guard/transactional publication before
+accepting a replacement save. Reset expansion only clears expansion choices and
+never queries or resets other preferences.
+
+The file store uses process coordination, revision-checked writes and atomic
+replacement. A cross-process conflict requires explicit Reload or Overwrite.
+Reload retires its abandoned pending generation only after successful guarded
+restoration and cannot discard a newer change. Overwrite is still conditional
+against a freshly observed revision. Unsupported atomic filesystem operations
+fail rather than publishing a partial file.
+
+## Close and application shutdown
+
+```java
+// Tab close, on FX thread:
+attachment.close();
+grid.close();
+
+// Application shutdown: asynchronous; do not block the FX thread.
+configuration.flushAsync();
+configuration.closeAsync(); // also flushes; failure leaves the service retryable
+// Only after explicit user consent to quit without settings:
+configuration.discardAndCloseAsync();
+```
+
+Chain/await completion stages in the application exit coordinator; the snippet
+lists operations, not permission to ignore their completion. A failed flush must
+be handled before exit. Close does not own external executors. Explicit discard
+retires pending work but cannot undo a write already committed. Detaching a grid
+stops observation/cancels its unfinished restore, not already accepted app saves.
+
+## Qualification
+
+Automated component/state, codec, lifecycle and real separate-process storage tests
+are provided. For native interaction qualification after running DataGridGroupingTest:
+
+```sh
+python3 fx/scripts/data-grid-probe.py
+# macOS bundle for native accessibility tooling:
+python3 fx/scripts/data-grid-probe.py --app
+```
+
+This opens actual JavaFX DataGrid controls with fictional records and a resource/
+query trace. Use native pointer/keyboard input to qualify the recorded acceptance
+scenarios; it is not a browser mock and emits no synthetic OS input. It has no
+application persistence or real DNS/network data. Runtime/platform evidence and
+remaining limits are recorded in the Workspace implementation record.
+
+For repeatable macOS held-input checks (Escape during a drag, invalid/outside
+native drops and timed edge hovering), the separate opt-in fixture uses AWT
+Robot for pointer/keyboard input and JavaFX Robot for capture. It operates only
+its fictional-data window and owned popups; no application data or DNS is used.
+
+```sh
+./mvnw -pl fx -am -Dtest=DataGridNativeInteractionTest \
+ -Dneitzellib.nativeGridTest=true -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+Without `neitzellib.nativeGridTest=true`, its five native tests are skipped.
+On macOS the Java launcher and launching terminal or IDE need event-posting
+permission in Privacy & Security → Accessibility. A permission-denied process
+fails before posting input; that failure does not establish a gesture failure.
+Restore any temporary permissions after testing. Keep the desktop idle: checks
+stop if focus leaves their window and owned popups. Cleanup releases input and
+disposes retained rows even on failure. Captures go to `fx/target/native-grid`.
+Cancellation waits for the native drag-completion callback before releasing the
+button or starting another gesture, including macOS's return animation.
diff --git a/fx/docs/data-grid.md b/fx/docs/data-grid.md
index 2b9691b..782e97a 100644
--- a/fx/docs/data-grid.md
+++ b/fx/docs/data-grid.md
@@ -1,5 +1,7 @@
# Local DataGrid and request coordination
+For direct declarations, columns and data bindings in FXML, see [FXML controls](fxml-controls.md).
+
`DataGrid` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
```java
@@ -23,7 +25,8 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
## Operations
-- First/Previous/Next/Last, page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
+- Vertical separators mark column boundaries in headers and data rows, follow resizing/reordering, and use the active theme border color. Group headings span the columns.
+- First/Previous/Next/Last use vector navigation icons with tooltips and accessible page names. Page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
@@ -43,3 +46,11 @@ The application must provide a serial owner-thread callback executor when using
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
+
+## Interactive layout and grouping
+
+Column resize/reorder, grouping chips, disclosure and keyboard Column settings
+are now opt-in DataGrid features. Application-name-based saved setups are an
+optional attachment using the existing versioned setup model. See the
+[layout, grouping and persistence guide](data-grid-layout.md) for mappings,
+component lifetime, startup/recovery, storage concurrency and shutdown.
diff --git a/fx/docs/fxml-controls.md b/fx/docs/fxml-controls.md
new file mode 100644
index 0000000..9fa6f79
--- /dev/null
+++ b/fx/docs/fxml-controls.md
@@ -0,0 +1,112 @@
+# Controls in FXML
+
+Every public visual control supplied by `fx` can be declared in ordinary FXML.
+`FXMLLoader` constructs the view without a database, DNS connection or injection
+context. The optional `ViewLoader` applies NeitzelLib binding declarations.
+
+| Control | FXML configuration | Data and lifetime |
+| --- | --- | --- |
+| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
+| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
+| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
+| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
+| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
+| `javafx.scene.control.ToolBar` | Standard `items` and `orientation` | Standard JavaFX control, deliberately reused by the library |
+
+Supporting objects such as coordinators, sources, setup stores, popup hosts,
+result renderers, theme managers and tray integrations are application/runtime
+objects, rather than controls to insert in a scene graph.
+
+## DataGrid
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+Initialize the model's `List people` before loading. Bean and Java record
+rows are supported. After `ViewLoader.load`, call the injected grid's `load()` or
+`loadAsync()` on the FX thread. The data binding shares the model's observable
+list. Add, remove, replace, permute or use an extractor update on that list to
+request a refresh immediately, invalidating older pending results. The existing
+query (filters/sort/page) is retained; use `setAll` for a single batch update. Replacing `grid.items` detaches
+the old list. Rows are snapshots: mutating a field without an observable update
+requires `refresh()`.
+
+Configure before the first runtime operation. `initialize()` completes setup
+without querying, allowing an application to attach persistence before calling
+`loadAsync()`. Nothing loads in the constructor, and FXML without data displays
+column headers in a query-free preview. State is null until initialization.
+
+For ordinary `FXMLLoader`, provide the list in its namespace and use
+`items="$people"`, or assign/bind `itemsProperty()` after loading. The same
+explicit loading and closing contract applies. `DirectBinding` requires
+`ViewLoader`; the usual collection-binding limitations in the main reference
+still apply, including replacing model attributes through the ViewModel.
+
+A local grid requires a stable unique row key: `keyAttribute="id"` reads a public
+bean getter or record accessor. Alternatively supply `keyFactory` and
+`keyComparator` in Java before initialization. Keys must be comparable when no
+comparator is supplied. Duplicate/null keys fail the query visibly. The local
+grid owns its virtual-thread executor and releases it on `close()`.
+
+For an external queried grid, bind `source` instead of `items`. Column IDs must
+match the source mappings. The source and executor remain application-owned.
+Changing an initialized source starts a request using the current filters/sort
+and first page, as with the programmatic interface. External checklist filters
+need an explicitly supplied `candidates` provider; local sources supply one.
+
+Column defaults: `attribute` uses `id`, `kind="TEXT"`, width 150, minimum 80,
+maximum 1200, fixed position -1 (movable), filterable true, checklist disabled.
+Kinds are `TEXT`, `INTEGER`, `DECIMAL`, `BOOLEAN`. Text and numeric filter editors
+are built in; boolean values can render/group and use programmatic conditions,
+but have no built-in editor. Set `filterable="false"` for display-only columns.
+`groupAttribute` optionally separates stable group values from displayed/filter
+values; `groupLabels` maps those values to display labels without changing group
+identity. `type` supplies a stable schema type for saved setups; the default is
+`neitzel..v1`. Keep type IDs and setup versions stable across upgrades.
+
+The default row factory creates labels. Supply a Java `rowFactory` for custom
+nodes, styles, tooltips or actions; use `DataGridColumn.getValue(row)` to share
+the FXML mappings. FXML can also reference factories using `$factory` namespace
+values. Selection is available through the stable read-only
+`selectedKeyProperty()` and `selectedElementProperty()`; call `select(key)` to
+change it. Existing programmatic constructor and queried-grid behavior remain
+supported.
+
+## Bounded integer spinner
+
+```xml
+
+
+```
+
+Use `` in a ViewLoader binding list. Valid typing commits
+immediately; invalid typing and bounds follow [bounded integer inputs](integer-spinners.md).
+The original `IntegerSpinners.nonNegative(...)` factory remains available.
+
+See [bars](bars.md), [docking](docking.md) and the main [FXML reference](../README.md)
+for the existing controls. The host designer needs the updated library on its
+classpath; this feature does not replace a separately pinned Designer runtime.
diff --git a/fx/docs/integer-spinners.md b/fx/docs/integer-spinners.md
index 593e725..368126c 100644
--- a/fx/docs/integer-spinners.md
+++ b/fx/docs/integer-spinners.md
@@ -24,3 +24,10 @@ container.getChildren().add(quantity);
```
Import `javafx.scene.control.Spinner` and `de.neitzel.fx.control.IntegerSpinners`; `container` is your Pane. Read `quantity.getValue()` to obtain the committed number. Set a programmatic value through `quantity.getValueFactory().setValue(...)`. Use the factory's bounds as UI constraints and keep independent business validation where the value is saved. The helper does not add an FXML binding declaration or create a Model Attribute automatically.
+
+## FXML
+
+Declare `NonNegativeIntegerSpinner` with `minimum`, `maximum`, and `initialValue`
+constructor attributes. Bind its writable `number` property with `DirectBinding`;
+it shares the value factory property and supports both directions. See the
+[FXML controls guide](fxml-controls.md#bounded-integer-spinner).
diff --git a/fx/docs/quick-start.md b/fx/docs/quick-start.md
index c1ad889..fc244b3 100644
--- a/fx/docs/quick-start.md
+++ b/fx/docs/quick-start.md
@@ -1,13 +1,13 @@
# Your first JavaFX application
-This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0. The source build below uses the matching release tag.
+This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.1. The source build below uses the matching release tag.
## Prepare the library
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
```bash
-git clone --branch v1.0 https://gitea.neitzel.de/konrad/NeitzelLib.git
+git clone --branch v1.0.1 https://gitea.neitzel.de/konrad/NeitzelLib.git
cd NeitzelLib
./mvnw -pl fx-example -am install
./mvnw -f fx-example/pom.xml javafx:run
@@ -66,7 +66,7 @@ hello-fx/
de.neitzel.lib
fx
- 1.0
+ 1.0.1
org.slf4j
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
| Symptom | Check |
| --- | --- |
-| Maven cannot resolve `de.neitzel.lib:fx:1.0` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
+| Maven cannot resolve `de.neitzel.lib:fx:1.0.1` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
diff --git a/fx/docs/saved-setups.md b/fx/docs/saved-setups.md
index 9c10fb0..c7cf1f3 100644
--- a/fx/docs/saved-setups.md
+++ b/fx/docs/saved-setups.md
@@ -1,6 +1,7 @@
# Saved DataGrid setups
-Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson.
+Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson. An optional application-owned attachment
+now supplies automatic storage/timing; see [layout and persistence](data-grid-layout.md).
## Configure and save
@@ -48,3 +49,12 @@ Appending a new column does not itself require a migration when the saved defini
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
+
+## Grouping format and automatic storage
+
+Format version 2 adds ordered grouping columns and typed expansion-path choices.
+The version-one constructor/codec path remains available; compatible old documents
+inherit developer grouping defaults at restore. Preserve explicit expansion choices
+even when equal to defaults. The optional file integration wraps the setup in a
+strict grid/context/revision document and uses conditional atomic replacement.
+The plain GridSetupJson API remains available for application-managed storage.
diff --git a/fx/docs/table-results.md b/fx/docs/table-results.md
index 1b499a8..a2b1aec 100644
--- a/fx/docs/table-results.md
+++ b/fx/docs/table-results.md
@@ -18,10 +18,15 @@ Factories may supply freshly bound FXML Components as HBox roots. They must map
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
-`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. This first integration point supplies programmatic ordering/sizing, not drag UI. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
+`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. The result integration now also supplies native resize/reorder and grouping support
+when composed by DataGrid; the stable programmatic operations remain available. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
-This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. Ordering and sizing use the documented programmatic API; drag reorder/resize is not supplied by this result renderer.
+This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. DataGrid exposes both programmatic layout operations and native resize/reorder interactions over this result renderer.
+
+[DataGrid layout/grouping](data-grid-layout.md) documents the component-preserving
+projection path. Local grouping must not call `show` to recreate current-page
+editors; `show` remains the guarded replacement/publication boundary.
diff --git a/fx/pom.xml b/fx/pom.xml
index 40dedfd..cccf171 100644
--- a/fx/pom.xml
+++ b/fx/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.lib
neitzellib
- 1.1-SNAPSHOT
+ 1.0.1
fx
diff --git a/fx/scripts/data-grid-probe.py b/fx/scripts/data-grid-probe.py
new file mode 100644
index 0000000..c51a294
--- /dev/null
+++ b/fx/scripts/data-grid-probe.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python3
+"""Launch the real DataGrid native qualification surface after DataGridGroupingTest.
+
+On macOS, --app creates an addressable app bundle for native accessibility tools.
+All generated artifacts stay under fx/target. No application data or persistence.
+"""
+import pathlib
+import shutil
+import subprocess
+import sys
+import xml.etree.ElementTree as ET
+import zipfile
+
+module = pathlib.Path(__file__).resolve().parent.parent
+report = module / 'target/surefire-reports/TEST-de.neitzel.fx.view.DataGridGroupingTest.xml'
+if not report.exists():
+ sys.exit('First run ./mvnw -pl fx -am -Dtest=DataGridGroupingTest -Dsurefire.failIfNoSpecifiedTests=false test')
+properties = {p.get('name'): p.get('value') for p in ET.parse(report).getroot().find('properties')}
+classpath = properties.get('surefire.test.class.path', properties['java.class.path'])
+app_name = 'DataGridProbe'
+main = 'de.neitzel.fx.view.DataGridNativeProbe'
+if '--app' in sys.argv:
+ work = module / 'target/native-probe'
+ inputs = work / 'input'
+ inputs.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(inputs / 'probe.jar', 'w') as archive:
+ seen = set()
+ for entry in classpath.split(':'):
+ path = pathlib.Path(entry)
+ if path.is_dir():
+ for file in path.rglob('*'):
+ if file.is_file() and str(file.relative_to(path)) not in seen:
+ relative = str(file.relative_to(path))
+ seen.add(relative)
+ archive.write(file, relative)
+ elif path.suffix == '.jar':
+ target = inputs / path.name
+ if target.exists() and target.read_bytes() != path.read_bytes():
+ sys.exit('Conflicting dependency filename: ' + path.name)
+ shutil.copy2(path, target)
+ app = work / (app_name + '.app')
+ if app.exists():
+ shutil.rmtree(app)
+ subprocess.run(['jpackage', '--type', 'app-image', '--name', app_name,
+ '--input', str(inputs), '--dest', str(work), '--main-jar', 'probe.jar',
+ '--main-class', main, '--mac-package-identifier', 'de.neitzel.datagrid.probe',
+ '--java-options', '--enable-native-access=ALL-UNNAMED',
+ '--java-options', '-Dneitzellib.nativeGridOutput=' + str(module / 'target/native-grid')], check=True)
+ print(app, flush=True)
+ raise SystemExit(subprocess.call([str(app / ('Contents/MacOS/' + app_name))]))
+raise SystemExit(subprocess.call(['java', '--enable-native-access=ALL-UNNAMED', '-cp', classpath,
+ main], cwd=module.parent))
diff --git a/fx/src/main/java/de/neitzel/fx/control/IntegerSpinners.java b/fx/src/main/java/de/neitzel/fx/control/IntegerSpinners.java
index 95637ad..d1f93f9 100644
--- a/fx/src/main/java/de/neitzel/fx/control/IntegerSpinners.java
+++ b/fx/src/main/java/de/neitzel/fx/control/IntegerSpinners.java
@@ -18,10 +18,13 @@ public final class IntegerSpinners {
* @return an editable spinner
*/
public static Spinner nonNegative(int min, int max, int value) {
+ return new NonNegativeIntegerSpinner(min, max, value);
+ }
+
+ static void configure(Spinner 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 spinner = new Spinner<>(min, max, value);
spinner.setEditable(true);
spinner.getEditor().setTextFormatter(new TextFormatter(change -> {
String text = change.getControlNewText();
@@ -46,6 +49,5 @@ public final class IntegerSpinners {
spinner.getEditor().setText(spinner.getValue().toString());
}
});
- return spinner;
}
}
diff --git a/fx/src/main/java/de/neitzel/fx/control/NonNegativeIntegerSpinner.java b/fx/src/main/java/de/neitzel/fx/control/NonNegativeIntegerSpinner.java
new file mode 100644
index 0000000..bdc5d9f
--- /dev/null
+++ b/fx/src/main/java/de/neitzel/fx/control/NonNegativeIntegerSpinner.java
@@ -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 {
+ 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 numberProperty() {
+ return getValueFactory().valueProperty();
+ }
+
+ public Integer getNumber() {
+ return numberProperty().get();
+ }
+
+ public void setNumber(Integer value) {
+ numberProperty().set(value);
+ }
+}
diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java
index 794e92e..5c188c9 100644
--- a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java
+++ b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java
@@ -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 extends VBox implements AutoCloseable {
private final Table table = new Table();
- private final TableResults renderer;
- private final GridCoordinator coordinator;
+ private TableResults renderer;
+ private GridCoordinator coordinator;
private final ReadOnlyObjectWrapper> 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 pageSize = new ComboBox<>();
- private final GridQuery initial;
- private final List columnDefinitions;
+ private GridQuery initial;
+ private List columnDefinitions;
private GridDefinition setupDefinition;
private Map> setupMigrations = Map.of();
private final ReadOnlyObjectWrapper
> restorationAdjustments =
@@ -50,11 +54,201 @@ public final class DataGrid 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 defaultGrouping = List.of();
+ private GridSetup developerDefaults;
+ private boolean hasPublished, restoredPublication;
+ private GridQuery lastPublishedQuery;
+ private long restoreSerial, lastRestoredSerial;
+ private GridPersistenceAttachment attachment;
+ private GridColumnSettings 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 declaration = new DataGridDeclaration<>(this);
+ private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>();
+ private final ReadOnlyObjectWrapper 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 getColumns() {
+ return declaration.columns();
+ }
+
+ public ObjectProperty> itemsProperty() {
+ return declaration.itemsProperty();
+ }
+
+ public ObservableList getItems() {
+ return itemsProperty().get();
+ }
+
+ public void setItems(ObservableList 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 getSource() {
+ return declaration.sourceProperty().get();
+ }
+
+ public ObjectProperty> sourceProperty() {
+ return declaration.sourceProperty();
+ }
+
+ public Function getRowFactory() {
+ return declaration.rowFactory;
+ }
+
+ public void setRowFactory(Function factory) {
+ declaration.beforeOpen();
+ declaration.rowFactory = factory;
+ }
+
+ public Function getKeyFactory() {
+ return declaration.keyFactory;
+ }
+
+ public void setKeyFactory(Function factory) {
+ declaration.beforeOpen();
+ declaration.keyFactory = factory;
+ }
+
+ public Comparator getKeyComparator() {
+ return declaration.keyComparator;
+ }
+
+ public void setKeyComparator(Comparator 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 columns,
Function rowFactory,
GridSource source) {
+ this();
+ declaration.setInitialSource(source);
+ initialize(columns, rowFactory, source);
+ }
+
+ void initialize(
+ List columns,
+ Function rowFactory,
+ GridSource source) {
requireFx();
+ getChildren().clear();
columnDefinitions = List.copyOf(columns);
Objects.requireNonNull(source);
initial =
@@ -64,40 +258,37 @@ public final class DataGrid 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 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 extends VBox implements AutoCloseable {
}
public ReadOnlyObjectProperty selectedKeyProperty() {
- return renderer.selectedKeyProperty();
+ return selectedKey.getReadOnlyProperty();
}
public ReadOnlyObjectProperty selectedElementProperty() {
- return renderer.selectedElementProperty();
+ return selectedElement.getReadOnlyProperty();
}
public void select(K key) {
@@ -191,6 +410,15 @@ public final class DataGrid extends VBox implements AutoCloseable {
}
public void setSource(GridSource 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 source) {
check();
closeFilter();
var q = query();
@@ -220,15 +448,14 @@ public final class DataGrid 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> next = Map.copyOf(migrations);
if (coordinator.isRestoring())
@@ -247,18 +474,18 @@ public final class DataGrid extends VBox implements AutoCloseable {
Map 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> restorationAdjustmentsProperty() {
@@ -287,6 +514,12 @@ public final class DataGrid 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 widths = new LinkedHashMap<>();
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
coordinator.restoreSetup(
@@ -296,7 +529,11 @@ public final class DataGrid 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 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 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 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 s) {
@@ -592,7 +862,27 @@ public final class DataGrid extends VBox implements AutoCloseable {
yield pageLabel(requested.page()) + " — total unknown";
}
};
- status.setText(message);
+ List 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 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 loadAsync() {
+ return awaitOperation(this::load, -1);
+ }
+
+ public CompletionStage restoreSetupAsync(GridSetup setup) {
+ long serial = ++restoreSerial;
+ return awaitOperation(() -> restoreSetup(setup), serial);
+ }
+
+ private CompletionStage awaitOperation(Runnable action, long serial) {
+ check();
+ action.run();
+ long generation = coordinator.state().generation();
+ CompletableFuture future = new CompletableFuture<>();
+ javafx.beans.value.ChangeListener> 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 groupingColumns() {
+ return renderer.groupingColumns();
+ }
+
+ public boolean groupingEnabled() {
+ return renderer.groupingEnabled();
+ }
+
+ public void configureGrouping(
+ List> columns,
+ boolean enabled,
+ List defaults,
+ boolean collapsed,
+ int inactiveHistoryLimit) {
+ check();
+ renderer.configureGrouping(columns, enabled, defaults, collapsed, inactiveHistoryLimit);
+ defaultGrouping = List.copyOf(defaults);
+ developerDefaults = null;
+ drawGroupingBar();
+ }
+
+ public void setGroupingColumns(List 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 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();
+ 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 attachPersistence(
+ GridApplicationConfiguration config, String gridId) {
+ return attachPersistence(config, gridId, null);
+ }
+
+ public GridPersistenceAttachment 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