Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Compose controls in virtual rows

Русская версия

Use ui::virtualRows when each model record needs interactive controls: a task with a checkbox, an editable name and a Remove button, for example. The view creates ordinary control subtrees for the visible records. The model retains the data when a row leaves the viewport.

For a list whose rows are formatted text, use VirtualList. For columns with headers, use VirtualTable.

Task lists

The complete program has two task models. Work and Personal switch the model used by the same view. Each row contains a CheckBox, Label, LineEdit and Button. The asterisk marks the active model, independently of keyboard focus on a button. The bounded panel shows the visible range, exact task count and current row. F10 closes the application.

Move between rows and list selectors, switch models and restore the current and reading positions.

Complete source.

Complete program

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
#include <portals/ui_virtual_rows.hpp>
#include <array>
#include <format>
#include <string>
using namespace portals;
struct Task {
bool done;
std::string caption;
std::string category;
bool operator==(const Task &) const = default;
};
std::string taskPosition(const VirtualRowsPosition &position) {
if (!position.count) {
return "Preparing tasks...";
}
if (*position.count == 0) {
return "No tasks";
}
if (!position.firstIndex || !position.visible) {
return "Preparing tasks...";
}
auto result = std::format("Visible {}-{} of {}", *position.firstIndex + 1, *position.firstIndex + position.visible,
*position.count);
if (position.currentIndex) {
const bool outside = *position.currentIndex < *position.firstIndex ||
*position.currentIndex >= *position.firstIndex + position.visible;
result += std::format(" | Current {}{}", *position.currentIndex + 1, outside ? " (outside view)" : "");
}
return result;
}
int main() {
auto work =
ui::model(std::array{Task{false, "Review release notes", "Docs"}, Task{true, "Check package install", "Build"},
Task{false, "Verify keyboard focus", "UI"}, Task{false, "Review translations", "Docs"},
Task{false, "Publish documentation", "Docs"}, Task{false, "Remove old artifacts", "Build"},
Task{false, "Review accessibility", "UI"}, Task{false, "Check resize behavior", "UI"},
Task{false, "Prepare the change log", "Docs"}, Task{false, "Review package metadata", "Build"},
Task{false, "Record the new example", "UI"}, Task{false, "Review the final patch", "Review"}});
auto personal = ui::model(std::array{Task{false, "Buy groceries", "Home"}, Task{true, "Water the plants", "Home"},
Task{false, "Read a chapter", "Study"}, Task{false, "Practice French", "Study"},
Task{false, "Plan the weekend", "Home"}, Task{false, "Sort the photos", "Home"},
Task{false, "Back up the notes", "Home"}, Task{false, "Call a friend", "Home"}});
auto navigation = ui::navigation(work, {.readingAnchor = true});
auto current = navigation.current();
auto position = rows.position();
// clang-format off
return ui::scene(ui::vbox(
ui::hbox(
ui::button(current, ui::bySource<Task>({{work, "Work *"}, {personal, "Work"}}))
.onClick([navigation, work] { navigation.model(work); }),
ui::button(current, ui::bySource<Task>({{work, "Personal"}, {personal, "Personal *"}}))
.onClick([navigation, personal] { navigation.model(personal); })),
ui::virtualRows(navigation, [](auto row) {
return ui::hbox(
ui::checkbox("", row.field(&Task::done)),
ui::label(row.field(&Task::category)).width(8),
ui::lineEdit(row.field(&Task::caption)).maxWidth(36),
ui::button("Remove").onClick([row] { return row.erase(); }));
}).reference(rows).height(8).framed("rounded", "Task lists"),
ui::label(position, taskPosition),
ui::label(position, [](const VirtualRowsPosition &value) -> std::string {
return value.editing ? "Tab fields | Esc rows | F10 quit"
: "Up/Down rows | F2 fields | Tab lists | F10 quit";
})).maxWidth(76))
| ui::theme(nordTheme())
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()
Owning committed row-host orientation; native cursor sources never invent ordinals.
Definition virtual_rows.hpp:53
std::optional< std::uint64_t > count
Exact finite extent; never an estimate.
Definition virtual_rows.hpp:59
std::optional< std::uint64_t > currentIndex
Zero-based finite ordinal, absent for native cursors.
Definition virtual_rows.hpp:56
std::size_t visible
Ready visible row assignments, excluding retained edit state.
Definition virtual_rows.hpp:58
std::optional< std::uint64_t > firstIndex
First visible finite ordinal, absent for native cursors.
Definition virtual_rows.hpp:57

The standalone guide project builds guide_virtual_rows and links portals::core. Include <portals/ui_virtual_rows.hpp> to opt into this API.

Move between lists, rows and fields

The view has two keyboard modes. In row navigation, the whole view is one stop in the outer Tab order. You can return to the list selectors without visiting every checkbox, field and button in the model.

Key Row navigation Inside the current row's controls
Tab / Shift+Tab Move to the next / previous outer control Move between this row's controls
Up / Down Move the current row and reveal it The focused control keeps its own input behavior
Enter / F2 Enter the current row's controls The focused control keeps its own input behavior
Escape Keep row navigation Return to row navigation after checked editing admission

At the first or last row, another arrow does not send focus to the list selectors. The current row follows stable record identity; scrolling the reading window and changing the current record remain separate operations. Mouse input can enter the ordinary controls. A rejected edit transition keeps its draft and validation state; Escape does not introduce a blanket commit or cancel policy.

Enter or F2 opens the current row; Escape returns to row navigation. The next recording also shows field focus, editing and removal.

Enter row controls, change a checkbox and task name, then remove the current record.

Observe the current position

Keep a ui::Ref<VirtualRows<T>>; its position() method exposes a read-only model. Place labels bound to that model after the view in the scene description. The complete program uses ordinary labels for the position and keyboard mode. Updates follow accepted view changes; the application does not need a polling timer or a second mutable position variable.

VirtualRowsPosition separates the current record from the reading window:

Member Meaning
resource, current Source-qualified current record identity, or no current record.
currentIndex, firstIndex Optional exact zero-based ordinals; unavailable for unknown-total cursor sources.
visible Ready records visible in the window, excluding retained offscreen editors.
count Optional exact source count; absence does not mean zero.
hasBefore, hasAfter Optional knowledge that more records exist in each direction.
windowStatus Optional native delivery state.
editing Whether focus is inside the current row's controls.

The task program displays one-based numbers for people. The file-backed program shows visible records and known traversal directions, without an invented count or percentage. Navigation::current() and ui::bySource provide accepted active source captions; merely focusing a selector does not switch its model.

Records, fields and callbacks

The row factory returns a fresh ordinary description. row.field(&Task::done) binds the checkbox to that exact record; it does not follow the current selection. Reordering the model cannot redirect a saved field or action to a different row. When an assignment retires, its saved handles report CLOSED.

row.value() borrows an immutable value only while the factory runs. Copy the fields needed to build labels. A later callback can call row.snapshot() to obtain a checked owning data lease. Retaining that lease keeps the original data page alive and uses the source's page budget; it does not retain controls. The record and any borrowed members remain readable while the lease lives.

The field adapters use the same editing contract as other model-bound controls. The default edit mode is IMMEDIATE. Validation, conflicts and endpoint failures remain checked outcomes. A read-only provider requires an explicit writable EditEndpoint before a row field can change its data.

Use ui::label(row.field(&Task::category)) for a live accepted field value. It updates without replacing the active editor. A label constructed from row.value().category is a factory snapshot; it refreshes when that row recipe is rebuilt. While an assignment is retained for focus or local editor history, its snapshot-only labels retain their original text. Prefer field bindings for independently changing captions.

With EXPLICIT editing, one unfinished row can remain retained outside the viewport. Its draft, Undo history, cursor, selection and validation state stay together. Starting another unfinished row fails before changing its data. With ON_COMPLETION, scrolling an unfinished row out of view is rejected; finish or cancel it explicitly first. Scrolling does not silently commit or cancel edits.

Accepted Undo history remains local to the mounted editor. Committing does not clear that history while the editor remains mounted. After a completed row is destroyed and remounted, it starts with a new editor history. The view does not retain completed editor histories for every record ever visited. These policies do not change an independently owned EditSession.

Models, states and derived values declared inside a row factory belong to that assignment and are released when it retires. A shared model declared outside the factory retains its scene ownership even when its first consumer is a row. A newly declared cold model cannot be read before it is mounted; checked access reports CLOSED until publication.

Size and composition

The example limits its whole panel with maxWidth(76) and lets the name field shrink in a narrower terminal. This does not measure every record in the model. Choose viewport width limits for your composition; the host does not scan a potentially unbounded source to discover its longest row.

height(8) sets the viewport height in terminal cells, including its frame. VirtualRowsOptions::rowHeight sets the common height of a record's child composition; its default is one cell. Use a larger value for a ui::vbox of fields. A child requiring more height than its slot reports INVALID_GEOMETRY.

maxRows bounds the number of visible assignments; its default is 256. This is a view resource limit, independent of the number of records in the model. An oversized viewport is rejected rather than silently hiding required rows.

Natural record height

Use .autoRowHeight() when records contain different compositions of fields. The task-card example puts the editable title in one row and optional notes below it. Each card has its own frame, so shorter records occupy less vertical space. height(13) still controls the viewport; it does not set each card's height.

Task cards with different composed heights, a current marker and a visible reading range.
Navigating, switching sources and restoring a task-card reading position.
// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
#include <portals/ui_virtual_rows.hpp>
#include <array>
#include <format>
#include <string>
using namespace portals;
struct TaskCard {
bool done;
std::string title;
std::string category;
std::string note;
std::string next;
bool operator==(const TaskCard &) const = default;
};
std::string cardPosition(const VirtualRowsPosition &position) {
if (!position.count || !position.firstIndex || !position.visible) {
return "No visible tasks";
}
return std::format("Visible {}-{} of {} | Current {}", *position.firstIndex + 1,
*position.firstIndex + position.visible, *position.count,
position.currentIndex.value_or(*position.firstIndex) + 1);
}
int main() {
auto work = ui::model(
std::array{TaskCard{false, "Check keyboard navigation", "UI", "Keep focus on the selected task.",
"Then edit its title with F2."},
TaskCard{true, "Check the installed package", "Build", "", ""},
TaskCard{false, "Review the guide", "Docs", "Check the complete application and its animation.", ""},
TaskCard{false, "Try a narrow window", "UI", "Resize the terminal while reading this task.",
"The same task should remain in view."},
TaskCard{false, "Publish the notes", "Docs", "", ""},
TaskCard{false, "Remove old artifacts", "Build", "Keep the EXE and GIF for review.", ""}});
auto personal = ui::model(std::array{
TaskCard{false, "Read a chapter", "Study", "Resume from the saved bookmark.", ""},
TaskCard{false, "Plan the weekend", "Home", "", ""}, TaskCard{true, "Water the plants", "Home", "", ""}});
auto navigation = ui::navigation(work, {.readingAnchor = true});
auto current = navigation.current();
auto position = cards.position();
// clang-format off
return ui::scene(ui::vbox(
ui::hbox(
ui::button(current, ui::bySource<TaskCard>({{work, "Work *"}, {personal, "Work"}}))
.onClick([navigation, work] { navigation.model(work); }),
ui::button(current, ui::bySource<TaskCard>({{work, "Personal"}, {personal, "Personal *"}}))
.onClick([navigation, personal] { navigation.model(personal); })),
ui::virtualRows(navigation, [](auto row) {
return ui::vbox(
ui::hbox(ui::checkbox("", row.field(&TaskCard::done)),
ui::lineEdit(row.field(&TaskCard::title)),
ui::button("Remove").onClick([row] { return row.erase(); })),
ui::label(row.field(&TaskCard::note)).visible(!row.value().note.empty()),
ui::label(row.field(&TaskCard::next)).visible(!row.value().next.empty()))
.framed("rounded", row.value().category);
}).autoRowHeight().reference(cards).height(13).framed("rounded", "Task cards"),
ui::label(position, cardPosition),
ui::label(position, [](const VirtualRowsPosition &value) -> std::string {
return value.editing ? "Tab fields | Esc cards | F10 quit"
: "Up/Down | F2 edit | Tab lists | F10 quit";
})).maxWidth(76))
| ui::theme(nordTheme())
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
auto reference(ui::Ref< T > value)
Definition ui_static.hpp:572

Build portals_docs_virtual_row_cards with PORTALS_BUILD_TESTS=ON. The complete source uses the same ordinary checkbox, label, editor and button factories as the fixed-height example. The active source is marked with *; keyboard focus is shown independently. Up/Down select records; Enter/F2 enters their controls and Escape returns to record navigation. In natural-height mode, wheel and page movement can pass through the inside of a record taller than the viewport.

The wheel reads through individual terminal rows while the current record stays selected. This also exposes the inside of a card taller than the viewport.

Cell-by-cell reading through composed task cards.

Enter/F2 opens the current card's existing controls; Tab moves between its fields.

Editing the current task card and returning to record navigation.

Resizing the terminal retains the current record and reading place. Ordinary one-line labels clip to the available width.

The same task remains current as the real terminal viewport narrows and widens.

The host measures a bounded set of real row compositions at their available content width. It does not read every record to build a global height index. Resize and changes to the measured composition preserve the first stable record and its cell offset, clamping that offset when a record becomes shorter. Source switching retains this reading position through the existing bounded history. Unknown-total sources keep their cursor capabilities and do not acquire an invented count or global pixel extent. A multi-record finite scrollbar uses record positions, not a fully indexed sum of all record heights. A single measured finite record can use its known cell height as an exact local extent. Natural-height finite views keep a stable scrollbar column while their source is nonempty, including when every record fits. This keeps the measurement width constant. The default fixed-height mode continues to hide an unnecessary bar. Set scrollbar = false in VirtualRowsOptions to omit that column.

Natural sizing does not change the text behavior of a child. Ordinary Label remains one-line; its visibility in this example is chosen when the row recipe is created. A child that already supports width-dependent wrapping may change its measured height when the available width changes. .autoRowHeight(false) selects the configured common rowHeight again. Advanced limits remain optional through VirtualRowsOptions; the ordinary example needs no explicit measurement options.

A viewport child without a natural content height still needs an explicit finite height. A completely empty composition occupies at least one cell, keeping the number of required records bounded. Cell offsets are retained in the host's in-memory source history; portable checkpoint codecs do not serialize this additional offset.

Host options

Pass a VirtualRowsOptions value as the third argument to ui::virtualRows.

Member Default Meaning
rowHeight 1 Positive common height in fixed mode, in terminal cells.
maxRows 256 Positive limit on assignments required by the visible viewport.
overscanRows 2 Additional native records requested for bounded row-step overlap.
maxPendingRows 4096 Positive cap on queued relative movement: records in fixed mode, cells in natural-height mode.
editing EditOptions{} Common edit mode and retained field/byte limits.
checkpoints ModelCheckpointOptions{} Existing bounded source-position history settings.
scrollbar true Use the styled finite-source scrollbar; natural-height mode retains its column for nonempty data.
currentIndicator true Reserve a left cell for the current-row marker.
autoRowHeight false Measure positive record heights from bounded composed content; .autoRowHeight() is the ordinary fluent form.

During a replacement, staged and retiring child trees can coexist. maxRows does not mean that the process contains at most that many controls: a row may contain several controls, and one unfinished edit may retain an extra row. The source separately accounts for prepared pages and explicitly retained data leases. Over-limit movement is rejected with a checked error.

Style the controls and frame

The host's style type is VirtualRows. Its children retain their ordinary style types: CheckBox, Label, LineEdit and Button. Their guides list supported properties and states. A row composition may add classes and IDs using the ordinary description API. Apply themes to the scene in the usual way.

Use .framed("rounded", "Task lists") for a titled boundary. Frame glyphs, title decoration and colors use the common styling guide. The current-row marker is separate from focus on an individual child. The vertical scrollbar uses the existing scrollbar styles in a compact right gutter inside the frame. This is not ScrollArea's ON_FRAME placement. Unknown-total sources do not acquire a fabricated scrollbar scale. Each child retains its own input and presentation behavior when entered.

Sources without a known count

ui::model<T>(provider) accepts a shared_ptr<WindowProvider<T>> and returns a distinct window-source descriptor. Pass that descriptor to ui::virtualRows with the same row factory. It does not invent a total count or require the source to implement random access.

The source's capabilities determine whether backward traversal, row seeking and tail navigation are available. rowCount() is empty for these sources. Provider loading runs on the existing application worker; factories and control updates run on the UI thread using already prepared immutable pages.

The file-backed program uses the existing FileLogModel as a WindowProvider<LogLine>. Each visible log record has its own Inspect button. Inspect obtains a checked data lease and copies its text into a separate label.

Inspect and scroll records loaded from application.log.

Complete file-backed source.

Complete file-backed program

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/log_file.hpp>
#include <portals/ui_lyra.hpp>
#include <portals/ui_style.hpp>
#include <portals/ui_virtual_rows.hpp>
#include <expected>
#include <filesystem>
#include <format>
#include <string>
std::string logPosition(const portals::VirtualRowsPosition &position) {
const auto above = position.hasBefore ? (*position.hasBefore ? "more above" : "start") : "above unknown";
const auto below = position.hasAfter ? (*position.hasAfter ? "more below" : "end") : "below unknown";
return std::format("{} records visible | {} | {}", position.visible, above, below);
}
int main(int argc, char **argv) {
using namespace portals;
std::string path = "application.log";
bool help{};
// clang-format off
auto cli = ::lyra::cli()
| ::lyra::help(help)
| ::lyra::arg(path, "file")("UTF-8 log file; default: application.log");
return [&]() -> std::expected<ui::Scene, ManagedError> {
auto file = FileLogModel::create(std::filesystem::path(std::u8string(path.begin(), path.end())));
if (!file) {
return std::unexpected(ManagedError{
.cause = file.error().error == FileLogError::NO_MEMORY
}
ui::Ref<Label> inspected;
auto position = rows.position();
auto model = ui::model<LogLine>(*file);
return ui::scene(ui::vbox(
ui::label(path),
ui::virtualRows(model, [inspected](auto row) {
return ui::hbox(
ui::button("Inspect").onClick([row, inspected] {
return row.snapshot().transform([inspected](const auto &snapshot) {
inspected.text() = std::string(snapshot.value().text);
});
}),
ui::spacing(1),
ui::label(std::string(row.value().text)));
}).reference(rows).height(10).framed("rounded", "Log records"),
ui::label(inspected, "Choose Inspect to read a record here."),
ui::label(position, logPosition),
ui::label(position, [](const VirtualRowsPosition &value) -> std::string {
return value.editing ? "Enter/Space Inspect | Esc rows | F10 quit"
: "Up/Down rows | F2 controls | F10 quit";
})).maxWidth(88))
| ui::theme(nordTheme())
| ui::onKey("F10 | Ctrl+C", ui::quit);
}
| ui::runApp(argc, argv, ui::lyra::cli(cli, {.automaticHelp = false, .helpRequested = &help}));
// clang-format on
}
static std::expected< std::shared_ptr< FileLogModel >, FileLogFailure > create(std::filesystem::path path, FileLogOptions options={}, ModelResource continuation={})
Model< VirtualRowsPosition > position() const
Definition ui_virtual_rows.hpp:841
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
@ NO_MEMORY
A bounded allocation failed.
Definition log_file_error.hpp:18
@ MOUNT
Create the scene root or attach and register a managed widget.
Definition managed_diagnostics.hpp:49
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
std::optional< bool > hasAfter
Known forward availability, absent when unknown.
Definition virtual_rows.hpp:61
std::optional< bool > hasBefore
Known backward availability, absent when unknown.
Definition virtual_rows.hpp:60

Build guide_virtual_log_rows, linked to portals::lyra, and pass a UTF-8 log:

guide_virtual_log_rows application.log
guide_virtual_log_rows --help

The default path is application.log. This record-based example uses the existing FileLogOptions: records are bounded to 32 KiB by default, and the source does not build a complete row index. Use DocumentView for a document viewer with text/hex modes and long-line handling.

Operation Finite model Native window source
Count Exact model extent rowCount() is empty
Prepare data Existing model range protocol Existing background worker and bounded pages
Move by row or page Within the model's capabilities Retained overlap, then provider traversal capabilities
Write a field Writable model backend or explicit endpoint Explicit writable endpoint
Return to a remembered position Existing model position resolver Stable row seeking through seekRow

Switch the existing view

Keep ui::Ref<VirtualRows<T>> rows and attach it using .reference(rows) on the description. Call rows.model(other) in a UI handler. The checked spelling is rows.setModel(other); the short spelling reports a failure through the scene. The same spelling supports replacement within the view's source family: finite models replace finite models, and window providers replace window providers. An existing view cannot switch between a finite descriptor and a window-source descriptor; such a request returns a checked refusal and keeps its source. Keep and reuse descriptors when returning to the same logical source.

The default REMEMBER policy restores the source's saved reading position. For a forward-only provider that cannot resolve a saved row, restoration returns a checked unsupported/unavailable outcome and preserves the installed source. This does not prohibit the first visit to a source with no saved position. Choose .model(other, {.restore = ModelRestorePolicy::RESET}) to start at its initial position explicitly. Restoration requires row seeking valid for that logical source; a cursor cannot be reused after its delivery session ends.

Failures and limits

Failed staging retains the last committed row set. Allocation, factory, geometry, thread, lifetime and source errors are reported through the checked interfaces. The host's lastError() and native sourceError() expose different error domains; windowStatus() exposes delivery state.

Virtualization bounds the controls and prepared pages retained by the view. It does not change how an application-owned model stores records, or make an O(N) source mutation constant time. Keep heavy parsing, I/O and expensive source updates off the UI thread. Separately retained data leases consume source credits and can cause backpressure.