Toggle
A command with persistent selection.
Try it
Toggle bold formatting to switch the button label between “Bold off” and “Bold on”. This preview runs the exact code sample shown on this page.
Basic use
use gpui::{Context, ParentElement};
use xgpui_luma_look_radix as radix;
use xgpui_luma::infra::presenter::HasPresenter;
struct Example {
control: xgpui_luma::controls::toggle::Toggle,
bold: bool,
}
impl Example {
fn new(cx: &mut Context<Self>) -> Self {
let control = radix::Toggle::new("toggle")
.with_data(false)
.content(|state, _| gpui::div().child(if state.data.selected { "Bold on" } else { "Bold off" }))
.on_value_changed(cx, |app: &mut Self, selected, cx| {
app.bold = selected;
cx.notify();
})
.spawn(cx);
Self { control, bold: false }
}
}Integration snippet, checked against the current SDK and Radix crates. cx is the initialized owner context. The control retains its callbacks; callback owners are held weakly. Render self.control.clone() in the owner’s view.
SDK behavior & customization
Change carries selected. Use for mode selection rather than a one-shot action.
Use the module’s template contract for structural changes. Builder modifiers and item templates vary by control.
Events
Callbacks update application state. Repeated registrations append; the control retains them and holds the owner weakly. cx.notify() requests an owner redraw. set_data synchronizes state silently; on_value_changed follows the existing user-change event.
| Event / payload | Callback | Application use |
|---|---|---|
Change { selected: bool } | .on_value_changed(cx, |app, selected, cx| { … }) | Update the application’s selected mode. |
FocusChanged { focused: bool } | .on_focus_changed(cx, |app, focused, cx| { … }) | Focus state changed. |
EnabledChanged { enabled: bool } | .on_enabled_changed(cx, |app, enabled, cx| { … }) | Enabled state changed. |
HoverChanged { hovered: bool } | .on_hover_changed(cx, |app, hovered, cx| { … }) | Pointer hover state changed. |
ToggleEvent · Event definitions. Use .on_event(cx, |app, event, cx| { … }) for all events. Factory-created controls support the same callbacks through ToggleEventExt. Existing cx.subscribe observers remain supported.