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