From 514cc7fb8ec85824aa4f62adecd52585fe8a9093 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Tue, 24 Nov 2026 14:31:31 +0100 Subject: [PATCH 1/3] Open an independent FXML component in a managed view context --- fx/README.md | 2 ++ .../java/de/neitzel/fx/view/ViewLoader.java | 26 +++++++++++++++++++ .../de/neitzel/fx/view/ManagedViewTest.java | 20 ++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/fx/README.md b/fx/README.md index acf22ce..0c9767c 100644 --- a/fx/README.md +++ b/fx/README.md @@ -48,6 +48,8 @@ The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Applic Depend on `de.neitzel.lib:fx`. That module depends on `core`, `injection` and on JavaFX base, controls, graphics, fxml, and web. Application types the container constructs use `jakarta.inject.Singleton` or `jakarta.inject.Named`. +Use `ViewLoader.loadComponent(type, model, context, models)` to open a reusable Component directly from its own FXML. It returns a managed `LoadedView` with the same Component, ViewModel selection and binding lifetime as an embedded instance. + ## Dependencies These are the versions configured by this source snapshot, not a promise of compatibility with every newer release: diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java index 6ada1fb..8f2d174 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java @@ -94,6 +94,32 @@ public final class ViewLoader { return load(fxml, model, context, models.openView()); } + /** + * Opens a Component's own fx:root document with the supplied Model. The Component selects + * its ViewModel in the same context as its nested Views. Closing the result detaches its + * bindings and releases its controller and children. + * + * @param type the injected Component class with a sibling ClassName.fxml + * @param model the initial non-null Model + * @param context the application container + * @param models the owner of the View and its Model identity + * @return the initialized Component and its effective ViewModel + */ + public static LoadedView loadComponent(Class type, Object model, + ApplicationContext context, ViewModelContext models) { + java.util.Objects.requireNonNull(model, "Component Model"); + ViewLifetime lifetime = models.openView(); + try { + Parent root = type.cast(Components.fresh(type, context, lifetime)); + Components.setModel(root, model, lifetime); + Object viewModel = ViewModels.of(models, model, ViewModels.namedOn(type)); + return new LoadedView(root, viewModel, lifetime); + } catch (RuntimeException | Error failure) { + lifetime.rollback(failure); + throw failure; + } + } + private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) { LoadSession session = LoadSession.nest(); try { diff --git a/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java b/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java index c596f92..ea5ae58 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java @@ -93,6 +93,26 @@ class ManagedViewTest { }); } + @Test + void opensAComponentDirectlyAndDetachesOnlyItsOwnBindings() throws Exception { + FxThread.onFx(() -> { + var model = new Address("Main"); + var services = new ApplicationContext("de.neitzel.fx.view.component"); + var type = de.neitzel.fx.view.component.AddressForm.class; + try (var models = new ViewModelContext()) { + var first = ViewLoader.loadComponent(type, model, services, models); + var second = ViewLoader.loadComponent(type, model, services, models); + assertSame(first.getViewModel(), second.getViewModel()); + var input = field(first.getRoot(), "#streetField"); + input.setText("Shared"); + assertEquals("Shared", field(second.getRoot(), "#streetField").getText()); + first.close(); + input.setText("Detached"); + assertEquals("Shared", model.getStreet()); + } + }); + } + @Test void removingARepeatChildDetachesItsBindings() throws Exception { FxThread.onFx(() -> { From e4f1fd3c96f79f22da8998f5a03d05363e30b1e2 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Tue, 24 Nov 2026 20:49:45 +0100 Subject: [PATCH 2/3] Bind saved HTML and replaceable suggestion catalogues toward the view --- fx/docs/fxml-controls.md | 14 ++++- fx/docs/html-viewer.md | 12 ++++ .../fx/control/AutoCompleteTextField.java | 42 +++++++++++-- .../de/neitzel/fx/control/HtmlViewer.java | 12 ++++ .../neitzel/fx/view/DirectBindingApplier.java | 15 ++++- .../de/neitzel/fx/control/HtmlViewerTest.java | 33 ++++++++++ .../fx/view/ListSourceBindingTest.java | 62 +++++++++++++++++++ 7 files changed, 182 insertions(+), 8 deletions(-) create mode 100644 fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java diff --git a/fx/docs/fxml-controls.md b/fx/docs/fxml-controls.md index a8eb5c1..2da595c 100644 --- a/fx/docs/fxml-controls.md +++ b/fx/docs/fxml-controls.md @@ -9,8 +9,8 @@ context. The optional `ViewLoader` applies NeitzelLib binding declarations. | `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size, `selectionMode` 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.control.AutoCompleteTextField` | Standard TextField attributes and a `suggestions` list of strings | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action | -| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Explicit `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) | +| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes, fixed `suggestions` and a bindable `suggestionsSource` of type `ObservableList` | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action | +| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Bind local text to `html` or use `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) | | `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model | | `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 | @@ -114,3 +114,13 @@ 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. + +### Model-driven suggestions + +Use `` +for an observable list of strings. A non-null source (including an empty list) takes precedence over +the fixed FXML entries in `getSuggestions()`. The popup follows replacements and edits to the active +list while the field is attached. Choosing a match sets the field text and fires its action. +Setting the source to null or unbinding `suggestionsSourceProperty()` restores the fixed entries. +Closing a managed DirectBinding restores its previous list source. Removing the field from its +scene dismisses the popup and detaches its list listener. diff --git a/fx/docs/html-viewer.md b/fx/docs/html-viewer.md index dd9c207..c53669d 100644 --- a/fx/docs/html-viewer.md +++ b/fx/docs/html-viewer.md @@ -34,6 +34,18 @@ message are included. New loads cancel pending work and discard stale results. `clear()` releases the current content and leaves the viewer reusable. `close()` also cancels pending work, is idempotent, and makes future loads fail. +## Model-driven source + +Bind a string toward the viewer with a DirectBinding such as +``. +For plain JavaFX use `viewer.htmlProperty().bind(source)`. Each changed string uses +the offline `loadHtml` preparation. A null or blank value clears the document. +Rapid changes cancel older preparations and revoke earlier media grants. +The property contains the supplied source. Displaying a prepared document, loading a file, +granting image access or clearing the viewer changes the display without writing to the model. +The next change to the bound text takes effect. Unbinding leaves the current display in place. +Close the viewer on disposal to detach a JavaFX binding and cancel outstanding work. + ## External images Each displayed document starts offline. The included **Load external media** diff --git a/fx/src/main/java/de/neitzel/fx/control/AutoCompleteTextField.java b/fx/src/main/java/de/neitzel/fx/control/AutoCompleteTextField.java index a249a6f..72a7b63 100644 --- a/fx/src/main/java/de/neitzel/fx/control/AutoCompleteTextField.java +++ b/fx/src/main/java/de/neitzel/fx/control/AutoCompleteTextField.java @@ -1,9 +1,13 @@ package de.neitzel.fx.control; import java.util.Locale; +import javafx.beans.InvalidationListener; +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; +import javafx.collections.WeakListChangeListener; import javafx.event.ActionEvent; import javafx.scene.control.ListView; import javafx.scene.control.TextField; @@ -16,6 +20,18 @@ import javafx.stage.Popup; public final class AutoCompleteTextField extends TextField { private static final int ROW_HEIGHT = 26; private final ObservableList suggestions = FXCollections.observableArrayList(); + private final ObjectProperty> suggestionsSource = + new SimpleObjectProperty<>(this, "suggestionsSource") { + @Override public void unbind() { + if (isBound()) { + super.unbind(); + set(null); + } + } + }; + private final ListChangeListener contentChanged = change -> updateSuggestions(); + private final WeakListChangeListener weakContentChanged = new WeakListChangeListener<>(contentChanged); + private ObservableList observedSuggestions; private final ListView choices = new ListView<>(); private final Popup popup = new Popup(); private boolean accepting; @@ -29,9 +45,12 @@ public final class AutoCompleteTextField extends TextField { var value = choices.getSelectionModel().getSelectedItem(); if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value); }); - suggestions.addListener((ListChangeListener) change -> updateSuggestions()); + suggestionsSource.addListener((InvalidationListener) ignored -> observeSuggestions()); textProperty().addListener((property, before, after) -> updateSuggestions()); - sceneProperty().addListener((property, before, after) -> popup.hide()); + sceneProperty().addListener((property, before, after) -> { + popup.hide(); + observeSuggestions(); + }); disabledProperty().addListener((property, before, disabled) -> { if (disabled) popup.hide(); }); @@ -42,6 +61,21 @@ public final class AutoCompleteTextField extends TextField { return suggestions; } + /** Optional live catalogue. Without a source the fixed FXML suggestions are used. */ + public ObjectProperty> suggestionsSourceProperty() { return suggestionsSource; } + public ObservableList getSuggestionsSource() { return suggestionsSource.get(); } + public void setSuggestionsSource(ObservableList value) { suggestionsSource.set(value); } + + private void observeSuggestions() { + var source = getSuggestionsSource(); + var next = getScene() == null ? null : source == null ? suggestions : source; + if (observedSuggestions == next) return; + if (observedSuggestions != null) observedSuggestions.removeListener(weakContentChanged); + observedSuggestions = next; + if (next != null) next.addListener(weakContentChanged); + updateSuggestions(); + } + private void handleKey(KeyEvent event) { var selection = choices.getSelectionModel(); if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) { @@ -67,11 +101,11 @@ public final class AutoCompleteTextField extends TextField { } private void updateSuggestions() { - if (accepting || !isFocused() || isDisabled() || getScene() == null + if (observedSuggestions == null || accepting || !isFocused() || isDisabled() || getScene() == null || getScene().getWindow() == null || !getScene().getWindow().isShowing()) return; String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT); var matches = prefix.isEmpty() ? java.util.List.of() - : suggestions.stream().filter(value -> value != null && !value.isBlank()) + : observedSuggestions.stream().filter(value -> value != null && !value.isBlank()) .filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList(); choices.getItems().setAll(matches); choices.getSelectionModel().clearSelection(); diff --git a/fx/src/main/java/de/neitzel/fx/control/HtmlViewer.java b/fx/src/main/java/de/neitzel/fx/control/HtmlViewer.java index ffe647a..57210b1 100644 --- a/fx/src/main/java/de/neitzel/fx/control/HtmlViewer.java +++ b/fx/src/main/java/de/neitzel/fx/control/HtmlViewer.java @@ -34,6 +34,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable { private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload external media"); private final StringProperty mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers."); private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found."); + private final StringProperty html = new SimpleStringProperty(this, "html"); private HtmlDocument document; private Task pending; private long generation; @@ -41,6 +42,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable { public HtmlViewer() { getStyleClass().add("html-viewer"); + html.addListener((observable, before, value) -> { + if (closed) return; + if (value == null || value.isBlank()) clear(); + else loadHtml(value); + }); browser.setContextMenuEnabled(false); browser.getEngine().setJavaScriptEnabled(false); loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty())); @@ -153,6 +159,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable { @Override public void close() { requireFxThread(); if (closed) return; + html.unbind(); clear(); closed = true; } @@ -166,6 +173,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable { if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread."); } + /** Local source text. Imperative display operations do not publish values to this input. */ + public StringProperty htmlProperty() { return html; } + public String getHtml() { return html.get(); } + public void setHtml(String value) { requireOpen(); html.set(value); } + public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); } public boolean isLoading() { return loading.get(); } public ReadOnlyObjectProperty errorProperty() { return error.getReadOnlyProperty(); } diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java index 0f6fa6a..564d161 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java @@ -5,6 +5,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; +import javafx.beans.InvalidationListener; import javafx.beans.property.Property; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; @@ -58,7 +59,8 @@ final class DirectBindingApplier { return; } if (attribute.getValue() instanceof ObservableList values) { - assignList(controlProperty, values, lifetime); + if ("view".equals(binding.getDirection())) alignTowardView(controlProperty, attribute, lifetime); + else assignList(controlProperty, values, lifetime); return; } String converterName = binding.getConverter(); @@ -551,8 +553,17 @@ final class DirectBindingApplier { private static void alignTowardView(Property controlProperty, ObservableValue attribute, ViewLifetime lifetime) { Property control = (Property) controlProperty; + Object previous = control.getValue(); control.setValue(attribute.getValue()); - lifetime.listen(attribute, (observable, oldValue, newValue) -> control.setValue(newValue)); + // ChangeListeners may suppress a new list whose elements equal the previous list. + InvalidationListener follow = ignored -> control.setValue(attribute.getValue()); + attribute.addListener(follow); + lifetime.own(() -> { + attribute.removeListener(follow); + if ((previous instanceof ObservableList || control.getValue() instanceof ObservableList) + && control.getValue() == attribute.getValue()) + control.setValue(previous); + }); } /** diff --git a/fx/src/test/java/de/neitzel/fx/control/HtmlViewerTest.java b/fx/src/test/java/de/neitzel/fx/control/HtmlViewerTest.java index db873b3..cd3619c 100644 --- a/fx/src/test/java/de/neitzel/fx/control/HtmlViewerTest.java +++ b/fx/src/test/java/de/neitzel/fx/control/HtmlViewerTest.java @@ -62,6 +62,39 @@ class HtmlViewerTest { return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load"); } + @Test void boundLocalTextReplacesPendingWorkAndDetachesOnClose() throws Exception { + var ref = new AtomicReference(); + var source = new javafx.beans.property.SimpleStringProperty("

First

"); + var replacement = new javafx.beans.property.SimpleStringProperty("

Second

"); + fx(() -> { + var viewer = new HtmlViewer(); + ref.set(viewer); + viewer.htmlProperty().bind(source); + viewer.htmlProperty().bind(replacement); + source.set("

Detached

"); + replacement.set("

Third

"); + }); + var viewer = ref.get(); + try { + await(() -> !viewer.isLoading() && loaded(viewer) && browser(viewer).getEngine().getDocument() + .getDocumentElement().getTextContent().contains("Third")); + fx(() -> { + viewer.clear(); + assertEquals("

Third

", replacement.get()); + replacement.set(null); + replacement.set(" "); + assertNull(viewer.getError()); + assertFalse(viewer.isExternalImagesAllowed()); + replacement.set("

Pending

"); + viewer.close(); + assertFalse(viewer.htmlProperty().isBound()); + replacement.set("

Too late

"); + assertFalse(viewer.isLoading()); + assertEquals("

Pending

", viewer.getHtml()); + }); + } finally { fx(viewer::close); } + } + @Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception { fx(() -> { var loader = new javafx.fxml.FXMLLoader(); diff --git a/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java b/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java new file mode 100644 index 0000000..fa2c30c --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java @@ -0,0 +1,62 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.control.AutoCompleteTextField; +import de.neitzel.injection.ApplicationContext; +import java.util.Map; +import javafx.beans.property.ListProperty; +import javafx.beans.property.SimpleListProperty; +import javafx.collections.FXCollections; +import javafx.scene.control.ComboBox; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class ListSourceBindingTest { + public static class Tags { + private final ListProperty tags = + new SimpleListProperty<>(FXCollections.observableArrayList("First")); + public ListProperty tagsProperty() { return tags; } + } + + @BeforeAll static void toolkit() throws Exception { DataGridTest.start(); } + + @Test void viewBindingTracksEqualListReplacementAndRestoresThePreviousItems() throws Exception { + DataGridTest.fx(() -> { + var model = new Tags(); + var combo = new ComboBox(); + var previous = combo.getItems(); + var binding = new DirectBinding(); + binding.setControl("combo"); + binding.setProperty("items"); + binding.setPath("tags"); + binding.setDirection("view"); + try (var models = new ViewModelContext(); var lifetime = new ViewLifetime(models)) { + DirectBindingApplier.apply(Map.of("combo", combo), model, binding, new ApplicationContext(Tags.class), lifetime); + assertSame(model.tags.get(), combo.getItems()); + var replacement = FXCollections.observableArrayList("First"); + model.tags.set(replacement); + assertSame(replacement, combo.getItems()); + model.tags.set(null); + assertNull(combo.getItems()); + } + assertSame(previous, combo.getItems()); + model.tags.set(FXCollections.observableArrayList("Detached")); + assertSame(previous, combo.getItems()); + }); + } + + @Test void ordinaryJavaFxBindingReturnsToFixedSuggestionsOnUnbind() throws Exception { + DataGridTest.fx(() -> { + var field = new AutoCompleteTextField(); + field.getSuggestions().add("Fixed"); + var model = new Tags(); + field.suggestionsSourceProperty().bind(model.tags); + assertSame(model.tags.get(), field.getSuggestionsSource()); + field.suggestionsSourceProperty().unbind(); + assertNull(field.getSuggestionsSource()); + model.tags.set(FXCollections.observableArrayList("Detached")); + assertNull(field.getSuggestionsSource()); + assertEquals(java.util.List.of("Fixed"), field.getSuggestions()); + }); + } +} From 4a455e63ab844e5070d90fd7a4e4d0abc85bc2df Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Tue, 24 Nov 2026 20:52:35 +0100 Subject: [PATCH 3/3] Document one-way list replacement in the FX binding guide --- fx/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fx/README.md b/fx/README.md index 0c9767c..cc1ebe3 100644 --- a/fx/README.md +++ b/fx/README.md @@ -175,7 +175,7 @@ For `both` and `model`, the write happens when the JavaFX property changes, incl `BindingList` is the element that holds direct bindings, computed bindings, command bindings, and repeats. Its default property is `elements`, so the children in FXML are the list. An unknown child fails the load with `Not a binding element:`. Command bindings require a managed View. -When the attribute value is already an `ObservableList`, the control property is set to that same list. Direction and converter are not consulted. The tag binding names `direction="view"` and still shares the list. See [A list of simple values](#a-list-of-simple-values). +When the attribute value is already an `ObservableList`, the control property is set to that same list. With `direction="view"`, the control also follows replacement of the list reference, including a replacement with equal elements. Closing a managed View detaches that observation and restores the previous list if the control still holds the supplied list. Other directions retain their shared-list assignment. The writable observable-list path bypasses converters. See [A list of simple values](#a-list-of-simple-values). A binding that names no such control fails with `No control "` and the id. A missing `xxxProperty()` method fails with `No property` and the property name. A method that returns something other than a `Property` fails with `did not return a property`.