Skip to main content

gpui_material_components/fab/
extended.rs

1use gpui::prelude::FluentBuilder;
2use gpui::{
3    AnyElement, App, AvailableSpace, ElementId, Empty, IntoElement, ParentElement, Pixels,
4    RenderOnce, SharedString, Size, Styled, Window, canvas, div, point, px, size,
5};
6use gpui_material_foundation::{OverlayMotion, animate, current_material_theme};
7use gpui_material_theme::{Direction, MotionKind, MotionSpeed, TypographyEmphasis};
8
9use crate::action::icon_slot;
10
11use super::{
12    fab_builders,
13    types::{FabAppearance, FabContent},
14};
15
16/// An elevated action with a label or custom content and an optional icon.
17/// All presentations share one action, accessible name, and focus handle.
18#[derive(IntoElement)]
19pub struct ExtendedFab {
20    content: FabContent,
21    icon: Option<AnyElement>,
22    custom_content: Option<AnyElement>,
23    expanded: bool,
24    appearance: FabAppearance,
25}
26
27impl ExtendedFab {
28    /// Creates an action with a leading icon and a label.
29    pub fn new(
30        id: impl Into<ElementId>,
31        label: impl Into<SharedString>,
32        icon: impl IntoElement,
33    ) -> Self {
34        Self {
35            icon: Some(icon.into_any_element()),
36            ..Self::text(id, label)
37        }
38    }
39
40    /// Creates a text-only action. The label also supplies its accessible name.
41    pub fn text(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
42        Self {
43            content: FabContent::new(id, label),
44            icon: None,
45            custom_content: None,
46            expanded: true,
47            appearance: FabAppearance::default(),
48        }
49    }
50
51    fab_builders!();
52
53    /// Replaces the rendered label with decorative content. The constructor's
54    /// accessible name and optional icon still belong to the action.
55    pub fn content(mut self, content: impl IntoElement) -> Self {
56        self.custom_content = Some(content.into_any_element());
57        self
58    }
59
60    /// Applies the caller's expansion state. An icon-bearing action collapses
61    /// to a square. Iconless actions retain their content in both states.
62    pub fn expanded(mut self, expanded: bool) -> Self {
63        self.expanded = expanded;
64        self
65    }
66}
67
68impl RenderOnce for ExtendedFab {
69    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
70        let (height, icon, _, padding, gap, role) = self.content.size.metrics();
71        let theme = current_material_theme(window, cx);
72        let direction = theme.layout.direction;
73        let extent = theme.layout.density.interactive_size(height);
74        let visual_height = theme.layout.density.visual_size(height);
75        let scheme = theme.motion;
76        let motion = self.appearance.motion(
77            &self.content.id,
78            extent.max(f32::from(window.viewport_size().width)),
79            window,
80            cx,
81        );
82        let action = self.content.action(Empty);
83        let interactive = self.appearance.interactive(&action, motion, window, cx);
84        if motion.alpha == 0. {
85            return Empty.into_any_element();
86        }
87        let (progress, opacity) = if self.icon.is_some() {
88            let reduced = cx.reduce_motion();
89            let mut sample = |channel, kind| {
90                animate(
91                    (action.id.clone(), channel),
92                    f32::from(self.expanded),
93                    scheme.spec(kind, MotionSpeed::Fast, reduced),
94                    window,
95                    cx,
96                )
97                .clamp(0., 1.)
98            };
99            (
100                sample("expansion", MotionKind::Spatial),
101                sample("label-opacity", MotionKind::Effects),
102            )
103        } else {
104            (1., 1.)
105        };
106        let (icon_size, padding, gap) = if self.icon.is_some() {
107            let collapsed_padding = (height - icon) / 2.;
108            (
109                icon,
110                collapsed_padding + (padding - collapsed_padding) * progress,
111                gap * progress,
112            )
113        } else {
114            (0., padding, 0.)
115        };
116        let ink = self
117            .appearance
118            .style
119            .colors
120            .content(action.disabled, false)
121            .unwrap_or_else(|| action.style.foreground(action.disabled, window, cx));
122        let typography = role.style(TypographyEmphasis::Baseline);
123        let mut custom_content = self.custom_content;
124        let mut custom_measured = None;
125        let mut pre_shaped = None;
126        let label_width = if progress == 0. {
127            px(0.)
128        } else if let Some(content) = &mut custom_content {
129            let measured = window.with_text_style(
130                Some(gpui::TextStyleRefinement {
131                    color: Some(ink),
132                    font_size: Some(px(typography.size).into()),
133                    line_height: Some(px(typography.line_height).into()),
134                    ..Default::default()
135                }),
136                |window| {
137                    content.layout_as_root(
138                        size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
139                        window,
140                        cx,
141                    )
142                },
143            );
144            custom_measured = Some(measured);
145            measured.width
146        } else if let Some((clean, shaped)) =
147            crate::text::shape_single_line(action.label.clone(), typography, 1., ink, window, cx)
148        {
149            let width = shaped.line().width.ceil();
150            pre_shaped = Some((clean, shaped));
151            width
152        } else {
153            px(0.)
154        };
155        let fixed_width = px(icon_size + gap + padding * 2.);
156        let width = (fixed_width + label_width * progress).max(px(extent));
157        // Keep the nominal width through visibility scaling. Only the resolved
158        // action is prepainted, so measurement creates no hitboxes or semantics.
159        let control = canvas(
160            move |bounds, window, cx| {
161                if motion.scale == 0. {
162                    return None;
163                }
164                let scale = if f32::from(bounds.size.width * motion.scale).is_finite() {
165                    motion.scale
166                } else {
167                    1.
168                };
169                let motion = OverlayMotion { scale, ..motion };
170                let pivot = self.appearance.animation.alignment.pivot(direction);
171                let assigned_width = bounds.size.width * scale;
172                let mut row = div()
173                    .flex()
174                    .items_center()
175                    .w(assigned_width)
176                    .px(px(padding * scale))
177                    .gap(px(gap * scale))
178                    .when(direction == Direction::Rtl, Styled::flex_row_reverse);
179                if let Some(icon) = self.icon {
180                    row = row.child(icon_slot(icon, icon_size * scale));
181                }
182                let mut action = action;
183                let available = (bounds.size.width - fixed_width).max(px(0.));
184                let label_width = (label_width * progress).min(available) * scale;
185                if label_width > px(0.) {
186                    if let Some(content) = custom_content {
187                        row = row.child(custom_label(
188                            content,
189                            custom_measured,
190                            label_width,
191                            px(visual_height * scale),
192                            opacity,
193                        ));
194                    } else if scale == 1.
195                        && let Some(shaped) = pre_shaped
196                    {
197                        row = row.child(crate::text::single_line_with_shaped(
198                            shaped,
199                            typography,
200                            1.,
201                            ink,
202                            (Some(label_width / progress), progress, opacity),
203                            window,
204                            cx,
205                        ));
206                    } else {
207                        row = row.child(crate::text::single_line(
208                            action.label.clone(),
209                            typography,
210                            scale,
211                            ink,
212                            (Some(label_width / progress), progress, opacity),
213                            window,
214                            cx,
215                        ));
216                    }
217                }
218                action.content = row.into_any_element();
219                let action = self
220                    .appearance
221                    .control(action, scale, interactive, window, cx);
222                let mut target = div()
223                    .w(assigned_width)
224                    .opacity(motion.alpha)
225                    .child(action)
226                    .into_any_element();
227                target.prepaint_as_root(
228                    motion.origin(bounds, pivot),
229                    bounds
230                        .size
231                        .map(|side| AvailableSpace::Definite(side * scale)),
232                    window,
233                    cx,
234                );
235                Some(target)
236            },
237            |_, target, window, cx| {
238                if let Some(mut target) = target {
239                    target.paint(window, cx);
240                }
241            },
242        );
243        div()
244            .w(width)
245            .h(px(extent))
246            .min_w(px(extent))
247            .min_h(px(extent))
248            .max_w_full()
249            .child(control.size_full())
250            .into_any_element()
251    }
252}
253
254fn custom_label(
255    mut content: AnyElement,
256    measured: Option<Size<Pixels>>,
257    width: Pixels,
258    height: Pixels,
259    opacity: f32,
260) -> gpui::Div {
261    div()
262        .w(width)
263        .h(height)
264        .min_w_0()
265        .overflow_hidden()
266        .opacity(opacity)
267        .child(
268            canvas(
269                move |bounds, window, cx| {
270                    // Reuse the initial MaxContent layout when it fits inside the allocated
271                    // slot; only re-layout when constrained tighter by available bounds.
272                    let actual_height = match measured {
273                        Some(size)
274                            if size.width <= bounds.size.width
275                                && size.height <= bounds.size.height =>
276                        {
277                            size.height
278                        }
279                        _ => {
280                            content
281                                .layout_as_root(
282                                    bounds.size.map(AvailableSpace::Definite),
283                                    window,
284                                    cx,
285                                )
286                                .height
287                        }
288                    };
289                    let origin = point(
290                        bounds.origin.x,
291                        bounds.origin.y + ((bounds.size.height - actual_height) / 2.).max(px(0.)),
292                    );
293                    content.prepaint_at(origin, window, cx);
294                    content
295                },
296                |_, mut content, window, cx| content.paint(window, cx),
297            )
298            .size_full(),
299        )
300}