A two-state button that can be on or off.
use gpui::{div, prelude::*, px, svg, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle::{Toggle, ToggleVariant};
use crate::icons::BOOKMARK;
#[derive(Default)]
pub struct Note {
bold: bool,
strikethrough: bool,
bookmarked: bool,
}
impl Render for Note {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.flex()
.flex_col()
.items_center()
.gap_4()
.child(
div()
.flex()
.items_center()
.gap_1()
.child(
Toggle::new("bold", self.bold)
.child(div().font_weight(FontWeight::BOLD).child("B"))
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.bold = *pressed;
cx.notify();
})),
)
.child(
Toggle::new("strikethrough", self.strikethrough)
.child(div().line_through().child("S"))
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.strikethrough = *pressed;
cx.notify();
})),
)
.child(
Toggle::new("bookmark", self.bookmarked)
.variant(ToggleVariant::Outline)
.child(svg().data(BOOKMARK).size(px(16.0)).text_color(theme.foreground))
.child("Bookmark")
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.bookmarked = *pressed;
cx.notify();
})),
),
)
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.when(self.bold, |this| this.font_weight(FontWeight::BOLD))
.when(self.strikethrough, |this| this.line_through())
.child("Pick up the dry cleaning before six."),
)
}
}Installation
Copies src/ui/toggle.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.rs.src/ui/toggle.rs use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui::{ div, point, prelude::*, px, AnimationExt, AnyElement, App, BoxShadow, ElementId, Entity, FocusHandle, FontWeight, Hsla, Interpolate, Pixels, SpringAnimation, SpringAnimationElement, SpringConfig, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; #[derive(Clone, Copy, Default, PartialEq)] pub enum ToggleVariant { #[default] Default, Outline, } #[derive(Clone, Copy, Default, PartialEq)] pub enum ToggleSize { Sm, #[default] Md, Lg, } impl ToggleSize { /// Height, which is also the minimum width, so a single glyph renders square. pub fn height(self) -> Pixels { match self { ToggleSize::Sm => px(32.0), ToggleSize::Md => px(36.0), ToggleSize::Lg => px(40.0), } } pub fn padding_x(self) -> Pixels { match self { ToggleSize::Sm => px(6.0), ToggleSize::Md => px(8.0), ToggleSize::Lg => px(10.0), } } } type ToggleHandler = Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// A two-state button. The parent view owns `pressed` and updates it in `on_toggle`. /// Content is whatever children you give it: a glyph, an icon, a label, or several. /// It is a tab stop; Space or Enter toggles it once focused. #[derive(IntoElement)] pub struct Toggle { id: ElementId, pressed: bool, variant: ToggleVariant, size: ToggleSize, disabled: bool, children: Vec<AnyElement>, focus_handle: Option<FocusHandle>, on_toggle: Option<ToggleHandler>, } impl Toggle { pub fn new(id: impl Into<ElementId>, pressed: bool) -> Self { Self { id: id.into(), pressed, variant: ToggleVariant::default(), size: ToggleSize::default(), disabled: false, children: Vec::new(), focus_handle: None, on_toggle: None, } } 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 } /// Focus the toggle 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 } /// Receives the *next* pressed value. pub fn on_toggle(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { self.on_toggle = Some(Box::new(handler)); self } } impl ParentElement for Toggle { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for Toggle { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let pressed = self.pressed; 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 key = ElementId::NamedChild(Arc::new(self.id.clone()), "ease".into()); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered && !disabled; let focus = self.focus_handle.unwrap_or_else(|| ease.read(cx).focus.clone()).tab_stop(!disabled); // 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); // Hover wins over pressed, as before; 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 { // GPUI paints a shadow's full shape under the element, so an outlined toggle // needs an opaque fill where shadcn's is transparent. (theme.background, theme.foreground) } else { (gpui::transparent_black(), theme.foreground) }; let target = Paint { // GPUI paints a shadow's whole shape, so a ringed toggle needs an opaque fill. bg: if focus_visible && bg.a == 0.0 { theme.background } else { bg }, fg, border: if focus_visible { theme.ring } else if outline { theme.input } else { gpui::transparent_black() }, }; let toggle = div() .id(self.id) .when(!disabled, |this| this.track_focus(&focus).end_visible_focus_on_press(&focus, cx)) .flex() .flex_none() .items_center() .justify_center() .gap_2() .h(self.size.height()) .min_w(self.size.height()) .px(self.size.padding_x()) .rounded(theme.radius) .text_sm() .font_weight(FontWeight::MEDIUM) .when(outline, |this| this.border_1()) .map(|this| { if focus_visible { this.shadow(focus_ring(theme.ring.opacity(0.5))) } else if outline { this.shadow_xs() } else { this } }) // Tracks hover even while disabled, so the flag is right once it is enabled. .on_hover(track_hover(&ease)) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| this.cursor_pointer()) .when_some(self.on_toggle.filter(|_| !disabled), |this, handler| { this.on_click(move |_, window, cx| handler(&!pressed, window, cx)) }) .children(self.children); ease_to(toggle, key, &ease, target, cx, |this, paint| { this.bg(paint.bg).text_color(paint.fg).border_color(paint.border) }) } } /// 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) } /// shadcn's `focus-visible:ring-[3px]`. fn focus_ring(color: Hsla) -> Vec<BoxShadow> { vec![BoxShadow { color, offset: point(px(0.), px(0.)), blur_radius: px(0.), spread_radius: px(3.), inset: false, }] } /// One control's hover flag, color transition and focus handle, kept across frames: a /// RenderOnce control is rebuilt every frame, but focus has to stay on the same handle. struct Ease { hovered: bool, focus: FocusHandle, /// 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, |_, cx| Ease { hovered: false, focus: cx.focus_handle(), from_to: None, start: 0.0, run: 0.0, shown: Rc::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;
Usage
use crate::ui::toggle::*;Examples
Outline
ToggleVariant::Outline adds a border and a light shadow, for toggles that sit on their own.
use gpui::{div, prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle::{Toggle, ToggleVariant};
use crate::icons::{BOLD, ITALIC};
#[derive(Default)]
pub struct ToggleOutline {
italic: bool,
bold: bool,
}
impl Render for ToggleOutline {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.flex()
.items_center()
.gap_2()
.child(
Toggle::new("outline-italic", self.italic)
.variant(ToggleVariant::Outline)
.child(svg().data(ITALIC).size(px(16.0)).text_color(fg))
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.italic = *pressed;
cx.notify();
})),
)
.child(
Toggle::new("outline-bold", self.bold)
.variant(ToggleVariant::Outline)
.child(svg().data(BOLD).size(px(16.0)).text_color(fg))
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.bold = *pressed;
cx.notify();
})),
)
}
}With Text
Children can mix an icon and a label; the toggle grows to fit them.
use gpui::{prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::toggle::Toggle;
use crate::icons::ITALIC;
#[derive(Default)]
pub struct ToggleWithText {
italic: bool,
}
impl Render for ToggleWithText {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
Toggle::new("with-text-italic", self.italic)
.child(svg().data(ITALIC).size(px(16.0)).text_color(fg))
.child("Italic")
.on_toggle(cx.listener(|this, pressed: &bool, _, cx| {
this.italic = *pressed;
cx.notify();
}))
}
}Size
ToggleSize::Sm is 32px tall, Md (the default) 36px and Lg 40px.
use gpui::{div, prelude::*, Context, Window};
use crate::ui::toggle::{Toggle, ToggleSize, ToggleVariant};
#[derive(Default)]
pub struct ToggleSizes {
pressed: [bool; 3],
}
impl Render for ToggleSizes {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let sizes = [
(ToggleSize::Sm, "Small"),
(ToggleSize::Md, "Default"),
(ToggleSize::Lg, "Large"),
];
div()
.flex()
.items_center()
.gap_2()
.children(sizes.into_iter().enumerate().map(|(ix, (size, label))| {
Toggle::new(("toggle-size", ix), self.pressed[ix])
.variant(ToggleVariant::Outline)
.size(size)
.child(label)
.on_toggle(cx.listener(move |this, pressed: &bool, _, cx| {
this.pressed[ix] = *pressed;
cx.notify();
}))
}))
}
}Disabled
disabled(true) dims the toggle and ignores clicks, whether it is pressed or not.
use gpui::{div, prelude::*};
use crate::ui::toggle::{Toggle, ToggleVariant};
pub fn toggle_disabled() -> impl IntoElement {
div()
.flex()
.items_center()
.gap_2()
.child(Toggle::new("toggle-disabled-default", false).disabled(true).child("Disabled"))
.child(
Toggle::new("toggle-disabled-outline", true)
.variant(ToggleVariant::Outline)
.disabled(true)
.child("Disabled"),
)
}API Reference
ToggleVariant
ToggleVariant::DefaultToggleVariant::OutlineToggleSize
ToggleSize::SmToggleSize::MdToggleSize::LgToggle
A two-state button. The parent view owns pressed and updates it in on_toggle. Content is whatever children you give it: a glyph, an icon, a label, or several. It is a tab stop; Space or Enter toggles it once focused.
Toggle::new(id: impl Into<ElementId>, pressed: bool) -> Self.variant(variant: ToggleVariant).size(size: ToggleSize).disabled(disabled: bool).focus_handle(handle: FocusHandle)Focus the toggle 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_toggle(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* pressed value.