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

Русская версия · Control examples

Use a radio group when one value must be chosen from a small resident set; for a searchable or paged source use choices. The RadioGroup API describes options and checked updates. Build the complete program below as guide_radio_group in the standalone guide project; run the resulting executable in a terminal. The recording shows the larger device-settings composition.

RadioGroup displays resident choices with one selected stable value and one local active option. Each group is one Tab stop. By default arrows move active without changing the model, wrapping and skipping hidden/disabled options; Home/End move to the first/last available option. Space or Enter confirms active. Clicking an enabled visible row selects it directly. Blur never confirms. Navigation alone changes no revision and sends no onChange. Repeating the selected value is a no-op. With no eligible option, input changes no value.

Use .immediate() to select while navigating, or .selectionMode(RadioSelectionMode::IMMEDIATE) for the explicit enum. .immediate(false) restores the default ON_ACTIVATION. Low-level construction accepts the same defaulted policy after WidthPolicy; resources use radioSelectionMode=IMMEDIATE or ON_ACTIVATION. This default differs from earlier releases where arrows immediately selected.

To build the standalone guide from the repository root:

cmake -S docs/examples -B build/guide-examples
cmake --build build/guide-examples --config Release --target guide_radio_group

Start with labels

ui::Ref<RadioGroup> mode;
auto scene = ui::scene(ui::radioGroup(mode, {"Fast", "Balanced", "Quiet"}));

The scene creates and owns the model, generates row identities and initially selects the first enabled visible option. An empty group has no selection. The complete device settings example includes model-owned choices, disabled and hidden options, a read-only group, theme styling, framing and resizing. Build portals_radio_group_example with PORTALS_BUILD_EXAMPLES=ON; run the resulting executable in a native terminal. F10 exits through the standard runner, which restores the terminal and reports typed setup/runtime errors. The application links to portals::core (C++23).

Keyboard selection, focus and a read-only radio group

Still frame

Use the same model and reference

The following complete client creates scene-owned state without exposing binding tokens or requiring hand-written IDs or text segmentation:

1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#include <portals/ui.hpp>
4
8int main() {
9 using namespace portals;
10
12 ui::Ref<Label> selected;
13
14 // clang-format off
15 auto scene = ui::scene([=](ManagedScene &owner) {
16 return ui::vbox(
17 ui::label("Arrows move | Space/Enter selects | F10 closes"),
18 ui::radioGroup(mode, owner.radioState({"Fast", "Balanced", "Quiet"})),
19 ui::label(selected, "Fast"));
20 });
21
22 return scene
23 | ui::onChange(mode, [selected](const RadioGroupValue &value) {
24 selected.text() = value.selectedText();
25 })
26 | ui::onKey(key::F10, ui::quit)
27 | ui::runApp();
28 // clang-format on
29}
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
std::expected< ManagedState< RadioGroupValue >, ManagedError > radioState(std::span< const TextValue > captions, KeyTextResolver resolver={}, CollectionLimits limits={})
Coherent immutable resident options and optional selection; copies share all row storage....
Definition radio_group.hpp:43
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

ui::radioGroup(ref, owner.radioState(...)) retains the original checked state creation error. To share or observe the state, retain its ManagedState handle inside the scene factory. Passing an existing ManagedState<RadioGroupValue> preserves its exact value, including an explicit absence of selection; mounting never writes an initial default into that external model.

mode.value() returns the authoritative owning value with checked affinity and liveness. mode.select(value.selectedId()) performs a programmatic selection and returns the original PropertyUpdate<RadioGroupValue> receipt. Pass std::nullopt to clear the selection. The user cannot toggle the selected option off. Programmatic selection may select a disabled or hidden existing ID; an unknown full ID returns INVALID_ARGUMENT without committing. Failed select commands also enter the existing scene error collector as radio.select, including when a void callback ignores the returned result. Successful receipts remain unchanged; low-level ManagedScene::selectRadio only returns its checked result.

ui::onChange receives successful changed user commits only. Programmatic writes, failed input and equal/no-op writes do not notify it. A callback can accept const RadioGroupValue& or the exact const PropertyUpdate<RadioGroupValue>&. Values and receipts own their immutable source. selectedText() borrows from that owner; retain the value/snapshot when keeping the text after the callback. Use selectedId() to distinguish an empty caption from no selection. Callback failure cannot roll back a committed value. Appending a callback while delivering an event takes effect on the next event; removing the group stops the remaining callbacks for that event.

Options, identity and updates

For per-option availability, use ordinary cold data:

ui::radioGroup(std::vector<RadioOption>{
{"Fast"}, {"Quiet"}, {"Unavailable", false}, {"Legacy", true, false}});

The same vector is accepted by owner.radioState(...). Captions also accept TextValue and i18n("key"); pass an explicit KeyTextResolver when using resource keys. Resolution and Unicode measurement use the receiving scene's actual WidthPolicy during preparation. Missing resources and invalid text keep their original typed diagnostic. There are no model reads or user formatters in painting/layout. Control characters use the existing text placeholders.

For domain data that is reordered, renamed or replaced, construct RowCollection<RadioItem> with existing full RowId {value, generation} identities and validated GraphemeText, then create a checked RadioGroupValue::from(rows, selectedId). Reuse full IDs for the same domain value; advance the generation when reusing an ID for another value. A source with mixed width policies or an absent selected ID is rejected. A new value can carry a replacement selection or nullopt in the same atomic state update.

withSelection(...) shares the source rows and prepared navigation index. Changing selection does not copy the row vector. Generated shorthand IDs are local to their immutable source; they do not promise identity across independently created label collections. Pointer input uses the last arranged source ID and checks it against the latest model. A removed/now-ineligible candidate or replaced shorthand source consumes the stale click without committing or calling onChange; the existing model synchronization refreshes the display. Reordered explicit IDs continue to identify the same domain row.

Hidden items occupy no row. Disabled items remain visible. Both are skipped by user navigation; an already selected disabled/hidden item retains its value. .readOnly() retains focus, active navigation and programmatic writes while prohibiting user selection in both modes. Active identity survives focus changes and external selection-only writes. If it becomes ineligible, it falls back to eligible selected, then the first eligible option; selection is preserved. Group visibility/enabled state follows the ordinary tree/router rules. The default resident cap is the existing configurable CollectionLimits::maxRows of 4096; oversized sources fail without truncation. This control does not provide a lazy/paged source or a search popup.

Style and size

RadioGroup is the natural style identity for typed and loaded controls. Ordinary IDs/classes, Control selectors, theme layers and manual ControlStyle normal/focused/disabled appearances apply. While the group has focus, the active caption uses focused; after blur it uses normal. The selected marker keeps selected, so both states remain visible on the same or different rows. Disabled takes precedence for both parts. Without a stylesheet, the selected marker inherits manual ControlStyle::focused, preserving custom colors. ( ) and (*) have equal measured widths.

All built-in themes use the theme's muted disabled-text color on the surface for read-only groups, without bold, italic or underline. Read-only groups remain focusable and navigable; the active caption and focused chrome retain the normal focused palette. Selected markers use the surface background in both editable and read-only groups. RadioGroup:read-only is an orthogonal sparse qualifier; it composes with one role, for example RadioGroup:read-only:focused or RadioGroup:selected:read-only. Application styles can override these defaults. See styles.

Rebuild consumers against the matching SDK: the appended selector qualifier and widget virtual hook change the API/vtable, while existing constructor and aggregate prefixes remain source-compatible.

Natural width is the widest visible caption plus chrome; natural height is the number of visible options. The standard fit/min/max/flex and frame modifiers remain available. Narrow allocations clip complete graphemes. Bound painting visits only rows intersecting the cumulative ancestor clip. A directly created, unbound low-level group is safely empty and paints its own local allocation; binding supplies the checked tree geometry context. Low-level callers retain the RadioGroupBinding, call sync() for model updates, and use syncRadioGroup for focus/eligibility presentation between frames.

Load a scene

The builtin RadioGroup creates an empty internally owned source. Supply real options or an authoritative code model through the existing explicit SceneResourceRegistry::add<RadioGroup> factory. No resource array grammar or delimiter-encoded caption list is implied. A factory returning ui::radioGroup({"Fast", "Balanced", "Quiet"}) can be registered as Modes; the registry forwards the applicable scalar settings and preserves the natural RadioGroup style identity. Resolve scene.get<RadioGroup>("mode") to use the same value, select and onChange API.

Complete loaded client:

1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#include <portals/ui.hpp>
4
8int main() {
9 using namespace portals;
10
11 // clang-format off
12 return []() -> std::expected<ui::Scene, ManagedError> {
14
15 options.format = ui::SceneResourceFormat::CONFIGURATION;
16 auto registered = options.registry.add<RadioGroup>("Modes", [](ui::SceneResourceArguments) {
17 return ui::radioGroup({"Fast", "Balanced", "Quiet"});
18 });
19
20 if (!registered) {
22
23 failure.sceneResource = std::make_shared<SceneResourceError>(
24 SceneResourceError{.code = registered.error(), .line = 0, .column = 0});
25
26 return std::unexpected(failure);
27 }
28
29 auto scene = ui::scene(R"scene(
30 scene {
31 VBox {
32 Label { "Arrows move | Space/Enter selects | F10 closes" }
33 Modes#mode { radioInitial.index=1 radioSelectionMode=ON_ACTIVATION classes="settings" width=24 }
34 Label#selected { "Balanced" }
35 }
36 }
37 )scene", options);
38 auto mode = scene.get<RadioGroup>("mode");
39 auto selected = scene.get<Label>("selected");
40
41 return std::move(scene)
42 | ui::onChange(mode, [selected](const RadioGroupValue &value) {
43 selected.text() = value.selectedText();
44 })
45 | ui::onKey(key::F10, ui::quit);
46 } | ui::runApp();
47 // clang-format on
48}
Noninteractive Unicode label; text remains data, including control characters.
Definition controls.hpp:142
Ordinary one-focus-stop, model-owned resident radio group with clipped row painting.
Definition radio_group.hpp:86
std::expected< void, SceneResourceErrorCode > add(std::string_view name, Factory factory, bool children=false)
Register an explicitly typed custom recipe; existing names cannot be replaced.
Definition ui_scene_resource.hpp:147
DynamicRef get(std::string_view name, std::source_location origin=std::source_location::current())
@ 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
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
std::shared_ptr< const SceneResourceError > sceneResource
Shared immutable runtime scene source, category and position; copies allocate no memory....
Definition managed_diagnostics.hpp:90
Owning resource position, independent of parser, scene and widget lifetimes.
Definition scene_resource_error.hpp:39
Owning primitive inputs to a registered typed recipe factory; no evaluated expressions.
Definition ui_scene_resource.hpp:40
Explicit resource-loader configuration; no process-global registry or locale. Configure without concu...
Definition ui_scene_resource.hpp:487
SceneResourceFormat format
Explicit grammar; ordinary resources retain their syntax.
Definition ui_scene_resource.hpp:492
SceneResourceRegistry registry
Owning copied/moved typed allowlist and factory captures.
Definition ui_scene_resource.hpp:488
scene {
Modes#mode {
radioInitial.index = 1
readOnly = false
width = 24
classes = "settings"
}
}

radioInitial.index is the zero-based original option ordinal, including hidden options. radioInitial.enabled=false explicitly starts unselected; true requires an index. False together with an index is invalid. An out-of-range index is invalid. These literals apply only to an internally created shorthand model; any initial override with an external authoritative state returns a typed INVALID_ARGUMENT instead of overwriting the model. readOnly and common sizing/frame properties are shared with the typed recipe. Captions, models, handlers and localization resolvers remain code-owned.

Binding to another scene or adding a duplicate binding returns INVALID_ARGUMENT; existing thread, node lifetime, frame and budget errors propagate. A successful model receipt may report rejected/cancelled observer notifications; this does not undo the commit. Do not retry equal writes to deliver notifications: observe/read the latest snapshot to resynchronize.

Styling reference

The natural selector is RadioGroup. Normal and disabled styles paint rows; focused paints the active row caption, and selected paints the selected marker. A disabled row uses disabled style for both. Manual ControlStyle supplies normal/focused/disabled; selected defaults to focused. The built-in theme may override these fields. Markers ( ) and (*) are fixed by the implementation; PSS has no marker-glyph property. header and caret are not painted.

The common paint properties apply to each painted target:

Property Value
foreground #RRGGBB text/ink color
background #RRGGBB fill color
bold true or false
italic true or false
underline true or false

Manual ControlStyle defaults use terminal colors, normal text, bold focus and italic disabled text. Theme and PSS declarations override individual manual fields; unspecified fields retain lower-layer values, including explicit false. A selector without a state supplies all variants. See cascade and selectors and styles.

Layout properties width and height accept nonnegative cell counts, auto, fit-content, or flex(positive weight); min-width, max-width, min-height, and max-height accept nonnegative cell counts. They require selectors without state or :read-only; Except for min-width, these size declarations are runtime PSS only. Conflicting widget bounds reject the update and retain the previous style and geometry; constraints and recipe precedence are explained in layout. These affect allocation, not the glyphs themselves.

RadioGroup { min-width: 16; }
RadioGroup:focused { bold: true; }
RadioGroup:selected { foreground: #62b4d7; }