feat(fx-example): demonstrate MVVM docking with local and global bars

This commit is contained in:
2026-11-15 22:42:56 +01:00
parent e20f8e0756
commit 0aa9f7fae3
9 changed files with 461 additions and 1 deletions
+3 -1
View File
@@ -4,7 +4,9 @@ This runnable application demonstrates [NeitzelLib FX](../fx/README.md) and [inj
Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md)
and [docking](../fx/docs/docking.md) without initializing MVVM or injection.
Their guides describe the implemented behavior and launch options.
Their guides describe the implemented behavior and launch options. The
[MVVM docking editor](docs/docking-mvvm.md) shows how an already loaded View and
its local bars move between windows while global commands follow the active editor.
## Build and run
+55
View File
@@ -0,0 +1,55 @@
# MVVM content and local/global bars
The docking API accepts an ordinary Node. This example passes the root of one
`LoadedView` to a `Dockable`; the manager never loads that View again. Its Note
JavaBean, ViewModel, TextArea, local toolbar and local status bar remain the same
objects when the tab moves, floats or returns. A second editor uses a plain
TextArea without a ViewModel.
Build from the repository root with Java 25, without replacing installed runtime
artifacts used by the Designer:
```sh
./mvnw -pl fx-example -am package
java --enable-native-access=ALL-UNNAMED \
-cp 'fx-example/target/classes:fx/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.mvvm.MvvmDockingMain
```
In the example:
1. Edit Notes. Its tab title gains an asterisk and the local character count changes.
2. Choose **Move Notes to tools**, **Float Notes**, then **Return Notes**. The
local Clear note button and status bar travel with the editor; the global
command and status bars stay in the main window.
3. While Notes is floating, click **Checkpoint active** in the main window.
Notes keeps its command target when focus enters that toolbar. The command
records a checkpoint in memory and clears the asterisk; it does not save a file.
4. Select Plain editor. The checkpoint command is disabled for this content, and
the global status identifies the newly active Dockable.
5. Close Notes with its tab close button to run the application's close hook.
`MvvmEditor.fxml` declares a bidirectional DirectBinding between the TextArea and
the Note's `text` attribute. Application updates use `LoadedView.property("text")`;
calling a JavaBean setter directly does not notify an already loaded ViewModel.
`MvvmEditor` binds the Dockable title and local status to presentation properties.
`MvvmDockingWorkspace` binds the global command availability and status to
`activeDockableProperty()`. These are application bindings, not a docking-specific
MVVM service.
The application adapter owns its change listener and derived bindings. Its
`onClosed` and `onDiscarded` hooks release those resources explicitly. Moves,
collapse and veto do not run those hooks. A rejected factory-created editor is
discarded; rejection of a directly supplied Dockable leaves cleanup to its caller.
This does not dispose the LoadedView or evict the runtime's strong Model-to-ViewModel
identity cache. See the [MVVM lifetime contract](../../fx/docs/architecture.md).
`MvvmDockingTest` loads the actual example FXML and checks model/property/control
edits before and after moves, object identity, bar ownership, global toolbar
focus and resource hooks. Its Scene-focus assertions complement the separately
qualified [native keyboard transfer tests](../../fx/docs/docking-floating.md);
this integration test does not claim to inject native keystrokes.
For entirely independent docking and bars without initializing MVVM or injection,
use the [plain docking example](../../fx/docs/docking.md) and
[standalone bars example](../../fx/docs/bars.md).
@@ -0,0 +1,19 @@
package de.neitzel.fx.example.docking.mvvm;
import javafx.application.Application;
import javafx.stage.Stage;
/** Visible example of optional MVVM content hosted by the plain docking API. */
public final class MvvmDockingApp extends Application {
private MvvmDockingWorkspace workspace;
@Override public void start(Stage stage) {
workspace = new MvvmDockingWorkspace(stage);
stage.setTitle("NeitzelLib — MVVM editor and local/global bars");
stage.show();
}
@Override public void stop() {
if (workspace != null) workspace.close();
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.docking.mvvm;
import javafx.application.Application;
/** Classpath launcher that does not extend JavaFX Application. */
public final class MvvmDockingMain {
private MvvmDockingMain() { }
public static void main(String[] args) { Application.launch(MvvmDockingApp.class, args); }
}
@@ -0,0 +1,91 @@
package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.scene.Scene;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.StringBinding;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import lombok.Getter;
/** Composes global bars with an optional MVVM editor and ordinary JavaFX content. */
public final class MvvmDockingWorkspace implements AutoCloseable {
@Getter private final DockingManager manager;
@Getter private final MvvmEditor editor;
@Getter private final Dockable plain;
private final ToolBar globalTools;
private final Button save;
private final Label active;
private final BooleanBinding saveDisabled;
private final StringBinding activeText;
public MvvmDockingWorkspace(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setPreferredWidth(360);
pane.getInitialLayout().setRight(tools);
Button move = new Button("Move Notes to tools");
Button floating = new Button("Float Notes");
Button returning = new Button("Return Notes");
save = new Button("Checkpoint active");
save.setId("saveActive");
globalTools = new ToolBar(save, move, floating, returning);
globalTools.setId("globalTools");
StatusBar globalStatus = new StatusBar();
globalStatus.setId("globalStatus");
active = new Label();
active.setId("activeStatus");
globalStatus.getLeftItems().add(active);
globalStatus.getRightItems().add(new Label("Checkpoints stay in memory"));
BorderPane shell = new BorderPane(pane, globalTools, null, globalStatus, null);
stage.setScene(new Scene(shell, 1040, 620));
manager = DockingManager.attach(stage, pane, new DockingOptions());
editor = new MvvmEditor("notes");
plain = new Dockable(new DockableId("plain"), new TextArea("A plain JavaFX editor needs no ViewLoader."));
plain.setTitle("Plain editor");
saveDisabled = Bindings.createBooleanBinding(
() -> manager.activeDockable() != editor.getDockable() || !editor.dirtyProperty().get(),
manager.activeDockableProperty(), editor.dirtyProperty());
save.disableProperty().bind(saveDisabled);
activeText = Bindings.createStringBinding(
() -> manager.activeDockable() == null ? "No active content" : "Active: " + manager.activeDockable().getTitle(),
manager.activeDockableProperty(), editor.getDockable().titleProperty(), plain.titleProperty());
active.textProperty().bind(activeText);
save.setOnAction(event -> {
if (manager.activeDockable() == editor.getDockable()) editor.checkpoint();
});
manager.open(plain, DockTarget.area("editors"));
manager.open(editor.getDockable(), DockTarget.area("editors"));
move.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.area("tools")));
floating.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.floating()));
returning.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.returnToMain()));
}
/** Releases application-owned global bindings when this demonstration ends. */
@Override public void close() {
save.disableProperty().unbind();
saveDisabled.dispose();
active.textProperty().unbind();
activeText.dispose();
for (var item : globalTools.getItems()) {
if (item instanceof Button button) {
button.setOnAction(null);
button.setDisable(true);
}
}
editor.close();
}
}
@@ -0,0 +1,80 @@
package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.injection.ApplicationContext;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.Property;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.value.ChangeListener;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import lombok.Getter;
/** Application adapter: one loaded View becomes ordinary Dockable content. */
public final class MvvmEditor implements AutoCloseable {
@Getter private final Note model = new Note("Edit this note, then move or float its tab.");
@Getter private final LoadedView view;
@Getter private final Dockable dockable;
private final Property<String> text;
private final Label status;
private final Button clear;
private final StringBinding titleBinding;
private final StringBinding statusBinding;
private String checkpoint;
private boolean released;
private final ReadOnlyBooleanWrapper dirty = new ReadOnlyBooleanWrapper(this, "dirty");
private final ChangeListener<String> changed = (observable, old, current) -> dirty.set(!java.util.Objects.equals(checkpoint, current));
@SuppressWarnings("unchecked")
public MvvmEditor(String id) {
view = ViewLoader.load(MvvmEditor.class.getResource("MvvmEditor.fxml"), model,
new ApplicationContext(MvvmEditor.class));
text = (Property<String>) view.property("text");
TextArea input = (TextArea) view.getRoot().lookup("#text");
dockable = new Dockable(new DockableId(id), view.getRoot());
dockable.setFocusTarget(() -> input);
checkpoint = model.getText();
text.addListener(changed);
titleBinding = Bindings.createStringBinding(() -> "Notes" + (dirty.get() ? " *" : ""), dirty);
dockable.titleProperty().bind(titleBinding);
status = (Label) view.getRoot().lookup("#localMessage");
statusBinding = Bindings.createStringBinding(() -> java.util.Objects.toString(text.getValue(), "").length() + " characters", text);
status.textProperty().bind(statusBinding);
ToolBar tools = (ToolBar) view.getRoot().lookup("#localTools");
clear = (Button) tools.getItems().getFirst();
clear.setOnAction(event -> input.clear());
dockable.setOnClosed(this::close);
dockable.setOnDiscarded(this::close);
}
public ReadOnlyBooleanProperty dirtyProperty() { return dirty.getReadOnlyProperty(); }
/** Records an in-memory checkpoint; this example does not write a file. */
public void checkpoint() {
if (released) return;
checkpoint = text.getValue();
dirty.set(false);
}
/** Releases this adapter's resources, not the LoadedView or global ViewModel identity cache. */
@Override public void close() {
if (released) return;
released = true;
text.removeListener(changed);
dockable.titleProperty().unbind();
titleBinding.dispose();
status.textProperty().unbind();
statusBinding.dispose();
status.setText("Released application listeners");
clear.setOnAction(null);
clear.setDisable(true);
}
}
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model de.neitzel.fx.example.model.Note?>
<?import de.neitzel.fx.control.StatusBar?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToolBar?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList><DirectBinding control="text" property="text" path="text" direction="both"/></BindingList>
</fx:define>
<top><ToolBar fx:id="localTools"><items><Button fx:id="clear" text="Clear note"/></items></ToolBar></top>
<center><TextArea fx:id="text" wrapText="true"/></center>
<bottom><StatusBar fx:id="localStatus">
<leftItems><Label fx:id="localMessage"/></leftItems>
<rightItems><Label text="This bar travels with Notes"/></rightItems>
</StatusBar></bottom>
</BorderPane>
@@ -0,0 +1,181 @@
package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.CloseResult;
import javafx.application.Platform;
import javafx.beans.property.Property;
import javafx.scene.Node;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** The example's loaded FXML and public docking operations are the integration boundary. */
class MvvmDockingTest {
@BeforeAll
static void startJavaFx() throws Exception {
CountDownLatch started = new CountDownLatch(1);
try { Platform.startup(started::countDown); }
catch (IllegalStateException alreadyStarted) { started.countDown(); }
assertTrue(started.await(10, TimeUnit.SECONDS));
onFx(() -> Platform.setImplicitExit(false));
}
@Test
void closeAndDiscardReleaseApplicationBindingsWithoutClaimingMvvmCacheDisposal() throws Exception {
onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage main = new Stage();
try (MvvmDockingWorkspace workspace = new MvvmDockingWorkspace(main)) {
main.show();
MvvmEditor editor = workspace.getEditor();
set(editor.getView().property("text"), "Unsaved before close");
assertInstanceOf(CloseResult.Closed.class,
workspace.getManager().requestTabClose(editor.getDockable().getId()).toCompletableFuture().join());
assertFalse(editor.getDockable().titleProperty().isBound(), "Actual close releases application title binding");
Label status = (Label) editor.getView().getRoot().lookup("#localMessage");
assertEquals("Released application listeners", status.getText());
String title = editor.getDockable().getTitle();
set(editor.getView().property("text"), "The retained ViewModel is still accessible");
assertEquals(title, editor.getDockable().getTitle());
assertEquals("Released application listeners", status.getText());
AtomicReference<MvvmEditor> prepared = new AtomicReference<>();
assertInstanceOf(ActionResult.Rejected.class, workspace.getManager().open(new DockableId("unused"), () -> {
MvvmEditor unused = new MvvmEditor("unused");
prepared.set(unused);
return unused.getDockable();
}, DockTarget.area("missing-area")));
assertTrue(workspace.getManager().findDockable(new DockableId("unused")).isEmpty());
assertFalse(prepared.get().getDockable().titleProperty().isBound(), "Rejected factory content uses onDiscarded");
Label discardedStatus = (Label) prepared.get().getView().getRoot().lookup("#localMessage");
assertEquals("Released application listeners", discardedStatus.getText());
set(prepared.get().getView().property("text"), "After discard");
assertEquals("Released application listeners", discardedStatus.getText());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
@Test
void aGlobalActionKeepsItsActiveEditorWhenFocusMovesToTheMainToolbar() throws Exception {
onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage main = new Stage();
try (MvvmDockingWorkspace workspace = new MvvmDockingWorkspace(main)) {
main.show();
main.getScene().getRoot().applyCss();
main.getScene().getRoot().layout();
Button save = (Button) main.getScene().getRoot().lookup("#saveActive");
Label active = (Label) main.getScene().getRoot().lookup("#activeStatus");
assertNotNull(save, "The global toolbar exposes an active-editor action");
assertNotNull(active);
assertTrue(save.isDisabled(), "An unchanged document needs no checkpoint");
MvvmEditor editor = workspace.getEditor();
TextArea plain = (TextArea) workspace.getPlain().getContent();
String unchangedPlain = plain.getText();
set(editor.getView().property("text"), "Changed while floating");
assertFalse(save.isDisabled());
workspace.getManager().move(editor.getDockable().getId(), DockTarget.floating());
main.toFront();
main.requestFocus();
save.requestFocus();
assertSame(save, main.getScene().getFocusOwner());
assertSame(editor.getDockable(), workspace.getManager().activeDockable());
assertTrue(active.getText().contains("Notes *"));
save.fire();
assertTrue(save.isDisabled());
assertEquals("Notes", editor.getDockable().getTitle());
assertEquals("Changed while floating", editor.getModel().getText());
assertEquals(unchangedPlain, plain.getText());
workspace.getManager().activate(workspace.getPlain().getId());
assertTrue(save.isDisabled(), "Plain content has no MVVM checkpoint command");
assertTrue(active.getText().contains("Plain editor"));
set(editor.getView().property("text"), "Changed again");
assertTrue(save.isDisabled(), "Changes in an inactive document do not steal the action target");
workspace.getManager().activate(editor.getDockable().getId());
assertFalse(save.isDisabled());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
@Test
void theSameLoadedEditorAndItsBarsKeepBidirectionalBindingsAcrossEveryMove() throws Exception {
onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage main = new Stage();
try (MvvmDockingWorkspace workspace = new MvvmDockingWorkspace(main)) {
main.show();
MvvmEditor editor = workspace.getEditor();
var loaded = editor.getView();
var model = editor.getModel();
var viewModel = loaded.getViewModel();
TextArea text = (TextArea) loaded.getRoot().lookup("#text");
Node localTools = loaded.getRoot().lookup("#localTools");
Node localStatus = loaded.getRoot().lookup("#localStatus");
Node globalTools = main.getScene().getRoot().lookup("#globalTools");
Node globalStatus = main.getScene().getRoot().lookup("#globalStatus");
assertNotNull(localTools);
assertNotNull(localStatus);
assertNotNull(globalTools);
assertNotNull(globalStatus);
text.setText("Unsaved edits");
assertEquals("Unsaved edits", model.getText());
int step = 0;
for (DockTarget target : List.of(DockTarget.area("tools"), DockTarget.floating(), DockTarget.returnToMain())) {
assertInstanceOf(ActionResult.Applied.class, workspace.getManager().move(editor.getDockable().getId(), target));
assertSame(loaded.getRoot(), editor.getDockable().getContent());
assertSame(viewModel, editor.getView().getViewModel());
assertSame(model, editor.getModel());
assertSame(text.getScene(), localTools.getScene());
assertSame(text.getScene(), localStatus.getScene());
assertSame(main.getScene(), globalTools.getScene());
assertSame(main.getScene(), globalStatus.getScene());
assertEquals("Unsaved edits", text.getText());
set(loaded.property("text"), "From model " + ++step);
assertEquals("From model " + step, text.getText());
assertEquals(text.getText(), model.getText());
text.setText("Unsaved edits");
assertEquals("Unsaved edits", loaded.property("text").getValue());
assertTrue(editor.getDockable().getTitle().endsWith("*"));
}
assertSame(main, text.getScene().getWindow());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
@SuppressWarnings("unchecked")
private static void set(Property<?> property, String value) { ((Property<String>) property).setValue(value); }
private static void onFx(CheckedAction action) throws Exception {
CountDownLatch done = new CountDownLatch(1);
AtomicReference<Throwable> failure = new AtomicReference<>();
Platform.runLater(() -> {
try { action.run(); }
catch (Throwable thrown) { failure.set(thrown); }
finally { done.countDown(); }
});
assertTrue(done.await(15, TimeUnit.SECONDS), "JavaFX operation completed");
if (failure.get() != null) fail("MVVM docking integration failed", failure.get());
}
@FunctionalInterface
private interface CheckedAction { void run() throws Exception; }
}