Skip to main content

gpui_material_extras/toolbar/
fab_menu.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    Anchor, AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, SharedString, Styled, Window, deferred, div, point, px,
6};
7use gpui_base::{FocusTrapElement, Positioner};
8use gpui_material_components::{FabColor, FabSize, FabVisibilityAnimation, Icon, IconName};
9use gpui_material_foundation::{
10    ThemeScope, animate, color, current_material_theme, logical_anchor,
11};
12use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, MotionKind, MotionSpeed};
13
14use super::{Invoke, activate_key, focus_handle, style_button};
15
16mod menu;
17mod trigger;
18
19use trigger::{TriggerContent, TriggerRenderContext};
20
21type Expand = Rc<dyn Fn(bool, &mut Window, &mut App)>;
22
23/// An individually labeled FAB menu action. Supply a stable id for each item.
24pub struct FabMenuItem {
25    id: SharedString,
26    label: SharedString,
27    icon: Option<AnyElement>,
28    content: Option<AnyElement>,
29    colors: FabMenuItemColors,
30    disabled: bool,
31    invoke: Option<Invoke>,
32}
33
34impl FabMenuItem {
35    /// Creates a FAB menu item with a stable `id`, accessible `label`, and Material `icon`.
36    pub fn new(
37        id: impl Into<SharedString>,
38        label: impl Into<SharedString>,
39        icon: IconName,
40    ) -> Self {
41        Self {
42            id: id.into(),
43            label: label.into(),
44            icon: Some(Icon::new(icon).into_any_element()),
45            content: None,
46            colors: FabMenuItemColors::default(),
47            disabled: false,
48            invoke: None,
49        }
50    }
51
52    /// Uses arbitrary decorative content while retaining the supplied action name.
53    pub fn custom(
54        id: impl Into<SharedString>,
55        label: impl Into<SharedString>,
56        content: impl IntoElement,
57    ) -> Self {
58        Self {
59            id: id.into(),
60            label: label.into(),
61            icon: None,
62            content: Some(content.into_any_element()),
63            colors: FabMenuItemColors::default(),
64            disabled: false,
65            invoke: None,
66        }
67    }
68
69    /// Sets a custom icon element for this menu item.
70    pub fn icon(mut self, icon: impl IntoElement) -> Self {
71        self.icon = Some(icon.into_any_element());
72        self
73    }
74
75    /// Replaces the item's visible label. Its accessible name remains the same.
76    pub fn content(mut self, content: impl IntoElement) -> Self {
77        self.content = Some(content.into_any_element());
78        self
79    }
80
81    /// Overrides the container and content colors for this menu item.
82    pub fn colors(mut self, colors: FabMenuItemColors) -> Self {
83        self.colors = colors;
84        self
85    }
86
87    /// Disables activation and keyboard focus navigation on this menu item when `true`.
88    pub fn disabled(mut self, disabled: bool) -> Self {
89        self.disabled = disabled;
90        self
91    }
92
93    /// Registers a callback invoked when this menu item is activated.
94    pub fn on_activate(mut self, invoke: impl Fn(&mut Window, &mut App) + 'static) -> Self {
95        self.invoke = Some(Rc::new(invoke));
96        self
97    }
98}
99
100/// Optional colors for an individual FAB menu action.
101#[derive(Clone, Copy, Debug, Default, PartialEq)]
102pub struct FabMenuItemColors {
103    /// Background fill color when enabled.
104    pub container: Option<Hsla>,
105    /// Icon and label color when enabled.
106    pub content: Option<Hsla>,
107    /// Background fill color when disabled.
108    pub disabled_container: Option<Hsla>,
109    /// Icon and label color when disabled.
110    pub disabled_content: Option<Hsla>,
111}
112
113/// Horizontal alignment of a FAB menu relative to its trigger.
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115pub enum FabMenuAlignment {
116    /// Aligns the menu stack with the leading edge of the trigger (mirrored in RTL).
117    Start,
118    /// Centers the menu stack above the trigger.
119    Center,
120    /// Aligns the menu stack with the trailing edge of the trigger (mirrored in RTL).
121    #[default]
122    End,
123}
124
125impl FabMenuAlignment {
126    fn anchor(self, direction: Direction) -> Anchor {
127        let anchor = match self {
128            Self::Start => Anchor::BottomLeft,
129            Self::Center => Anchor::BottomCenter,
130            Self::End => Anchor::BottomRight,
131        };
132        logical_anchor(anchor, direction)
133    }
134}
135
136/// Optional appearance of one endpoint of the FAB menu trigger transition.
137#[derive(Clone, Copy, Debug, Default, PartialEq)]
138pub struct FabMenuTriggerAppearance {
139    /// Trigger button side length in logical pixels.
140    pub size: Option<Pixels>,
141    /// Corner shape of the trigger button.
142    pub shape: Option<CornerShape>,
143    /// Icon size in logical pixels.
144    pub icon_size: Option<Pixels>,
145    /// Background fill color of the trigger button.
146    pub container_color: Option<Hsla>,
147    /// Foreground icon/content color of the trigger button.
148    pub content_color: Option<Hsla>,
149    /// Shadow elevation of the trigger button.
150    pub elevation: Option<Elevation>,
151}
152
153/// Interpolated collapsed and expanded trigger appearances.
154#[derive(Clone, Copy, Debug, Default, PartialEq)]
155pub struct FabMenuTriggerStyle {
156    /// Trigger appearance when the menu is collapsed.
157    pub collapsed: FabMenuTriggerAppearance,
158    /// Trigger appearance when the menu is expanded.
159    pub expanded: FabMenuTriggerAppearance,
160}
161
162/// A floating action button that opens a stack of commands above it.
163/// Provide two to six actions with stable IDs.
164#[derive(IntoElement)]
165pub struct FabMenu {
166    id: ElementId,
167    open_label: SharedString,
168    close_label: SharedString,
169    icon: IconName,
170    open_content: Option<TriggerContent>,
171    close_content: Option<TriggerContent>,
172    items: Vec<FabMenuItem>,
173    size: FabSize,
174    color: FabColor,
175    focus: Option<FocusHandle>,
176    expanded: Option<bool>,
177    on_expanded_change: Option<Expand>,
178    alignment: FabMenuAlignment,
179    trigger_style: FabMenuTriggerStyle,
180    visible: Option<bool>,
181    visibility_animation: FabVisibilityAnimation,
182}
183
184impl FabMenu {
185    /// Creates a FAB menu with an element `id`, collapsed accessible `open_label`, `icon`, and `items`.
186    pub fn new(
187        id: impl Into<ElementId>,
188        open_label: impl Into<SharedString>,
189        icon: IconName,
190        items: impl IntoIterator<Item = FabMenuItem>,
191    ) -> Self {
192        Self {
193            id: id.into(),
194            open_label: open_label.into(),
195            close_label: "Close actions".into(),
196            icon,
197            open_content: None,
198            close_content: None,
199            items: items.into_iter().collect(),
200            size: FabSize::Small,
201            color: FabColor::Primary,
202            focus: None,
203            expanded: None,
204            on_expanded_change: None,
205            alignment: FabMenuAlignment::default(),
206            trigger_style: FabMenuTriggerStyle::default(),
207            visible: None,
208            visibility_animation: FabVisibilityAnimation::default(),
209        }
210    }
211
212    /// Sets the accessible label used on the trigger button while the menu is expanded.
213    /// Defaults to `"Close actions"`.
214    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
215        self.close_label = label.into();
216        self
217    }
218
219    /// Replaces the collapsed trigger icon with a custom icon element scaled to the trigger's icon size.
220    pub fn open_icon(mut self, icon: impl IntoElement) -> Self {
221        self.open_content = Some(TriggerContent::Icon(icon.into_any_element()));
222        self
223    }
224
225    /// Replaces the expanded close icon with a custom icon element scaled to the trigger's icon size.
226    pub fn close_icon(mut self, icon: impl IntoElement) -> Self {
227        self.close_content = Some(TriggerContent::Icon(icon.into_any_element()));
228        self
229    }
230
231    /// Replaces the collapsed trigger's inner content with arbitrary decorative artwork.
232    pub fn open_content(mut self, content: impl IntoElement) -> Self {
233        self.open_content = Some(TriggerContent::Custom(content.into_any_element()));
234        self
235    }
236
237    /// Replaces the expanded trigger's inner content with arbitrary decorative artwork.
238    pub fn close_content(mut self, content: impl IntoElement) -> Self {
239        self.close_content = Some(TriggerContent::Custom(content.into_any_element()));
240        self
241    }
242
243    /// Renders caller-owned expansion. Without this setter, the menu retains its value.
244    pub fn expanded(mut self, expanded: bool) -> Self {
245        self.expanded = Some(expanded);
246        self
247    }
248
249    /// Reports a requested expansion value from the trigger, dismissal, or selection.
250    pub fn on_expanded_change(
251        mut self,
252        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
253    ) -> Self {
254        self.on_expanded_change = Some(Rc::new(handler));
255        self
256    }
257
258    /// Sets horizontal alignment of the expanded menu stack relative to the trigger.
259    pub fn alignment(mut self, alignment: FabMenuAlignment) -> Self {
260        self.alignment = alignment;
261        self
262    }
263
264    /// Overrides the collapsed and expanded appearance endpoints of the trigger button.
265    pub fn trigger_style(mut self, style: FabMenuTriggerStyle) -> Self {
266        self.trigger_style = style;
267        self
268    }
269
270    /// Controls the presence of the trigger independently of expansion.
271    pub fn visible(mut self, visible: bool) -> Self {
272        self.visible = Some(visible);
273        self
274    }
275
276    /// Sets the animation style used when toggling [`Self::visible`].
277    pub fn visibility_animation(mut self, animation: FabVisibilityAnimation) -> Self {
278        self.visibility_animation = animation;
279        self
280    }
281
282    /// Sets the collapsed [`FabSize`] preset (`Small`, `Medium`, or `Large`). Defaults to `Small`.
283    pub fn size(mut self, size: FabSize) -> Self {
284        self.size = size;
285        self
286    }
287
288    /// Sets the [`FabColor`] role preset for the trigger and default menu items. Defaults to `Primary`.
289    pub fn color(mut self, color: FabColor) -> Self {
290        self.color = color;
291        self
292    }
293
294    /// Uses a caller-owned focus handle for the toggle button.
295    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
296        self.focus = Some(focus.clone());
297        self
298    }
299}
300
301#[derive(Default)]
302struct MenuState {
303    open: Cell<bool>,
304    interactive: Cell<bool>,
305    bounds: Cell<Bounds<Pixels>>,
306    trigger_bounds: Cell<Bounds<Pixels>>,
307    scroll: gpui::ScrollHandle,
308}
309
310#[derive(Clone, Copy)]
311struct MenuStyle {
312    ink: Hsla,
313    fill: Hsla,
314    ring: Hsla,
315    rtl: bool,
316    anchor: Anchor,
317    max_width: Pixels,
318    alpha: f32,
319    reveal: f32,
320}
321
322impl MenuStyle {
323    fn colors(self, item: &FabMenuItem) -> (Hsla, Hsla) {
324        if item.disabled {
325            (
326                item.colors
327                    .disabled_container
328                    .unwrap_or_else(|| self.ink.opacity(0.12)),
329                item.colors
330                    .disabled_content
331                    .unwrap_or_else(|| self.ink.opacity(0.38)),
332            )
333        } else {
334            (
335                item.colors.container.unwrap_or(self.fill),
336                item.colors.content.unwrap_or(self.ink),
337            )
338        }
339    }
340}
341
342struct MenuFocus {
343    trigger: FocusHandle,
344    scope: FocusHandle,
345    open_focus: FocusHandle,
346    handles: Vec<(FocusHandle, bool)>,
347}
348
349impl RenderOnce for FabMenu {
350    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
351        let retained = window.use_keyed_state((self.id.clone(), "menu-state"), cx, |_, _| {
352            Rc::new(MenuState::default())
353        });
354        let state = retained.read(cx).clone();
355        let theme = current_material_theme(window, cx);
356        let direction = theme.layout.direction;
357        let motion = theme.motion;
358        let tone = |role| color(theme.colors.color(role));
359        let (background, foreground, strong, strong_ink) = fab_roles(self.color);
360        let fill = tone(background);
361        let ink = tone(foreground);
362        let strong_fill = tone(strong);
363        let strong_ink = tone(strong_ink);
364        let ring = tone(ColorRole::OnSurface);
365        let shadow = tone(ColorRole::Shadow);
366        let viewport = window.viewport_size();
367        let cap = f32::from(viewport.width.min(viewport.height)).max(0.);
368        let show = self.visible.unwrap_or(true);
369        let (scale, visibility_alpha, pivot) =
370            self.visible.map_or((1., 1., point(0.5, 0.5)), |visible| {
371                self.visibility_animation
372                    .frame(&self.id, visible, cap.max(1.), window, cx)
373            });
374        let interactive = show && cap > 0. && scale > 0. && visibility_alpha > 0.;
375        state.interactive.set(interactive);
376        let has_items = !self.items.is_empty();
377        let open = interactive && has_items && self.expanded.unwrap_or_else(|| state.open.get());
378        let was_open = state.open.replace(open);
379        let alpha = animate(
380            (self.id.clone(), "menu-alpha"),
381            f32::from(open),
382            motion.spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
383            window,
384            cx,
385        )
386        .clamp(0., 1.);
387        let reveal = animate(
388            (self.id.clone(), "menu-reveal"),
389            f32::from(open),
390            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
391            window,
392            cx,
393        )
394        .clamp(0., 1.);
395
396        let id = self.id.clone();
397        let focus = self.prepare_focus(open, was_open, &state, window, cx);
398        let request = self.expansion_request(&state, &focus, has_items);
399        let visual =
400            self.trigger_visual((fill, ink, strong_fill, strong_ink), cap, reveal, direction);
401        let scale = if visual.size > 0. {
402            scale.min(cap / visual.size)
403        } else {
404            0.
405        };
406        let anchor = self.alignment.anchor(direction);
407        let style = MenuStyle {
408            fill,
409            ink,
410            ring,
411            rtl: direction == Direction::Rtl,
412            anchor,
413            max_width: (viewport.width - px(24.)).clamp(px(0.), px(360.)),
414            alpha,
415            reveal,
416        };
417        let exit_bounds = state.bounds.get();
418        let mut root = div().id(id.clone()).flex_none();
419        if visibility_alpha > 0. {
420            let side = px(visual.size);
421            let mut footprint = div().relative().size(side).flex_none();
422            if scale > 0. {
423                let trigger_ctx = TriggerRenderContext {
424                    id: &id,
425                    state: &state,
426                    focus: &focus,
427                    request: &request,
428                    visual,
429                    style,
430                    shadow,
431                    scale,
432                    visibility_alpha,
433                    open,
434                    interactive,
435                    has_items,
436                };
437                let layer = self.render_trigger_layer(&trigger_ctx, window, cx);
438                if self.visible.is_none() {
439                    root = root.child(layer);
440                } else {
441                    let distance = side * (1. - scale);
442                    footprint = footprint.child(
443                        div()
444                            .absolute()
445                            .left(distance * pivot.x)
446                            .top(distance * pivot.y)
447                            .child(layer),
448                    );
449                    root = root.child(footprint);
450                }
451            } else {
452                root = root.child(footprint);
453            }
454        }
455        if !open && alpha > 0. && exit_bounds.size.width > px(0.) {
456            let x = match anchor {
457                Anchor::BottomLeft => exit_bounds.left(),
458                Anchor::BottomCenter => exit_bounds.center().x,
459                _ => exit_bounds.right(),
460            };
461            root = root.child(
462                deferred(
463                    Positioner::corner(anchor, point(x, exit_bounds.bottom())).child(
464                        ThemeScope::inherit(
465                            self.render_actions(&focus.handles, &state, &request, style, window),
466                            window,
467                            cx,
468                        ),
469                    ),
470                )
471                .with_priority(100),
472            );
473        }
474        if open {
475            root.on_key_down(move |event, window, cx| {
476                if event.keystroke.key == "escape" {
477                    request(false, window, cx);
478                    cx.stop_propagation();
479                }
480            })
481            .focus_trap((id, "focus-trap"), &focus.scope)
482            .into_any_element()
483        } else {
484            root.into_any_element()
485        }
486    }
487}
488
489fn fab_roles(value: FabColor) -> (ColorRole, ColorRole, ColorRole, ColorRole) {
490    use ColorRole::*;
491    match value {
492        FabColor::Primary => (PrimaryContainer, OnPrimaryContainer, Primary, OnPrimary),
493        FabColor::Secondary => (
494            SecondaryContainer,
495            OnSecondaryContainer,
496            Secondary,
497            OnSecondary,
498        ),
499        FabColor::Tertiary => (TertiaryContainer, OnTertiaryContainer, Tertiary, OnTertiary),
500        FabColor::PrimaryStrong => (Primary, OnPrimary, PrimaryContainer, OnPrimaryContainer),
501        FabColor::SecondaryStrong => (
502            Secondary,
503            OnSecondary,
504            SecondaryContainer,
505            OnSecondaryContainer,
506        ),
507        FabColor::TertiaryStrong => (Tertiary, OnTertiary, TertiaryContainer, OnTertiaryContainer),
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    use gpui::{ElementId, SharedString};
514
515    use super::menu::item_part_id;
516
517    #[test]
518    fn fab_menu_item_part_ids_are_scoped_by_menu_id() {
519        let first_icon = item_part_id(
520            &ElementId::from("menu-a"),
521            "fab-menu-icon",
522            SharedString::from("copy"),
523        );
524        let second_icon = item_part_id(
525            &ElementId::from("menu-b"),
526            "fab-menu-icon",
527            SharedString::from("copy"),
528        );
529        let first_label = item_part_id(
530            &ElementId::from("menu-a"),
531            "fab-menu-label",
532            SharedString::from("copy"),
533        );
534        assert_ne!(first_icon, second_icon);
535        assert_ne!(first_icon, first_label);
536    }
537}