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