Skip to main content

gpui_material_components/navigation/
bottom_app_bar.rs

1use gpui::{
2    AnyElement, App, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
3    Pixels, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
4    Window, div, prelude::FluentBuilder, px,
5};
6use gpui_base::TestSupportExt;
7use gpui_material_foundation::{
8    Surface, animate, current_material_strings, current_material_theme, resolve_edges,
9};
10use gpui_material_theme::{
11    ColorRole, CornerRole, Direction, Elevation, LogicalEdges, MotionKind, MotionSpec, MotionSpeed,
12};
13
14use super::app_bar::{self, AppBarScrollBehavior, AppBarScrollState};
15
16/// Optional pigment overrides for [`BottomAppBar`]. Omitted fields use the window theme.
17#[derive(Clone, Copy, Debug, Default, PartialEq)]
18pub struct BottomAppBarColors {
19    /// Background color override for the bottom app bar surface.
20    pub container: Option<Hsla>,
21    /// Inherited foreground color override for bar actions and content.
22    pub content: Option<Hsla>,
23}
24
25/// Material 3 Bottom App Bar (80 dp default height, `SurfaceContainer`, `Elevation::Level2`).
26/// Mounts seamlessly in [`crate::Scaffold::bottom_bar`] or standalone layouts.
27#[derive(IntoElement)]
28pub struct BottomAppBar {
29    id: ElementId,
30    actions: Vec<AnyElement>,
31    fab: Option<AnyElement>,
32    height: Option<Pixels>,
33    colors: BottomAppBarColors,
34    padding: LogicalEdges,
35    elevation: Elevation,
36    scroll: Option<ScrollHandle>,
37    scroll_behavior: Option<(AppBarScrollBehavior, Entity<AppBarScrollState>)>,
38    accessible_label: Option<SharedString>,
39}
40
41impl BottomAppBar {
42    /// Default Material 3 bottom app bar height (80 dp).
43    pub const DEFAULT_HEIGHT: Pixels = px(80.);
44
45    /// Default Material 3 bottom app bar padding (4 dp start, 16 dp end, 12 dp vertical).
46    pub const DEFAULT_PADDING: LogicalEdges = LogicalEdges::new(12., 16., 12., 4.);
47
48    /// Creates a bottom app bar with the given element ID and default Material 3 styling.
49    pub fn new(id: impl Into<ElementId>) -> Self {
50        Self {
51            id: id.into(),
52            actions: Vec::new(),
53            fab: None,
54            height: None,
55            colors: BottomAppBarColors::default(),
56            padding: Self::DEFAULT_PADDING,
57            elevation: Elevation::Level2,
58            scroll: None,
59            scroll_behavior: None,
60            accessible_label: None,
61        }
62    }
63
64    /// Appends one leading action control (typically an `IconButton`).
65    pub fn action(mut self, action: impl IntoElement) -> Self {
66        self.actions.push(action.into_any_element());
67        self
68    }
69
70    /// Appends multiple leading action controls in logical start order.
71    pub fn actions(mut self, actions: impl IntoIterator<Item = AnyElement>) -> Self {
72        self.actions.extend(actions);
73        self
74    }
75
76    /// Places a docked/embedded floating action button at the logical trailing end.
77    pub fn fab(mut self, fab: impl IntoElement) -> Self {
78        self.fab = Some(fab.into_any_element());
79        self
80    }
81
82    /// Sets the bar height in logical pixels. Defaults to 80 dp scaled by theme density.
83    pub fn height(mut self, height: Pixels) -> Self {
84        let value = f32::from(height);
85        if value.is_finite() && value > 0. {
86            self.height = Some(height);
87        }
88        self
89    }
90
91    /// Overrides container and inherited content colors independently.
92    pub fn colors(mut self, colors: BottomAppBarColors) -> Self {
93        self.colors = colors;
94        self
95    }
96
97    /// Overrides logical inner insets.
98    pub fn padding(mut self, padding: LogicalEdges) -> Self {
99        self.padding = padding.sanitize();
100        self
101    }
102
103    /// Sets the surface tonal and shadow elevation. Defaults to `Elevation::Level2`.
104    pub fn elevation(mut self, elevation: Elevation) -> Self {
105        self.elevation = elevation;
106        self
107    }
108
109    /// Links a GPUI content `ScrollHandle` for scroll-driven hiding when `scroll_behavior` is set.
110    pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
111        self.scroll = Some(scroll.clone());
112        self
113    }
114
115    /// Configures hide-on-scroll behavior backed by a retained `Entity<AppBarScrollState>`.
116    pub fn scroll_behavior(
117        mut self,
118        behavior: AppBarScrollBehavior,
119        state: &Entity<AppBarScrollState>,
120    ) -> Self {
121        self.scroll_behavior = Some((behavior, state.clone()));
122        self
123    }
124
125    /// Sets the accessible name for the `Role::Toolbar` landmark. Defaults to
126    /// [`gpui_material_theme::MaterialStrings::bottom_app_bar`] (`"Bottom app bar"`).
127    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
128        self.accessible_label = Some(label.into());
129        self
130    }
131}
132
133impl RenderOnce for BottomAppBar {
134    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
135        let theme = current_material_theme(window, cx);
136        let direction = theme.layout.direction;
137        let rtl = direction == Direction::Rtl;
138        let full_height = self.height.map_or_else(
139            || {
140                theme
141                    .layout
142                    .density
143                    .interactive_size(f32::from(Self::DEFAULT_HEIGHT))
144            },
145            f32::from,
146        );
147        let full_height_px = px(full_height);
148
149        let collapsed_fraction = if let Some((behavior, state)) = &self.scroll_behavior {
150            let handle_offset = self
151                .scroll
152                .as_ref()
153                .map(|handle| app_bar::length(-handle.offset().y).unwrap_or(0.));
154            let position = state.update(cx, |state, _| {
155                state.prepare(handle_offset, full_height, Some(*behavior), true)
156            });
157            let motion = if position.settling && !cx.reduce_motion() {
158                theme
159                    .motion
160                    .spec(MotionKind::Spatial, MotionSpeed::Default, false)
161            } else {
162                MotionSpec::Instant
163            };
164            let fraction = animate(
165                (self.id.clone(), "bottom-app-bar-collapse"),
166                position.target,
167                motion,
168                window,
169                cx,
170            )
171            .clamp(0., 1.);
172            if state.update(cx, |state, _| state.display(position, fraction)) {
173                let weak = state.downgrade();
174                window.defer(cx, move |_, cx| {
175                    let _ = weak.update(cx, |_, cx| cx.notify());
176                });
177            }
178            fraction
179        } else {
180            0.
181        };
182
183        let visible_height = px((full_height * (1. - collapsed_fraction)).max(0.));
184        let scope = window
185            .use_keyed_state((self.id.clone(), "bottom-app-bar-focus"), cx, |_, cx| {
186                cx.focus_handle().tab_stop(false)
187            })
188            .read(cx)
189            .clone();
190
191        if visible_height <= px(0.5) {
192            if scope.contains_focused(window, cx) {
193                let focus = window.focused(cx);
194                window.defer(cx, move |window, cx| {
195                    if window
196                        .focused(cx)
197                        .is_none_or(|current| Some(current) == focus)
198                    {
199                        window.focus_next(cx);
200                    }
201                });
202            }
203            return div()
204                .id(self.id)
205                .test_support()
206                .w_full()
207                .h(px(0.))
208                .overflow_hidden()
209                .into_any_element();
210        }
211
212        let edges = resolve_edges(self.padding, direction);
213
214        let actions_row = div()
215            .id((self.id.clone(), "actions"))
216            .test_support()
217            .flex()
218            .items_center()
219            .gap(px(4.))
220            .when(rtl, Styled::flex_row_reverse)
221            .children(self.actions);
222
223        let bar_row = div()
224            .w_full()
225            .h(full_height_px)
226            .pl(edges.left)
227            .pr(edges.right)
228            .pt(edges.top)
229            .pb(edges.bottom)
230            .flex()
231            .items_center()
232            .justify_between()
233            .when(rtl, Styled::flex_row_reverse)
234            .child(actions_row)
235            .children(self.fab.map(|fab| {
236                div()
237                    .id((self.id.clone(), "fab-slot"))
238                    .test_support()
239                    .flex_none()
240                    .child(fab)
241            }));
242
243        let surface = Surface::new(ColorRole::SurfaceContainer)
244            .shape(CornerRole::None.shape())
245            .tonal_elevation(self.elevation)
246            .shadow_elevation(self.elevation)
247            .when_some(self.colors.container, Surface::container_color)
248            .when_some(self.colors.content, Surface::content_color)
249            .w_full()
250            .h(visible_height)
251            .overflow_hidden()
252            .child(bar_row);
253
254        let accessible_label = self.accessible_label.unwrap_or_else(|| {
255            SharedString::from(current_material_strings(window, cx).bottom_app_bar.clone())
256        });
257
258        div()
259            .id(self.id)
260            .test_support()
261            .role(Role::Toolbar)
262            .aria_label(accessible_label)
263            .track_focus(&scope)
264            .w_full()
265            .h(visible_height)
266            .flex_none()
267            .overflow_hidden()
268            .child(surface)
269            .into_any_element()
270    }
271}