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}
12
13impl Button {
14    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
15        Self {
16            base: ButtonLike::new(id),
17            label: label.into(),
18            label_color: None,
19        }
20    }
21
22    pub fn color(mut self, label_color: impl Into<Option<Color>>) -> Self {
23        self.label_color = label_color.into();
24        self
25    }
26}
27
28impl Selectable for Button {
29    fn selected(mut self, selected: bool) -> Self {
30        self.base = self.base.selected(selected);
31        self
32    }
33}
34
35impl Disableable for Button {
36    fn disabled(mut self, disabled: bool) -> Self {
37        self.base = self.base.disabled(disabled);
38        self
39    }
40}
41
42impl Clickable for Button {
43    fn on_click(
44        mut self,
45        handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static,
46    ) -> Self {
47        self.base = self.base.on_click(handler);
48        self
49    }
50}
51
52impl ButtonCommon for Button {
53    fn id(&self) -> &ElementId {
54        self.base.id()
55    }
56
57    fn style(mut self, style: ButtonStyle) -> Self {
58        self.base = self.base.style(style);
59        self
60    }
61
62    fn size(mut self, size: ButtonSize) -> Self {
63        self.base = self.base.size(size);
64        self
65    }
66
67    fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
68        self.base = self.base.tooltip(tooltip);
69        self
70    }
71}
72
73impl RenderOnce for Button {
74    type Rendered = ButtonLike;
75
76    fn render(self, _cx: &mut WindowContext) -> Self::Rendered {
77        let label_color = if self.base.disabled {
78            Color::Disabled
79        } else if self.base.selected {
80            Color::Selected
81        } else {
82            self.label_color.unwrap_or_default()
83        };
84
85        self.base.child(
86            Label::new(self.label)
87                .color(label_color)
88                .line_height_style(LineHeightStyle::UILabel),
89        )
90    }
91}