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