A set of joined toggles with single or multiple selection.
use gpui::{div, prelude::*, Context, FontWeight, Window};
use crate::ui::toggle::ToggleVariant;
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
#[derive(Default)]
pub struct EditorToolbar {
styles: Vec<usize>,
align: Vec<usize>,
}
impl Render for EditorToolbar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.items_center()
.gap_4()
.child(
ToggleGroup::new("text-style", ToggleGroupMode::Multiple)
.variant(ToggleVariant::Outline)
.selected(self.styles.clone())
.item(div().font_weight(FontWeight::BOLD).child("B"))
.item(div().underline().child("U"))
.item(div().line_through().child("S"))
.on_change(cx.listener(|this, styles: &Vec<usize>, _, cx| {
this.styles = styles.clone();
cx.notify();
})),
)
.child(
ToggleGroup::new("text-align", ToggleGroupMode::Single)
.selected(self.align.clone())
.item("Left")
.item("Center")
.item("Right")
.on_change(cx.listener(|this, align: &Vec<usize>, _, cx| {
this.align = align.clone();
cx.notify();
})),
)
}
}Installation
Copies src/ui/toggle_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/toggle_group.rs.src/ui/toggle_group.rs use std::{ cell::{Cell, RefCell}, rc::Rc, sync::Arc, }; use gpui::{ canvas, div, prelude::*, px, quad, AnimationExt, AnyElement, App, BorderStyle, Bounds, Corners, ElementId, Entity, FocusHandle, FontWeight, Hsla, Interpolate, KeyDownEvent, Pixels, SpringAnimation, SpringAnimationElement, SpringConfig, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; use crate::ui::toggle::{ToggleSize, ToggleVariant}; type ChangeHandler = Rc<dyn Fn(&Vec<usize>, &mut Window, &mut App) + 'static>; #[derive(Clone, Copy, Default, PartialEq)] pub enum ToggleGroupMode { /// At most one item is pressed. Pressing the active item clears the selection. #[default] Single, /// Any number of items can be pressed. Multiple, } /// The direction the items are laid out in. #[derive(Clone, Copy, Default, PartialEq)] pub enum ToggleGroupOrientation { /// Items in a row, left to right. #[default] Horizontal, /// Items in a column, top to bottom, stretched to the widest item. Vertical, } /// A row of joined toggles. The parent view owns `selected` (item indices) and updates /// it in `on_change`, which receives the next selection in item order. /// /// The group is one tab stop, like Radix's roving focus: the arrow keys (and Home/End) move /// between items and Space or Enter toggles the one with the focus ring. #[derive(IntoElement)] pub struct ToggleGroup { id: ElementId, mode: ToggleGroupMode, selected: Vec<usize>, variant: ToggleVariant, size: ToggleSize, disabled: bool, orientation: ToggleGroupOrientation, spacing: Pixels, items: Vec<AnyElement>, focus_handle: Option<FocusHandle>, on_change: Option<ChangeHandler>, } /// The group's focus handle and which item the keyboard is on. A RenderOnce group is rebuilt /// every frame, so both live in keyed state; the handle has to stay the same for focus to stick. struct Roving { focus: FocusHandle, active: Option<usize>, } impl ToggleGroup { pub fn new(id: impl Into<ElementId>, mode: ToggleGroupMode) -> Self { Self { id: id.into(), mode, selected: Vec::new(), variant: ToggleVariant::default(), size: ToggleSize::default(), disabled: false, orientation: ToggleGroupOrientation::default(), spacing: px(0.0), items: Vec::new(), focus_handle: None, on_change: None, } } pub fn selected(mut self, selected: impl IntoIterator<Item = usize>) -> Self { self.selected = selected.into_iter().collect(); self } pub fn item(mut self, content: impl IntoElement) -> Self { self.items.push(content.into_any_element()); self } pub fn variant(mut self, variant: ToggleVariant) -> Self { self.variant = variant; self } pub fn size(mut self, size: ToggleSize) -> Self { self.size = size; self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Lays the items out in a row (the default) or a column. pub fn orientation(mut self, orientation: ToggleGroupOrientation) -> Self { self.orientation = orientation; self } /// Space between items. Zero (the default) joins them into one segmented control; /// anything larger gives each item its own rounded corners and border. pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self { self.spacing = spacing.into(); 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(&Vec<usize>, &mut Window, &mut App) + 'static, ) -> Self { self.on_change = Some(Rc::new(handler)); self } } impl RenderOnce for ToggleGroup { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let disabled = self.disabled; let outline = self.variant == ToggleVariant::Outline; let (hover_bg, hover_fg) = if outline { (theme.accent, theme.accent_foreground) } else { (theme.muted, theme.muted_foreground) }; let clear = gpui::transparent_black(); let radius = theme.radius; let last = self.items.len().saturating_sub(1); let mode = self.mode; let selected = Rc::new(self.selected); let height = self.size.height(); let padding_x = self.size.padding_x(); let vertical = self.orientation == ToggleGroupOrientation::Vertical; let joined = self.spacing <= px(0.0); let count = self.items.len(); let roving_key = ElementId::NamedChild(Arc::new(self.id.clone()), "roving".into()); let roving = window.use_keyed_state(roving_key, cx, |_, cx| Roving { focus: cx.focus_handle(), active: None, }); let focus = self .focus_handle .unwrap_or_else(|| roving.read(cx).focus.clone()) .tab_stop(!disabled && count > 0); // 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); // Focus lands on the first pressed item, else the first, as in Radix. let active = roving .read(cx) .active .filter(|&ix| ix < count) .or_else(|| selected.first().copied()) .unwrap_or(0); let mut items: Vec<AnyElement> = Vec::new(); for (ix, content) in self.items.into_iter().enumerate() { let pressed = selected.contains(&ix); let handler = self.on_change.clone().filter(|_| !disabled); let selected = selected.clone(); let (first, end) = (ix == 0, ix == last); let ringed = focus_visible && ix == active; let key = ElementId::NamedChild(Arc::new(self.id.clone()), format!("item-{ix}").into()); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered && !disabled; // Hover wins over pressed; the colors ease between all three states. let (bg, fg) = if hovered { (hover_bg, hover_fg) } else if pressed { (theme.accent, theme.accent_foreground) } else if outline { // Opaque so the shadow doesn't show through the items. (theme.background, theme.foreground) } else { (clear, theme.foreground) }; let target = Paint { bg, fg, border: match (outline, ringed) { (true, true) => theme.ring, (true, false) => theme.input, (false, _) => clear, }, }; let item = div() .id(ix) .flex() .flex_none() .items_center() .justify_center() .gap_2() // A minimum, so taller content (e.g. a label under a glyph) grows the item. .min_h(height) .min_w(height) .px(padding_x) .text_sm() .font_weight(FontWeight::MEDIUM) .when(!joined, |this| this.rounded(radius)) .when(joined && !vertical, |this| { this.when(first, |this| this.rounded_l(radius)) .when(end, |this| this.rounded_r(radius)) }) .when(joined && vertical, |this| { this.when(first, |this| this.rounded_t(radius)) .when(end, |this| this.rounded_b(radius)) }) // Joined items share edges: only the first draws its leading border, so // neighbours meet on one 1px line. .when(outline, |this| { if !joined { this.border_1().shadow_xs() } else if vertical { this.border_x_1().border_b_1().when(first, |this| this.border_t_1()) } else { this.border_y_1().border_r_1().when(first, |this| this.border_l_1()) } }) // Tracks hover even while disabled, so the flag is right once enabled. .on_hover(track_hover(&ease)) .when(!disabled, |this| this.cursor_pointer()) .when_some(handler, |this, handler| { let roving = roving.clone(); this.on_click(move |_, window, cx| { roving.update(cx, |roving, _| roving.active = Some(ix)); handler(&toggled(mode, &selected, ix), window, cx); }) }) .child(content); items.push( ease_to(item, key, &ease, target, cx, |this, paint| { this.bg(paint.bg).text_color(paint.fg).border_color(paint.border) }) .into_any_element(), ); } let keys = self.on_change.clone().filter(|_| !disabled && count > 0).map(|handler| { let roving = roving.clone(); move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| { let next = match event.keystroke.key.as_str() { "left" | "up" => active.checked_sub(1).unwrap_or(count - 1), "right" | "down" => (active + 1) % count, "home" => 0, "end" => count - 1, "space" | "enter" => { cx.stop_propagation(); handler(&toggled(mode, &selected, active), window, cx); return; } _ => return, }; cx.stop_propagation(); roving.update(cx, |roving, cx| { roving.active = Some(next); cx.notify(); }); } }); // The ring is painted after every item, like shadcn's `focus-visible:z-10`: as the focused // item's own shadow, the next item would paint over its edge. let item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>> = Rc::default(); let ring = focus_visible.then(|| { let (item_bounds, color) = (item_bounds.clone(), theme.ring.opacity(0.5)); let corners = item_corners(active, last, joined, vertical, radius); canvas( |_, _, _| {}, move |_, _, window, _| { if let Some(bounds) = item_bounds.borrow().get(active) { window.paint_quad(quad( bounds.dilate(RING_WIDTH), corners.map(|radius| if *radius > px(0.) { *radius + RING_WIDTH } else { px(0.) }), gpui::transparent_black(), RING_WIDTH, color, BorderStyle::Solid, )); } }, ) .absolute() .size_0() }); div() .on_children_prepainted(move |bounds, _, _| *item_bounds.borrow_mut() = bounds) .id(self.id) .when(!disabled, |this| this.track_focus(&focus).end_visible_focus_on_press(&focus, cx)) .when_some(keys, |this, keys| this.on_key_down(keys)) .flex() .when(vertical, |this| this.flex_col().items_stretch()) .when(!vertical, |this| this.items_center()) .gap(self.spacing) .rounded(radius) // Spaced items each carry their own shadow; a group shadow would fill the gaps. .when(outline && joined, |this| this.shadow_xs()) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .children(items) .children(ring) } } /// How far the focus ring reaches outside an item, like shadcn's `ring-[3px]`. const RING_WIDTH: Pixels = px(3.0); /// Item `ix`'s corner radii: joined items round only the group's outer corners. fn item_corners(ix: usize, last: usize, joined: bool, vertical: bool, radius: Pixels) -> Corners<Pixels> { let (zero, first, end) = (px(0.), ix == 0, ix == last); let pick = |rounded: bool| if rounded { radius } else { zero }; match (joined, vertical) { (false, _) => Corners::all(radius), (true, false) => Corners { top_left: pick(first), bottom_left: pick(first), top_right: pick(end), bottom_right: pick(end), }, (true, true) => Corners { top_left: pick(first), top_right: pick(first), bottom_left: pick(end), bottom_right: pick(end), }, } } /// The selection after toggling item `ix`. fn toggled(mode: ToggleGroupMode, selected: &[usize], ix: usize) -> Vec<usize> { let pressed = selected.contains(&ix); match mode { ToggleGroupMode::Single if pressed => Vec::new(), ToggleGroupMode::Single => vec![ix], ToggleGroupMode::Multiple => { let mut next: Vec<usize> = selected.iter().copied().filter(|&i| i != ix).collect(); if !pressed { next.push(ix); next.sort_unstable(); } next } } } /// shadcn's `transition-colors` (150ms) as a critically damped spring: quick, no overshoot. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// The colors a control eases between as it is hovered or changes state. #[derive(Clone, Copy, PartialEq)] struct Paint { bg: Hsla, fg: Hsla, border: Hsla, } impl Paint { fn mix(self, to: Self, t: f32) -> Self { Self { bg: mix(self.bg, to.bg, t), fg: mix(self.fg, to.fg, t), border: mix(self.border, to.border, t), } } } /// Blends like CSS: a transparent end only fades the other color in or out, rather than /// passing through a dark gray. fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla { let from = if from.a == 0.0 { to.opacity(0.0) } else { from }; let to = if to.a == 0.0 { from.opacity(0.0) } else { to }; Hsla::interpolate(from, to, t) } /// One control's hover flag and color transition, kept across frames. #[derive(Default)] struct Ease { hovered: bool, /// The colors eased from and to; `None` before the first render. from_to: Option<(Paint, Paint)>, /// Every new target moves the spring on by one, so an interrupted transition keeps its /// velocity; `start` is where the current one began. start: f32, run: f32, /// What the spring painted last and at which position, where the next transition starts. shown: Rc<Cell<Option<(Paint, f32)>>>, } fn ease_state(key: ElementId, window: &mut Window, cx: &mut App) -> Entity<Ease> { window.use_keyed_state(key, cx, |_, _| Ease::default()) } /// An `on_hover` listener that records hover in `ease`, re-rendering only on a change. fn track_hover(ease: &Entity<Ease>) -> impl Fn(&bool, &mut Window, &mut App) + 'static { let ease = ease.clone(); move |hovered, _, cx| { ease.update(cx, |ease, cx| { if ease.hovered != *hovered { ease.hovered = *hovered; cx.notify(); } }) } } /// Paints `element` with colors easing toward `target` from whatever was showing, like a CSS /// color transition. A newly mounted element starts at `target`, so nothing fades in on load. fn ease_to<E: IntoElement + 'static>( element: E, id: ElementId, ease: &Entity<Ease>, target: Paint, cx: &mut App, paint: impl FnOnce(E, Paint) -> E + 'static, ) -> SpringAnimationElement<E> { let (from, start, run, shown) = ease.update(cx, |ease, _| { match ease.from_to { Some((_, to)) if to == target => {} Some((_, to)) => { let (shown, position) = ease.shown.get().unwrap_or((to, ease.run)); ease.from_to = Some((shown, target)); ease.start = position; ease.run += 1.0; } None => ease.from_to = Some((target, target)), } let from = ease.from_to.map_or(target, |(from, _)| from); (from, ease.start, ease.run, ease.shown.clone()) }); element.with_spring(id, SpringAnimation::new(EASE).to(run), move |element, position| { let span = run - start; let t = if span > 0.0 { ((position - start) / span).clamp(0.0, 1.0) } else { 1.0 }; let now = from.mix(target, t); shown.set(Some((now, position))); paint(element, now) }) }Register the module
// src/ui/mod.rs pub mod toggle_group;
Usage
use crate::ui::toggle_group::*;Examples
Outline
ToggleVariant::Outline draws one border around the group, with a divider between items.
use gpui::{prelude::*, Context, Window};
use crate::ui::toggle::ToggleVariant;
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
pub struct ToggleGroupOutline {
selected: Vec<usize>,
}
// "All" starts selected, so `Default` is written out instead of derived.
impl Default for ToggleGroupOutline {
fn default() -> Self {
Self { selected: vec![0] }
}
}
impl Render for ToggleGroupOutline {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ToggleGroup::new("toggle-group-outline", ToggleGroupMode::Single)
.variant(ToggleVariant::Outline)
.selected(self.selected.clone())
.item("All")
.item("Missed")
.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
this.selected = selected.clone();
cx.notify();
}))
}
}Size
size takes the same ToggleSize values as a single toggle and applies them to every item.
use gpui::{div, prelude::*, Context, Window};
use crate::ui::toggle::{ToggleSize, ToggleVariant};
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
#[derive(Default)]
pub struct ToggleGroupSizes {
small: Vec<usize>,
large: Vec<usize>,
}
impl Render for ToggleGroupSizes {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.items_start()
.gap_4()
.child(
ToggleGroup::new("toggle-group-sm", ToggleGroupMode::Single)
.variant(ToggleVariant::Outline)
.size(ToggleSize::Sm)
.selected(self.small.clone())
.item("Top")
.item("Bottom")
.item("Left")
.item("Right")
.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
this.small = selected.clone();
cx.notify();
})),
)
.child(
ToggleGroup::new("toggle-group-lg", ToggleGroupMode::Single)
.variant(ToggleVariant::Outline)
.size(ToggleSize::Lg)
.selected(self.large.clone())
.item("Top")
.item("Bottom")
.item("Left")
.item("Right")
.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
this.large = selected.clone();
cx.notify();
})),
)
}
}Spacing
spacing separates the items, and each one gets its own rounded border.
use gpui::{prelude::*, px, Context, Window};
use crate::ui::toggle::{ToggleSize, ToggleVariant};
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
#[derive(Default)]
pub struct ToggleGroupSpacing {
selected: Vec<usize>,
}
impl Render for ToggleGroupSpacing {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ToggleGroup::new("toggle-group-spacing", ToggleGroupMode::Single)
.variant(ToggleVariant::Outline)
.size(ToggleSize::Sm)
.spacing(px(8.0))
.selected(self.selected.clone())
.item("Top")
.item("Bottom")
.item("Left")
.item("Right")
.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
this.selected = selected.clone();
cx.notify();
}))
}
}Vertical
ToggleGroupOrientation::Vertical stacks the items in a column.
use gpui::{prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle::ToggleVariant;
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode, ToggleGroupOrientation};
use crate::icons::{BOLD, ITALIC, UNDERLINE};
pub struct ToggleGroupVertical {
selected: Vec<usize>,
}
// Bold and italic start pressed, so `Default` is written out instead of derived.
impl Default for ToggleGroupVertical {
fn default() -> Self {
Self { selected: vec![0, 1] }
}
}
impl Render for ToggleGroupVertical {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
let icon = |data: &'static [u8]| svg().data(data).size(px(16.0)).text_color(fg);
ToggleGroup::new("toggle-group-vertical", ToggleGroupMode::Multiple)
.variant(ToggleVariant::Outline)
.orientation(ToggleGroupOrientation::Vertical)
.selected(self.selected.clone())
.item(icon(BOLD))
.item(icon(ITALIC))
.item(icon(UNDERLINE))
.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
this.selected = selected.clone();
cx.notify();
}))
}
}Disabled
disabled(true) dims the whole group and ignores clicks on every item.
use gpui::{prelude::*, px, svg, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
use crate::icons::{BOLD, ITALIC, UNDERLINE};
pub fn toggle_group_disabled(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
let icon = |data: &'static [u8]| svg().data(data).size(px(16.0)).text_color(fg);
ToggleGroup::new("toggle-group-disabled", ToggleGroupMode::Multiple)
.disabled(true)
.selected([0])
.item(icon(BOLD))
.item(icon(ITALIC))
.item(icon(UNDERLINE))
}Custom
Items take any element, so a font weight picker can preview each weight above its name.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle::ToggleVariant;
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
const WEIGHTS: [(&str, FontWeight); 4] = [
("Light", FontWeight::LIGHT),
("Normal", FontWeight::NORMAL),
("Medium", FontWeight::MEDIUM),
("Bold", FontWeight::BOLD),
];
pub struct ToggleGroupCustom {
selected: Vec<usize>,
}
// "Normal" starts selected, so `Default` is written out instead of derived.
impl Default for ToggleGroupCustom {
fn default() -> Self {
Self { selected: vec![1] }
}
}
impl Render for ToggleGroupCustom {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let weight = WEIGHTS[self.selected.first().copied().unwrap_or(1)].0;
let group = WEIGHTS.iter().fold(
ToggleGroup::new("toggle-group-custom", ToggleGroupMode::Single)
.variant(ToggleVariant::Outline)
.spacing(px(8.0))
.selected(self.selected.clone()),
|group, &(name, weight)| {
group.item(
div()
.flex()
.flex_col()
.items_center()
.w(px(48.0))
.py_2()
.child(div().text_xl().font_weight(weight).child("Aa"))
.child(div().text_xs().font_weight(FontWeight::NORMAL).child(name)),
)
},
);
div()
.flex()
.flex_col()
.gap_3()
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Font Weight"))
.child(group.on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
// Keep one weight chosen: clicking the active item would otherwise clear it.
if !selected.is_empty() {
this.selected = selected.clone();
cx.notify();
}
})))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(format!("Headings use the {weight} weight.")),
)
}
}API Reference
ToggleGroupMode
ToggleGroupMode::SingleAt most one item is pressed. Pressing the active item clears the selection.
ToggleGroupMode::MultipleAny number of items can be pressed.
ToggleGroupOrientation
The direction the items are laid out in.
ToggleGroupOrientation::HorizontalItems in a row, left to right.
ToggleGroupOrientation::VerticalItems in a column, top to bottom, stretched to the widest item.
ToggleGroup
A row of joined toggles. The parent view owns selected (item indices) and updates it in on_change, which receives the next selection in item order. The group is one tab stop, like Radix's roving focus: the arrow keys (and Home/End) move between items and Space or Enter toggles the one with the focus ring.
ToggleGroup::new(id: impl Into<ElementId>, mode: ToggleGroupMode) -> Self.selected(selected: impl IntoIterator<Item = usize>).item(content: impl IntoElement).variant(variant: ToggleVariant).size(size: ToggleSize).disabled(disabled: bool).orientation(orientation: ToggleGroupOrientation)Lays the items out in a row (the default) or a column.
.spacing(spacing: impl Into<Pixels>)Space between items. Zero (the default) joins them into one segmented control; anything larger gives each item its own rounded corners and border.
.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(&Vec<usize>, &mut Window, &mut App) + 'static)