Related actions joined into one control with shared borders and square inner corners.
use gpui::{div, prelude::*, App, Window};
use crate::ui::button::{ButtonSize, ButtonVariant};
use crate::ui::button_group::{ButtonGroup, GroupButton};
pub fn button_group_demo(_window: &mut Window, _cx: &mut App) -> impl IntoElement {
div()
.flex()
.flex_col()
.items_center()
.gap_4()
.child(
ButtonGroup::new("message-actions")
.child(GroupButton::new("Archive").on_click(|_, _, _| println!("archived")))
.child(GroupButton::new("Report"))
.child(GroupButton::new("Snooze")),
)
.child(
ButtonGroup::new("range")
.variant(ButtonVariant::Secondary)
.size(ButtonSize::Sm)
.child(GroupButton::new("Day"))
.child(GroupButton::new("Week"))
.child(GroupButton::new("Month"))
.child(GroupButton::new("Year").disabled(true)),
)
}Installation
Copies src/ui/button_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/button_group.rs.src/ui/button_group.rs use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui::{ div, prelude::*, px, AnimationExt, AnyElement, App, ClickEvent, ElementId, Entity, FontWeight, Hsla, Interpolate, SharedString, SpringAnimation, SpringAnimationElement, SpringConfig, Window, }; use crate::theme::ActiveTheme; use crate::ui::button::{ButtonSize, ButtonVariant}; type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// One segment of a [`ButtonGroup`]. pub struct GroupButton { label: SharedString, disabled: bool, icon_only: bool, leading: Option<AnyElement>, trailing: Option<AnyElement>, on_click: Option<ClickHandler>, } impl GroupButton { pub fn new(label: impl Into<SharedString>) -> Self { Self { label: label.into(), disabled: false, icon_only: false, leading: None, trailing: None, on_click: None, } } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// An element before the label, usually an icon. SVG icons don't inherit the text color, /// so give them the color of the group's text. pub fn leading(mut self, element: impl IntoElement) -> Self { self.leading = Some(element.into_any_element()); self } /// An element after the label, such as a chevron on a menu trigger. pub fn trailing(mut self, element: impl IntoElement) -> Self { self.trailing = Some(element.into_any_element()); self } /// Makes the segment a square as wide as the group is tall, for a lone icon. Pass an empty /// label and the icon through `leading`. pub fn icon_only(mut self) -> Self { self.icon_only = true; self } pub fn on_click( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_click = Some(Box::new(handler)); self } } /// Related actions joined into one control: inner corners are square and neighbours share /// a border. Segments are drawn here rather than as `Button`s because a `Button` always /// rounds all four corners, but they use the same variants, sizes and colors. #[derive(IntoElement)] pub struct ButtonGroup { id: ElementId, variant: ButtonVariant, size: ButtonSize, vertical: bool, buttons: Vec<GroupButton>, } impl ButtonGroup { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), variant: ButtonVariant::Outline, size: ButtonSize::default(), vertical: false, buttons: Vec::new(), } } /// Defaults to `Outline`, the usual look for a toolbar of related actions. pub fn variant(mut self, variant: ButtonVariant) -> Self { self.variant = variant; self } pub fn size(mut self, size: ButtonSize) -> Self { self.size = size; self } /// Stacks the segments top to bottom instead of left to right. Segments stretch to the /// widest one. pub fn vertical(mut self) -> Self { self.vertical = true; self } pub fn child(mut self, button: GroupButton) -> Self { self.buttons.push(button); self } } impl RenderOnce for ButtonGroup { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let radius = theme.radius; let outline = self.variant == ButtonVariant::Outline; let vertical = self.vertical; let clear = gpui::transparent_black(); // Same palette as `Button`, so a group sits naturally next to standalone buttons. let (bg, fg, hover_bg, hover_fg) = match self.variant { ButtonVariant::Default => ( theme.primary, theme.primary_foreground, theme.primary.opacity(0.9), theme.primary_foreground, ), ButtonVariant::Secondary => ( theme.secondary, theme.secondary_foreground, theme.secondary.opacity(0.8), theme.secondary_foreground, ), ButtonVariant::Outline => { (theme.background, theme.foreground, theme.accent, theme.accent_foreground) } ButtonVariant::Ghost => { (clear, theme.foreground, theme.accent, theme.accent_foreground) } ButtonVariant::Destructive => ( theme.destructive, theme.destructive_foreground, theme.destructive.opacity(0.9), theme.destructive_foreground, ), // A link has no surface to join, so it reads like a row of ghost buttons in the // primary color. ButtonVariant::Link => (clear, theme.primary, theme.accent, theme.primary), }; let (height, pad_x) = match self.size { ButtonSize::Xs => (px(24.0), px(8.0)), ButtonSize::Compact => (px(28.0), px(12.0)), ButtonSize::Sm => (px(32.0), px(12.0)), ButtonSize::Md => (px(36.0), px(16.0)), ButtonSize::Lg => (px(40.0), px(24.0)), }; let last = self.buttons.len().saturating_sub(1); let mut children: Vec<AnyElement> = Vec::new(); for (ix, button) in self.buttons.into_iter().enumerate() { // Filled variants have no border to share, so a hairline marks the seam instead. if ix > 0 && !outline { let seam = div().flex_none().bg(theme.input); let seam = if vertical { seam.h(px(1.0)).w_full() } else { seam.w(px(1.0)).h(height) }; children.push(seam.into_any_element()); } let disabled = button.disabled; let (first, end) = (ix == 0, ix == last); let key = ElementId::NamedChild(Arc::new(self.id.clone()), format!("segment-{ix}").into()); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered && !disabled; let target = Paint { bg: if hovered { hover_bg } else { bg }, fg: if hovered { hover_fg } else { fg }, border: if outline { theme.input } else { clear }, }; let segment = div() .id(ix) .flex() .flex_none() .items_center() .justify_center() .gap_2() .h(height) .map(|this| if button.icon_only { this.w(height) } else { this.px(pad_x) }) .text_sm() .font_weight(FontWeight::MEDIUM) .map(|this| { if vertical { this.when(first, |this| this.rounded_t(radius)) .when(end, |this| this.rounded_b(radius)) } else { this.when(first, |this| this.rounded_l(radius)) .when(end, |this| this.rounded_r(radius)) } }) // Only the first segment draws the leading edge, so neighbours share one // 1px border. .when(outline, |this| { 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.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| { this.cursor_pointer() // Sinks 1px while pressed, like a standalone Button. .relative() .active(|style| style.top(px(1.0))) }) .when_some(button.on_click.filter(|_| !disabled), |this, handler| { this.on_click(move |event, window, cx| handler(event, window, cx)) }) .children(button.leading) .when(!button.label.is_empty(), |this| this.child(button.label)) .children(button.trailing); // The hover background eases in and out, like shadcn's `transition-all`. children.push( ease_to(segment, key, &ease, target, cx, |this, paint| { this.bg(paint.bg).text_color(paint.fg).border_color(paint.border) }) .into_any_element(), ); } div() .id(self.id) .flex() .map(|this| if vertical { this.flex_col().items_stretch() } else { this.items_center() }) .rounded(radius) .when(outline, |this| this.shadow_xs()) .children(children) } } /// 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 button_group;
Usage
use crate::ui::button_group::*;Examples
Orientation
vertical() stacks the segments top to bottom, as in this pair of zoom controls.
use gpui::{prelude::*, px, svg, App, Hsla, Svg, Window};
use crate::theme::ActiveTheme;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::icons::{MINUS, PLUS};
pub fn button_group_orientation(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
ButtonGroup::new("zoom")
.vertical()
.child(GroupButton::new("").icon_only().leading(icon(PLUS, fg)))
.child(GroupButton::new("").icon_only().leading(icon(MINUS, fg)))
}
fn icon(data: &'static [u8], color: Hsla) -> Svg {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Size
size on the group sets the height and padding of every segment, from ButtonSize::Xs to Lg.
use gpui::{div, prelude::*, px, svg, App, Hsla, Svg, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::ButtonSize;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::icons::PLUS;
pub fn button_group_size(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
let group = |id: &'static str, size: ButtonSize| {
ButtonGroup::new(id)
.size(size)
.child(GroupButton::new(id))
.child(GroupButton::new("Button"))
.child(GroupButton::new("Group"))
.child(GroupButton::new("").icon_only().leading(icon(PLUS, fg)))
};
div()
.flex()
.flex_col()
.items_start()
.gap_6()
.child(group("Small", ButtonSize::Sm))
.child(group("Default", ButtonSize::Md))
.child(group("Large", ButtonSize::Lg))
}
fn icon(data: &'static [u8], color: Hsla) -> Svg {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Nested
Put several groups in a row with a gap between them to build a toolbar of related clusters.
use gpui::{div, prelude::*, px, svg, App, Hsla, Svg, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::ButtonSize;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::icons::{AUDIO_LINES, PLUS};
pub fn button_group_nested(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.flex()
.items_center()
.gap_2()
.child(
ButtonGroup::new("pages")
.size(ButtonSize::Sm)
.child(GroupButton::new("1"))
.child(GroupButton::new("2"))
.child(GroupButton::new("3")),
)
.child(
ButtonGroup::new("tools")
.size(ButtonSize::Sm)
.child(GroupButton::new("").icon_only().leading(icon(PLUS, fg)))
.child(GroupButton::new("").icon_only().leading(icon(AUDIO_LINES, fg))),
)
}
fn icon(data: &'static [u8], color: Hsla) -> Svg {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Separator
Outline segments share a border, but filled variants have none, so the group draws a hairline between them. No separate separator element is needed.
use gpui::prelude::*;
use crate::ui::button::{ButtonSize, ButtonVariant};
use crate::ui::button_group::{ButtonGroup, GroupButton};
pub fn button_group_separator() -> impl IntoElement {
ButtonGroup::new("clipboard")
.variant(ButtonVariant::Secondary)
.size(ButtonSize::Sm)
.child(GroupButton::new("Copy"))
.child(GroupButton::new("Paste"))
}Split
A split button: a main action joined to an icon-only secondary action, separated by the group's hairline.
use gpui::{prelude::*, px, svg, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::ButtonVariant;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::icons::PLUS;
pub fn button_group_split(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().secondary_foreground;
ButtonGroup::new("split")
.variant(ButtonVariant::Secondary)
.child(GroupButton::new("Button"))
.child(
GroupButton::new("")
.icon_only()
.leading(svg().data(PLUS).flex_none().size(px(16.0)).text_color(fg)),
)
}Dropdown Menu
A split button whose chevron opens a DropdownMenu. The whole group is the menu's trigger, so the main action calls cx.stop_propagation() to keep its click from opening the menu.
use gpui::{div, prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::popover::Align;
use crate::icons::CHEVRON_DOWN;
#[derive(Default)]
pub struct ButtonGroupDropdownMenu {
open: bool,
}
impl Render for ButtonGroupDropdownMenu {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
// Tall enough for the menu to open downward inside the preview.
div().h(px(220.0)).child(
DropdownMenu::new("follow-menu", self.open)
.align(Align::End)
.width(px(192.0))
.trigger(
ButtonGroup::new("follow")
.child(GroupButton::new("Follow").on_click(|_, _, cx| {
cx.stop_propagation();
println!("followed");
}))
.child(
GroupButton::new("")
.icon_only()
.leading(svg().data(CHEVRON_DOWN).flex_none().size(px(16.0)).text_color(fg)),
),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Mute conversation"))
.item(MenuItem::new("Mark as read"))
.item(MenuItem::new("Report conversation"))
.separator()
.item(MenuItem::new("Block user").destructive(true)),
)
}
}Popover
A group whose chevron opens a Popover with more options for the main action.
use gpui::{div, prelude::*, px, svg, Context, FontWeight, Hsla, Svg, Window};
use crate::theme::ActiveTheme;
use crate::ui::button_group::{ButtonGroup, GroupButton};
use crate::ui::popover::{Align, Popover};
use crate::icons::{BOT, CHEVRON_DOWN};
#[derive(Default)]
pub struct ButtonGroupPopover {
open: bool,
}
impl Render for ButtonGroupPopover {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (fg, muted) = (theme.foreground, theme.muted_foreground);
div().h(px(200.0)).child(
Popover::new("copilot", self.open)
.align(Align::End)
.width(px(260.0))
.trigger(
ButtonGroup::new("copilot-actions")
.child(
GroupButton::new("Copilot")
.leading(icon(BOT, fg))
.on_click(|_, _, cx| cx.stop_propagation()),
)
.child(GroupButton::new("").icon_only().leading(icon(CHEVRON_DOWN, fg))),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(div().font_weight(FontWeight::MEDIUM).child("Start a new task with Copilot"))
.child(
div()
.mt_1()
.text_color(muted)
.child("Describe your task in natural language and Copilot will open a pull request."),
),
)
}
}
fn icon(data: &'static [u8], color: Hsla) -> Svg {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}API Reference
GroupButton
One segment of a [ButtonGroup].
GroupButton::new(label: impl Into<SharedString>) -> Self.disabled(disabled: bool).leading(element: impl IntoElement)An element before the label, usually an icon. SVG icons don't inherit the text color, so give them the color of the group's text.
.trailing(element: impl IntoElement)An element after the label, such as a chevron on a menu trigger.
.icon_only()Makes the segment a square as wide as the group is tall, for a lone icon. Pass an empty label and the icon through leading.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)ButtonGroup
Related actions joined into one control: inner corners are square and neighbours share a border. Segments are drawn here rather than as Buttons because a Button always rounds all four corners, but they use the same variants, sizes and colors.
ButtonGroup::new(id: impl Into<ElementId>) -> Self.variant(variant: ButtonVariant)Defaults to Outline, the usual look for a toolbar of related actions.
.size(size: ButtonSize).vertical()Stacks the segments top to bottom instead of left to right. Segments stretch to the widest one.
.child(button: GroupButton)