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::*, ElevationIndex, Spacing};
  7
  8/// A trait for buttons that can be Selected. Enables setting the [`ButtonStyle`] of a button when it is selected.
  9pub trait SelectableButton: Selectable {
 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    Negative,
 53    Warning,
 54    Positive,
 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::Negative => 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::Positive => 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::Negative => Color::Error,
 93            TintColor::Warning => Color::Warning,
 94            TintColor::Positive => 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) => tint.button_like_style(cx),
206            ButtonStyle::Subtle => ButtonLikeStyles {
207                background: cx.theme().colors().ghost_element_hover,
208                border_color: transparent_black(),
209                label_color: Color::Default.color(cx),
210                icon_color: Color::Default.color(cx),
211            },
212            ButtonStyle::Transparent => ButtonLikeStyles {
213                background: transparent_black(),
214                border_color: transparent_black(),
215                // TODO: These are not great
216                label_color: Color::Muted.color(cx),
217                // TODO: These are not great
218                icon_color: Color::Muted.color(cx),
219            },
220        }
221    }
222
223    pub(crate) fn active(self, cx: &mut WindowContext) -> ButtonLikeStyles {
224        match self {
225            ButtonStyle::Filled => ButtonLikeStyles {
226                background: cx.theme().colors().element_active,
227                border_color: transparent_black(),
228                label_color: Color::Default.color(cx),
229                icon_color: Color::Default.color(cx),
230            },
231            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
232            ButtonStyle::Subtle => ButtonLikeStyles {
233                background: cx.theme().colors().ghost_element_active,
234                border_color: transparent_black(),
235                label_color: Color::Default.color(cx),
236                icon_color: Color::Default.color(cx),
237            },
238            ButtonStyle::Transparent => ButtonLikeStyles {
239                background: transparent_black(),
240                border_color: transparent_black(),
241                // TODO: These are not great
242                label_color: Color::Muted.color(cx),
243                // TODO: These are not great
244                icon_color: Color::Muted.color(cx),
245            },
246        }
247    }
248
249    #[allow(unused)]
250    pub(crate) fn focused(self, cx: &mut WindowContext) -> ButtonLikeStyles {
251        match self {
252            ButtonStyle::Filled => ButtonLikeStyles {
253                background: cx.theme().colors().element_background,
254                border_color: cx.theme().colors().border_focused,
255                label_color: Color::Default.color(cx),
256                icon_color: Color::Default.color(cx),
257            },
258            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
259            ButtonStyle::Subtle => ButtonLikeStyles {
260                background: cx.theme().colors().ghost_element_background,
261                border_color: cx.theme().colors().border_focused,
262                label_color: Color::Default.color(cx),
263                icon_color: Color::Default.color(cx),
264            },
265            ButtonStyle::Transparent => ButtonLikeStyles {
266                background: transparent_black(),
267                border_color: cx.theme().colors().border_focused,
268                label_color: Color::Accent.color(cx),
269                icon_color: Color::Accent.color(cx),
270            },
271        }
272    }
273
274    #[allow(unused)]
275    pub(crate) fn disabled(
276        self,
277        elevation: Option<ElevationIndex>,
278        cx: &mut WindowContext,
279    ) -> ButtonLikeStyles {
280        match self {
281            ButtonStyle::Filled => ButtonLikeStyles {
282                background: cx.theme().colors().element_disabled,
283                border_color: cx.theme().colors().border_disabled,
284                label_color: Color::Disabled.color(cx),
285                icon_color: Color::Disabled.color(cx),
286            },
287            ButtonStyle::Tinted(tint) => tint.button_like_style(cx),
288            ButtonStyle::Subtle => ButtonLikeStyles {
289                background: cx.theme().colors().ghost_element_disabled,
290                border_color: cx.theme().colors().border_disabled,
291                label_color: Color::Disabled.color(cx),
292                icon_color: Color::Disabled.color(cx),
293            },
294            ButtonStyle::Transparent => ButtonLikeStyles {
295                background: transparent_black(),
296                border_color: transparent_black(),
297                label_color: Color::Disabled.color(cx),
298                icon_color: Color::Disabled.color(cx),
299            },
300        }
301    }
302}
303
304/// The height of a button.
305///
306/// Can also be used to size non-button elements to align with [`Button`]s.
307#[derive(Default, PartialEq, Clone, Copy)]
308pub enum ButtonSize {
309    Large,
310    #[default]
311    Default,
312    Compact,
313    None,
314}
315
316impl ButtonSize {
317    pub fn rems(self) -> Rems {
318        match self {
319            ButtonSize::Large => rems_from_px(32.),
320            ButtonSize::Default => rems_from_px(22.),
321            ButtonSize::Compact => rems_from_px(18.),
322            ButtonSize::None => rems_from_px(16.),
323        }
324    }
325}
326
327/// A button-like element that can be used to create a custom button when
328/// prebuilt buttons are not sufficient. Use this sparingly, as it is
329/// unconstrained and may make the UI feel less consistent.
330///
331/// This is also used to build the prebuilt buttons.
332#[derive(IntoElement)]
333pub struct ButtonLike {
334    pub(super) base: Div,
335    id: ElementId,
336    pub(super) style: ButtonStyle,
337    pub(super) disabled: bool,
338    pub(super) selected: bool,
339    pub(super) selected_style: Option<ButtonStyle>,
340    pub(super) width: Option<DefiniteLength>,
341    pub(super) height: Option<DefiniteLength>,
342    pub(super) layer: Option<ElevationIndex>,
343    size: ButtonSize,
344    rounding: Option<ButtonLikeRounding>,
345    tooltip: Option<Box<dyn Fn(&mut WindowContext) -> AnyView>>,
346    cursor_style: CursorStyle,
347    on_click: Option<Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>>,
348    children: SmallVec<[AnyElement; 2]>,
349}
350
351impl ButtonLike {
352    pub fn new(id: impl Into<ElementId>) -> Self {
353        Self {
354            base: div(),
355            id: id.into(),
356            style: ButtonStyle::default(),
357            disabled: false,
358            selected: false,
359            selected_style: None,
360            width: None,
361            height: None,
362            size: ButtonSize::Default,
363            rounding: Some(ButtonLikeRounding::All),
364            tooltip: None,
365            children: SmallVec::new(),
366            cursor_style: CursorStyle::PointingHand,
367            on_click: None,
368            layer: None,
369        }
370    }
371
372    pub fn new_rounded_left(id: impl Into<ElementId>) -> Self {
373        Self::new(id).rounding(ButtonLikeRounding::Left)
374    }
375
376    pub fn new_rounded_right(id: impl Into<ElementId>) -> Self {
377        Self::new(id).rounding(ButtonLikeRounding::Right)
378    }
379
380    pub(crate) fn height(mut self, height: DefiniteLength) -> Self {
381        self.height = Some(height);
382        self
383    }
384
385    pub(crate) fn rounding(mut self, rounding: impl Into<Option<ButtonLikeRounding>>) -> Self {
386        self.rounding = rounding.into();
387        self
388    }
389}
390
391impl Disableable for ButtonLike {
392    fn disabled(mut self, disabled: bool) -> Self {
393        self.disabled = disabled;
394        self
395    }
396}
397
398impl Selectable for ButtonLike {
399    fn selected(mut self, selected: bool) -> Self {
400        self.selected = selected;
401        self
402    }
403}
404
405impl SelectableButton for ButtonLike {
406    fn selected_style(mut self, style: ButtonStyle) -> Self {
407        self.selected_style = Some(style);
408        self
409    }
410}
411
412impl Clickable for ButtonLike {
413    fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self {
414        self.on_click = Some(Box::new(handler));
415        self
416    }
417
418    fn cursor_style(mut self, cursor_style: CursorStyle) -> Self {
419        self.cursor_style = cursor_style;
420        self
421    }
422}
423
424impl FixedWidth for ButtonLike {
425    fn width(mut self, width: DefiniteLength) -> Self {
426        self.width = Some(width);
427        self
428    }
429
430    fn full_width(mut self) -> Self {
431        self.width = Some(relative(1.));
432        self
433    }
434}
435
436impl ButtonCommon for ButtonLike {
437    fn id(&self) -> &ElementId {
438        &self.id
439    }
440
441    fn style(mut self, style: ButtonStyle) -> Self {
442        self.style = style;
443        self
444    }
445
446    fn size(mut self, size: ButtonSize) -> Self {
447        self.size = size;
448        self
449    }
450
451    fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
452        self.tooltip = Some(Box::new(tooltip));
453        self
454    }
455
456    fn layer(mut self, elevation: ElevationIndex) -> Self {
457        self.layer = Some(elevation);
458        self
459    }
460}
461
462impl VisibleOnHover for ButtonLike {
463    fn visible_on_hover(mut self, group_name: impl Into<SharedString>) -> Self {
464        self.base = self.base.visible_on_hover(group_name);
465        self
466    }
467}
468
469impl ParentElement for ButtonLike {
470    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
471        self.children.extend(elements)
472    }
473}
474
475impl RenderOnce for ButtonLike {
476    fn render(self, cx: &mut WindowContext) -> impl IntoElement {
477        let style = self
478            .selected_style
479            .filter(|_| self.selected)
480            .unwrap_or(self.style);
481
482        self.base
483            .h_flex()
484            .id(self.id.clone())
485            .group("")
486            .flex_none()
487            .h(self.height.unwrap_or(self.size.rems().into()))
488            .when_some(self.width, |this, width| this.w(width).justify_center())
489            .when_some(self.rounding, |this, rounding| match rounding {
490                ButtonLikeRounding::All => this.rounded_md(),
491                ButtonLikeRounding::Left => this.rounded_l_md(),
492                ButtonLikeRounding::Right => this.rounded_r_md(),
493            })
494            .gap(Spacing::Small.rems(cx))
495            .map(|this| match self.size {
496                ButtonSize::Large => this.px(Spacing::Medium.rems(cx)),
497                ButtonSize::Default | ButtonSize::Compact => this.px(Spacing::Small.rems(cx)),
498                ButtonSize::None => this,
499            })
500            .bg(style.enabled(self.layer, cx).background)
501            .when(self.disabled, |this| this.cursor_not_allowed())
502            .when(!self.disabled, |this| {
503                this.cursor_pointer()
504                    .hover(|hover| hover.bg(style.hovered(self.layer, cx).background))
505                    .active(|active| active.bg(style.active(cx).background))
506            })
507            .when_some(
508                self.on_click.filter(|_| !self.disabled),
509                |this, on_click| {
510                    this.on_mouse_down(MouseButton::Left, |_, cx| cx.prevent_default())
511                        .on_click(move |event, cx| {
512                            cx.stop_propagation();
513                            (on_click)(event, cx)
514                        })
515                },
516            )
517            .when_some(self.tooltip, |this, tooltip| {
518                this.tooltip(move |cx| tooltip(cx))
519            })
520            .children(self.children)
521    }
522}