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 super::*;
223    use crate::{h_stack, v_stack, LabelColor, Story};
224    use gpui2::{rems, Div, Render};
225    use strum::IntoEnumIterator;
226
227    pub struct ButtonStory;
228
229    impl Render for ButtonStory {
230        type Element = Div<Self>;
231
232        fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
233            let states = InteractionState::iter();
234
235            Story::container(cx)
236                .child(Story::title_for::<_, Button<Self>>(cx))
237                .child(
238                    div()
239                        .flex()
240                        .gap_8()
241                        .child(
242                            div()
243                                .child(Story::label(cx, "Ghost (Default)"))
244                                .child(h_stack().gap_2().children(states.clone().map(|state| {
245                                    v_stack()
246                                        .gap_1()
247                                        .child(
248                                            Label::new(state.to_string()).color(LabelColor::Muted),
249                                        )
250                                        .child(
251                                            Button::new("Label").variant(ButtonVariant::Ghost), // .state(state),
252                                        )
253                                })))
254                                .child(Story::label(cx, "Ghost – Left Icon"))
255                                .child(h_stack().gap_2().children(states.clone().map(|state| {
256                                    v_stack()
257                                        .gap_1()
258                                        .child(
259                                            Label::new(state.to_string()).color(LabelColor::Muted),
260                                        )
261                                        .child(
262                                            Button::new("Label")
263                                                .variant(ButtonVariant::Ghost)
264                                                .icon(Icon::Plus)
265                                                .icon_position(IconPosition::Left), // .state(state),
266                                        )
267                                })))
268                                .child(Story::label(cx, "Ghost – Right Icon"))
269                                .child(h_stack().gap_2().children(states.clone().map(|state| {
270                                    v_stack()
271                                        .gap_1()
272                                        .child(
273                                            Label::new(state.to_string()).color(LabelColor::Muted),
274                                        )
275                                        .child(
276                                            Button::new("Label")
277                                                .variant(ButtonVariant::Ghost)
278                                                .icon(Icon::Plus)
279                                                .icon_position(IconPosition::Right), // .state(state),
280                                        )
281                                }))),
282                        )
283                        .child(
284                            div()
285                                .child(Story::label(cx, "Filled"))
286                                .child(h_stack().gap_2().children(states.clone().map(|state| {
287                                    v_stack()
288                                        .gap_1()
289                                        .child(
290                                            Label::new(state.to_string()).color(LabelColor::Muted),
291                                        )
292                                        .child(
293                                            Button::new("Label").variant(ButtonVariant::Filled), // .state(state),
294                                        )
295                                })))
296                                .child(Story::label(cx, "Filled – Left Button"))
297                                .child(h_stack().gap_2().children(states.clone().map(|state| {
298                                    v_stack()
299                                        .gap_1()
300                                        .child(
301                                            Label::new(state.to_string()).color(LabelColor::Muted),
302                                        )
303                                        .child(
304                                            Button::new("Label")
305                                                .variant(ButtonVariant::Filled)
306                                                .icon(Icon::Plus)
307                                                .icon_position(IconPosition::Left), // .state(state),
308                                        )
309                                })))
310                                .child(Story::label(cx, "Filled – Right Button"))
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                                                .icon(Icon::Plus)
321                                                .icon_position(IconPosition::Right), // .state(state),
322                                        )
323                                }))),
324                        )
325                        .child(
326                            div()
327                                .child(Story::label(cx, "Fixed With"))
328                                .child(h_stack().gap_2().children(states.clone().map(|state| {
329                                    v_stack()
330                                        .gap_1()
331                                        .child(
332                                            Label::new(state.to_string()).color(LabelColor::Muted),
333                                        )
334                                        .child(
335                                            Button::new("Label")
336                                                .variant(ButtonVariant::Filled)
337                                                // .state(state)
338                                                .width(Some(rems(6.).into())),
339                                        )
340                                })))
341                                .child(Story::label(cx, "Fixed With – Left Icon"))
342                                .child(h_stack().gap_2().children(states.clone().map(|state| {
343                                    v_stack()
344                                        .gap_1()
345                                        .child(
346                                            Label::new(state.to_string()).color(LabelColor::Muted),
347                                        )
348                                        .child(
349                                            Button::new("Label")
350                                                .variant(ButtonVariant::Filled)
351                                                // .state(state)
352                                                .icon(Icon::Plus)
353                                                .icon_position(IconPosition::Left)
354                                                .width(Some(rems(6.).into())),
355                                        )
356                                })))
357                                .child(Story::label(cx, "Fixed With – Right Icon"))
358                                .child(h_stack().gap_2().children(states.clone().map(|state| {
359                                    v_stack()
360                                        .gap_1()
361                                        .child(
362                                            Label::new(state.to_string()).color(LabelColor::Muted),
363                                        )
364                                        .child(
365                                            Button::new("Label")
366                                                .variant(ButtonVariant::Filled)
367                                                // .state(state)
368                                                .icon(Icon::Plus)
369                                                .icon_position(IconPosition::Right)
370                                                .width(Some(rems(6.).into())),
371                                        )
372                                }))),
373                        ),
374                )
375                .child(Story::label(cx, "Button with `on_click`"))
376                .child(
377                    Button::new("Label")
378                        .variant(ButtonVariant::Ghost)
379                        .on_click(Arc::new(|_view, _cx| println!("Button clicked."))),
380                )
381        }
382    }
383}