Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Share navigation between model views

Русская версия · Model bookmarks

Use one navigation context when a list and table should follow the same current record. Create separate contexts when each view needs an independent cursor. The scene owns the context; removing a view does not erase its position.

For ordinary declarative consumers, pass ui::navigation(model) directly to list and table factories. Model workspaces show complete programs. The advanced operations below use the checked managed API in <portals/managed.hpp>. The model, scene and view nodes in the fragment already exist on the UI thread. Both views use the same ManagedModel<T>:

auto navigation = scene.navigation(model);
if (!navigation) {
return std::unexpected(navigation.error());
}
auto listBinding = scene.bindNavigation(list, *navigation);
if (!listBinding) {
return listBinding;
}
return scene.bindNavigation(table, *navigation);

The context creates its resource identity automatically. Creating another context for the same managed model reuses the resource domain but keeps its cursor separate. Bindings are opt-in; unbound views keep their existing behavior.

Current, selection and reading position

current() publishes the logical current record. selection() publishes an independent bounded selected set. readingAnchor() identifies the first record being read. Keyboard focus and fractional viewport offsets remain local to each view. Scrolling alone never changes current.

Default bindings share current. Pass NavigationBindingOptions{.readingAnchor = true} to also share the reading anchor. Each projection maps the stable row identity to its own order; views do not copy each other's screen offsets. A projection without the requested record leaves its own viewport in place. Absence from a filtered projection does not establish deletion from the source.

A binding to another model requires the explicit NavigationProjection::PRESERVES_ROW_IDS agreement. The caller guarantees that complete row identities refer to the original resource. The library cannot prove that guarantee from equal ordinal positions.

setSelection canonicalizes complete IDs and defaults to at most 1024 entries, configurable through NavigationOptions::maxSelectedRows. The channel is available to observers; the standard list/table binding still uses its existing single-current selection behavior. It does not add multi-selection painting to those controls.

Preparation and idle delivery

Bindings read current and reading state during view preparation. When a later view materializes a new canonical position, the scene requests an ordinary next frame so earlier views can consume the latest value without another input. The first paint may still contain the earlier prepared state; atomic same-pixel-frame presentation is not guaranteed. Unchanged positions do not keep requesting frames. This continuation does not raise the preparation-pass budget or change failure handling for genuine LAYOUT nonconvergence. Direct context navigation still requires the provider's bounded identity-lookup capability.

Update and resolve

navigate(RowId) uses bounded identity lookup. A surviving row keeps its current identity across insertions and reordering. A ready identity index can update exact position metadata even while the row payload is pending. bookmark() and readingBookmark() return the latest revision-qualified metadata separately from the logical channels. Reordering the same record does not notify current observers.

Removal needs a complete PositionChangeMap, supplied with setChangeMap, or a provider reply. The default affinity chooses a surviving successor, then a predecessor at the end. Missing proof does not silently choose the old row number. A pending result retains the bookmark; it retries on model publication or explicit resolution, without polling. The finite fallback cannot promise convergence when the provider cannot expose the required replacement identity through its base snapshot.

For an external resolver, create a context with a ModelResource and source session, call beginResolve, perform I/O on the existing worker path, and deliver applyReply on the UI thread. Session, target revision and request sequence reject stale replies. The generic context does not require a total row count or own a scheduler.

Lifetime, errors and scope

Handles are weak and UI-affine. Use them on the scene's thread; wrong-thread access returns WRONG_THREAD, and access after scene closure returns CLOSED. Closing the scene cancels pending resolution. Bookmarks and copied channel snapshots remain independent values. Provider errors and allocation failures use the existing typed error paths. Successful earlier channels can remain committed if a later channel fails; retrying does not duplicate their logical notifications.

This integration covers managed finite-model lists and tables plus the generic navigation context. LogView source switching provides its own bounded reading checkpoints. Model switching restores list/table positions by default. Current-record forms and persistent storage remain separate integrations. The existing low-level model and view APIs remain available.

Complete provider-integration example

Three lists follow the same stable current city across different ordering

Full source shows three framed lists. The first two share reading position; all three share current, including a reverse-order projection. Tab changes focus, arrows navigate, and F10 closes the application. Build portals_docs_model_navigation with tests enabled, or compile the source against the installed SDK. This advanced example keeps the provider and checked binding steps visible; it is not a compact model-descriptor tutorial.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <array>
#include <functional>
#include <string_view>
#include <utility>
using namespace portals;
// Static names outlive every snapshot; views borrow no mutable or temporary strings.
class Cities final : public ModelSnapshot<std::string_view> {
public:
explicit Cities(bool reverse = false) : ModelSnapshot(1, NAMES.size()), reverse_(reverse) {
for (std::size_t index = 0; index < rows_.size(); ++index) {
const auto original = reverse ? rows_.size() - index - 1 : index;
rows_[index] = {{original + 1, 1}, NAMES[original]};
}
}
ModelRows<std::string_view> read(RowRange range) const override {
return {RangeState::READY, std::span(rows_).subspan(range.first, range.count), {}};
}
RowLookup locateRow(RowId id) const override {
if (id.generation != 1 || id.value == 0 || id.value > rows_.size()) {
return {RowLookupState::NOT_FOUND, 0};
}
return {RowLookupState::FOUND, reverse_ ? rows_.size() - id.value : id.value - 1};
}
private:
static constexpr std::array<std::string_view, 12> NAMES{"Paris", "Prague", "London", "Tokyo", "Oslo", "Berlin",
"Vienna", "Helsinki", "Madrid", "Lisbon", "Rome", "Tallinn"};
std::array<ModelRow<std::string_view>, NAMES.size()> rows_;
bool reverse_{};
};
GraphemeText cityCaption(std::string_view name) {
return GraphemeText::from(name).value();
}
template <class Source> auto cityList(Source source) {
return ui::virtualList(std::move(source), std::identity{}, cityCaption).width(20).height(7);
}
int main() {
// clang-format off
return ui::scene([&](ManagedScene &) {
auto source = ui::model<std::string_view>(std::make_shared<Cities>());
auto reverse = ui::model<std::string_view>(std::make_shared<Cities>(true));
navigation = ui::navigation(source, {.readingAnchor = true});
return ui::vbox(
ui::label("Shared cities | Tab: focus | arrows: current | wheel: read | F10: quit"),
ui::hbox(
cityList(navigation).framed("rounded", "Cities"),
cityList(navigation).framed("rounded", "Same order"),
cityList(reverse).reference(reversed).framed("rounded", "Reverse order")),
ui::label("Current is shared. Scrolling the first two views shares their reading position."));
})
| ui::configure([&navigation, reversed](ManagedScene &owner) -> std::expected<void, ManagedError> {
auto managed = navigation.managed();
if (!managed) {
return std::unexpected(managed.error());
}
return owner.bindNavigation(reversed.node(), *managed,
{.projection = NavigationProjection::PRESERVES_ROW_IDS});
})
| ui::theme(nordTheme())
| ui::onKey(key::F10, ui::quit)
| ui::runApp();
// clang-format on
}
Owning validated UTF-8 and immutable extended grapheme measurements.
Definition text.hpp:145
static std::expected< GraphemeText, TextError > from(std::string_view bytes, WidthPolicy policy={}, TextLimits limits={})
Validate, segment and measure a single logical UTF-8 buffer.
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
std::expected< void, ManagedError > bindNavigation(Node< VirtualList< T > > node, ManagedNavigation navigation, NavigationBindingOptions options={})
Definition managed_navigation_views.hpp:257
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
Cold explicit shared navigation; ordinary model-source views stay independent.
Definition ui_model.hpp:248
Node< T > node() const noexcept
Definition ui_ref.hpp:731
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
auto reference(ui::Ref< T > value)
Definition ui_static.hpp:572
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()