button_like.rs

  1#![allow(missing_docs)]
  2use gpui::{relative, CursorStyle, DefiniteLength, MouseButton};
  3use gpui::{transparent_black, AnyElement, AnyView, ClickEvent, Hsla, Rems};
  4use smallvec::SmallVec;
  5
  6use crate::{prelude::*, DynamicSpacing, ElevationIndex};
  7
  8/// A trait for buttons that can be Selected. Enables setting the [`ButtonStyle`] of a button when it is selected.
  9pub trait SelectableButton: Toggleable {
 10    fn selected_style(self, style: ButtonStyle) -> Self;
 11}
 12
 13/// A common set of traits all buttons must implement.
 14pub trait ButtonCommon: Clickable + Disableable {
 15    /// A unique element ID to identify the button.
 16    fn id(&self) -> &ElementId;
 17
 18    /// The visual style of the button.
 19    ///
 20    /// Most commonly will be [`ButtonStyle::Subtle`], or [`ButtonStyle::Filled`]
 21    /// for an emphasized button.
 22    fn style(self, style: ButtonStyle) -> Self;
 23
 24    /// The size of the button.
 25    ///
 26    /// Most buttons will use the default size.
 27    ///
 28    /// [`ButtonSize`] can also be used to help build non-button elements
 29    /// that are consistently sized with buttons.
 30    fn size(self, size: ButtonSize) -> Self;
 31
 32    /// The tooltip that shows when a user hovers over the button.
 33    ///
 34    /// Nearly all interactable elements should have a tooltip. Some example
 35    /// exceptions might a scroll bar, or a slider.
 36    fn tooltip(self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self;
 37
 38    fn layer(self, elevation: ElevationIndex) -> Self;
 39}
 40
 41#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
 42pub enum IconPosition {
 43    #[default]
 44    Start,
 45    End,
 46}
 47
 48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
 49pub enum TintColor {
 50    #[default]
 51    Accent,
 52    Error,
 53    Warning,
 54    Success,
 55}
 56
 57impl TintColor {
 58    fn button_like_style(self, cx: &mut WindowContext) -> ButtonLikeStyles {
 59        match self {
 60            TintColor::Accent => ButtonLikeStyles {
 61                background: cx.theme().status().info_background,
 62                border_color: cx.theme().status().info_border,
 63                label_color: cx.theme().colors().text,
 64                icon_color: cx.theme().colors().text,
 65            },
 66            TintColor::Error => ButtonLikeStyles {
 67                background: cx.theme().status().error_background,
 68                border_color: cx.theme().status().error_border,
 69                label_color: cx.theme().colors().text,
 70                icon_color: cx.theme().colors().text,
 71            },
 72            TintColor::Warning => ButtonLikeStyles {
 73                background: cx.theme().status().warning_background,
 74                border_color: cx.theme().status().warning_border,
 75                label_color: cx.theme().colors().text,
 76                icon_color: cx.theme().colors().text,
 77            },
 78            TintColor::Success => ButtonLikeStyles {
 79                background: cx.theme().status().success_background,
 80                border_color: cx.theme().status().success_border,
 81                label_color: cx.theme().colors().text,
 82                icon_color: cx.theme().colors().text,
 83            },
 84        }
 85    }
 86}
 87
 88impl From<TintColor> for Color {
 89    fn from(tint: TintColor) -> Self {
 90        match tint {
 91            TintColor::Accent => Color::Accent,
 92            TintColor::Error => Color::Error,
 93            TintColor::Warning => Color::Warning,
 94            TintColor::Success => Color::Success,
 95        }
 96    }
 97}
 98
 99// Used to go from ButtonStyle -> Color through tint colors.
100impl From<ButtonStyle> for Color {
101    fn from(style: ButtonStyle) -> Self {
102        match style {
103            ButtonStyle::Tinted(tint) => tint.into(),
104            _ => Color::Default,
105        }
106    }
107}
108
109/// The visual appearance of a button.
110#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
111pub enum ButtonStyle {
112    /// A filled button with a solid background color. Provides emphasis versus
113    /// the more common subtle button.
114    Filled,
115
116    /// Used to emphasize a button in some way, like a selected state, or a semantic
117    /// coloring like an error or success button.
118    Tinted(TintColor),
119
120    /// The default button style, used for most buttons. Has a transparent background,
121    /// but has a background color to indicate states like hover and active.
122    #[default]
123    Subtle,
124
125    /// Used for buttons that only change foreground color on hover and active states.
126    ///
127    /// TODO: Better docs for this.
128    Transparent,
129}
130
131#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
132pub(crate) enum ButtonLikeRounding {
133    All,
134    Left,
135    Right,
136}
137
138#[derive(Debug, Clone)]
139pub(crate) struct ButtonLikeStyles {
140    pub background: Hsla,
141    #[allow(unused)]
142    pub border_color: Hsla,
143    #[allow(unused)]
144    pub label_color: Hsla,
145    #[allow(unused)]
146    pub icon_color: Hsla,
147}
148
149fn element_bg_from_elevation(elevation: Option<ElevationIndex>, cx: &mut WindowContext) -> Hsla {
150    match elevation {
151        Some(ElevationIndex::Background) => cx.theme().colors().element_background,
152        Some(ElevationIndex::ElevatedSurface) => cx.theme().colors().elevated_surface_background,
153        Some(ElevationIndex::Surface) => cx.theme().colors().surface_background,
154        Some(ElevationIndex::ModalSurface) => cx.theme().colors().background,
155        _ => cx.theme().colors().element_background,
156    }
157}
158
159impl ButtonStyle {
160    pub(crate) fn enabled(
161        self,
162        elevation: Option<ElevationIndex>,
163        cx: &mut WindowContext,
164    ) -> ButtonLikeStyles {
165        match self {
166            ButtonStyle::Filled => ButtonLikeStyles {
167                background: element_bg_from_elevation(elevation, cx),
168                border_color: transparent_black(),
169                label_color: Color::Default.color(cx),
170                icon_color: Color::Default.color(cx),
171            },
172            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
173            ButtonStyle::Subtle => ButtonLikeStyles {
174                background: cx.theme().colors().ghost_element_background,
175                border_color: transparent_black(),
176                label_color: Color::Default.color(cx),
177                icon_color: Color::Default.color(cx),
178            },
179            ButtonStyle::Transparent => ButtonLikeStyles {
180                background: transparent_black(),
181                border_color: transparent_black(),
182                label_color: Color::Default.color(cx),
183                icon_color: Color::Default.color(cx),
184            },
185        }
186    }
187
188    pub(crate) fn hovered(
189        self,
190        elevation: Option<ElevationIndex>,
191        cx: &mut WindowContext,
192    ) -> ButtonLikeStyles {
193        match self {
194            ButtonStyle::Filled => {
195                let mut filled_background = element_bg_from_elevation(elevation, cx);
196                filled_background.fade_out(0.92);
197
198                ButtonLikeStyles {
199                    background: filled_background,
200                    border_color: transparent_black(),
201                    label_color: Color::Default.color(cx),
202                    icon_color: Color::Default.color(cx),
203                }
204            }
205            ButtonStyle::Tinted(tint) => {
206                let mut styles = tint.button_like_style(cx);
207                let theme = cx.theme();
208                styles.background = theme.darken(styles.background, 0.05, 0.2);
209                styles
210            }
211            ButtonStyle::Subtle => ButtonLikeStyles {
212                background: cx.theme().colors().ghost_element_hover,
213                border_color: transparent_black(),
214                label_color: Color::Default.color(cx),
215                icon_color: Color::Default.color(cx),
216            },
217            ButtonStyle::Transparent => ButtonLikeStyles {
218                background: transparent_black(),
219                border_color: transparent_black(),
220                // TODO: These are not great
221                label_color: Color::Muted.color(cx),
222                // TODO: These are not great
223                icon_color: Color::Muted.color(cx),
224            },
225        }
226    }
227
228    pub(crate) fn active(self, cx: &mut WindowContext) -> ButtonLikeStyles {
229        match self {
230            ButtonStyle::Filled => ButtonLikeStyles {
231                background: cx.theme().colors().element_active,
232                border_color: transparent_black(),
233                label_color: Color::Default.color(cx),
234                icon_color: Color::Default.color(cx),
235            },
236            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
237            ButtonStyle::Subtle => ButtonLikeStyles {
238                background: cx.theme().colors().ghost_element_active,
239                border_color: transparent_black(),
240                label_color: Color::Default.color(cx),
241                icon_color: Color::Default.color(cx),
242            },
243            ButtonStyle::Transparent => ButtonLikeStyles {
244                background: transparent_black(),
245                border_color: transparent_black(),
246                // TODO: These are not great
247                label_color: Color::Muted.color(cx),
248                // TODO: These are not great
249                icon_color: Color::Muted.color(cx),
250            },
251        }
252    }
253
254    #[allow(unused)]
255    pub(crate) fn focused(self, cx: &mut WindowContext) -> ButtonLikeStyles {
256        match self {
257            ButtonStyle::Filled => ButtonLikeStyles {
258                background: cx.theme().colors().element_background,
259                border_color: cx.theme().colors().border_focused,
260                label_color: Color::Default.color(cx),
261                icon_color: Color::Default.color(cx),
262            },
263            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
264            ButtonStyle::Subtle => ButtonLikeStyles {
265                background: cx.theme().colors().ghost_element_background,
266                border_color: cx.theme().colors().border_focused,
267                label_color: Color::Default.color(cx),
268                icon_color: Color::Default.color(cx),
269            },
270            ButtonStyle::Transparent => ButtonLikeStyles {
271                background: transparent_black(),
272                border_color: cx.theme().colors().border_focused,
273                label_color: Color::Accent.color(cx),
274                icon_color: Color::Accent.color(cx),
275            },
276        }
277    }
278
279    #[allow(unused)]
280    pub(crate) fn disabled(
281        self,
282        elevation: Option<ElevationIndex>,
283        cx: &mut WindowContext,
284    ) -> ButtonLikeStyles {
285        match self {
286            ButtonStyle::Filled => ButtonLikeStyles {
287                background: cx.theme().colors().element_disabled,
288                border_color: cx.theme().colors().border_disabled,
289                label_color: Color::Disabled.color(cx),
290                icon_color: Color::Disabled.color(cx),
291            },
292            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
293            ButtonStyle::Subtle => ButtonLikeStyles {
294                background: cx.theme().colors().ghost_element_disabled,
295                border_color: cx.theme().colors().border_disabled,
296                label_color: Color::Disabled.color(cx),
297                icon_color: Color::Disabled.color(cx),
298            },
299            ButtonStyle::Transparent => ButtonLikeStyles {
300                background: transparent_black(),
301                border_color: transparent_black(),
302                label_color: Color::Disabled.color(cx),
303                icon_color: Color::Disabled.color(cx),
304            },
305        }
306    }
307}
308
309/// The height of a button.
310///
311/// Can also be used to size non-button elements to align with [`Button`]s.
312#[derive(Default, PartialEq, Clone, Copy)]
313pub enum ButtonSize {
314    Large,
315    #[default]
316    Default,
317    Compact,
318    None,
319}
320
321impl ButtonSize {
322    pub fn rems(self) -> Rems {
323        match self {
324            ButtonSize::Large => rems_from_px(32.),
325            ButtonSize::Default => rems_from_px(22.),
326            ButtonSize::Compact => rems_from_px(18.),
327            ButtonSize::None => rems_from_px(16.),
328        }
329    }
330}
331
332/// A button-like element that can be used to create a custom button when
333/// prebuilt buttons are not sufficient. Use this sparingly, as it is
334/// unconstrained and may make the UI feel less consistent.
335///
336/// This is also used to build the prebuilt buttons.
337#[derive(IntoElement)]
338pub struct ButtonLike {
339    pub(super) base: Div,
340    id: ElementId,
341    pub(super) style: ButtonStyle,
342    pub(super) disabled: bool,
343    pub(super) selected: bool,
344    pub(super) selected_style: Option<ButtonStyle>,
345    pub(super) width: Option<DefiniteLength>,
346    pub(super) height: Option<DefiniteLength>,
347    pub(super) layer: Option<ElevationIndex>,
348    size: ButtonSize,
349    rounding: Option<ButtonLikeRounding>,
350    tooltip: Option<Box<dyn Fn(&mut WindowContext) -> AnyView>>,
351    cursor_style: CursorStyle,
352    on_click: Option<Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>>,
353    children: SmallVec<[AnyElement; 2]>,
354}
355
356impl ButtonLike {
357    pub fn new(id: impl Into<ElementId>) -> Self {
358        Self {
359            base: div(),
360            id: id.into(),
361            style: ButtonStyle::default(),
362            disabled: false,
363            selected: false,
364            selected_style: None,
365            width: None,
366            height: None,
367            size: ButtonSize::Default,
368            rounding: Some(ButtonLikeRounding::All),
369            tooltip: None,
370            children: SmallVec::new(),
371            cursor_style: CursorStyle::PointingHand,
372            on_click: None,
373            layer: None,
374        }
375    }
376
377    pub fn new_rounded_left(id: impl Into<ElementId>) -> Self {
378        Self::new(id).rounding(ButtonLikeRounding::Left)
379    }
380
381    pub fn new_rounded_right(id: impl Into<ElementId>) -> Self {
382        Self::new(id).rounding(ButtonLikeRounding::Right)
383    }
384
385    pub(crate) fn height(mut self, height: DefiniteLength) -> Self {
386        self.height = Some(height);
387        self
388    }
389
390    pub(crate) fn rounding(mut self, rounding: impl Into<Option<ButtonLikeRounding>>) -> Self {
391        self.rounding = rounding.into();
392        self
393    }
394}
395
396impl Disableable for ButtonLike {
397    fn disabled(mut self, disabled: bool) -> Self {
398        self.disabled = disabled;
399        self
400    }
401}
402
403impl Toggleable for ButtonLike {
404    fn toggle_state(mut self, selected: bool) -> Self {
405        self.selected = selected;
406        self
407    }
408}
409
410impl SelectableButton for ButtonLike {
411    fn selected_style(mut self, style: ButtonStyle) -> Self {
412        self.selected_style = Some(style);
413        self
414    }
415}
416
417impl Clickable for ButtonLike {
418    fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self {
419        self.on_click = Some(Box::new(handler));
420        self
421    }
422
423    fn cursor_style(mut self, cursor_style: CursorStyle) -> Self {
424        self.cursor_style = cursor_style;
425        self
426    }
427}
428
429impl FixedWidth for ButtonLike {
430    fn width(mut self, width: DefiniteLength) -> Self {
431        self.width = Some(width);
432        self
433    }
434
435    fn full_width(mut self) -> Self {
436        self.width = Some(relative(1.));
437        self
438    }
439}
440
441impl ButtonCommon for ButtonLike {
442    fn id(&self) -> &ElementId {
443        &self.id
444    }
445
446    fn style(mut self, style: ButtonStyle) -> Self {
447        self.style = style;
448        self
449    }
450
451    fn size(mut self, size: ButtonSize) -> Self {
452        self.size = size;
453        self
454    }
455
456    fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
457        self.tooltip = Some(Box::new(tooltip));
458        self
459    }
460
461    fn layer(mut self, elevation: ElevationIndex) -> Self {
462        self.layer = Some(elevation);
463        self
464    }
465}
466
467impl VisibleOnHover for ButtonLike {
468    fn visible_on_hover(mut self, group_name: impl Into<SharedString>) -> Self {
469        self.base = self.base.visible_on_hover(group_name);
470        self
471    }
472}
473
474impl ParentElement for ButtonLike {
475    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
476        self.children.extend(elements)
477    }
478}
479
480impl RenderOnce for ButtonLike {
481    fn render(self, cx: &mut WindowContext) -> impl IntoElement {
482        let style = self
483            .selected_style
484            .filter(|_| self.selected)
485            .unwrap_or(self.style);
486
487        self.base
488            .h_flex()
489            .id(self.id.clone())
490            .group("")
491            .flex_none()
492            .h(self.height.unwrap_or(self.size.rems().into()))
493            .when_some(self.width, |this, width| this.w(width).justify_center())
494            .when_some(self.rounding, |this, rounding| match rounding {
495                ButtonLikeRounding::All => this.rounded_md(),
496                ButtonLikeRounding::Left => this.rounded_l_md(),
497                ButtonLikeRounding::Right => this.rounded_r_md(),
498            })
499            .gap(DynamicSpacing::Base04.rems(cx))
500            .map(|this| match self.size {
501                ButtonSize::Large => this.px(DynamicSpacing::Base06.rems(cx)),
502                ButtonSize::Default | ButtonSize::Compact => {
503                    this.px(DynamicSpacing::Base04.rems(cx))
504                }
505                ButtonSize::None => this,
506            })
507            .bg(style.enabled(self.layer, cx).background)
508            .when(self.disabled, |this| this.cursor_not_allowed())
509            .when(!self.disabled, |this| {
510                this.cursor_pointer()
511                    .hover(|hover| hover.bg(style.hovered(self.layer, cx).background))
512                    .active(|active| active.bg(style.active(cx).background))
513            })
514            .when_some(
515                self.on_click.filter(|_| !self.disabled),
516                |this, on_click| {
517                    this.on_mouse_down(MouseButton::Left, |_, cx| cx.prevent_default())
518                        .on_click(move |event, cx| {
519                            cx.stop_propagation();
520                            (on_click)(event, cx)
521                        })
522                },
523            )
524            .when_some(self.tooltip, |this, tooltip| {
525                this.tooltip(move |cx| tooltip(cx))
526            })
527            .children(self.children)
528    }
529}