Release NeitzelLib 1.0.1 with declarative DataGrid controls and saved setups
This commit is contained in:
@@ -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<Consumer<State>> 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<GridSetupStore.Key, Slot> 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<State> 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<Loaded> 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<Void> overwriteAsync(
|
||||
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||
synchronized (this) {
|
||||
accept(key, setup, owner, true);
|
||||
}
|
||||
return retryAsync(key);
|
||||
}
|
||||
|
||||
public CompletionStage<Void> 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<Void> 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<GridSetupStore.Key> 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<Void> 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<Void> 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<Slot> 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 <V> CompletionStage<V> submit(Callable<V> action) {
|
||||
CompletableFuture<V> 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;
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
||||
Consumer<FilterCondition> 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<Column> 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<String, Column> definitions = new LinkedHashMap<>();
|
||||
columns.forEach(c -> definitions.put(c.id(), c));
|
||||
@@ -123,7 +123,15 @@ public record GridDefinition(String id, int version, List<Column> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,20 @@ public record GridSetup(
|
||||
List<ColumnState> columns,
|
||||
List<SortKey> sort,
|
||||
List<FilterCondition> filters,
|
||||
PageRequest page) {
|
||||
PageRequest page,
|
||||
GroupingSetup grouping) {
|
||||
/** Source/binary-compatible constructor for version-one clients. */
|
||||
public GridSetup(
|
||||
int formatVersion,
|
||||
String definitionId,
|
||||
int definitionVersion,
|
||||
List<ColumnState> columns,
|
||||
List<SortKey> sort,
|
||||
List<FilterCondition> 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");
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>(
|
||||
String id,
|
||||
MemoryColumn.Kind kind,
|
||||
Function<T, FilterValue> read,
|
||||
Function<FilterValue, String> label) {
|
||||
public GroupColumn {
|
||||
Checks.id(id);
|
||||
Objects.requireNonNull(kind);
|
||||
Objects.requireNonNull(read);
|
||||
Objects.requireNonNull(label);
|
||||
}
|
||||
|
||||
public static <T> GroupColumn<T> text(String id, Function<T, String> 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 <T> GroupColumn<T> integer(String id, Function<T, Long> 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 <T> GroupColumn<T> decimal(String id, Function<T, java.math.BigDecimal> 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 <T> GroupColumn<T> bool(String id, Function<T, Boolean> 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());
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<GroupPath, Boolean> choices = new LinkedHashMap<>();
|
||||
private Set<GroupPath> 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<GroupPath> 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<GroupingSetup.Choice> snapshot() {
|
||||
return choices.entrySet().stream()
|
||||
.map(e -> new GroupingSetup.Choice(e.getKey(), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void restore(List<GroupingSetup.Choice> 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--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Segment> 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<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<K, T>(GridRow<K, T> row, Map<String, Value> values) {
|
||||
public Captured {
|
||||
Objects.requireNonNull(row);
|
||||
values = Map.copyOf(values);
|
||||
}
|
||||
}
|
||||
|
||||
public record Snapshot<K, T>(List<Captured<K, T>> rows, Map<String, GroupColumn<T>> columns) {
|
||||
public Snapshot {
|
||||
rows = List.copyOf(rows);
|
||||
columns = Map.copyOf(columns);
|
||||
}
|
||||
}
|
||||
|
||||
public record Node<K, T>(
|
||||
GroupPath path, String label, List<Node<K, T>> children, List<GridRow<K, T>> rows) {
|
||||
public Node {
|
||||
children = List.copyOf(children);
|
||||
rows = List.copyOf(rows);
|
||||
}
|
||||
|
||||
public int count() {
|
||||
return rows.size();
|
||||
}
|
||||
}
|
||||
|
||||
public static <K, T> Snapshot<K, T> capture(
|
||||
List<GridRow<K, T>> rows, Collection<GroupColumn<T>> columns) {
|
||||
Map<String, GroupColumn<T>> mappings = new LinkedHashMap<>();
|
||||
for (var c : columns)
|
||||
if (mappings.putIfAbsent(c.id(), c) != null)
|
||||
throw new IllegalArgumentException("Duplicate group mapping");
|
||||
List<Captured<K, T>> captured = new ArrayList<>();
|
||||
for (var row : rows) {
|
||||
Map<String, Value> 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 <K, T> List<Node<K, T>> project(Snapshot<K, T> snapshot, List<String> 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 <K, T> List<Node<K, T>> build(
|
||||
List<Captured<K, T>> rows, List<String> order, int depth, GroupPath parent) {
|
||||
if (depth == order.size()) return List.of();
|
||||
String id = order.get(depth);
|
||||
Map<FilterValue, List<Captured<K, T>>> buckets = new LinkedHashMap<>();
|
||||
for (var row : rows)
|
||||
buckets.computeIfAbsent(row.values().get(id).key(), ignored -> new ArrayList<>())
|
||||
.add(row);
|
||||
List<FilterValue> keys = new ArrayList<>(buckets.keySet());
|
||||
keys.sort(GroupColumn::compare);
|
||||
List<Node<K, T>> 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 <K, T> List<GroupPath> paths(List<Node<K, T>> nodes) {
|
||||
List<GroupPath> paths = new ArrayList<>();
|
||||
for (var node : nodes) {
|
||||
paths.add(node.path());
|
||||
paths.addAll(paths(node.children()));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
}
|
||||
@@ -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<String> columns, List<Choice> choices) {
|
||||
public record Choice(GroupPath path, boolean expanded) {
|
||||
public Choice {
|
||||
Objects.requireNonNull(path);
|
||||
}
|
||||
}
|
||||
|
||||
public GroupingSetup {
|
||||
columns = List.copyOf(columns);
|
||||
choices = List.copyOf(choices);
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (String id : columns) {
|
||||
Checks.id(id);
|
||||
if (!ids.add(id)) throw new IllegalArgumentException("Repeated grouping column");
|
||||
}
|
||||
Set<GroupPath> 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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user