Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Runnable examples

Control examples pair protected-password, loading-indicator and bounded-log programs with complete scene-resource variants.

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

Start with click handlers, then the gallery. Both use the owning declarative scene: describe controls, attach behavior, and finish with ui::runApp(). The library collects typed setup errors and restores the terminal before reporting runtime failures. Low-level APIs remain available for customization and tests. The custom-widget section explains painting and preparation explicitly; the first examples do not require those details.

Build with PORTALS_BUILD_EXAMPLES=ON. Examples open your terminal. Automated replay terminals, finite checks and stress workloads live under tests/ and tools/benchmarks/, outside the public entry points.

Choose an example

The categories describe the learning path; the source directories remain stable.

Category Program and guide What it demonstrates
Basics Boolean Switch, portals_switch_example Model-backed toggles, read-only policy and concise programmatic assignments.
Basics Numeric Slider, portals_slider_example Volume and balance, live previews, Reset and gesture completion.
Basics Command desk, portals_commands_example One Save command in a menu, a button and a shortcut; an editable draft and a saved caption. No CLI.
Showcase Shipping desk, portals_choices_example Editable city choice, full-source popup browsing, delivery selection and dark/light palette changes. No CLI.
Showcase Unicode panels, portals_unicode_panels Two synthetic file tables with Cyrillic, CJK, emoji and combining text, framed panels and an anchored popup. No filesystem access. See Unicode qualification.
Showcase Progress workbench, portals_progress_workbench Name a work item, adjust fractional progress, reset or complete it, and record accepted actions in a bounded log. Gauge command contracts explain range errors; F10 exits.
Showcase Search journal, portals_search_journal_example Edit the operator name, search two Unicode troubleshooting notes and record selected matches in a bounded log. F3/Shift+F3 navigate; buttons switch notes, clear the journal or return to its tail.
Basics click handlers, portals_click_handlers Observing refs, late click handlers and short quit. No CLI.
Basics live captions and editing events Draft versus accepted text, user edits and Enter/focus-loss outcomes without manual subscriptions. Built with tests enabled.
Basics compact framed form, portals_compact_form Ready-made border and gauge, fixed sizing, a plain button and exact-ref styling; no custom widget or CLI.
Basics protected editor, portals_docs_editor_display Internal editor state, owning placeholder, password display and checked undoable Clear; no CLI. Built with tests enabled.
Basics data presentation, portals_docs_data_state Explicit loading, ready, empty, failed, offline and refreshing states around ordinary content; no CLI. Built with tests enabled.
Basics bounded log, portals_log_view_example Complete in-memory text batches, bounded newest-record retention, grapheme wrapping and follow-tail pause/resume. No file or worker integration.
Basics file-backed log, portals_file_log_example Open application.log, prepare a bounded window on workers and follow appended records.
Basics document viewer, portals_document_view_example Read and switch text sources with bounded background windows, line numbers and explicit refresh.
Basics Choose a document, portals_document_files_example A path field, Open, a positional CLI path, text/hex modes and recovery from read errors.
Basics SQL and Markdown source colors, portals_document_highlight_example Two independently scrolling documents, theme-controlled syntax roles and worker-prepared lexical context.
Basics hex document viewer, portals_document_hex_example Switch the same byte source between text and hexadecimal views, with bounded worker preparation and styled byte classes.
Basics resource form, portals_scene_resource Runtime scene text, named references and existing managed actions; see scene loading.
Basics literal search, portals_find_bar_example A bounded in-memory document, exact case-sensitive grapheme-aligned matches and wrapping navigation; resource version. No file access or persistence.
Basics named controls, portals_named_controls Shared initial editor settings, independent histories, a sparse instance override and a three-state checkbox.
Basics gallery guide, sources, portals_gallery A function returning a lazy scene, internal editor/checkbox state, buttons, six themes and CLI preflight.
Showcase account settings, portals_form_field_example Required text fields, synchronous validation, help/messages, custom checkbox editor and focus on the first invalid draft. No CLI or persistence.
Showcase editor history, source, portals_editor_history Immediate, editing-finished and explicit model application; Undo/Redo; draft and published values.
Showcase dashboard guide, sources, portals_dashboard A table and chart sharing an immutable model, delayed pages and bounded provider work.
Customization custom widget guide, sources, portals_custom_widget A final widget, retained painting, managed presentation and a function returning a lazy scene.
Basics live text lists, portals_docs_text_transforms Native editor draft → words/graphemes → virtual lists; build and contracts.
Customization nested scroll form, portals_docs_nested_scroll Editable fields, internal-state checkboxes and nested frame-edge bars; contracts. Built with tests enabled.
Customization modal settings, portals_docs_dialog Retained editable dialog, inline open/dismiss and ordinary cleanup; contracts. Built with tests enabled.
Basics nonmodal help panel, portals_docs_nonmodal_dialog Open and close a help panel while the main input remains usable; guide. Built with tests enabled.
Basics modal choices, portals_docs_message_box Three ready-made modal choice sets, safe cancellation defaults and a deferred MessageResult callback; contracts. Built with tests enabled.
Customization custom choice dialog, portals_docs_dialog_actions Own body controls, a standard YES/NO set and optional frame close; contracts. Built with tests enabled.
Basics checkbox change handlers, portals_docs_check_change Three-state cycle and a typed change handler without manual bindings; no CLI. Built with tests enabled.
Basics notifications, portals_docs_toast Application-owned bounded messages, explicit actions and expiry without automatic focus changes; no CLI. Built with tests enabled.
Basics key hints and help, portals_docs_key_help Annotated commands, shared hints/help, enable and rebind controls; no terminal emulator or CLI. Built with tests enabled.
User theme selector, portals_docs_theme_selector Add a modal theme catalog with previews, Apply, Cancel and explicit recovery. Built with tests enabled.
Customization checked theme previews, portals_docs_theme_selection Compose custom preview, apply and cancel actions with checked results and preserved overrides. Built with tests enabled.
Experimental compile-time styles Compile-time descriptors and PSS checking: optional advanced material, not prerequisites for a form.

F10 exits the interactive programs. The gallery, custom widget and dashboard also bind the exact Ctrl+C shortcut. Their F10 quit bindings are unmodified; modified quit chords do not inherit the older modifier-insensitive matching. Mouse routing depends on the active terminal protocol. No example promises restoration after forced process termination.

Unicode panels

Run portals_unicode_panels to compare a two-panel interface in your terminal. The names are built-in fixtures; the program never reads or changes files. Tab and Shift+Tab move focus, arrows select rows, F9 or the top buttons open the anchored panel, and Escape closes it. Clicking outside or moving keyboard focus out of the panel also closes it. F10 exits and restores the terminal. The top row mimics a menu using ordinary buttons; it is not a menu framework. The popup choices update the footer to confirm activation; they do not change the fixed qualification column widths.

The fixtures include Japanese and Chinese names, Cyrillic, simple emoji, ZWJ sequences, a family, a flag, skin tone, text/emoji variation selectors, combining accents, a keycap and ambiguous-width characters. Long names deliberately meet the clipping edge. Resize the terminal, open and close the popup, and check that the following columns and panel borders remain aligned.

--emoji-width 1 selects the existing one-cell emoji policy; the default is --emoji-width 2. --help prints the options without opening the interface. The scene uses the built-in Modern theme for tables, selection, buttons and frames; its client code does not assign a separate RGB palette.

No dependencies beyond those of the native examples are required. Success and help exit with code 0; invalid CLI exits with code 2, and setup or runtime failure exits with code 1 and a diagnostic.

Portals measures grapheme clusters using its explicit width policy. The terminal and font independently decide their display width and glyph availability. Missing glyphs, unsupported emoji composition and a mismatched terminal width policy can therefore remain visible even when clipping and cell invariants pass. A fallback font can also draw a glyph beyond its assigned cells even when the terminal and application agree on width. Portals clips complete graphemes to cell rectangles; this does not set a pixel clip inside the terminal renderer. The qualification corpus keeps its original variation selectors and combining marks so that these host/font limitations remain visible. This program makes that distinction inspectable; it does not promise universal emoji rendering. See text contracts for the supported width policy.

Complete first program

This is the complete current source, including its entry point. It has no private helpers, manual binding tokens, stop source or presentation-sync loop.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
auto scene = ui::scene(ui::vbox(ui::lineEdit(message, ""),
ui::button(add, "Add Hello")));
return scene
| ui::onClick(add,
[message] {
message.text() += "Hello!";
})
| ui::onKey(key::F10, ui::quit)
| ui::runApp();
}
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
Public Portals API.
Definition action.hpp:8

Clicking Add Hello appends an undoable change. ui::quit is a command accepted by ui::onKey; inside an admitted handler, ui::quit() closes its current scene. Refs observe controls and do not prolong their lifetime. See handler parameters, propagation and lifetime.

Themes, application styles and customization

Public examples use the standard runner and default style-layer metadata. Explicit source labels, trace export, replay clocks and transport assertions belong to diagnostics material and test harnesses; they are not prerequisites for a form.

The gallery and dashboard include a Themes button and the default Ctrl+K, Ctrl+T shortcut. The selector previews choices; Apply commits and Cancel restores the previous theme. F2 remains a quick theme switch.

The gallery and custom widget accept --theme NAME and --ansi16; F2 cycles modern, turbo, nord, gruvbox, tokyo-night, and catppuccin-latte. The latter four adapt Textual palettes, not its complete widget design. --ansi16 maps emitted colors to the terminal's configured sixteen-color palette.

The gallery is the ordinary gallery::form(ui::opts(options)) function; there is no stationary gallery class to manage. Its native Lyra schema binds -t/--theme and --ansi16 to caller-owned options. The final ui::runApp(argc, argv, ui::lyra::cli(lyraCli)) parses before application settings, mounting or terminal acquisition. --help returns zero; invalid options return two with an owning command-line diagnostic. Keep the options alive through the synchronous run. Link this CLI entry point with portals::lyra; the gallery's form itself uses the core scene API. See command-line startup.

portals_gallery --theme nord --ansi16
portals_gallery --help

Include <portals/ui_style.hpp> for style stages. A theme supplies the theme layer. Add stable application declarations with scene | ui::style(add, "* { bold: true; }"); subsequent theme changes preserve application overrides. An explicit file source uses ui::file(path) with the same style stage. Read style layers and precedence, including checked failure behavior and layer limits, before adding multiple overrides.

Current PSS rules set concrete declarations. Runtime $name, theme.text, content-size expressions and importing arbitrary external theme formats are planned work; these examples do not pretend those bindings already exist. Colors and supported attributes can be customized. A general effects system, shadow engine and arbitrary border styles are not supplied by this catalogue.

Compact controls

The framed form combines ui::border, ui::gauge, ui::plainButton and .width(24). Its late click handler appends an undoable text change; the exact-ref stylesheet affects only its Add button. F10 or Ctrl+C requests ordinary runner cleanup. It has no parser, transport emulator or local widget implementation. See compact primitives for complete method and pipe forms, clipping and checked limits.

The dashboard uses .flexX() for its editor and .flexY(2) / .flexY() for the table and chart. These declarations use the existing layout solver; the provider and model lifetimes remain separate from UI composition.

Dashboard data and loading

portals_dashboard --rate 10000 --fps 30 --rows 1000000 --seed 42
portals_dashboard --rate 0 --delay-ms 250 --ansi16 --ascii
portals_dashboard --mode replay --duration-ms 5000

Read the UI composition separately from the provider. A recorded price source is an ordinary provider mode; it is not a replay terminal or another event loop. The provider owns bounded page requests, retry and cancellation. Its shutdown runs before the scene retires the model. Virtual tables and charts share managed preparation and use layout-derived extents. --rate accepts 0..10000 scheduled ticks/second; zero demonstrates idle and delayed range navigation without market updates. --fps accepts 1..1000 frames/second. --rows sets 1..1000000000 logical instruments without creating a widget per row. --seed controls the deterministic synthetic tape. --mode synthetic|replay selects the data source. The replay tape lives in examples/replay/data.hpp and is compiled into the executable, so running from another directory needs no data file or network. Replay loops its 16 recorded prices in order.

--delay-ms delays acquisition of an uncached page (0..60000 ms). The first page is immediately ready. Moving within a useful page keeps its original load deadline even when the view replaces its model request. A cache miss can show loading placeholders; completing a useful page does not require releasing the arrow key. Table and chart keep independent model requests and share bounded provider page availability.

Loading option Default Meaning
Showcase Shipping desk, portals_choices_example Editable city choice, full-source popup browsing, delivery selection and dark/light palette changes. No CLI.
--page-rows N 256 Logical rows per fixed page.
--cache-pages N 8 Maximum availability records, including the initial page and queued work.
--cache-bytes N 262144 Charged row payload budget for one generated snapshot, in bytes.
--load-jobs N 4 Maximum simultaneous delayed page jobs.
--prefetch-pages N 1 Adjacent pages considered in each consumer's navigation direction; zero disables prefetch.

Positive sizes must fit size_t. Invalid or undersized combinations fail setup; a viewport that cannot fit the effective page budget produces a failed range. The byte charge uses a full page of ModelRow<Quote> even for the final short page. It excludes allocator overhead and old immutable snapshots retained by the model, so it is not a process memory limit. Demand takes priority over prefetch. The separate finite dashboard check prints cache hit/miss page probes, useful/cancelled jobs and page/job/byte high-water counters after shutdown.

This synthetic provider caches availability of stable logical instruments, not network data. Each snapshot regenerates their values from its own market aggregate and revision. Reusing arbitrary provider results across revisions needs an explicit source contract. Readiness publication also works with --rate 0; an idle page does not cause repeated publication or redraw. No full-model cache is built.

--pump-budget sets 1..10000 ticks per provider callback, default 512. The source aggregates every generated tick into OHLC before publishing display snapshots. Only immutable display updates coalesce. A late timer retains the next ungenerated ordinal and catches up in bounded callbacks; scheduled ticks and actually generated ticks are distinct. Stop cancels remaining scheduled generation rather than claiming that ungenerated data was processed. This demo provider runs on the UI owner; it is not a benchmark of an independent market worker.

The managed scene pins the shared model once per frame for both table and candle chart, including any bounded layout retries. Logical instruments share the market OHLC with a deterministic price offset. Table formatting covers only visible rows; preparation retains visible rows plus two overscan rows per side. No million-row materialization is performed. The title and editable note exercise ordinary text controls. Dashboard candles use one-cell Unicode wicks and filled bodies by default; --ascii selects ASCII candle brushes; the title already uses ASCII. --ansi16 selects actual ANSI16 encoding, not an advertised capability flag. Both themes are compiled typed equivalents of the distributed PSS themes and require no runtime theme-file lookup. Themes change controls, table colors and the chart background; rising/falling market colors remain distinct.

Tab switches focus, arrows/Home/End select/scroll the table, Enter commits the note, and F2 switches Modern/Turbo. The Inspect button deliberately sets the note to its existing value. With the test-owned diagnostic launcher (portals_dashboard_check --rate 0 --trace trace.json), focus Inspect and press Enter: the metadata trace distinguishes handler return, value_unchanged, and frame_not_requested. Text values and terminal bytes are not exported. File errors are reported after terminal restoration, independently of a prior run failure.

--duration-ms stops an interactive run after at most the next provider service opportunity (up to 3600000 ms); zero leaves it interactive. Output/host stalls can still extend real cleanup, as documented by TerminalSession. A separate test harness replays finite keyboard/resize input and prints frame/tick/byte/queue totals after close.

The gallery and custom widget entry points use scoped ui::quit() and ui::runApp. The runner reports typed setup and runtime failures after attempting terminal cleanup. Their scene objects also provide typed run() for headless replay.

Customize a final widget

The custom-widget entry point uses the same application pipeline as the gallery. meter_example::meter(ui::opts(options)) returns an owning scene. The implementation shows the additional work needed for a new widget: retained presentation, state-backed input, preparation, measurement and painting. Read these files after the first control examples.

1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#include "../gallery/options.hpp"
4#include "fluent_meter.hpp"
5
7int main(int argc, char **argv) {
8 using namespace portals;
9
10 example::Options options;
11 auto lyraCli = example::commandLine(options);
12
13 // clang-format off
14 return [&] {
15 return meter_example::meter(ui::opts(options));
16 }
17 | ui::runApp(argc, argv, ui::lyra::cli(lyraCli));
18 // clang-format on
19}

The native editor and dashboard also use Lyra preflight and the standard runner. Their stationary application objects own the state borrowed by callbacks; keep each object alive until its synchronous runApp call returns. The editor now uses the standard runner exit policy: a successful typed run returns zero while recoverable diagnostics are still reported. Fatal setup, input or cleanup failures return one.

Verification and complete advanced specimens

Finite harnesses are in tests/examples/; low-level before specimens and shared test terminals are in tests/support/. They are built separately from interactive programs. The installed-package consumer compiles the public sources and executes finite contracts against the installed SDK. Offline staging includes their test support as well as the public source.

See compact API examples, low-level versus managed composition, virtual preparation, and performance measurements for complete advanced consumers. Passing a headless replay does not establish native terminal appearance or restoration under every host.

Guide examples

The small programs in these guides live in docs/examples. From the Portals source root:

cmake -S docs/examples -B build/guide-examples -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build/guide-examples

Run build/guide-examples/docs_basic.exe on Windows or build/guide-examples/docs_basic on Linux/macOS. F10 closes interactive programs. See the editor history demonstration for editing scenarios.

Selected guide programs have named targets in the root build when PORTALS_BUILD_TESTS=ON. For example, after configuring that preset, build the nonmodal dialog example with cmake --build build/windows-msvc-debug --target portals_docs_nonmodal_dialog. Other guide examples can be built with the standalone guide project above.

The ordinary scroll guide builds as guide_scroll_controls: eight buttons in a titled 28-by-6 outer frame with an on-frame scrollbar, wheel/key/drag input, and Exit/F10 cleanup.

The frame and title gallery builds as guide_frame_styles; the on-frame scrollbar gallery builds as guide_scrollbar_gallery. Both guides include native recordings, static previews and complete declarative sources. The test-enabled root build names these targets portals_docs_frame_styles and portals_docs_scrollbar_gallery.

The nested settings form builds as guide_nested_scroll; the root test-enabled build names it portals_docs_nested_scroll. It uses editable fields and internal-state checkboxes with two ON_FRAME areas.

Browser sample

Gallery and Level in WebAssembly are opt-in experimental browser scenes. They use xterm.js and the incremental runner; building native examples does not build this target.

Three-state checkbox

The ThreeState example uses ui::threeState() with a fixed input cycle and exits through ui::runApp(). Its complete source is included in the guide; the optional group update helper preserves partial failures.

Gallery sources

gallery/main.cpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include "fluent_form.hpp"
#include "options.hpp"
int main(int argc, char **argv) {
using namespace portals;
example::Options options;
auto lyraCli = example::commandLine(options);
// clang-format off
return [&] {
return gallery::form(ui::opts(options));
}
| ui::runApp(argc, argv, ui::lyra::cli(lyraCli));
// clang-format on
}

gallery/fluent_form.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "settings.hpp"
#include "themes.hpp"
#include <portals/ui.hpp>
namespace gallery {
inline std::expected<void, portals::ManagedError> cycleTheme(portals::ui::Ref<portals::ThemeSelector> themes) {
using namespace portals;
const auto observed = themes.snapshot();
if (!observed) {
return std::unexpected(observed.error());
}
const auto &snapshot = **observed;
const auto &current =
snapshot.status == ui::ThemeSelectionStatus::ACTIVE ? snapshot.previewedId : snapshot.lastCommittedId;
const bool currentIsMeaningful = snapshot.status != ui::ThemeSelectionStatus::SUPERSEDED;
const auto next =
currentIsMeaningful && current ? (example::themeIndex(*current) + 1) % example::THEME_PRESETS.size() : 0;
return themes.preview(example::THEME_PRESETS[next].name).and_then([themes] {
return themes.commit();
});
}
inline portals::ui::Scene form(portals::ui::OptionsRef<example::Options> options, std::function<void()> run = {},
portals::ui::SceneOptions policies = {}) {
using namespace portals;
ui::Ref<ThemeSelector> selector;
ui::Ref<LineEdit> name;
// clang-format off
auto body = ui::vbox(
ui::label("Portals gallery | F2 theme | F10 quit"),
ui::label("Name (live preview below; Enter commits; Tab changes focus):"),
ui::lineEdit(name, "Portals", {.options = {.editMode = EditMode::EXPLICIT}}),
ui::label(name.text()),
ui::checkbox("Alerts"),
ui::button("Run (no model change)", [run = std::move(run)] {
if (run) {
run();
}
}),
ui::button("Quit", [] { ui::quit(); }),
ui::button("Themes", [selector] { return selector.open(); }));
return ui::scene(policies, std::move(body),
ui::themeSelector(selector, example::themeCatalog(options.get().theme)))
| ui::applicationOptions([options, result = policies.application]() mutable {
result.writer.colorMode = options.get().ansi16 ? ColorMode::ANSI16 : ColorMode::TRUE_COLOR;
return result;
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::onKey("F2", [selector] { return cycleTheme(selector); });
// clang-format on
}
} // namespace gallery
const T & get() const noexcept
Definition ui_app.hpp:32
std::expected< LogStatus, ManagedError > status() const
Definition ui_ref.hpp:1379
consteval auto selector(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:844
ApplicationOptions application
Existing runner policies, applied once at prepare.
Definition ui_scene.hpp:18

gallery/options.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "settings.hpp"
#include "themes.hpp"
#include <algorithm>
#include <portals/ui_lyra.hpp>
#include <string>
namespace example {
inline auto commandLine(Options &options) {
return lyra::cli()
| lyra::opt(options.theme, "name")["-t"]["--theme"]("Initial theme").choices([](const std::string &name) {
return std::ranges::any_of(THEME_PRESETS, [&name](const auto &preset) {
return preset.name == name;
});
})
| lyra::opt(options.ansi16)["--ansi16"]("Use sixteen ANSI colors");
}
} // namespace example

Editor history source

editor_history/main.cpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include "editor.hpp"
#include <portals/ui_lyra.hpp>
int main(int argc, char **argv) {
using namespace portals;
editor_history::Demo demo;
return demo.scene()
| ui::reportOnError()
| ui::runApp(argc, argv, ui::lyra::cli(::lyra::cli{}));
}

Dashboard sources

dashboard/main.cpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include "cli.hpp"
int main(int argc, char **argv) {
using namespace portals;
dashboard::Options data;
dashboard::DisplayOptions display;
auto lyraCli = dashboard::commandLine(data, display);
// clang-format off
return [&] {
dashboard::FluentScene dashboard(ui::opts(data));
auto scene = std::move(dashboard.scene());
scene
| ui::applicationOptions([&data, &display] {
data.replay = display.mode == "replay";
options.framesPerSecond = display.framesPerSecond;
return options;
});
return scene;
}
| ui::runApp(argc, argv, ui::lyra::cli(lyraCli));
// clang-format on
}
@ ANSI16
Nearest standard RGB palette entry encoded as SGR 30-37/90-97 and 40-47/100-107.
Definition diff.hpp:19
@ TRUE_COLOR
RGB SGR 38;2/48;2, preserving the existing default.
Definition diff.hpp:18
Finite runner and component policies; one owner services all I/O.
Definition application.hpp:76
FrameWriterLimits writer
Output encoding and owned-frame limits.
Definition application.hpp:83
std::uint32_t framesPerSecond
Positive cap, at most 1000; no catch-up frames.
Definition application.hpp:86
ColorMode colorMode
Fixed output palette for this writer's complete lifetime.
Definition diff.hpp:104

dashboard/dashboard.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "provider.hpp"
#include <format>
#include <memory>
#include <portals/table_column.hpp>
#include <portals/text_format.hpp>
#include <portals/ui.hpp>
namespace dashboard {
using namespace portals;
using example::take;
namespace detail {
struct Presentation {
ui::Description<Column> recipe(ManagedScene &owner, Application &app, Options options) {
app_ = &app;
provider_ = std::make_unique<Provider>(app, options);
name_ = take(owner.state<std::string>("Market note"));
model_ = take(owner.model<Quote>(provider_->initialSnapshot()));
const auto inspect = [this]() -> std::expected<void, TreeError> {
const auto value = name_.snapshot();
if (!value) {
return std::unexpected(value.error());
}
const auto updated = name_.set((*value)->value);
if (!updated) {
return std::unexpected(updated.error());
}
return {};
};
const auto priceText = cellFormat<double>("{:.2f}", app.widthPolicy());
const auto columns = take(tableColumns(
app.widthPolicy(),
tableColumn("Instrument", &Quote::instrument, cellFormat<std::uint64_t>("SYM-{:07}", app.widthPolicy()), 13),
tableColumn<Quote>(
"Open",
[](const Quote &quote) {
return quote.prices.open;
},
priceText, 12),
tableColumn<Quote>(
"High",
[](const Quote &quote) {
return quote.prices.high;
},
priceText, 12),
tableColumn<Quote>(
"Low",
[](const Quote &quote) {
return quote.prices.low;
},
priceText, 12),
tableColumn<Quote>(
"Close",
[](const Quote &quote) {
return quote.prices.close;
},
priceText, 12)));
const ui::VirtualTableConfig<Quote> tableConfig{.prepared = [this](const auto &pin, const auto &work) {
return tablePrepared(pin, work);
}};
const ui::ChartConfig<Quote> chartConfig{
.options = {.mode = ChartMode::CANDLES,
.width_policy = app.widthPolicy(),
.glyph_set = options.ascii ? ChartGlyphSet::ASCII : ChartGlyphSet::BOX_DRAWING,
.candle_gap = 1},
.first = [this]() -> std::expected<std::uint64_t, TreeError> {
return firstRow_;
},
.prepared =
[this](const auto &pin, const auto &work) {
return chartPrepared(pin, work);
}};
// clang-format off
auto body = ui::vbox(LinearOptions{.padding = {.left = 1, .right = 1}},
ui::label(title_, "Portals market | F2 theme | F10 quit"),
ui::hbox(LinearOptions{.gap = 2}, ui::lineEdit(editor_, name_).flexX(),
ui::button(inspectButton_, "Inspect", inspect),
ui::button("Themes", [selector = selector_] { return selector.open(); })),
ui::label(status_, "Starting market"),
ui::virtualTable(table_, model_, columns, tableConfig).flexY(2),
ui::vbox().height(1),
ui::vbox(ui::chart(chart_, model_, &Quote::prices, chartConfig)).flexY());
// clang-format on
return body;
}
std::expected<void, ManagedError> configure(Application &app) {
take(app.router().setFocus(table_.node()));
provider_->start(model_);
return {};
}
std::expected<void, ManagedError> cycleTheme() {
const auto next = !turbo_;
return selector_.preview(next ? "turbo" : "modern")
.and_then([this] {
return selector_.commit();
})
.transform([this, next] {
turbo_ = next;
});
}
std::expected<void, TreeError> tablePrepared(const ModelFrame<Quote> &pin,
const std::optional<ModelRequest<Quote>> &work) {
auto read = app_->tree().read(table_.node(), [&](const auto &table) {
firstRow_ = table.firstRow();
pendingVisible_ = table.rangeState() == RangeState::PENDING;
});
return read.and_then([&] {
return provider_->tablePrepared(pin, work);
});
}
std::expected<void, TreeError> chartPrepared(const ModelFrame<Quote> &,
const std::optional<ModelRequest<Quote>> &work) {
provider_->chartPrepared(work);
// Ref::text mutation is disallowed during managed preparation; this is the existing view callback.
const auto caption = std::format("Committed {} | {} ticks | {}", turbo_ ? "Turbo" : "Modern",
provider_->tickCount(), pendingVisible_ ? "Loading" : "Live");
return setControlText(app_->tree(), status_.node(), example::text(caption, app_->widthPolicy()));
}
Application *app_{};
std::unique_ptr<Provider> provider_;
ui::Ref<ThemeSelector> selector_;
ui::Ref<Label> title_, status_;
ui::Ref<LineEdit> editor_;
ui::Ref<Button> inspectButton_;
ui::Ref<VirtualTable<Quote>> table_;
ui::Ref<Chart<Quote>> chart_;
ManagedState<std::string> name_;
ManagedModel<Quote> model_;
std::uint64_t firstRow_{};
bool pendingVisible_{}, turbo_{};
};
} // namespace detail
class FluentScene {
public:
explicit FluentScene(Options options = {}, ui::SceneOptions runtime = {})
: FluentScene([options] {
return options;
},
runtime) {
}
explicit FluentScene(ui::OptionsRef<Options> options, ui::SceneOptions runtime = {})
: FluentScene([options] {
return options.get();
},
runtime) {
}
ui::Scene &scene() noexcept {
return scene_;
}
FluentScene(const FluentScene &) = delete;
FluentScene &operator=(const FluentScene &) = delete;
FluentScene(FluentScene &&) = delete;
FluentScene &operator=(FluentScene &&) = delete;
private:
FluentScene(std::function<Options()> readOptions, ui::SceneOptions runtime)
: scene_(makeScene(std::move(readOptions), runtime)) {
}
static ui::Scene makeScene(std::function<Options()> readOptions, ui::SceneOptions runtime) {
auto state = std::make_shared<detail::Presentation>();
ui::ThemeSelectorCatalog catalog{
.choices = {{"modern", "Modern", modernTheme}, {"turbo", "Turbo", turboTheme}},
.initialId = "modern"};
ui::ThemeSelectorOptions selectorOptions;
selectorOptions.onCommitted = [state](std::string_view id) -> std::expected<void, ManagedError> {
state->turbo_ = id == "turbo";
return {};
};
auto scene = ui::scene(runtime, [state, readOptions = std::move(readOptions)](ManagedScene &owner, Application &app) {
return state->recipe(owner, app, readOptions());
},
ui::themeSelector(state->selector_, catalog, selectorOptions));
// clang-format off
scene
| ui::onKey(ui::pressRepeat("F2"), [state] { return state->cycleTheme(); })
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::configure([state](ManagedScene &, Application &app) {
return state->configure(app);
});
// clang-format on
scene.onStop([state] {
if (state->provider_) {
auto provider = std::move(state->provider_);
provider->stop();
}
});
return scene;
}
ui::Scene scene_;
};
} // namespace dashboard
One UI owner for scheduler, tree, routing and a single terminal run. All calls/destruction except req...
Definition application.hpp:358
WidthPolicy widthPolicy() const noexcept
EventRouter & router() noexcept
std::expected< void, TreeError > setFocus(Node< Widget > node)
Focus a live eligible registered node, or return INVALID_ARGUMENT; requests paint.
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
std::expected< ManagedModel< T >, ManagedError > model(std::shared_ptr< const ModelSnapshot< T > > initial, ModelOptions options={}, ManagedViewHandler< T > prepared={})
Create a scene-owned model and a weak typed UI handle.
Definition managed_views.hpp:65
std::expected< ManagedState< T >, ManagedError > state(T initial, Invalidation kind=Invalidation::PAINT, PropertyOptions options={})
Create UI-owned state with guaranteed dirty-frame recovery of missed notifications.
Definition managed.hpp:655
Single-use owning construction recipe; no mounted widget ownership.
Definition ui_description.hpp:48
Scene & onStop(Callback callback, std::source_location origin=std::source_location::current()) &
Definition ui_scene.hpp:508
consteval auto id(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:865
StyleSheet modernTheme()
std::expected< std::array< TableColumn< T >, 1+sizeof...(Rest)>, TextError > tableColumns(WidthPolicy policy, TableColumnSpec< T > first, Rest &&...rest)
Assemble a fixed schema and allocate deterministic table-local identities.
Definition table_column.hpp:265
TableColumn< T > tableColumn(TableColumnOptions options, Projection projection, Formatter formatter)
Compose an owning typed column from explicit projection and text formatting.
Definition table_column.hpp:84
StyleSheet turboTheme()
std::expected< void, TreeError > setControlText(WidgetTree &tree, Node< Control > node, GraphemeText text)
Replace owning text between frames; equal bytes/policy are a no-op, changes invalidate layout.
std::function< std::expected< void, ManagedError >(std::string_view)> onCommitted
Optional synchronous UI callback, invoked once after a successful guarded commit. The ID borrow expir...
Definition theme_selector.hpp:64

dashboard/provider.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "../gallery/common.hpp"
#include "../replay/data.hpp"
#include "loading.hpp"
#include <array>
#include <portals/chart.hpp>
#include <portals/managed.hpp>
#include <ranges>
namespace dashboard {
using namespace portals;
using example::take;
struct Options {
std::uint64_t rows{1000000};
std::uint32_t rate{1000};
std::uint64_t seed{42};
std::size_t maxTicksPerPump{512};
std::uint64_t delayMs{};
LoadingOptions loading;
std::uint64_t durationMs{};
bool replay{};
bool ascii{};
};
struct Quote {
std::uint64_t instrument;
Ohlc prices;
};
// Each logical instrument follows the same lossless market aggregate with a fixed
// price offset. Pages own bounded prefetched ranges around the table and chart.
class Snapshot final : public ModelSnapshot<Quote> {
public:
struct Page {
RowRange range;
std::vector<ModelRow<Quote>> rows;
};
Snapshot(std::uint64_t revision, std::uint64_t count, Ohlc aggregate, std::span<const RowRange> ranges,
bool budgetFailure = false)
: ModelSnapshot(revision, count), aggregate(aggregate), budgetFailure_(budgetFailure) {
for (auto range : ranges) {
range.first = std::min(range.first, count);
range.count = static_cast<std::size_t>(std::min<std::uint64_t>(range.count, count - range.first));
Page page{range, {}};
page.rows.reserve(range.count);
for (std::size_t i = 0; i < range.count; ++i) {
const auto index = range.first + i;
const double offset = static_cast<double>((index * 37) % 101) / 10.;
page.rows.push_back(
{{index + 1, 1},
{index,
{aggregate.open + offset, aggregate.high + offset, aggregate.low + offset, aggregate.close + offset}}});
}
pages_.push_back(std::move(page));
}
}
ModelRows<Quote> read(RowRange range) const override {
for (const auto &page : pages_) {
if (range.first >= page.range.first && range.first - page.range.first <= page.range.count && range.count <= page.range.count - static_cast<std::size_t>(range.first - page.range.first)) {
return {RangeState::READY,
std::span(page.rows).subspan(static_cast<std::size_t>(range.first - page.range.first), range.count),
{}};
}
}
return budgetFailure_ ? ModelRows<Quote>{RangeState::FAILED, {}, "requested range exceeds page cache budget"}
: ModelRows<Quote>{};
}
RowLookup locateRow(RowId id) const override {
return id.generation == 1 && id.value && id.value <= rowCount() ? RowLookup{RowLookupState::FOUND, id.value - 1}
: RowLookup{RowLookupState::NOT_FOUND};
}
const Ohlc aggregate;
private:
std::vector<Page> pages_;
bool budgetFailure_{};
};
inline double syntheticPrice(std::uint64_t index, std::uint64_t seed) noexcept {
// Unsigned arithmetic defines this deterministic integer generator on every toolchain.
auto value = index + seed * 0x9e3779b97f4a7c15ULL;
value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ULL;
value = (value ^ (value >> 27)) * 0x94d049bb133111ebULL;
return 100. + static_cast<double>((value ^ (value >> 31)) % 2001) / 100.;
}
inline std::expected<void, SchedulerError> forwardLatest(const Publisher<ModelSnapshot<Quote>> &publisher,
std::shared_ptr<const ModelSnapshot<Quote>> &pendingLatest) {
if (!pendingLatest) {
return {};
}
return publisher.publish(pendingLatest).transform([&](PublishResult) {
pendingLatest.reset();
});
}
class Provider {
public:
Provider(Application &app, Options options)
: app_(app), options_(options), scope_(take(app.scheduler().makeScope())),
loading_(options.loading, sizeof(ModelRow<Quote>), options.rows, options.delayMs), started_(app.now()) {
}
Provider(const Provider &) = delete;
Provider &operator=(const Provider &) = delete;
Provider(Provider &&) = delete;
Provider &operator=(Provider &&) = delete;
std::shared_ptr<const Snapshot> initialSnapshot() const {
return snapshot();
}
void start(ManagedModel<Quote> model) {
start(model, [] {
});
}
template <class Received>
requires std::invocable<Received &> && std::same_as<std::invoke_result_t<Received &>, void>
void start(ManagedModel<Quote> model, Received received) {
model_ = model;
ingress_ = take(app_.scheduler().connect<ModelSnapshot<Quote>>(
scope_,
[this, received = std::move(received)](auto value) mutable {
received();
pendingLatest_ = std::move(value);
forward();
},
SchedulerLane::DATA, SchedulerOverflow::REPLACE_LATEST));
schedule();
}
std::expected<void, TreeError> tablePrepared(const ModelFrame<Quote> &pin,
const std::optional<ModelRequest<Quote>> &work) {
return pin.read({0, 1}).transform([&](const auto &base) {
// Chart preparation follows table preparation and shares this immutable aggregate.
preparedAggregate_ = base.rows().empty() ? aggregate() : base.rows()[0].value.prices;
accept(0, work, preparedAggregate_);
});
}
void chartPrepared(const std::optional<ModelRequest<Quote>> &work) {
accept(1, work, preparedAggregate_);
}
void stop() {
if (stoppedAt_) {
return;
}
take(timer_.disconnect());
for (auto &slot : requests_) {
if (slot.request) {
slot.request->cancel();
slot.request.reset();
}
}
loading_.stop();
pendingLatest_.reset();
stoppedAt_ = app_.now();
}
std::uint64_t rows() const noexcept {
return options_.rows;
}
std::uint64_t pendingTicks() const noexcept {
return scheduledTicks_ - ticks_;
}
std::optional<SchedulerTime> stoppedAt() const noexcept {
return stoppedAt_;
}
std::uint64_t tickCount() const noexcept {
return ticks_;
}
std::uint64_t scheduledTicks() const noexcept {
return scheduledTicks_;
}
Ohlc aggregate() const noexcept {
return bucket_.value().value_or(Ohlc{100, 100, 100, 100});
}
const LoadingMetrics &loadingMetrics() const noexcept {
return loading_.metrics();
}
private:
static constexpr std::uint64_t PROVIDER_CADENCE_MS = 10;
struct RequestSlot {
std::optional<ModelRequest<Quote>> request;
Ohlc aggregate{};
};
std::shared_ptr<const Snapshot> snapshot() const {
const auto ranges = loading_.readyRanges();
return std::make_shared<const Snapshot>(ticks_ + 1, options_.rows, aggregate(), ranges);
}
void accept(std::size_t index, const std::optional<ModelRequest<Quote>> &request, Ohlc aggregate) {
if (!request) {
return;
}
auto &slot = requests_[index];
loading_.setDemand(index, request->range(), app_.now());
if (slot.request) {
slot.request->cancel();
}
slot.request = *request;
slot.aggregate = aggregate;
}
void forward() {
auto result = forwardLatest(take(model_.publisher()), pendingLatest_);
if (!result && result.error() != SchedulerError::WOULD_BLOCK) {
take(std::move(result));
}
}
void serviceRanges() {
loading_.advance(app_.now());
// Reverse order deliberately exercises independent chart/table completions.
for (std::size_t index = requests_.size(); index-- > 0;) {
auto &slot = requests_[index];
if (!slot.request) {
continue;
}
if (slot.request->stopRequested()) {
slot.request.reset();
continue;
}
const auto failure = !loading_.admitted(index);
if (!failure && !loading_.loaded(slot.request->range())) {
continue;
}
const auto ranges = loading_.readyRanges();
const auto page =
std::make_shared<const Snapshot>(slot.request->dataRevision(), options_.rows, slot.aggregate, ranges, failure);
auto completed = slot.request->complete(page);
if (completed || completed.error() == SchedulerError::CLOSED) {
slot.request.reset();
} else if (completed.error() != SchedulerError::WOULD_BLOCK) {
take(std::move(completed));
}
}
}
void pump() {
const auto elapsed = app_.now() - started_;
const auto target = (elapsed / 1000) * options_.rate + ((elapsed % 1000) * options_.rate) / 1000;
scheduledTicks_ = target;
const auto previous = ticks_;
const auto batchEnd = ticks_ + std::min<std::uint64_t>(target - ticks_, options_.maxTicksPerPump);
while (ticks_ < batchEnd) {
const auto price = options_.replay ? example::REPLAY_PRICES[ticks_ % example::REPLAY_PRICES.size()]
: syntheticPrice(ticks_, options_.seed);
if (!bucket_.add(price)) {
throw std::runtime_error("nonfinite generated tick");
}
++ticks_;
}
serviceRanges();
forward();
if (ticks_ != previous || retrySnapshot_) {
auto published = ingress_.publisher.publish(snapshot());
retrySnapshot_ = !published && published.error() == SchedulerError::WOULD_BLOCK;
if (!published && !retrySnapshot_) {
take(std::move(published));
}
}
if (options_.durationMs && elapsed >= options_.durationMs) {
app_.requestStop();
return;
}
schedule();
}
void schedule() {
timer_ = take(app_.scheduler().at(scope_, app_.now() + PROVIDER_CADENCE_MS, [this] {
pump();
}));
}
Application &app_;
Options options_;
UiScope scope_;
Subscription timer_;
SchedulerConnection<ModelSnapshot<Quote>> ingress_;
ManagedModel<Quote> model_;
std::shared_ptr<const ModelSnapshot<Quote>> pendingLatest_;
std::array<RequestSlot, 2> requests_;
PageLoading loading_;
OhlcBucket bucket_;
Ohlc preparedAggregate_{};
std::uint64_t started_, ticks_{}, scheduledTicks_{};
std::optional<SchedulerTime> stoppedAt_;
bool retrySnapshot_{};
};
} // namespace dashboard
std::expected< ModelRange< T >, TreeError > read(RowRange range) const
Direct bounded read from the base snapshot, without asynchronous requests or overlays.
Definition model.hpp:472
double low
Minimum accepted tick.
Definition chart.hpp:17
double open
First accepted tick in the domain bucket.
Definition chart.hpp:15
double close
Last accepted tick.
Definition chart.hpp:18
double high
Maximum accepted tick.
Definition chart.hpp:16

Custom widget sources

The complete entry point appears in Customize a final widget.

custom_widget/meter.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "../gallery/common.hpp"
#include "../gallery/themes.hpp"
#include <format>
#include <portals/input_match.hpp>
#include <portals/text_format.hpp>
#include <portals/ui.hpp>
namespace meter_example {
using namespace portals;
using example::take;
inline constexpr int MIN_LEVEL = 0;
inline constexpr int MAX_LEVEL = 100;
inline constexpr int INITIAL_LEVEL = 50;
inline constexpr int LEVEL_STEP = 5;
inline constexpr int BAR_TOP = 2;
class LevelMeter final : public Widget {
public:
std::expected<bool, TreeError> prepare(int value) {
if (initialized_ && value_ == value) {
return false;
}
auto label = formatText("Level {}% | Left/Right adjust | F2 theme | F10 quit", value);
if (!label) {
return std::unexpected(TreeError::INVALID_ARGUMENT);
}
label_ = std::move(*label);
value_ = value;
initialized_ = true;
return true;
}
std::expected<CellSize, TreeError> measure(CellSize available) override {
return available;
}
std::expected<void, TreeError> arrange(CellRect rect) override {
size_ = rect.size();
return {};
}
std::expected<void, TreeError> paint(PaintContext &context) override {
const auto area = take(CellRect::from({}, size_));
const auto bar =
take(CellRect::from({0, std::min(BAR_TOP, size_.height)},
{static_cast<std::int32_t>(static_cast<std::int64_t>(size_.width) * value_ / MAX_LEVEL),
std::max(0, size_.height - BAR_TOP)}));
const auto normal = computedStyle() ? computedStyle()->normal : CellStyle{};
const auto focused = computedStyle() ? computedStyle()->focused : CellStyle{};
const std::array<RenderCommand, 3> commands{FillCommand{area, area, normal},
FillCommand{bar, area, focused},
TextCommand{{}, label_, area, normal}};
return context.submit(commands);
}
private:
int value_{};
bool initialized_{};
CellSize size_{};
GraphemeText label_ = example::text("");
};
} // namespace meter_example
CellSize size() const noexcept
Return the normalized cell extents by value; no errors.
virtual std::expected< void, TreeError > submit(std::span< const RenderCommand > commands)=0
Borrow commands.
UI-owned extension object. Hooks borrow their arguments for one call. Models are separate explicit ow...
Definition widget.hpp:32
std::expected< GraphemeText, TextError > formatText(WidthPolicy policy, std::format_string< Args... > pattern, Args &&...args)
Format and validate an owning text value with an explicit width policy.
Definition text_format.hpp:22
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27

custom_widget/fluent_meter.hpp

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "../gallery/settings.hpp"
#include "meter.hpp"
#include <portals/ui_style.hpp>
namespace meter_example {
inline ui::Scene meter(ui::OptionsRef<example::Options> options, ui::SceneOptions policies = {}) {
auto level = std::make_shared<ManagedState<int>>();
auto content = [options, level](ManagedScene &owner) -> std::expected<ui::Description<LevelMeter>, ManagedError> {
auto state = owner.state(INITIAL_LEVEL, Invalidation::PAINT);
if (!state) {
return std::unexpected(state.error());
}
*level = std::move(*state);
const auto theme = example::themeIndex(options.get().theme);
auto styled = owner.theme(example::THEME_PRESETS.at(theme).make());
if (!styled) {
return std::unexpected(styled.error());
}
// Install the typed theme fallback before composing the pipe shortcut registry.
auto input =
owner.onInput([&owner, theme = theme](const InputEvent &event) mutable -> std::expected<bool, ManagedError> {
if (!keyPressed(event, InputKey::F2, {})) {
return false;
}
const auto next = (theme + 1) % example::THEME_PRESETS.size();
return owner.theme(example::THEME_PRESETS[next].make()).transform([&theme, next] {
theme = next;
return true;
});
});
if (!input) {
return std::unexpected(input.error());
}
return ui::custom<LevelMeter>().style({.type = "Meter"}).onPrepare([level](LevelMeter &widget, Node<Widget>) {
// State changes invalidate the root; prepare only consumes its latest snapshot.
return level->snapshot().and_then([&widget](const auto &snapshot) {
return widget.prepare(snapshot->value);
});
});
};
auto adjust = [level](const KeyEvent &event) {
const auto step = event.key == InputKey::RIGHT ? LEVEL_STEP : -LEVEL_STEP;
return level->snapshot().and_then([level, step](const auto &snapshot) {
return level->set(std::clamp(snapshot->value + step, MIN_LEVEL, MAX_LEVEL));
});
};
return ui::scene(std::move(content), policies)
| ui::applicationOptions([options, result = policies.application]() mutable {
result.writer.colorMode = options.get().ansi16 ? ColorMode::ANSI16 : ColorMode::TRUE_COLOR;
return result;
})
| ui::style("Meter:focused { bold: true; }")
| ui::onKey(ui::pressRepeat({key::LEFT, key::RIGHT}), std::move(adjust))
| ui::onKey("F10 | Ctrl+C", ui::quit);
}
} // namespace meter_example
std::expected< void, ManagedError > onInput(std::function< std::expected< bool, ManagedError >(const InputEvent &)> callback)
std::expected< void, ManagedError > theme(StyleSheet sheet)
Borrowed typed options; the lvalue must outlive the synchronous lazy scene run.
Definition ui_app.hpp:22
Single-use lazy owner of one Application and ManagedScene; no second runtime. Construct and operate o...
Definition ui_scene.hpp:253
constexpr bool keyPressed(const InputEvent &event, InputKey key) noexcept
Match a semantic key press or repeat without extracting the event variant.
Definition input_match.hpp:18
@ PAINT
Painting is required; arranged geometry remains usable.
Definition widget_types.hpp:43
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
Policies for one lazy facade over the existing managed runtime.
Definition ui_scene.hpp:17

Compact framed form

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
// clang-format off
auto scene = ui::scene(ui::vbox(
ui::label("Portals | F10 quit"),
ui::lineEdit(message, ""),
ui::gauge(0.65).width(24),
ui::hbox(ui::button(add, "Add Hello"), ui::plainButton("Quit", [] { ui::quit(); }))).framed());
return scene
| ui::style(add, "*:focused { bold: true; }")
| ui::onClick(add, [message] {
message.text() += "Hello!";
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}

The advanced precise pointer example builds as guide_precise_scroll, linked with portals::lyra. --help performs no terminal I/O. --fifo-host declares host FIFO ordering; AUTO still falls back to ordinary scrolling when optional pixel support is unavailable.

The fractional thumb example uses one .scrollbar("fractional-block") modifier and ordinary key input to show one-eighth-cell edges on both axes. It builds as guide_fractional_scroll in the installed examples project and requires only portals::core. The complete source and terminal recording are included in the guide.

The popup menu example, target portals_docs_popup_menu, shows automatically hosted submenus, shared actions and explicit mnemonics.