|
Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
|
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.
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.
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.
This is the complete current source, including its entry point. It has no private helpers, manual binding tokens, stop source or presentation-sync loop.
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.
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.
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.
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.
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.
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.
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.
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.
The small programs in these guides live in docs/examples. From the Portals source root:
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.
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.
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.
The complete entry point appears in Customize a final widget.
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.