button.rs

  1use std::sync::Arc;
  2
  3use gpui2::{div, DefiniteLength, Hsla, MouseButton, WindowContext};
  4
  5use crate::{h_stack, Icon, IconColor, IconElement, Label, LabelColor};
  6use crate::{prelude::*, LineHeightStyle};
  7
  8#[derive(Default, PartialEq, Clone, Copy)]
  9pub enum IconPosition {
 10    #[default]
 11    Left,
 12    Right,
 13}
 14
 15#[derive(Default, Copy, Clone, PartialEq)]
 16pub enum ButtonVariant {
 17    #[default]
 18    Ghost,
 19    Filled,
 20}
 21
 22impl ButtonVariant {
 23    pub fn bg_color(&self, cx: &mut WindowContext) -> Hsla {
 24        let theme = theme(cx);
 25
 26        match self {
 27            ButtonVariant::Ghost => theme.ghost_element,
 28            ButtonVariant::Filled => theme.filled_element,
 29        }
 30    }
 31
 32    pub fn bg_color_hover(&self, cx: &mut WindowContext) -> Hsla {
 33        let theme = theme(cx);
 34
 35        match self {
 36            ButtonVariant::Ghost => theme.ghost_element_hover,
 37            ButtonVariant::Filled => theme.filled_element_hover,
 38        }
 39    }
 40
 41    pub fn bg_color_active(&self, cx: &mut WindowContext) -> Hsla {
 42        let theme = theme(cx);
 43
 44        match self {
 45            ButtonVariant::Ghost => theme.ghost_element_active,
 46            ButtonVariant::Filled => theme.filled_element_active,
 47        }
 48    }
 49}
 50
 51pub type ClickHandler<S> = Arc<dyn Fn(&mut S, &mut ViewContext<S>) + Send + Sync>;
 52
 53struct ButtonHandlers<V: 'static> {
 54    click: Option<ClickHandler<V>>,
 55}
 56
 57unsafe impl<S> Send for ButtonHandlers<S> {}
 58unsafe impl<S> Sync for ButtonHandlers<S> {}
 59
 60impl<V: 'static> Default for ButtonHandlers<V> {
 61    fn default() -> Self {
 62        Self { click: None }
 63    }
 64}
 65
 66#[derive(Component)]
 67pub struct Button<V: 'static> {
 68    disabled: bool,
 69    handlers: ButtonHandlers<V>,
 70    icon: Option<Icon>,
 71    icon_position: Option<IconPosition>,
 72    label: SharedString,
 73    variant: ButtonVariant,
 74    width: Option<DefiniteLength>,
 75}
 76
 77impl<V: 'static> Button<V> {
 78    pub fn new(label: impl Into<SharedString>) -> Self {
 79        Self {
 80            disabled: false,
 81            handlers: ButtonHandlers::default(),
 82            icon: None,
 83            icon_position: None,
 84            label: label.into(),
 85            variant: Default::default(),
 86            width: Default::default(),
 87        }
 88    }
 89
 90    pub fn ghost(label: impl Into<SharedString>) -> Self {
 91        Self::new(label).variant(ButtonVariant::Ghost)
 92    }
 93
 94    pub fn variant(mut self, variant: ButtonVariant) -> Self {
 95        self.variant = variant;
 96        self
 97    }
 98
 99    pub fn icon(mut self, icon: Icon) -> Self {
100        self.icon = Some(icon);
101        self
102    }
103
104    pub fn icon_position(mut self, icon_position: IconPosition) -> Self {
105        if self.icon.is_none() {
106            panic!("An icon must be present if an icon_position is provided.");
107        }
108        self.icon_position = Some(icon_position);
109        self
110    }
111
112    pub fn width(mut self, width: Option<DefiniteLength>) -> Self {
113        self.width = width;
114        self
115    }
116
117    pub fn on_click(mut self, handler: ClickHandler<V>) -> Self {
118        self.handlers.click = Some(handler);
119        self
120    }
121
122    pub fn disabled(mut self, disabled: bool) -> Self {
123        self.disabled = disabled;
124        self
125    }
126
127    fn label_color(&self) -> LabelColor {
128        if self.disabled {
129            LabelColor::Disabled
130        } else {
131            Default::default()
132        }
133    }
134
135    fn icon_color(&self) -> IconColor {
136        if self.disabled {
137            IconColor::Disabled
138        } else {
139            Default::default()
140        }
141    }
142
143    fn render_label(&self) -> Label {
144        Label::new(self.label.clone())
145            .color(self.label_color())
146            .line_height_style(LineHeightStyle::UILabel)
147    }
148
149    fn render_icon(&self, icon_color: IconColor) -> Option<IconElement> {
150        self.icon.map(|i| IconElement::new(i).color(icon_color))
151    }
152
153    pub fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
154        let icon_color = self.icon_color();
155
156        let mut button = h_stack()
157            .relative()
158            .id(SharedString::from(format!("{}", self.label)))
159            .p_1()
160            .text_size(ui_size(cx, 1.))
161            .rounded_md()
162            .bg(self.variant.bg_color(cx))
163            .hover(|style| style.bg(self.variant.bg_color_hover(cx)))
164            .active(|style| style.bg(self.variant.bg_color_active(cx)));
165
166        match (self.icon, self.icon_position) {
167            (Some(_), Some(IconPosition::Left)) => {
168                button = button
169                    .gap_1()
170                    .child(self.render_label())
171                    .children(self.render_icon(icon_color))
172            }
173            (Some(_), Some(IconPosition::Right)) => {
174                button = button
175                    .gap_1()
176                    .children(self.render_icon(icon_color))
177                    .child(self.render_label())
178            }
179            (_, _) => button = button.child(self.render_label()),
180        }
181
182        if let Some(width) = self.width {
183            button = button.w(width).justify_center();
184        }
185
186        if let Some(click_handler) = self.handlers.click.clone() {
187            button = button.on_mouse_down(MouseButton::Left, move |state, event, cx| {
188                click_handler(state, cx);
189            });
190        }
191
192        button
193    }
194}
195
196#[derive(Component)]
197pub struct ButtonGroup<V: 'static> {
198    buttons: Vec<Button<V>>,
199}
200
201impl<V: 'static> ButtonGroup<V> {
202    pub fn new(buttons: Vec<Button<V>>) -> Self {
203        Self { buttons }
204    }
205
206    fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
207        let mut el = h_stack().text_size(ui_size(cx, 1.));
208
209        for button in self.buttons {
210            el = el.child(button.render(_view, cx));
211        }
212
213        el
214    }
215}
216
217#[cfg(feature = "stories")]
218pub use stories::*;
219
220#[cfg(feature = "stories")]
221mod stories {
222    use gpui2::rems;
223    use strum::IntoEnumIterator;
224
225    use crate::{h_stack, v_stack, LabelColor, Story};
226
227    use super::*;
228
229    #[derive(Component)]
230    pub struct ButtonStory;
231
232    impl ButtonStory {
233        fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
234            let states = InteractionState::iter();
235
236            Story::container(cx)
237                .child(Story::title_for::<_, Button<V>>(cx))
238                .child(
239                    div()
240                        .flex()
241                        .gap_8()
242                        .child(
243                            div()
244                                .child(Story::label(cx, "Ghost (Default)"))
245                                .child(h_stack().gap_2().children(states.clone().map(|state| {
246                                    v_stack()
247                                        .gap_1()
248                                        .child(
249                                            Label::new(state.to_string()).color(LabelColor::Muted),
250                                        )
251                                        .child(
252                                            Button::new("Label").variant(ButtonVariant::Ghost), // .state(state),
253                                        )
254                                })))
255                                .child(Story::label(cx, "Ghost – Left Icon"))
256                                .child(h_stack().gap_2().children(states.clone().map(|state| {
257                                    v_stack()
258                                        .gap_1()
259                                        .child(
260                                            Label::new(state.to_string()).color(LabelColor::Muted),
261                                        )
262                                        .child(
263                                            Button::new("Label")
264                                                .variant(ButtonVariant::Ghost)
265                                                .icon(Icon::Plus)
266                                                .icon_position(IconPosition::Left), // .state(state),
267                                        )
268                                })))
269                                .child(Story::label(cx, "Ghost – Right Icon"))
270                                .child(h_stack().gap_2().children(states.clone().map(|state| {
271                                    v_stack()
272                                        .gap_1()
273                                        .child(
274                                            Label::new(state.to_string()).color(LabelColor::Muted),
275                                        )
276                                        .child(
277                                            Button::new("Label")
278                                                .variant(ButtonVariant::Ghost)
279                                                .icon(Icon::Plus)
280                                                .icon_position(IconPosition::Right), // .state(state),
281                                        )
282                                }))),
283                        )
284                        .child(
285                            div()
286                                .child(Story::label(cx, "Filled"))
287                                .child(h_stack().gap_2().children(states.clone().map(|state| {
288                                    v_stack()
289                                        .gap_1()
290                                        .child(
291                                            Label::new(state.to_string()).color(LabelColor::Muted),
292                                        )
293                                        .child(
294                                            Button::new("Label").variant(ButtonVariant::Filled), // .state(state),
295                                        )
296                                })))
297                                .child(Story::label(cx, "Filled – Left Button"))
298                                .child(h_stack().gap_2().children(states.clone().map(|state| {
299                                    v_stack()
300                                        .gap_1()
301                                        .child(
302                                            Label::new(state.to_string()).color(LabelColor::Muted),
303                                        )
304                                        .child(
305                                            Button::new("Label")
306                                                .variant(ButtonVariant::Filled)
307                                                .icon(Icon::Plus)
308                                                .icon_position(IconPosition::Left), // .state(state),
309                                        )
310                                })))
311                                .child(Story::label(cx, "Filled – Right Button"))
312                                .child(h_stack().gap_2().children(states.clone().map(|state| {
313                                    v_stack()
314                                        .gap_1()
315                                        .child(
316                                            Label::new(state.to_string()).color(LabelColor::Muted),
317                                        )
318                                        .child(
319                                            Button::new("Label")
320                                                .variant(ButtonVariant::Filled)
321                                                .icon(Icon::Plus)
322                                                .icon_position(IconPosition::Right), // .state(state),
323                                        )
324                                }))),
325                        )
326                        .child(
327                            div()
328                                .child(Story::label(cx, "Fixed With"))
329                                .child(h_stack().gap_2().children(states.clone().map(|state| {
330                                    v_stack()
331                                        .gap_1()
332                                        .child(
333                                            Label::new(state.to_string()).color(LabelColor::Muted),
334                                        )
335                                        .child(
336                                            Button::new("Label")
337                                                .variant(ButtonVariant::Filled)
338                                                // .state(state)
339                                                .width(Some(rems(6.).into())),
340                                        )
341                                })))
342                                .child(Story::label(cx, "Fixed With – Left Icon"))
343                                .child(h_stack().gap_2().children(states.clone().map(|state| {
344                                    v_stack()
345                                        .gap_1()
346                                        .child(
347                                            Label::new(state.to_string()).color(LabelColor::Muted),
348                                        )
349                                        .child(
350                                            Button::new("Label")
351                                                .variant(ButtonVariant::Filled)
352                                                // .state(state)
353                                                .icon(Icon::Plus)
354                                                .icon_position(IconPosition::Left)
355                                                .width(Some(rems(6.).into())),
356                                        )
357                                })))
358                                .child(Story::label(cx, "Fixed With – Right Icon"))
359                                .child(h_stack().gap_2().children(states.clone().map(|state| {
360                                    v_stack()
361                                        .gap_1()
362                                        .child(
363                                            Label::new(state.to_string()).color(LabelColor::Muted),
364                                        )
365                                        .child(
366                                            Button::new("Label")
367                                                .variant(ButtonVariant::Filled)
368                                                // .state(state)
369                                                .icon(Icon::Plus)
370                                                .icon_position(IconPosition::Right)
371                                                .width(Some(rems(6.).into())),
372                                        )
373                                }))),
374                        ),
375                )
376                .child(Story::label(cx, "Button with `on_click`"))
377                .child(
378                    Button::new("Label")
379                        .variant(ButtonVariant::Ghost)
380                        .on_click(Arc::new(|_view, _cx| println!("Button clicked."))),
381                )
382        }
383    }
384}