button.rs

  1use gpui::AnyView;
  2
  3use crate::prelude::*;
  4use crate::{ButtonCommon, ButtonLike, ButtonSize, ButtonStyle, Label, LineHeightStyle};
  5
  6#[derive(IntoElement)]
  7pub struct Button {
  8    base: ButtonLike,
  9    label: SharedString,
 10    label_color: Option<Color>,
 11    selected_label: Option<SharedString>,
 12}
 13
 14impl Button {
 15    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
 16        Self {
 17            base: ButtonLike::new(id),
 18            label: label.into(),
 19            label_color: None,
 20            selected_label: None,
 21        }
 22    }
 23
 24    pub fn color(mut self, label_color: impl Into<Option<Color>>) -> Self {
 25        self.label_color = label_color.into();
 26        self
 27    }
 28
 29    pub fn selected_label<L: Into<SharedString>>(mut self, label: impl Into<Option<L>>) -> Self {
 30        self.selected_label = label.into().map(Into::into);
 31        self
 32    }
 33}
 34
 35impl Selectable for Button {
 36    fn selected(mut self, selected: bool) -> Self {
 37        self.base = self.base.selected(selected);
 38        self
 39    }
 40}
 41
 42impl Disableable for Button {
 43    fn disabled(mut self, disabled: bool) -> Self {
 44        self.base = self.base.disabled(disabled);
 45        self
 46    }
 47}
 48
 49impl Clickable for Button {
 50    fn on_click(
 51        mut self,
 52        handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static,
 53    ) -> Self {
 54        self.base = self.base.on_click(handler);
 55        self
 56    }
 57}
 58
 59impl ButtonCommon for Button {
 60    fn id(&self) -> &ElementId {
 61        self.base.id()
 62    }
 63
 64    fn style(mut self, style: ButtonStyle) -> Self {
 65        self.base = self.base.style(style);
 66        self
 67    }
 68
 69    fn size(mut self, size: ButtonSize) -> Self {
 70        self.base = self.base.size(size);
 71        self
 72    }
 73
 74    fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
 75        self.base = self.base.tooltip(tooltip);
 76        self
 77    }
 78}
 79
 80impl RenderOnce for Button {
 81    type Rendered = ButtonLike;
 82
 83    fn render(self, _cx: &mut WindowContext) -> Self::Rendered {
 84        let label = self
 85            .selected_label
 86            .filter(|_| self.base.selected)
 87            .unwrap_or(self.label);
 88
 89        let label_color = if self.base.disabled {
 90            Color::Disabled
 91        } else if self.base.selected {
 92            Color::Selected
 93        } else {
 94            self.label_color.unwrap_or_default()
 95        };
 96
 97        self.base.child(
 98            Label::new(label)
 99                .color(label_color)
100                .line_height_style(LineHeightStyle::UILabel),
101        )
102    }
103}