button.rs

 1use gpui::AnyView;
 2
 3use crate::prelude::*;
 4use crate::{ButtonCommon, ButtonLike, ButtonSize2, ButtonStyle2, Label, LineHeightStyle};
 5
 6#[derive(IntoElement)]
 7pub struct Button {
 8    base: ButtonLike,
 9    label: SharedString,
10    label_color: Option<Color>,
11    selected: bool,
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: false,
21        }
22    }
23
24    pub fn selected(mut self, selected: bool) -> Self {
25        self.selected = selected;
26        self
27    }
28
29    pub fn color(mut self, label_color: impl Into<Option<Color>>) -> Self {
30        self.label_color = label_color.into();
31        self
32    }
33}
34
35impl Clickable for Button {
36    fn on_click(
37        mut self,
38        handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static,
39    ) -> Self {
40        self.base = self.base.on_click(handler);
41        self
42    }
43}
44
45impl Disableable for Button {
46    fn disabled(mut self, disabled: bool) -> Self {
47        self.base = self.base.disabled(disabled);
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: ButtonStyle2) -> Self {
58        self.base = self.base.style(style);
59        self
60    }
61
62    fn size(mut self, size: ButtonSize2) -> 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.selected {
80            Color::Selected
81        } else {
82            Color::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}