Skip to main content

gpui_material_extras/toolbar/
fab_menu.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    Anchor, AnyElement, App, Axis, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement,
5    IntoElement, ParentElement, Pixels, RenderOnce, Rgba, Role, SharedString,
6    StatefulInteractiveElement, Styled, Window, canvas, deferred, div, point,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::{Button, FocusTrapElement, Popup, Positioner, TestSupportExt};
10use gpui_material_components::{FabColor, FabSize, FabVisibilityAnimation, Icon, IconName, Text};
11use gpui_material_foundation::{
12    ThemeScope, animate, color, current_material_theme, elevation_shadows, logical_anchor,
13    move_roving_focus,
14};
15use gpui_material_theme::{
16    ColorRole, CornerShape, Direction, Elevation, MotionKind, MotionSpeed, TypeRole,
17};
18
19use super::{Invoke, activate_key, focus_handle, style_button};
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
162enum TriggerContent {
163    Icon(AnyElement),
164    Custom(AnyElement),
165}
166
167/// A floating action button that opens a stack of commands above it.
168/// Provide two to six actions with stable IDs.
169#[derive(IntoElement)]
170pub struct FabMenu {
171    id: ElementId,
172    open_label: SharedString,
173    close_label: SharedString,
174    icon: IconName,
175    open_content: Option<TriggerContent>,
176    close_content: Option<TriggerContent>,
177    items: Vec<FabMenuItem>,
178    size: FabSize,
179    color: FabColor,
180    focus: Option<FocusHandle>,
181    expanded: Option<bool>,
182    on_expanded_change: Option<Expand>,
183    alignment: FabMenuAlignment,
184    trigger_style: FabMenuTriggerStyle,
185    visible: Option<bool>,
186    visibility_animation: FabVisibilityAnimation,
187}
188
189impl FabMenu {
190    /// Creates a FAB menu with an element `id`, collapsed accessible `open_label`, `icon`, and `items`.
191    pub fn new(
192        id: impl Into<ElementId>,
193        open_label: impl Into<SharedString>,
194        icon: IconName,
195        items: impl IntoIterator<Item = FabMenuItem>,
196    ) -> Self {
197        Self {
198            id: id.into(),
199            open_label: open_label.into(),
200            close_label: "Close actions".into(),
201            icon,
202            open_content: None,
203            close_content: None,
204            items: items.into_iter().collect(),
205            size: FabSize::Small,
206            color: FabColor::Primary,
207            focus: None,
208            expanded: None,
209            on_expanded_change: None,
210            alignment: FabMenuAlignment::default(),
211            trigger_style: FabMenuTriggerStyle::default(),
212            visible: None,
213            visibility_animation: FabVisibilityAnimation::default(),
214        }
215    }
216
217    /// Sets the accessible label used on the trigger button while the menu is expanded.
218    /// Defaults to `"Close actions"`.
219    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
220        self.close_label = label.into();
221        self
222    }
223
224    /// Replaces the collapsed trigger icon with a custom icon element scaled to the trigger's icon size.
225    pub fn open_icon(mut self, icon: impl IntoElement) -> Self {
226        self.open_content = Some(TriggerContent::Icon(icon.into_any_element()));
227        self
228    }
229
230    /// Replaces the expanded close icon with a custom icon element scaled to the trigger's icon size.
231    pub fn close_icon(mut self, icon: impl IntoElement) -> Self {
232        self.close_content = Some(TriggerContent::Icon(icon.into_any_element()));
233        self
234    }
235
236    /// Replaces the collapsed trigger's inner content with arbitrary decorative artwork.
237    pub fn open_content(mut self, content: impl IntoElement) -> Self {
238        self.open_content = Some(TriggerContent::Custom(content.into_any_element()));
239        self
240    }
241
242    /// Replaces the expanded trigger's inner content with arbitrary decorative artwork.
243    pub fn close_content(mut self, content: impl IntoElement) -> Self {
244        self.close_content = Some(TriggerContent::Custom(content.into_any_element()));
245        self
246    }
247
248    /// Renders caller-owned expansion. Without this setter, the menu retains its value.
249    pub fn expanded(mut self, expanded: bool) -> Self {
250        self.expanded = Some(expanded);
251        self
252    }
253
254    /// Reports a requested expansion value from the trigger, dismissal, or selection.
255    pub fn on_expanded_change(
256        mut self,
257        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
258    ) -> Self {
259        self.on_expanded_change = Some(Rc::new(handler));
260        self
261    }
262
263    /// Sets horizontal alignment of the expanded menu stack relative to the trigger.
264    pub fn alignment(mut self, alignment: FabMenuAlignment) -> Self {
265        self.alignment = alignment;
266        self
267    }
268
269    /// Overrides the collapsed and expanded appearance endpoints of the trigger button.
270    pub fn trigger_style(mut self, style: FabMenuTriggerStyle) -> Self {
271        self.trigger_style = style;
272        self
273    }
274
275    /// Controls the presence of the trigger independently of expansion.
276    pub fn visible(mut self, visible: bool) -> Self {
277        self.visible = Some(visible);
278        self
279    }
280
281    /// Sets the animation style used when toggling [`Self::visible`].
282    pub fn visibility_animation(mut self, animation: FabVisibilityAnimation) -> Self {
283        self.visibility_animation = animation;
284        self
285    }
286
287    /// Sets the collapsed [`FabSize`] preset (`Small`, `Medium`, or `Large`). Defaults to `Small`.
288    pub fn size(mut self, size: FabSize) -> Self {
289        self.size = size;
290        self
291    }
292
293    /// Sets the [`FabColor`] role preset for the trigger and default menu items. Defaults to `Primary`.
294    pub fn color(mut self, color: FabColor) -> Self {
295        self.color = color;
296        self
297    }
298
299    /// Uses a caller-owned focus handle for the toggle button.
300    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
301        self.focus = Some(focus.clone());
302        self
303    }
304}
305
306#[derive(Default)]
307struct MenuState {
308    open: Cell<bool>,
309    interactive: Cell<bool>,
310    bounds: Cell<Bounds<Pixels>>,
311    trigger_bounds: Cell<Bounds<Pixels>>,
312    scroll: gpui::ScrollHandle,
313}
314
315#[derive(Clone, Copy)]
316struct MenuStyle {
317    ink: Hsla,
318    fill: Hsla,
319    ring: Hsla,
320    rtl: bool,
321    anchor: Anchor,
322    max_width: Pixels,
323    alpha: f32,
324    reveal: f32,
325}
326
327impl MenuStyle {
328    fn colors(self, item: &FabMenuItem) -> (Hsla, Hsla) {
329        if item.disabled {
330            (
331                item.colors
332                    .disabled_container
333                    .unwrap_or_else(|| self.ink.opacity(0.12)),
334                item.colors
335                    .disabled_content
336                    .unwrap_or_else(|| self.ink.opacity(0.38)),
337            )
338        } else {
339            (
340                item.colors.container.unwrap_or(self.fill),
341                item.colors.content.unwrap_or(self.ink),
342            )
343        }
344    }
345}
346
347struct MenuFocus {
348    trigger: FocusHandle,
349    scope: FocusHandle,
350    open_focus: FocusHandle,
351    handles: Vec<(FocusHandle, bool)>,
352}
353
354struct TriggerRenderContext<'a> {
355    id: &'a ElementId,
356    state: &'a Rc<MenuState>,
357    focus: &'a MenuFocus,
358    request: &'a Expand,
359    visual: TriggerVisual,
360    style: MenuStyle,
361    shadow: Hsla,
362    scale: f32,
363    visibility_alpha: f32,
364    open: bool,
365    interactive: bool,
366    has_items: bool,
367}
368
369impl FabMenu {
370    fn prepare_focus(
371        &self,
372        open: bool,
373        was_open: bool,
374        state: &Rc<MenuState>,
375        window: &mut Window,
376        cx: &mut App,
377    ) -> MenuFocus {
378        let interactive = state.interactive.get();
379        let has_items = !self.items.is_empty();
380        let trigger = self
381            .focus
382            .clone()
383            .unwrap_or_else(|| focus_handle(&self.id, "trigger-focus", window, cx));
384        let scope = focus_handle(&self.id, "menu-scope", window, cx);
385        let handles = self
386            .items
387            .iter()
388            .map(|item| {
389                let item_id = ElementId::from((self.id.clone(), item.id.clone()));
390                (focus_handle(&item_id, "focus", window, cx), !item.disabled)
391            })
392            .collect::<Vec<_>>();
393        let first = handles
394            .iter()
395            .find(|(_, enabled)| *enabled)
396            .map(|(handle, _)| handle.clone());
397        let open_focus = first.unwrap_or_else(|| scope.clone());
398        if open && !was_open {
399            let state = state.clone();
400            let open_focus = open_focus.clone();
401            window.defer(cx, move |window, cx| {
402                if state.open.get() {
403                    open_focus.focus(window, cx);
404                }
405            });
406        } else if !open
407            && ((was_open && scope.contains_focused(window, cx))
408                || (!interactive && trigger.is_focused(window)))
409        {
410            let state = state.clone();
411            let trigger_focus = trigger.clone();
412            let previous_focus = window.focused(cx);
413            window.defer(cx, move |window, cx| {
414                let current = window.focused(cx);
415                if state.open.get()
416                    || interactive != state.interactive.get()
417                    || current.is_some() && current != previous_focus
418                {
419                    return;
420                }
421                if interactive && has_items {
422                    trigger_focus.focus(window, cx);
423                } else if current.is_some() {
424                    window.blur(cx);
425                }
426            });
427        }
428        MenuFocus {
429            trigger,
430            scope,
431            open_focus,
432            handles,
433        }
434    }
435
436    fn expansion_request(
437        &self,
438        state: &Rc<MenuState>,
439        focus: &MenuFocus,
440        has_items: bool,
441    ) -> Expand {
442        let state = state.clone();
443        let trigger_focus = focus.trigger.clone();
444        let scope = focus.scope.clone();
445        let open_focus = focus.open_focus.clone();
446        let controlled = self.expanded.is_some();
447        let on_change = self.on_expanded_change.clone();
448        Rc::new(move |expanded, window, cx| {
449            if !state.interactive.get() || !has_items || state.open.get() == expanded {
450                return;
451            }
452            if !controlled {
453                state.open.set(expanded);
454                if expanded {
455                    open_focus.focus(window, cx);
456                } else if scope.contains_focused(window, cx) {
457                    trigger_focus.focus(window, cx);
458                }
459                window.refresh();
460            }
461            if let Some(on_change) = &on_change {
462                on_change(expanded, window, cx);
463            }
464        })
465    }
466
467    fn trigger_visual(
468        &self,
469        palette: (Hsla, Hsla, Hsla, Hsla),
470        cap: f32,
471        reveal: f32,
472        direction: Direction,
473    ) -> TriggerVisual {
474        let (fill, ink, strong_fill, strong_ink) = palette;
475        let (initial_size, initial_radius, initial_icon) = match self.size {
476            FabSize::Small => (56., 16., 24.),
477            FabSize::Medium => (80., 20., 28.),
478            FabSize::Large => (96., 28., 36.),
479        };
480        let collapsed = TriggerVisual {
481            size: initial_size,
482            corners: [initial_radius; 4],
483            icon: initial_icon,
484            fill,
485            ink,
486            elevation: Elevation::Level3.dp(),
487        }
488        .at(self.trigger_style.collapsed, cap, direction);
489        let expanded = TriggerVisual {
490            size: 56.,
491            corners: [28.; 4],
492            icon: 20.,
493            fill: strong_fill,
494            ink: strong_ink,
495            elevation: Elevation::Level3.dp(),
496        }
497        .at(self.trigger_style.expanded, cap, direction);
498        collapsed.interpolate(expanded, reveal)
499    }
500
501    fn render_trigger_layer(
502        &mut self,
503        ctx: &TriggerRenderContext<'_>,
504        window: &mut Window,
505        cx: &mut App,
506    ) -> AnyElement {
507        let content = if ctx.open {
508            self.close_content.take()
509        } else {
510            self.open_content.take()
511        };
512        let icon_size = px(ctx.visual.icon * ctx.scale);
513        let content = match content {
514            Some(TriggerContent::Custom(content)) => content,
515            Some(TriggerContent::Icon(icon)) => icon_content(icon, icon_size).into_any_element(),
516            None => Icon::new(if ctx.open { IconName::Close } else { self.icon })
517                .size(icon_size)
518                .into_any_element(),
519        };
520        let content = decorative_content((ctx.id.clone(), "trigger-content").into(), content)
521            .into_any_element();
522        if !ctx.interactive {
523            return ctx
524                .visual
525                .decorate(
526                    div().bg(ctx.visual.fill).text_color(ctx.visual.ink),
527                    ctx.scale,
528                    ctx.shadow,
529                    content,
530                )
531                .opacity(ctx.visibility_alpha)
532                .into_any_element();
533        }
534        let activate = {
535            let state = ctx.state.clone();
536            let request = ctx.request.clone();
537            move |window: &mut Window, cx: &mut App| request(!state.open.get(), window, cx)
538        };
539        let accessibility = activate.clone();
540        let request_accessibility = ctx.request.clone();
541        let keyboard = activate.clone();
542        let open = ctx.open;
543        let trigger = Button::new((ctx.id.clone(), "trigger"))
544            .track_focus(&ctx.focus.trigger)
545            .accessibility_label(if open {
546                self.close_label.clone()
547            } else {
548                self.open_label.clone()
549            })
550            .aria_expanded(open)
551            .disabled(!ctx.has_items)
552            .when(ctx.has_items, |trigger| {
553                trigger
554                    .on_click(move |_, window, cx| activate(window, cx))
555                    .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
556                        accessibility(window, cx)
557                    })
558                    .on_a11y_action(
559                        if open {
560                            gpui::AccessibleAction::Collapse
561                        } else {
562                            gpui::AccessibleAction::Expand
563                        },
564                        move |_, window, cx| request_accessibility(!open, window, cx),
565                    )
566                    .capture_key_down(move |event, window, cx| {
567                        activate_key(event, window, cx, &keyboard)
568                    })
569            });
570        let trigger = ctx
571            .visual
572            .decorate(
573                style_button(
574                    trigger,
575                    ctx.visual.fill,
576                    ctx.visual.ink,
577                    ctx.style.ring,
578                    ctx.has_items,
579                ),
580                ctx.scale,
581                ctx.shadow,
582                content,
583            )
584            .opacity(ctx.visibility_alpha);
585        let measure_trigger = ctx.state.clone();
586        let trigger = div().relative().child(trigger).child(
587            canvas(
588                move |bounds, _, _| measure_trigger.trigger_bounds.set(bounds),
589                |_, _, _, _| {},
590            )
591            .absolute()
592            .inset_0(),
593        );
594        let mut popup = Popup::new((ctx.id.clone(), "popup"), trigger)
595            .anchor(ctx.style.anchor)
596            .offset(px(8.));
597        if open {
598            let outside = ctx.request.clone();
599            let exclude_trigger = ctx.state.clone();
600            let record_bounds = ctx.state.clone();
601            let panel = div()
602                .id((ctx.id.clone(), "panel"))
603                .occlude()
604                .on_mouse_down_out(move |event, window, cx| {
605                    if !exclude_trigger
606                        .trigger_bounds
607                        .get()
608                        .contains(&event.position)
609                    {
610                        outside(false, window, cx);
611                    }
612                })
613                .child(self.render_actions(
614                    &ctx.focus.handles,
615                    ctx.state,
616                    ctx.request,
617                    ctx.style,
618                    window,
619                ));
620            popup = popup
621                .on_position(move |position, _| record_bounds.bounds.set(position.bounds))
622                .content(ThemeScope::inherit(panel, window, cx));
623        }
624        popup.into_any_element()
625    }
626
627    fn render_actions(
628        &mut self,
629        handles: &[(FocusHandle, bool)],
630        state: &Rc<MenuState>,
631        request: &Expand,
632        style: MenuStyle,
633        window: &Window,
634    ) -> AnyElement {
635        let available_height = (window.viewport_size().height - px(24.)).max(px(0.));
636        let items = std::mem::take(&mut self.items).into_iter().zip(handles);
637        if !state.open.get() {
638            return div()
639                .id((self.id.clone(), "exit"))
640                .test_support()
641                .role(Role::Group)
642                .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
643                .max_h(available_height)
644                .overflow_y_hidden()
645                .track_scroll(&state.scroll)
646                .children(items.map(|(item, _)| {
647                    let colors = style.colors(&item);
648                    menu_row(menu_pill(div(), item, style, colors), style.anchor)
649                }))
650                .into_any_element();
651        }
652
653        let key_handles = handles.to_vec();
654        let key_scroll = state.scroll.clone();
655        div()
656            .id((self.id.clone(), "actions"))
657            .test_support()
658            .role(Role::Menu)
659            .aria_label(self.open_label.clone())
660            .max_h(available_height)
661            .overflow_y_scroll()
662            .track_scroll(&state.scroll)
663            .on_key_down(move |event, window, cx| {
664                if event.keystroke.modifiers.modified() {
665                    return;
666                }
667                let focus = key_handles
668                    .iter()
669                    .map(|(handle, enabled)| (handle, *enabled))
670                    .collect::<Vec<_>>();
671                if let Some(index) = move_roving_focus(
672                    &focus,
673                    &event.keystroke.key,
674                    Axis::Vertical,
675                    Direction::Ltr,
676                    window,
677                    cx,
678                ) {
679                    key_scroll.scroll_to_item(index);
680                    cx.stop_propagation();
681                }
682            })
683            .children(items.map(|(mut item, (focus, enabled))| {
684                let invoke = item.invoke.take();
685                let request = request.clone();
686                let open = state.clone();
687                let activate = move |window: &mut Window, cx: &mut App| {
688                    if open.open.get() {
689                        request(false, window, cx);
690                        if let Some(invoke) = &invoke {
691                            invoke(window, cx);
692                        }
693                    }
694                };
695                let keyboard = activate.clone();
696                let accessibility = activate.clone();
697                let colors = style.colors(&item);
698                let button = Button::new((self.id.clone(), item.id.clone()))
699                    .role(Role::MenuItem)
700                    .accessibility_label(item.label.clone())
701                    .track_focus(focus)
702                    .disabled(!enabled)
703                    .when(*enabled, |button| {
704                        button
705                            .on_click(move |_, window, cx| activate(window, cx))
706                            .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
707                                accessibility(window, cx)
708                            })
709                            .capture_key_down(move |event, window, cx| {
710                                activate_key(event, window, cx, &keyboard)
711                            })
712                    });
713                menu_row(
714                    menu_pill(
715                        style_button(button, colors.0, colors.1, style.ring, *enabled),
716                        item,
717                        style,
718                        colors,
719                    ),
720                    style.anchor,
721                )
722            }))
723            .into_any_element()
724    }
725}
726
727fn menu_row(child: impl IntoElement, anchor: Anchor) -> impl IntoElement {
728    let row = div().flex().px(px(4.)).py(px(2.));
729    match anchor {
730        Anchor::BottomLeft => row.justify_start(),
731        Anchor::BottomCenter => row.justify_center(),
732        _ => row.justify_end(),
733    }
734    .child(child)
735}
736
737fn icon_content(icon: AnyElement, side: Pixels) -> gpui::Div {
738    div()
739        .size(side)
740        .flex_none()
741        .flex()
742        .items_center()
743        .justify_center()
744        .overflow_hidden()
745        .text_size(side)
746        .line_height(side)
747        .child(icon)
748}
749
750fn decorative_content(id: ElementId, content: impl IntoElement) -> impl IntoElement {
751    div()
752        .id(id)
753        .role(Role::Group)
754        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
755        .min_w_0()
756        .max_w_full()
757        .overflow_hidden()
758        .child(content)
759}
760
761fn menu_pill<E>(element: E, item: FabMenuItem, style: MenuStyle, (fill, ink): (Hsla, Hsla)) -> E
762where
763    E: Styled + ParentElement + FluentBuilder,
764{
765    let width = style.max_width * style.reveal;
766    let label = item.content.unwrap_or_else(|| {
767        Text::new(item.label)
768            .role(TypeRole::TitleMedium)
769            .into_any_element()
770    });
771    element
772        .flex()
773        .flex_row()
774        .flex_none()
775        .when(style.rtl, Styled::flex_row_reverse)
776        .items_center()
777        .justify_end()
778        .overflow_hidden()
779        .min_h(px(56.))
780        .max_w(width)
781        .rounded_full()
782        .bg(fill)
783        .text_color(ink)
784        .opacity(style.alpha)
785        .px(px(24.).min(width / 3.))
786        .gap(px(8.))
787        .children(item.icon.map(|icon| {
788            icon_content(icon, px(24.))
789                .id((ElementId::from("fab-menu-icon"), item.id.clone()))
790                .role(Role::Group)
791                .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
792        }))
793        .child(decorative_content(
794            (ElementId::from("fab-menu-label"), item.id).into(),
795            label,
796        ))
797}
798
799#[derive(Clone, Copy)]
800struct TriggerVisual {
801    size: f32,
802    corners: [f32; 4],
803    icon: f32,
804    fill: Hsla,
805    ink: Hsla,
806    elevation: f32,
807}
808
809impl TriggerVisual {
810    fn at(self, appearance: FabMenuTriggerAppearance, cap: f32, direction: Direction) -> Self {
811        let dimension = |value: Option<Pixels>, default| {
812            value
813                .map(f32::from)
814                .filter(|value| value.is_finite() && *value > 0.)
815                .unwrap_or(default)
816        };
817        let size = dimension(appearance.size, self.size).min(cap);
818        Self {
819            size,
820            corners: appearance
821                .shape
822                .unwrap_or(CornerShape::Radii(self.corners))
823                .radii(size, size, direction),
824            icon: dimension(appearance.icon_size, self.icon).min(size),
825            fill: appearance.container_color.unwrap_or(self.fill),
826            ink: appearance.content_color.unwrap_or(self.ink),
827            elevation: appearance.elevation.map_or(self.elevation, Elevation::dp),
828        }
829    }
830
831    fn interpolate(self, end: Self, fraction: f32) -> Self {
832        let mix = |a, b| a + (b - a) * fraction;
833        let color = |a, b| {
834            if fraction == 0. {
835                return a;
836            }
837            if fraction == 1. {
838                return b;
839            }
840            let a = Rgba::from(a);
841            let b = Rgba::from(b);
842            Rgba {
843                r: mix(a.r, b.r),
844                g: mix(a.g, b.g),
845                b: mix(a.b, b.b),
846                a: mix(a.a, b.a),
847            }
848            .into()
849        };
850        Self {
851            size: mix(self.size, end.size),
852            corners: std::array::from_fn(|index| mix(self.corners[index], end.corners[index])),
853            icon: mix(self.icon, end.icon),
854            fill: color(self.fill, end.fill),
855            ink: color(self.ink, end.ink),
856            elevation: mix(self.elevation, end.elevation),
857        }
858    }
859
860    fn decorate<E: Styled + ParentElement>(
861        self,
862        element: E,
863        scale: f32,
864        shadow: Hsla,
865        content: AnyElement,
866    ) -> E {
867        let [tl, tr, br, bl] = self.corners.map(|radius| px(radius * scale));
868        element
869            .size(px(self.size * scale))
870            .flex_none()
871            .flex()
872            .justify_center()
873            .items_center()
874            .rounded_tl(tl)
875            .rounded_tr(tr)
876            .rounded_br(br)
877            .rounded_bl(bl)
878            .shadow(elevation_shadows(self.elevation * scale, scale, shadow))
879            .child(content)
880    }
881}
882
883impl RenderOnce for FabMenu {
884    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
885        let retained = window.use_keyed_state((self.id.clone(), "menu-state"), cx, |_, _| {
886            Rc::new(MenuState::default())
887        });
888        let state = retained.read(cx).clone();
889        let theme = current_material_theme(window, cx);
890        let direction = theme.layout.direction;
891        let motion = theme.motion;
892        let tone = |role| color(theme.colors.color(role));
893        let (background, foreground, strong, strong_ink) = fab_roles(self.color);
894        let fill = tone(background);
895        let ink = tone(foreground);
896        let strong_fill = tone(strong);
897        let strong_ink = tone(strong_ink);
898        let ring = tone(ColorRole::OnSurface);
899        let shadow = tone(ColorRole::Shadow);
900        let viewport = window.viewport_size();
901        let cap = f32::from(viewport.width.min(viewport.height)).max(0.);
902        let show = self.visible.unwrap_or(true);
903        let (scale, visibility_alpha, pivot) =
904            self.visible.map_or((1., 1., point(0.5, 0.5)), |visible| {
905                self.visibility_animation
906                    .frame(&self.id, visible, cap.max(1.), window, cx)
907            });
908        let interactive = show && cap > 0. && scale > 0. && visibility_alpha > 0.;
909        state.interactive.set(interactive);
910        let has_items = !self.items.is_empty();
911        let open = interactive && has_items && self.expanded.unwrap_or_else(|| state.open.get());
912        let was_open = state.open.replace(open);
913        let alpha = animate(
914            (self.id.clone(), "menu-alpha"),
915            f32::from(open),
916            motion.spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
917            window,
918            cx,
919        )
920        .clamp(0., 1.);
921        let reveal = animate(
922            (self.id.clone(), "menu-reveal"),
923            f32::from(open),
924            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
925            window,
926            cx,
927        )
928        .clamp(0., 1.);
929
930        let id = self.id.clone();
931        let focus = self.prepare_focus(open, was_open, &state, window, cx);
932        let request = self.expansion_request(&state, &focus, has_items);
933        let visual =
934            self.trigger_visual((fill, ink, strong_fill, strong_ink), cap, reveal, direction);
935        let scale = if visual.size > 0. {
936            scale.min(cap / visual.size)
937        } else {
938            0.
939        };
940        let anchor = self.alignment.anchor(direction);
941        let style = MenuStyle {
942            fill,
943            ink,
944            ring,
945            rtl: direction == Direction::Rtl,
946            anchor,
947            max_width: (viewport.width - px(24.)).clamp(px(0.), px(360.)),
948            alpha,
949            reveal,
950        };
951        let exit_bounds = state.bounds.get();
952        let mut root = div().id(id.clone()).flex_none();
953        if visibility_alpha > 0. {
954            let side = px(visual.size);
955            let mut footprint = div().relative().size(side).flex_none();
956            if scale > 0. {
957                let trigger_ctx = TriggerRenderContext {
958                    id: &id,
959                    state: &state,
960                    focus: &focus,
961                    request: &request,
962                    visual,
963                    style,
964                    shadow,
965                    scale,
966                    visibility_alpha,
967                    open,
968                    interactive,
969                    has_items,
970                };
971                let layer = self.render_trigger_layer(&trigger_ctx, window, cx);
972                if self.visible.is_none() {
973                    root = root.child(layer);
974                } else {
975                    let distance = side * (1. - scale);
976                    footprint = footprint.child(
977                        div()
978                            .absolute()
979                            .left(distance * pivot.x)
980                            .top(distance * pivot.y)
981                            .child(layer),
982                    );
983                    root = root.child(footprint);
984                }
985            } else {
986                root = root.child(footprint);
987            }
988        }
989        if !open && alpha > 0. && exit_bounds.size.width > px(0.) {
990            let x = match anchor {
991                Anchor::BottomLeft => exit_bounds.left(),
992                Anchor::BottomCenter => exit_bounds.center().x,
993                _ => exit_bounds.right(),
994            };
995            root = root.child(
996                deferred(
997                    Positioner::corner(anchor, point(x, exit_bounds.bottom())).child(
998                        ThemeScope::inherit(
999                            self.render_actions(&focus.handles, &state, &request, style, window),
1000                            window,
1001                            cx,
1002                        ),
1003                    ),
1004                )
1005                .with_priority(100),
1006            );
1007        }
1008        if open {
1009            root.on_key_down(move |event, window, cx| {
1010                if event.keystroke.key == "escape" {
1011                    request(false, window, cx);
1012                    cx.stop_propagation();
1013                }
1014            })
1015            .focus_trap((id, "focus-trap"), &focus.scope)
1016            .into_any_element()
1017        } else {
1018            root.into_any_element()
1019        }
1020    }
1021}
1022
1023fn fab_roles(value: FabColor) -> (ColorRole, ColorRole, ColorRole, ColorRole) {
1024    use ColorRole::*;
1025    match value {
1026        FabColor::Primary => (PrimaryContainer, OnPrimaryContainer, Primary, OnPrimary),
1027        FabColor::Secondary => (
1028            SecondaryContainer,
1029            OnSecondaryContainer,
1030            Secondary,
1031            OnSecondary,
1032        ),
1033        FabColor::Tertiary => (TertiaryContainer, OnTertiaryContainer, Tertiary, OnTertiary),
1034        FabColor::PrimaryStrong => (Primary, OnPrimary, PrimaryContainer, OnPrimaryContainer),
1035        FabColor::SecondaryStrong => (
1036            Secondary,
1037            OnSecondary,
1038            SecondaryContainer,
1039            OnSecondaryContainer,
1040        ),
1041        FabColor::TertiaryStrong => (Tertiary, OnTertiary, TertiaryContainer, OnTertiaryContainer),
1042    }
1043}