Skip to main content

gpui_material_components/
fab.rs

1use std::rc::Rc;
2
3use gpui::prelude::FluentBuilder;
4use gpui::{
5    AnyElement, App, AvailableSpace, ElementId, Empty, Entity, FocusHandle, IntoElement,
6    ParentElement, Pixels, Point, RenderOnce, SharedString, Styled, Window, anchored, canvas,
7    deferred, div, point, px, size,
8};
9use gpui_material_foundation::{
10    InteractionSource, ThemeScope, animate, current_material_theme, logical_anchor,
11};
12use gpui_material_theme::{
13    ColorRole, CornerRole, CornerShape, Direction, Elevation, MotionKind, MotionSpec, MotionSpeed,
14    TypeRole, TypographyEmphasis,
15};
16
17use crate::action::{
18    Action, ActionControl, ActionLayout, ActionStyle, Activate, DisabledStyle, icon_slot,
19};
20use crate::button_style::{ButtonColors, ButtonElevations, ButtonStyle};
21use crate::motion::OverlayMotion;
22
23/// Expressive FAB sizes. Small is the 56 dp FAB and Small Extended FAB.
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum FabSize {
26    #[default]
27    Small,
28    Medium,
29    Large,
30}
31
32impl FabSize {
33    fn metrics(self) -> (f32, f32, CornerRole, f32, f32, TypeRole) {
34        // FabBaseline, FabMedium/Large, and ExtendedFabSmall/Medium/Large.
35        match self {
36            Self::Small => (56., 24., CornerRole::Large, 16., 8., TypeRole::TitleMedium),
37            Self::Medium => (
38                80.,
39                28.,
40                CornerRole::LargeIncreased,
41                26.,
42                12.,
43                TypeRole::TitleLarge,
44            ),
45            Self::Large => (
46                96.,
47                32.,
48                CornerRole::ExtraLarge,
49                28.,
50                16.,
51                TypeRole::HeadlineSmall,
52            ),
53        }
54    }
55}
56
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum FabColor {
59    #[default]
60    Primary,
61    Secondary,
62    Tertiary,
63    PrimaryStrong,
64    SecondaryStrong,
65    TertiaryStrong,
66}
67
68/// Logical pivot for the FAB's visibility transition.
69#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
70pub enum FabAlignment {
71    TopStart,
72    TopCenter,
73    TopEnd,
74    CenterStart,
75    #[default]
76    Center,
77    CenterEnd,
78    BottomStart,
79    BottomCenter,
80    BottomEnd,
81}
82
83impl FabAlignment {
84    fn pivot(self, direction: Direction) -> Point<f32> {
85        use FabAlignment::*;
86        let x = match self {
87            TopStart | CenterStart | BottomStart => 0.,
88            TopCenter | Center | BottomCenter => 0.5,
89            TopEnd | CenterEnd | BottomEnd => 1.,
90        };
91        let y = match self {
92            TopStart | TopCenter | TopEnd => 0.,
93            CenterStart | Center | CenterEnd => 0.5,
94            BottomStart | BottomCenter | BottomEnd => 1.,
95        };
96        point(
97            if direction == Direction::Rtl {
98                1. - x
99            } else {
100                x
101            },
102            y,
103        )
104    }
105}
106
107/// Appearance and disappearance motion for a controlled FAB.
108#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct FabVisibilityAnimation {
110    pub alignment: FabAlignment,
111    /// The ending scale of a hide and the starting scale of a show.
112    /// Negative, non-finite, or overflowing values use the default of 0.2.
113    pub target_scale: f32,
114    /// Defaults to the window theme's Fast Spatial motion.
115    pub scale_motion: Option<MotionSpec>,
116    /// Defaults to the window theme's Fast Effects motion.
117    pub alpha_motion: Option<MotionSpec>,
118}
119
120impl Default for FabVisibilityAnimation {
121    fn default() -> Self {
122        Self {
123            alignment: FabAlignment::Center,
124            target_scale: 0.2,
125            scale_motion: None,
126            alpha_motion: None,
127        }
128    }
129}
130
131impl FabVisibilityAnimation {
132    /// Resolves scale, alpha, and the physical pivot for related FAB components.
133    #[doc(hidden)]
134    pub fn frame(
135        self,
136        id: &ElementId,
137        visible: bool,
138        extent: f32,
139        window: &mut Window,
140        cx: &mut App,
141    ) -> (f32, f32, Point<f32>) {
142        let sample = self.sample(id, visible, extent, window, cx);
143        let direction = current_material_theme(window, cx).layout.direction;
144        (sample.scale, sample.alpha, self.alignment.pivot(direction))
145    }
146
147    fn sample(
148        self,
149        id: &ElementId,
150        visible: bool,
151        extent: f32,
152        window: &mut Window,
153        cx: &mut App,
154    ) -> OverlayMotion {
155        let scheme = current_material_theme(window, cx).motion;
156        let reduced = cx.reduce_motion();
157        let mut progress = |channel, kind, spec: Option<MotionSpec>| {
158            let spec = if reduced {
159                MotionSpec::Instant
160            } else {
161                spec.unwrap_or_else(|| scheme.spec(kind, MotionSpeed::Fast, false))
162            };
163            animate((id.clone(), channel), f32::from(visible), spec, window, cx)
164        };
165        let spatial = progress(
166            "fab-visibility-scale",
167            MotionKind::Spatial,
168            self.scale_motion,
169        );
170        let alpha = progress(
171            "fab-visibility-alpha",
172            MotionKind::Effects,
173            self.alpha_motion,
174        );
175        let target = if self.target_scale >= 0. && (self.target_scale * extent).is_finite() {
176            self.target_scale
177        } else {
178            Self::default().target_scale
179        };
180        let scale = ((1. - spatial) * target + spatial).max(0.);
181        OverlayMotion {
182            scale: if (scale * extent).is_finite() {
183                scale
184            } else {
185                1.
186            },
187            alpha: alpha.clamp(0., 1.),
188        }
189    }
190}
191
192struct FabContent {
193    id: ElementId,
194    name: SharedString,
195    size: FabSize,
196    color: FabColor,
197    disabled: bool,
198    focus: Option<FocusHandle>,
199    on_activate: Option<Activate>,
200}
201
202impl FabContent {
203    fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
204        Self {
205            id: id.into(),
206            name: name.into(),
207            size: FabSize::default(),
208            color: FabColor::default(),
209            disabled: false,
210            focus: None,
211            on_activate: None,
212        }
213    }
214
215    fn style(&self) -> ActionStyle {
216        let (height, _, corner, _, _, _) = self.size.metrics();
217        let (background, foreground) = match self.color {
218            FabColor::Primary => (ColorRole::PrimaryContainer, ColorRole::OnPrimaryContainer),
219            FabColor::Secondary => (
220                ColorRole::SecondaryContainer,
221                ColorRole::OnSecondaryContainer,
222            ),
223            FabColor::Tertiary => (ColorRole::TertiaryContainer, ColorRole::OnTertiaryContainer),
224            FabColor::PrimaryStrong => (ColorRole::Primary, ColorRole::OnPrimary),
225            FabColor::SecondaryStrong => (ColorRole::Secondary, ColorRole::OnSecondary),
226            FabColor::TertiaryStrong => (ColorRole::Tertiary, ColorRole::OnTertiary),
227        };
228        ActionStyle {
229            background: Some(background),
230            background_color: None,
231            foreground,
232            // Disabled FABs are a desktop extension; preserve the established
233            // Material disabled-container treatment for this extension.
234            disabled: DisabledStyle {
235                foreground: ColorRole::OnSurface,
236                background: Some((ColorRole::OnSurface, 0.12)),
237                outline: (ColorRole::OnSurface, 0.12),
238            },
239            height,
240            min_width: height,
241            corner,
242            pressed_corner: corner,
243            selected_corner: None,
244            corner_motion: (
245                gpui_material_theme::MotionKind::Spatial,
246                gpui_material_theme::MotionSpeed::Fast,
247            ),
248            outline: 0.,
249            elevation: Elevation::Level3,
250            hover_elevation: Elevation::Level4,
251        }
252    }
253
254    fn action(self, content: impl IntoElement) -> ActionControl {
255        ActionControl {
256            style: self.style(),
257            id: self.id,
258            label: self.name,
259            focus: self.focus,
260            disabled: self.disabled,
261            action: Action::Invoke(self.on_activate),
262            content: content.into_any_element(),
263        }
264    }
265}
266
267#[derive(Default)]
268struct FabAppearance {
269    style: ButtonStyle,
270    interaction_source: Option<Entity<InteractionSource>>,
271    visible: Option<bool>,
272    animation: FabVisibilityAnimation,
273}
274
275impl FabAppearance {
276    fn motion(
277        &self,
278        id: &ElementId,
279        extent: f32,
280        window: &mut Window,
281        cx: &mut App,
282    ) -> OverlayMotion {
283        self.visible.map_or(
284            OverlayMotion {
285                scale: 1.,
286                alpha: 1.,
287            },
288            |visible| self.animation.sample(id, visible, extent, window, cx),
289        )
290    }
291
292    fn interactive(
293        &self,
294        action: &ActionControl,
295        motion: OverlayMotion,
296        window: &mut Window,
297        cx: &mut App,
298    ) -> bool {
299        let interactive = self.visible != Some(false) && motion.alpha > 0. && motion.scale > 0.;
300        if !interactive {
301            action.clear_interaction(window, cx);
302        }
303        interactive
304    }
305
306    fn control(
307        &self,
308        action: ActionControl,
309        scale: f32,
310        interactive: bool,
311        window: &mut Window,
312        cx: &mut App,
313    ) -> AnyElement {
314        action.render_layout(
315            scale,
316            ActionLayout {
317                tab_stop: interactive,
318                decorative: !interactive,
319                appearance: self.style,
320                ..Default::default()
321            },
322            self.interaction_source.as_ref().filter(|_| interactive),
323            window,
324            cx,
325        )
326    }
327}
328
329macro_rules! fab_builders {
330    () => {
331        pub fn size(mut self, size: FabSize) -> Self {
332            self.content.size = size;
333            self
334        }
335
336        pub fn color(mut self, color: FabColor) -> Self {
337            self.content.color = color;
338            self
339        }
340
341        /// Desktop compatibility extension. Material recommends hiding a FAB
342        /// when its primary action is unavailable instead of disabling it.
343        pub fn disabled(mut self, disabled: bool) -> Self {
344            self.content.disabled = disabled;
345            self
346        }
347
348        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
349            self.content.focus = Some(focus.clone());
350            self
351        }
352
353        pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
354            self.content.on_activate = Some(Rc::new(handler));
355            self
356        }
357
358        /// Overrides the container shape for all interaction states.
359        pub fn shape(mut self, shape: CornerShape) -> Self {
360            self.appearance.style.shapes.resting = Some(shape);
361            self.appearance.style.shapes.pressed = Some(shape);
362            self
363        }
364
365        /// Sets the enabled and disabled container and content colors.
366        pub fn colors(mut self, colors: ButtonColors) -> Self {
367            self.appearance.style.colors = colors;
368            self
369        }
370
371        /// Overrides the elevation for each interaction state.
372        pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
373            self.appearance.style.elevations = elevations;
374            self
375        }
376
377        /// Reports interaction state through a caller-owned source.
378        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
379            self.appearance.interaction_source = Some(source.clone());
380            self
381        }
382
383        /// Applies the caller's visibility state. Use a stable ID across updates.
384        pub fn visible(mut self, visible: bool) -> Self {
385            self.appearance.visible = Some(visible);
386            self
387        }
388
389        /// Sets the pivot, hidden scale, and independent scale and alpha motions.
390        pub fn visibility_animation(mut self, animation: FabVisibilityAnimation) -> Self {
391            self.appearance.animation = animation;
392            self
393        }
394    };
395}
396
397/// An elevated icon action with a required accessibility name. Mount it beside
398/// the scroll viewport to keep its position fixed while content scrolls.
399#[derive(IntoElement)]
400pub struct Fab {
401    content: FabContent,
402    icon: AnyElement,
403    appearance: FabAppearance,
404}
405
406impl Fab {
407    pub fn new(
408        id: impl Into<ElementId>,
409        name: impl Into<SharedString>,
410        icon: impl IntoElement,
411    ) -> Self {
412        Self {
413            content: FabContent::new(id, name),
414            icon: icon.into_any_element(),
415            appearance: FabAppearance::default(),
416        }
417    }
418
419    fab_builders!();
420}
421
422impl RenderOnce for Fab {
423    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
424        let style = self.content.style();
425        let (_, icon_size, _, _, _, _) = self.content.size.metrics();
426        let icon_size = if self.content.size == FabSize::Large {
427            36.
428        } else {
429            icon_size
430        };
431        let theme = current_material_theme(window, cx);
432        let direction = theme.layout.direction;
433        let extent = theme.layout.density.interactive_size(style.height);
434        let motion = self.appearance.motion(&self.content.id, extent, window, cx);
435        let action = self
436            .content
437            .action(icon_slot(self.icon, icon_size * motion.scale));
438        if self.appearance.visible.is_none() {
439            return self.appearance.control(action, 1., true, window, cx);
440        }
441        let interactive = self.appearance.interactive(&action, motion, window, cx);
442        if motion.alpha == 0. {
443            return Empty.into_any_element();
444        }
445        let extent = px(extent);
446        let mut footprint = div().relative().size(extent).min_w(extent).min_h(extent);
447        if motion.scale > 0. {
448            let pivot = self.appearance.animation.alignment.pivot(direction);
449            let distance = extent * (1. - motion.scale);
450            let control = self
451                .appearance
452                .control(action, motion.scale, interactive, window, cx);
453            footprint = footprint.child(
454                div()
455                    .absolute()
456                    .left(distance * pivot.x)
457                    .top(distance * pivot.y)
458                    .opacity(motion.alpha)
459                    .child(control),
460            );
461        }
462        footprint.into_any_element()
463    }
464}
465
466/// An elevated action with a label or custom content and an optional icon.
467/// All presentations share one action, accessible name, and focus handle.
468#[derive(IntoElement)]
469pub struct ExtendedFab {
470    content: FabContent,
471    icon: Option<AnyElement>,
472    custom_content: Option<AnyElement>,
473    expanded: bool,
474    appearance: FabAppearance,
475}
476
477impl ExtendedFab {
478    /// Creates an action with a leading icon and a label.
479    pub fn new(
480        id: impl Into<ElementId>,
481        label: impl Into<SharedString>,
482        icon: impl IntoElement,
483    ) -> Self {
484        Self {
485            icon: Some(icon.into_any_element()),
486            ..Self::text(id, label)
487        }
488    }
489
490    /// Creates a text-only action. The label also supplies its accessible name.
491    pub fn text(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
492        Self {
493            content: FabContent::new(id, label),
494            icon: None,
495            custom_content: None,
496            expanded: true,
497            appearance: FabAppearance::default(),
498        }
499    }
500
501    fab_builders!();
502
503    /// Replaces the rendered label with decorative content. The constructor's
504    /// accessible name and optional icon still belong to the action.
505    pub fn content(mut self, content: impl IntoElement) -> Self {
506        self.custom_content = Some(content.into_any_element());
507        self
508    }
509
510    /// Applies the caller's expansion state. An icon-bearing action collapses
511    /// to a square. Iconless actions retain their content in both states.
512    pub fn expanded(mut self, expanded: bool) -> Self {
513        self.expanded = expanded;
514        self
515    }
516}
517
518impl RenderOnce for ExtendedFab {
519    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
520        let (height, icon, _, padding, gap, role) = self.content.size.metrics();
521        let theme = current_material_theme(window, cx);
522        let direction = theme.layout.direction;
523        let extent = theme.layout.density.interactive_size(height);
524        let visual_height = theme.layout.density.visual_size(height);
525        let scheme = theme.motion;
526        let motion = self.appearance.motion(
527            &self.content.id,
528            extent.max(f32::from(window.viewport_size().width)),
529            window,
530            cx,
531        );
532        let action = self.content.action(Empty);
533        let interactive = self.appearance.interactive(&action, motion, window, cx);
534        if motion.alpha == 0. {
535            return Empty.into_any_element();
536        }
537        let (progress, opacity) = if self.icon.is_some() {
538            let reduced = cx.reduce_motion();
539            let mut sample = |channel, kind| {
540                animate(
541                    (action.id.clone(), channel),
542                    f32::from(self.expanded),
543                    scheme.spec(kind, MotionSpeed::Fast, reduced),
544                    window,
545                    cx,
546                )
547                .clamp(0., 1.)
548            };
549            (
550                sample("expansion", MotionKind::Spatial),
551                sample("label-opacity", MotionKind::Effects),
552            )
553        } else {
554            (1., 1.)
555        };
556        let (icon_size, padding, gap) = if self.icon.is_some() {
557            let collapsed_padding = (height - icon) / 2.;
558            (
559                icon,
560                collapsed_padding + (padding - collapsed_padding) * progress,
561                gap * progress,
562            )
563        } else {
564            (0., padding, 0.)
565        };
566        let ink = self
567            .appearance
568            .style
569            .colors
570            .content(action.disabled, false)
571            .unwrap_or_else(|| action.style.foreground(action.disabled, window, cx));
572        let typography = role.style(TypographyEmphasis::Baseline);
573        let mut custom_content = self.custom_content;
574        let label_width = if progress == 0. {
575            px(0.)
576        } else if let Some(content) = &mut custom_content {
577            window
578                .with_text_style(
579                    Some(gpui::TextStyleRefinement {
580                        color: Some(ink),
581                        font_size: Some(px(typography.size).into()),
582                        line_height: Some(px(typography.line_height).into()),
583                        ..Default::default()
584                    }),
585                    |window| {
586                        content.layout_as_root(
587                            size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
588                            window,
589                            cx,
590                        )
591                    },
592                )
593                .width
594        } else {
595            crate::text::single_line_width(&action.label, typography, ink, window, cx)
596        };
597        let fixed_width = px(icon_size + gap + padding * 2.);
598        let width = (fixed_width + label_width * progress).max(px(extent));
599        // Keep the nominal width through visibility scaling. Only the resolved
600        // action is prepainted, so measurement creates no hitboxes or semantics.
601        let control = canvas(
602            move |bounds, window, cx| {
603                if motion.scale == 0. {
604                    return None;
605                }
606                let scale = if f32::from(bounds.size.width * motion.scale).is_finite() {
607                    motion.scale
608                } else {
609                    1.
610                };
611                let motion = OverlayMotion { scale, ..motion };
612                let pivot = self.appearance.animation.alignment.pivot(direction);
613                let assigned_width = bounds.size.width * scale;
614                let mut row = div()
615                    .flex()
616                    .items_center()
617                    .w(assigned_width)
618                    .px(px(padding * scale))
619                    .gap(px(gap * scale))
620                    .when(direction == Direction::Rtl, Styled::flex_row_reverse);
621                if let Some(icon) = self.icon {
622                    row = row.child(icon_slot(icon, icon_size * scale));
623                }
624                let mut action = action;
625                let available = (bounds.size.width - fixed_width).max(px(0.));
626                let label_width = (label_width * progress).min(available) * scale;
627                if label_width > px(0.) {
628                    if let Some(content) = custom_content {
629                        row = row.child(custom_label(
630                            content,
631                            label_width,
632                            px(visual_height * scale),
633                            opacity,
634                        ));
635                    } else {
636                        row = row.child(crate::text::single_line(
637                            action.label.clone(),
638                            typography,
639                            scale,
640                            ink,
641                            (Some(label_width / progress), progress, opacity),
642                            window,
643                            cx,
644                        ));
645                    }
646                }
647                action.content = row.into_any_element();
648                let action = self
649                    .appearance
650                    .control(action, scale, interactive, window, cx);
651                let mut target = div()
652                    .w(assigned_width)
653                    .opacity(motion.alpha)
654                    .child(action)
655                    .into_any_element();
656                target.prepaint_as_root(
657                    motion.origin(bounds, pivot),
658                    bounds
659                        .size
660                        .map(|side| AvailableSpace::Definite(side * scale)),
661                    window,
662                    cx,
663                );
664                Some(target)
665            },
666            |_, target, window, cx| {
667                if let Some(mut target) = target {
668                    target.paint(window, cx);
669                }
670            },
671        );
672        div()
673            .w(width)
674            .h(px(extent))
675            .min_w(px(extent))
676            .min_h(px(extent))
677            .max_w_full()
678            .child(control.size_full())
679            .into_any_element()
680    }
681}
682
683fn custom_label(mut content: AnyElement, width: Pixels, height: Pixels, opacity: f32) -> gpui::Div {
684    div()
685        .w(width)
686        .h(height)
687        .min_w_0()
688        .overflow_hidden()
689        .opacity(opacity)
690        .child(
691            canvas(
692                move |bounds, window, cx| {
693                    let actual = content.layout_as_root(
694                        bounds.size.map(AvailableSpace::Definite),
695                        window,
696                        cx,
697                    );
698                    let origin = point(
699                        bounds.origin.x,
700                        bounds.origin.y + ((bounds.size.height - actual.height) / 2.).max(px(0.)),
701                    );
702                    content.prepaint_at(origin, window, cx);
703                    content
704                },
705                |_, mut content, window, cx| content.paint(window, cx),
706            )
707            .size_full(),
708        )
709}
710
711/// Places a FAB inside the current window viewport at logical bottom-end.
712/// Mount this element beside the scroll owner so it stays visible while scrolling.
713#[derive(IntoElement)]
714pub struct FloatingAction {
715    action: AnyElement,
716    margin: gpui::Pixels,
717}
718
719impl FloatingAction {
720    pub fn new(action: impl IntoElement) -> Self {
721        Self {
722            action: action.into_any_element(),
723            margin: px(16.),
724        }
725    }
726
727    pub fn margin(mut self, margin: gpui::Pixels) -> Self {
728        self.margin = margin.max(px(0.));
729        self
730    }
731}
732
733impl RenderOnce for FloatingAction {
734    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
735        let viewport = window.viewport_size();
736        let direction = current_material_theme(window, cx).layout.direction;
737        let margin = self.margin.min(viewport.width.min(viewport.height) / 4.);
738        let x = if direction == Direction::Rtl {
739            margin
740        } else {
741            viewport.width - margin
742        };
743        deferred(
744            anchored()
745                .anchor(logical_anchor(gpui::Anchor::BottomRight, direction))
746                .position(gpui::point(x, viewport.height - margin))
747                .snap_to_window_with_margin(margin)
748                .child(ThemeScope::inherit(
749                    div()
750                        .max_w((viewport.width - margin * 2.).max(px(0.)))
751                        .child(self.action),
752                    window,
753                    cx,
754                )),
755        )
756    }
757}