button.rs

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