button.rs

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