A set of mutually exclusive options where only one can be selected.
use gpui::{div, prelude::*, Context, FontWeight, Window};
use crate::ui::radio_group::RadioGroup;
#[derive(Default)]
pub struct NotificationSettings {
notify_about: Option<usize>,
}
impl Render for NotificationSettings {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_4()
.child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child("Notify me about"))
.child(
RadioGroup::new("notify", self.notify_about)
.option("All new messages")
.option("Direct messages and mentions")
.option("Nothing")
.disabled_option("Only from my manager")
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.notify_about = Some(*ix);
cx.notify();
})),
)
}
}Installation
Copies src/ui/radio_group.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/radio_group.rs.src/ui/radio_group.rs use std::{rc::Rc, sync::Arc}; use gpui::{ div, point, prelude::*, px, AnimationExt, App, BoxShadow, ElementId, FocusHandle, FontWeight, Hsla, Interpolate, KeyDownEvent, SharedString, SpringAnimation, SpringConfig, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; /// shadcn's 150ms `transition-[color,box-shadow]` as a critically damped spring. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); type ChangeHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>; struct RadioOption { label: SharedString, description: Option<SharedString>, disabled: bool, } /// A set of mutually exclusive options. The parent view owns `selected` (an option index, /// or `None` before the first pick) and updates it in `on_change`. /// /// Like a native radio group, the group is one tab stop: focus shows on the checked option /// (or the first), the arrow keys move to the next option and select it, and Space selects /// the focused option when none is checked yet. #[derive(IntoElement)] pub struct RadioGroup { id: ElementId, selected: Option<usize>, options: Vec<RadioOption>, horizontal: bool, disabled: bool, invalid: bool, cards: bool, focus_handle: Option<FocusHandle>, on_change: Option<ChangeHandler>, } impl RadioGroup { pub fn new(id: impl Into<ElementId>, selected: Option<usize>) -> Self { Self { id: id.into(), selected, options: Vec::new(), horizontal: false, disabled: false, invalid: false, cards: false, focus_handle: None, on_change: None, } } pub fn option(mut self, label: impl Into<SharedString>) -> Self { self.options.push(RadioOption { label: label.into(), description: None, disabled: false, }); self } pub fn disabled_option(mut self, label: impl Into<SharedString>) -> Self { self.options.push(RadioOption { label: label.into(), description: None, disabled: true, }); self } /// An option with muted helper text under its label. pub fn option_with_description( mut self, label: impl Into<SharedString>, description: impl Into<SharedString>, ) -> Self { self.options.push(RadioOption { label: label.into(), description: Some(description.into()), disabled: false, }); self } /// Lay the options out in a row instead of a column. pub fn horizontal(mut self, horizontal: bool) -> Self { self.horizontal = horizontal; self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Draws destructive circles and labels, like `aria-invalid` in shadcn/ui. pub fn invalid(mut self, invalid: bool) -> Self { self.invalid = invalid; self } /// Draws each option as a bordered, full-width card with the circle at the end, like /// shadcn/ui's choice cards. The selected card gets a primary border and a tinted fill. pub fn cards(mut self, cards: bool) -> Self { self.cards = cards; self } /// Focus the group through this handle, such as `form.focus_handle(..)` or one from /// `cx.focus_handle()`, to move focus to it from code. Without one it keeps its own. pub fn focus_handle(mut self, handle: FocusHandle) -> Self { self.focus_handle = Some(handle); self } pub fn on_change(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self { self.on_change = Some(Rc::new(handler)); self } } impl RenderOnce for RadioGroup { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let group_disabled = self.disabled; let invalid = self.invalid; let cards = self.cards; let group_id = Arc::new(self.id.clone()); // Options the keyboard can land on, in order. let enabled: Vec<usize> = self .options .iter() .enumerate() .filter(|(_, option)| !group_disabled && !option.disabled) .map(|(ix, _)| ix) .collect(); // A RenderOnce group is rebuilt every frame, but focus has to stay on the same handle, // so the group keeps its own under its id unless the caller passes one. let focus = self .focus_handle .unwrap_or_else(|| { let key = ElementId::NamedChild(group_id.clone(), "focus".into()); window.use_keyed_state(key, cx, |_, cx| cx.focus_handle()).read(cx).clone() }) .tab_stop(!enabled.is_empty()); // Like CSS `:focus-visible`: the ring shows for keyboard use and after the form moves focus // here, not after a click. let focus_visible = focus_visible(&focus, window, cx); let focused_option = self .selected .filter(|ix| enabled.contains(ix)) .or_else(|| enabled.first().copied()); let mut options = Vec::with_capacity(self.options.len()); for (ix, option) in self.options.into_iter().enumerate() { let checked = self.selected == Some(ix); let ringed = focus_visible && focused_option == Some(ix); let disabled = group_disabled || option.disabled; let handler = self.on_change.clone().filter(|_| !disabled && !checked); let has_description = option.description.is_some(); // Hovering anywhere on the option (label included) darkens the circle's border. let key = ElementId::NamedChild(group_id.clone(), format!("option-{ix}").into()); let hover = window.use_keyed_state(key, cx, |_, _| false); let hovered = *hover.read(cx) && !disabled && !invalid; let (idle_border, hover_border) = if invalid { (theme.destructive, theme.destructive) } else if ringed { (theme.ring, theme.ring) } else { (theme.input, theme.muted_foreground) }; let dot = if invalid { theme.destructive } else { theme.primary }; let circle = div() .flex() .flex_none() .items_center() .justify_center() .size(px(16.0)) .rounded_full() .border_1() .bg(theme.background) .map(|this| { let ring = if invalid { Some(theme.destructive.opacity(0.2)) } else { ringed.then(|| theme.ring.opacity(0.5)) }; match ring { Some(color) => this.shadow(vec![BoxShadow { color, offset: point(px(0.), px(0.)), blur_radius: px(0.), spread_radius: px(3.), inset: false, }]), None => this.shadow_xs(), } }) // Lines the circle up with the label's 20px line when it starts at the top. .when(has_description, |this| this.mt(px(2.0))) // The dot grows and fades in when picked, and out when another is. .child(div().with_spring( "dot", SpringAnimation::new(EASE).to(checked), move |this, phase| { let t = phase.interpolate_clamped(0.0, 1.0); this.when(t > 0.01, |this| { this.size(px(8.0) * (0.5 + 0.5 * t)).rounded_full().bg(dot.opacity(t)) }) }, )) .with_spring("ring", SpringAnimation::new(EASE).to(hovered), move |this, phase| { this.border_color(phase.interpolate_clamped(idle_border, hover_border)) }); let text = div() .flex() .flex_col() .gap_1() .line_height(px(20.0)) .when(cards, |this| this.flex_1()) .child( div() .when(invalid, |this| this.text_color(theme.destructive)) .child(option.label), ) .when_some(option.description, |this, description| { this.child( div() .font_weight(FontWeight::NORMAL) .text_color(theme.muted_foreground) .child(description), ) }); let row = div() .id(ix) .flex() .when(has_description, |this| this.items_start()) .when(!has_description, |this| this.items_center()) .gap_3() .text_sm() .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| this.cursor_pointer()) .on_hover(move |hovered, _, cx| { hover.update(cx, |hover, cx| { if *hover != *hovered { *hover = *hovered; cx.notify(); } }) }) .map(|this| { if cards { this.w_full() .p_4() .rounded(theme.radius) .border_1() .child(text) .child(circle) } else { this.child(circle).child(text) } }) .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&ix, window, cx)) }); // A picked card's border and tint fade in. let (border, primary) = (theme.border, theme.primary); options.push(row.with_spring( ("card", ix), SpringAnimation::new(EASE).to(checked), move |this, phase| { if !cards { return this; } let t = phase.interpolate_clamped(0.0, 1.0); this.border_color(Hsla::interpolate(border, primary, t)) .bg(primary.opacity(0.05 * t)) }, )); } let selected = self.selected; let keys = self.on_change.clone().filter(|_| !enabled.is_empty()).map(|handler| { move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| { let position = focused_option.and_then(|ix| enabled.iter().position(|&e| e == ix)); let next = match (event.keystroke.key.as_str(), position) { ("down" | "right", Some(pos)) => enabled[(pos + 1) % enabled.len()], ("up" | "left", Some(pos)) => enabled[pos.checked_sub(1).unwrap_or(enabled.len() - 1)], ("space", Some(pos)) => enabled[pos], _ => return, }; cx.stop_propagation(); if selected != Some(next) { handler(&next, window, cx); } } }); div() .id(self.id) .when(focused_option.is_some(), |this| this.track_focus(&focus).end_visible_focus_on_press(&focus, cx)) .when_some(keys, |this, keys| this.on_key_down(keys)) .flex() .when(self.horizontal, |this| this.flex_row().gap_6()) .when(!self.horizontal, |this| this.flex_col().gap_3()) .children(options) } }Register the module
// src/ui/mod.rs pub mod radio_group;
Usage
use crate::ui::radio_group::*;Examples
Description
option_with_description adds muted helper text under an option's label.
use gpui::{prelude::*, Context, Window};
use crate::ui::radio_group::RadioGroup;
pub struct RadioGroupDescription {
spacing: Option<usize>,
}
// Starts on "Comfortable", so `Default` is written out instead of derived.
impl Default for RadioGroupDescription {
fn default() -> Self {
Self { spacing: Some(1) }
}
}
impl Render for RadioGroupDescription {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
RadioGroup::new("radio-group-description", self.spacing)
.option_with_description("Default", "Standard spacing for most use cases.")
.option_with_description("Comfortable", "More space between elements.")
.option_with_description("Compact", "Minimal spacing for dense layouts.")
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.spacing = Some(*ix);
cx.notify();
}))
}
}Choice Card
cards(true) draws each option as a full-width card; the whole card is clickable and the selected one is highlighted.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::radio_group::RadioGroup;
pub struct RadioGroupChoiceCard {
plan: Option<usize>,
}
// Starts on "Pro", so `Default` is written out instead of derived.
impl Default for RadioGroupChoiceCard {
fn default() -> Self {
Self { plan: Some(1) }
}
}
impl Render for RadioGroupChoiceCard {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(360.)).child(
RadioGroup::new("radio-group-choice-card", self.plan)
.cards(true)
.option_with_description("Plus", "For individuals and small teams.")
.option_with_description("Pro", "For growing businesses.")
.option_with_description("Enterprise", "For large teams and enterprises.")
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.plan = Some(*ix);
cx.notify();
})),
)
}
}Fieldset
Put the group in a FieldSet to give it a legend and description.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::field::FieldSet;
use crate::ui::radio_group::RadioGroup;
#[derive(Default)]
pub struct RadioGroupFieldset {
plan: Option<usize>,
}
impl Render for RadioGroupFieldset {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(360.)).child(
FieldSet::new()
.legend("Subscription Plan")
.description("Yearly and lifetime plans offer significant savings.")
.child(
RadioGroup::new("radio-group-fieldset", self.plan)
.option("Monthly ($9.99/month)")
.option("Yearly ($99.99/year)")
.option("Lifetime ($299.99)")
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.plan = Some(*ix);
cx.notify();
})),
),
)
}
}Disabled
disabled(true) on the group dims every option and ignores clicks. Use disabled_option to turn off a single option instead.
use gpui::prelude::*;
use crate::ui::radio_group::RadioGroup;
pub fn radio_group_disabled() -> impl IntoElement {
RadioGroup::new("radio-group-disabled", Some(0))
.option("Default")
.option("Comfortable")
.option("Compact")
.disabled(true)
}Invalid
invalid(true) draws destructive circles and labels, like aria-invalid. Here the error shows until an option is picked.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::field::FieldSet;
use crate::ui::radio_group::RadioGroup;
#[derive(Default)]
pub struct RadioGroupInvalid {
channel: Option<usize>,
}
impl Render for RadioGroupInvalid {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let invalid = self.channel.is_none();
let destructive = cx.theme().destructive;
div().w(px(360.)).child(
FieldSet::new()
.legend("Notification Preferences")
.description("Choose how you want to receive notifications.")
.child(
RadioGroup::new("radio-group-invalid", self.channel)
.option("Email only")
.option("SMS only")
.option("Both Email & SMS")
.invalid(invalid)
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.channel = Some(*ix);
cx.notify();
})),
)
.when(invalid, |this| {
this.child(
div()
.text_sm()
.text_color(destructive)
.child("Please select a notification preference."),
)
}),
)
}
}API Reference
RadioGroup
A set of mutually exclusive options. The parent view owns selected (an option index, or None before the first pick) and updates it in on_change. Like a native radio group, the group is one tab stop: focus shows on the checked option (or the first), the arrow keys move to the next option and select it, and Space selects the focused option when none is checked yet.
RadioGroup::new(id: impl Into<ElementId>, selected: Option<usize>) -> Self.option(label: impl Into<SharedString>).disabled_option(label: impl Into<SharedString>).option_with_description(label: impl Into<SharedString>, description: impl Into<SharedString>)An option with muted helper text under its label.
.horizontal(horizontal: bool)Lay the options out in a row instead of a column.
.disabled(disabled: bool).invalid(invalid: bool)Draws destructive circles and labels, like aria-invalid in shadcn/ui.
.cards(cards: bool)Draws each option as a bordered, full-width card with the circle at the end, like shadcn/ui's choice cards. The selected card gets a primary border and a tinted fill.
.focus_handle(handle: FocusHandle)Focus the group through this handle, such as form.focus_handle(..) or one from cx.focus_handle(), to move focus to it from code. Without one it keeps its own.
.on_change(handler: impl Fn(&usize, &mut Window, &mut App) + 'static)