Skip to main content

fc_ui/capabilities/primitives/
button.rs

1//! Button component with multiple variants and sizes.
2
3use crate::capabilities::foundation::icon_config::resolve_icon_path;
4use crate::capabilities::foundation::theme::use_theme;
5use crate::capabilities::primitives::icon_source::IconSource;
6use crate::capabilities::primitives::ripple::Ripple;
7use crate::capabilities::primitives::text::{Text, TextVariant};
8use gpui::{prelude::FluentBuilder as _, *};
9use std::rc::Rc;
10
11/// Render an icon from IconSource
12fn render_icon(icon_src: IconSource, size: Pixels, color: Hsla) -> impl IntoElement {
13    let svg_path = match icon_src {
14        IconSource::FilePath(path) => path,
15        IconSource::Named(name) => SharedString::from(resolve_icon_path(&name)),
16    };
17
18    svg().path(svg_path).size(size).text_color(color)
19}
20
21/// Render a loading spinner
22fn render_loading_spinner(size: Pixels, color: Hsla) -> impl IntoElement {
23    div().size(size).child(
24        svg()
25            .path(resolve_icon_path("loader"))
26            .size(size)
27            .text_color(color),
28    )
29}
30
31#[derive(Copy, Clone, Debug, PartialEq, Eq)]
32pub enum ButtonVariant {
33    Default,
34    Secondary,
35    Destructive,
36    Outline,
37    Ghost,
38    Link,
39}
40
41#[derive(Copy, Clone, Debug, PartialEq, Eq)]
42pub enum ButtonSize {
43    Sm,
44    Md,
45    Lg,
46    Icon,
47}
48#[derive(IntoElement)]
49pub struct Button {
50    id: ElementId,
51    base: Stateful<Div>,
52    label: SharedString,
53    aria_label: Option<SharedString>,
54    variant: ButtonVariant,
55    size: ButtonSize,
56    disabled: bool,
57    selected: bool,
58    loading: bool,
59    icon: Option<IconSource>,
60    icon_position: IconPosition,
61    tooltip: Option<SharedString>,
62    on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
63    ripple_enabled: bool,
64    style: StyleRefinement,
65}
66
67#[derive(Copy, Clone, Debug, PartialEq, Eq)]
68pub enum IconPosition {
69    Start,
70    End,
71}
72
73impl Button {
74    /// Create a new button with a unique ID and label.
75    ///
76    /// # Example
77    /// ```rust,ignore
78    /// Button::new("my-button", "Click me")
79    /// ```
80    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
81        let id = id.into();
82        let label = label.into();
83
84        Self {
85            id: id.clone(),
86            base: div().flex_shrink_0().id(id),
87            label,
88            aria_label: None,
89            variant: ButtonVariant::Default,
90            size: ButtonSize::Md,
91            disabled: false,
92            selected: false,
93            loading: false,
94            icon: None,
95            icon_position: IconPosition::Start,
96            tooltip: None,
97            on_click: None,
98            ripple_enabled: false,
99
100            style: StyleRefinement::default(),
101        }
102    }
103
104    /// Override the visible label with a clearer name for assistive technology.
105    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
106        self.aria_label = Some(label.into());
107        self
108    }
109
110    pub fn variant(mut self, variant: ButtonVariant) -> Self {
111        self.variant = variant;
112        self
113    }
114
115    pub fn size(mut self, size: ButtonSize) -> Self {
116        self.size = size;
117        self
118    }
119
120    pub fn disabled(mut self, disabled: bool) -> Self {
121        self.disabled = disabled;
122        self
123    }
124
125    pub fn selected(mut self, selected: bool) -> Self {
126        self.selected = selected;
127        self
128    }
129
130    pub fn loading(mut self, loading: bool) -> Self {
131        self.loading = loading;
132        self
133    }
134
135    pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
136        self.icon = Some(icon.into());
137        self
138    }
139
140    pub fn icon_position(mut self, position: IconPosition) -> Self {
141        self.icon_position = position;
142        self
143    }
144
145    /// Store a tooltip string. Never rendered: the button primitive is not
146    /// allowed to depend on the overlays capability, so nothing displays it.
147    #[deprecated(
148        note = "use overlays::tooltip to wrap the button; primitives cannot depend on overlays"
149    )]
150    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
151        self.tooltip = Some(tooltip.into());
152        self
153    }
154
155    pub fn on_click(
156        mut self,
157        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
158    ) -> Self {
159        self.on_click = Some(Rc::new(handler));
160        self
161    }
162
163    pub fn ripple(mut self, enabled: bool) -> Self {
164        self.ripple_enabled = enabled;
165        self
166    }
167
168    fn clickable(&self) -> bool {
169        !self.disabled && !self.loading && self.on_click.is_some()
170    }
171}
172
173impl Styled for Button {
174    fn style(&mut self) -> &mut StyleRefinement {
175        &mut self.style
176    }
177}
178
179impl InteractiveElement for Button {
180    fn interactivity(&mut self) -> &mut Interactivity {
181        self.base.interactivity()
182    }
183}
184
185impl StatefulInteractiveElement for Button {}
186
187impl RenderOnce for Button {
188    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
189        let theme = use_theme(cx);
190
191        let (height, px_h, text_size) = match self.size {
192            ButtonSize::Sm => (px(36.0), px(12.0), px(13.0)),
193            ButtonSize::Md => (px(40.0), px(16.0), px(14.0)),
194            ButtonSize::Lg => (px(44.0), px(20.0), px(15.0)),
195            ButtonSize::Icon => (px(40.0), px(10.0), px(14.0)),
196        };
197
198        let (bg, fg, border, hover_bg, hover_fg, has_shadow) = match self.variant {
199            ButtonVariant::Default => (
200                theme.tokens.primary,
201                theme.tokens.primary_foreground,
202                theme.tokens.primary,
203                theme.tokens.primary.opacity(0.9),
204                theme.tokens.primary_foreground,
205                true,
206            ),
207            ButtonVariant::Secondary => (
208                theme.tokens.secondary,
209                theme.tokens.secondary_foreground,
210                theme.tokens.secondary,
211                theme.tokens.secondary.opacity(0.8),
212                theme.tokens.secondary_foreground,
213                true,
214            ),
215            ButtonVariant::Destructive => (
216                theme.tokens.destructive,
217                theme.tokens.destructive_foreground,
218                theme.tokens.destructive,
219                theme.tokens.destructive.opacity(0.9),
220                theme.tokens.destructive_foreground,
221                true,
222            ),
223            ButtonVariant::Outline => (
224                gpui::transparent_black(),
225                theme.tokens.foreground,
226                theme.tokens.border,
227                theme.tokens.accent,
228                theme.tokens.accent_foreground,
229                false,
230            ),
231            ButtonVariant::Ghost => (
232                gpui::transparent_black(),
233                theme.tokens.foreground,
234                gpui::transparent_black(),
235                theme.tokens.accent,
236                theme.tokens.accent_foreground,
237                false,
238            ),
239            ButtonVariant::Link => (
240                gpui::transparent_black(),
241                theme.tokens.primary,
242                gpui::transparent_black(),
243                gpui::transparent_black(),
244                theme.tokens.primary.opacity(0.8),
245                false,
246            ),
247        };
248
249        let clickable = self.clickable();
250        let handler = self.on_click.clone();
251        let ripple_enabled = self.ripple_enabled && clickable;
252        let ripple_id = ElementId::Name(format!("{}-ripple", self.id).into());
253        let ripple_color = fg;
254
255        let focus_handle = window
256            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
257            .read(cx)
258            .clone();
259
260        let label_text = Text::new(self.label.clone())
261            .variant(TextVariant::Custom)
262            .size(text_size)
263            .weight(FontWeight::MEDIUM)
264            .font(theme.tokens.font_family.clone())
265            .color(fg);
266        let aria_label = self
267            .aria_label
268            .clone()
269            .unwrap_or_else(|| self.label.clone());
270
271        let icon_size = text_size * 1.2;
272        let icon = self.icon.clone();
273        let icon_pos = self.icon_position;
274        let is_loading = self.loading;
275        let is_selected = self.selected;
276        let user_style = self.style;
277
278        self.base
279            .role(Role::Button)
280            .aria_label(aria_label)
281            .aria_disabled(self.disabled || is_loading)
282            .when(!self.disabled && !is_loading, |this| {
283                this.track_focus(&focus_handle.tab_index(0).tab_stop(true))
284            })
285            .relative()
286            .overflow_hidden()
287            .flex()
288            .items_center()
289            .justify_center()
290            .gap_2()
291            .h(height)
292            .px(px_h)
293            .rounded(theme.tokens.radius_md)
294            .text_color(fg)
295            .bg(bg)
296            .when(has_shadow, |this| {
297                this.shadow(smallvec::smallvec![theme.tokens.shadow_xs])
298            })
299            .when(self.variant == ButtonVariant::Outline, |this| {
300                this.border_1().border_color(border)
301            })
302            .when(is_selected && !self.disabled, |this| {
303                this.bg(theme.tokens.accent)
304                    .text_color(theme.tokens.accent_foreground)
305                    .border_color(theme.tokens.accent)
306            })
307            .when(is_loading, |this| {
308                this.opacity(0.7).cursor(CursorStyle::Arrow)
309            })
310            .when(self.disabled && !is_loading, |this| {
311                this.opacity(0.5).cursor(CursorStyle::Arrow)
312            })
313            .when(!self.disabled && !is_loading, |this| {
314                let shadow_sm = theme.tokens.shadow_sm;
315                this.cursor(CursorStyle::PointingHand)
316                    .hover(move |style| {
317                        let hover_style = style.bg(hover_bg).text_color(hover_fg);
318                        if has_shadow {
319                            hover_style.shadow(smallvec::smallvec![shadow_sm])
320                        } else {
321                            hover_style
322                        }
323                    })
324                    .active(|style| style.opacity(0.9))
325            })
326            .map(|this| {
327                let mut div = this;
328                div.style().refine(&user_style);
329                div
330            })
331            .on_mouse_down(MouseButton::Left, move |_event, window, _| {
332                window.prevent_default();
333                if ripple_enabled {
334                    window.refresh();
335                }
336            })
337            .when_some(handler.filter(|_| clickable), |this, on_click| {
338                this.on_click(move |event, window, cx| {
339                    cx.stop_propagation();
340                    (on_click)(event, window, cx);
341                })
342            })
343            .when(self.ripple_enabled && clickable, |this| {
344                let size = height;
345                this.child(
346                    Ripple::new(ripple_id, point(size / 2.0, size / 2.0), ripple_color)
347                        .max_size(size * 2.5),
348                )
349            })
350            .child(
351                div()
352                    .flex()
353                    .items_center()
354                    .gap_2()
355                    .when(icon_pos == IconPosition::Start && !is_loading, |this| {
356                        this.when_some(icon.clone(), |this, icon_src| {
357                            this.child(render_icon(icon_src, icon_size, fg))
358                        })
359                    })
360                    .when(is_loading && icon_pos == IconPosition::Start, |this| {
361                        this.child(render_loading_spinner(icon_size, fg))
362                    })
363                    .child(
364                        div()
365                            .when(self.variant == ButtonVariant::Link, |this| this.underline())
366                            .child(label_text),
367                    )
368                    .when(icon_pos == IconPosition::End && !is_loading, |this| {
369                        this.when_some(icon.clone(), |this, icon_src| {
370                            this.child(render_icon(icon_src, icon_size, fg))
371                        })
372                    })
373                    .when(is_loading && icon_pos == IconPosition::End, |this| {
374                        this.child(render_loading_spinner(icon_size, fg))
375                    }),
376            )
377    }
378}