Skip to main content

frust_material/appbar/
bottom.rs

1// Ported from material_3_expressive v1.0.8 (MIT, © 2026 Paa Developments),
2// `lib/components/app_bars/m3e_app_bars.dart`'s `M3EAppBar.bottom` constructor
3// and its `_buildBottom` helper. See `super`'s module docs for the family's
4// porting decisions.
5
6//! The bottom app bar ([`bottom_app_bar`]): an action row docked to the bottom
7//! edge with an optional prominent/FAB slot at the trailing edge. Read
8//! [`super`]'s module docs first for the shared slot contract and metrics.
9//!
10//! Layout mirrors upstream's own `Row`: the actions run from the leading edge
11//! in reading order, a spacer eats the rest, and the fab slot (if any) sits
12//! flush against the trailing edge, everything vertically centered in the
13//! [`AppBarMetrics::bottom_height`] band. The fab slot is an opaque
14//! caller-supplied view like every other slot here — typically a real
15//! [`fn@crate::fab`], to which this widget adds no chrome of its own.
16//!
17//! **No cutout/notch.** Upstream's bottom bar has none — it is a plain
18//! `Material` with the FAB inside the same row (`_buildBottom`), not Flutter's
19//! own `BottomAppBar(shape: NotchedShape)`. This port carries that shape over
20//! rather than inventing a notch the reference never draws.
21//!
22//! The band is density-independent: `M3EAppBar.bottom` pins `density: regular`
23//! and reads `bottomHeight` straight off the theme, so there is no compact
24//! bottom bar to port. Its container role is `colors.surface_container`
25//! (upstream's `bottomBackgroundColor`), one step up from the top bar's
26//! `colors.surface`, and its corners are square with no shape-family knob —
27//! again upstream's own fixed choices for this constructor.
28
29use frust::Theme;
30use frust::authoring::{
31    AnyView, BoxConstraints, BuildCtx, ChangeFlags, ChildPod, EventCtx, EventResult, InputEvent,
32    LayoutCtx, PaintCtx, PaintScene, Role, SemanticsCtx, View, Widget, build_child,
33    rebuild_children, route_event, teardown_child, visit_children,
34};
35use kurbo::{Point, Size};
36use peniko::Color;
37
38use super::{
39    AppBarDensity, AppBarMetrics, GAP, PAD_X, finite_or_zero, push_bar_semantics,
40    resolve_bottom_container,
41};
42
43/// A declarative M3 bottom app bar. See the [module docs](self).
44pub struct BottomAppBarView<State: 'static> {
45    actions: Vec<AnyView<State>>,
46    fab: Option<AnyView<State>>,
47    background: Option<Color>,
48    semantic_label: Option<String>,
49}
50
51/// Create a bottom app bar with no actions and no fab slot (attach them with
52/// [`BottomAppBarView::actions`]/[`BottomAppBarView::fab`]) — upstream's
53/// `M3EAppBar.bottom`.
54pub fn bottom_app_bar<State: 'static>() -> BottomAppBarView<State> {
55    BottomAppBarView {
56        actions: Vec::new(),
57        fab: None,
58        background: None,
59        semantic_label: None,
60    }
61}
62
63/// PascalCase alias for [`bottom_app_bar`], matching the container view-fn
64/// vocabulary.
65#[allow(non_snake_case)]
66pub fn BottomAppBar<State: 'static>() -> BottomAppBarView<State> {
67    bottom_app_bar()
68}
69
70impl<State: 'static> BottomAppBarView<State> {
71    /// Attach the action slots, in reading order from the leading edge. Tint is
72    /// each supplied view's own responsibility — see [`super`]'s slot contract.
73    pub fn actions(mut self, actions: Vec<AnyView<State>>) -> Self {
74        self.actions = actions;
75        self
76    }
77
78    /// Attach the prominent/FAB slot at the trailing edge
79    /// (`floatingActionButton`).
80    pub fn fab(mut self, fab: AnyView<State>) -> Self {
81        self.fab = Some(fab);
82        self
83    }
84
85    /// Override the container fill, winning over the theme role and its
86    /// fallback alike.
87    pub fn background(mut self, color: Color) -> Self {
88        self.background = Some(color);
89        self
90    }
91
92    /// Label the bar's accessibility container. Unlabelled by default — a
93    /// bottom bar owns no title text to borrow one from.
94    pub fn semantic_label(mut self, label: impl Into<String>) -> Self {
95        self.semantic_label = Some(label.into());
96        self
97    }
98}
99
100/// Collect `view`'s actions followed by its fab slot (if any) into one ordered
101/// slice of [`AnyView`] references — the order the pods, hit-testing, and
102/// semantics all keep.
103fn slot_views<State: 'static>(view: &BottomAppBarView<State>) -> Vec<&AnyView<State>> {
104    let mut views = Vec::with_capacity(view.actions.len() + usize::from(view.fab.is_some()));
105    views.extend(view.actions.iter());
106    if let Some(fab) = &view.fab {
107        views.push(fab);
108    }
109    views
110}
111
112/// The retained widget for a [`BottomAppBarView`].
113pub struct BottomAppBarWidget {
114    /// Every action, then the fab slot (if any).
115    slots: Vec<ChildPod>,
116    action_count: usize,
117    has_fab: bool,
118    background: Option<Color>,
119    label: Option<String>,
120}
121
122impl<State: 'static> View<State> for BottomAppBarView<State> {
123    type Element = BottomAppBarWidget;
124
125    fn build(&self, ctx: &mut BuildCtx<'_>) -> BottomAppBarWidget {
126        let slots = slot_views(self)
127            .into_iter()
128            .map(|view| build_child(view, ctx))
129            .collect();
130        BottomAppBarWidget {
131            slots,
132            action_count: self.actions.len(),
133            has_fab: self.fab.is_some(),
134            background: self.background,
135            label: self.semantic_label.clone(),
136        }
137    }
138
139    fn rebuild(
140        &self,
141        prev: &Self,
142        element: &mut BottomAppBarWidget,
143        ctx: &mut BuildCtx<'_>,
144    ) -> ChangeFlags {
145        let mut flags = rebuild_children(
146            &slot_views(prev),
147            &slot_views(self),
148            &mut element.slots,
149            ctx,
150            |view: &&AnyView<State>| *view,
151            |_| None,
152        );
153
154        if element.action_count != self.actions.len() {
155            element.action_count = self.actions.len();
156            flags |= ChangeFlags::LAYOUT;
157        }
158        let has_fab = self.fab.is_some();
159        if element.has_fab != has_fab {
160            element.has_fab = has_fab;
161            flags |= ChangeFlags::LAYOUT;
162        }
163        if element.background != self.background {
164            element.background = self.background;
165            flags |= ChangeFlags::PAINT;
166        }
167        element.label = self.semantic_label.clone();
168        flags
169    }
170
171    fn teardown(&self, element: &mut BottomAppBarWidget, ctx: &mut BuildCtx<'_>) {
172        for (view, pod) in slot_views(self).into_iter().zip(element.slots.iter_mut()) {
173            teardown_child(view, pod, ctx);
174        }
175    }
176}
177
178impl Widget for BottomAppBarWidget {
179    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
180        let width = finite_or_zero(bc.max().width);
181        let band = AppBarMetrics::for_density(AppBarDensity::Regular).bottom_height;
182        let slot_bc = BoxConstraints::loose(Size::new(f64::INFINITY, band));
183
184        let mut left = PAD_X;
185        for pod in self.slots[..self.action_count].iter_mut() {
186            let size = pod.layout_child(ctx, &slot_bc);
187            pod.set_origin(Point::new(left, (band - size.height) / 2.0));
188            left += size.width + GAP;
189        }
190
191        // The fab slot hugs the trailing edge, whatever the action row's own
192        // width came to (upstream's `Spacer` between the two).
193        if self.has_fab {
194            let pod = &mut self.slots[self.action_count];
195            let size = pod.layout_child(ctx, &slot_bc);
196            pod.set_origin(Point::new(
197                width - PAD_X - size.width,
198                (band - size.height) / 2.0,
199            ));
200        }
201
202        bc.constrain(Size::new(width, band))
203    }
204
205    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
206        let fill = self
207            .background
208            .unwrap_or_else(|| resolve_bottom_container(Theme::from_paint_ctx(ctx)));
209        scene.fill_rect(ctx.origin(), ctx.size(), fill);
210        for pod in &mut self.slots {
211            pod.paint_child(ctx, scene);
212        }
213    }
214
215    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
216        route_event(&mut self.slots, ctx, event)
217    }
218
219    fn semantics(&self, ctx: &mut SemanticsCtx) {
220        push_bar_semantics(ctx, Role::Toolbar, self.label.as_deref(), &self.slots);
221    }
222
223    visit_children!(slots);
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use frust_widgets::test_support::{RecordingScene, leaf_any};
230
231    /// The band every assertion below is written against.
232    const BAND: f64 = 80.0;
233
234    fn ctx(counter: &mut u64) -> BuildCtx<'_> {
235        BuildCtx::new(counter)
236    }
237
238    fn build(view: &BottomAppBarView<()>) -> BottomAppBarWidget {
239        let mut counter = 0u64;
240        View::<()>::build(view, &mut ctx(&mut counter))
241    }
242
243    fn layout(w: &mut BottomAppBarWidget, bc: &BoxConstraints) -> Size {
244        let mut lctx = LayoutCtx::new();
245        w.layout(&mut lctx, bc)
246    }
247
248    #[test]
249    fn actions_run_from_the_leading_edge_and_the_fab_hugs_the_trailing_one() {
250        let view: BottomAppBarView<()> = bottom_app_bar()
251            .actions(vec![
252                leaf_any(24.0, 24.0),
253                leaf_any(24.0, 24.0),
254                leaf_any(24.0, 24.0),
255            ])
256            .fab(leaf_any(56.0, 56.0));
257        let mut w = build(&view);
258        let size = layout(&mut w, &BoxConstraints::loose(Size::new(400.0, 200.0)));
259        assert_eq!(size, Size::new(400.0, BAND));
260
261        assert_eq!(w.slots[0].origin().x, PAD_X);
262        assert_eq!(w.slots[1].origin().x, PAD_X + 24.0 + GAP);
263        assert_eq!(w.slots[2].origin().x, PAD_X + 2.0 * (24.0 + GAP));
264        // The fab is the last pod, flush against the trailing edge.
265        assert_eq!(
266            w.slots[3].origin().x + w.slots[3].size().width,
267            400.0 - PAD_X
268        );
269        // Everything is centered in the band.
270        assert_eq!(w.slots[0].origin().y, (BAND - 24.0) / 2.0);
271        assert_eq!(w.slots[3].origin().y, (BAND - 56.0) / 2.0);
272    }
273
274    #[test]
275    fn a_bar_without_a_fab_still_spans_the_width() {
276        let view: BottomAppBarView<()> = bottom_app_bar().actions(vec![leaf_any(24.0, 24.0)]);
277        let mut w = build(&view);
278        let size = layout(&mut w, &BoxConstraints::loose(Size::new(320.0, 200.0)));
279        assert_eq!(size, Size::new(320.0, BAND));
280        assert_eq!(w.slots.len(), 1);
281    }
282
283    #[test]
284    fn unthemed_paint_uses_the_fallback_container() {
285        let view: BottomAppBarView<()> = bottom_app_bar();
286        let mut w = build(&view);
287        layout(&mut w, &BoxConstraints::loose(Size::new(300.0, 200.0)));
288        let mut scene = RecordingScene::default();
289        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(300.0, BAND));
290        w.paint(&mut pctx, &mut scene);
291        assert_eq!(scene.rects[0].1, Size::new(300.0, BAND));
292    }
293
294    #[test]
295    fn themed_paint_resolves_surface_container() {
296        struct ColorRecorder {
297            colors: Vec<Color>,
298        }
299        impl PaintScene for ColorRecorder {
300            fn fill_rect(&mut self, _o: Point, _s: Size, c: Color) {
301                self.colors.push(c);
302            }
303            fn draw_text(&mut self, _o: Point, _t: &str) {}
304        }
305
306        let theme = crate::baseline();
307        let view: BottomAppBarView<()> = bottom_app_bar();
308        let mut w = build(&view);
309        layout(&mut w, &BoxConstraints::loose(Size::new(300.0, 200.0)));
310        let mut scene = ColorRecorder { colors: Vec::new() };
311        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(300.0, BAND)).with_theme(&theme);
312        w.paint(&mut pctx, &mut scene);
313        assert_eq!(scene.colors[0], theme.scheme().surface_container);
314    }
315
316    #[test]
317    fn rebuild_adopts_a_new_fab_slot() {
318        let mut counter = 0u64;
319        let prev: BottomAppBarView<()> = bottom_app_bar().actions(vec![leaf_any(24.0, 24.0)]);
320        let mut w = View::<()>::build(&prev, &mut ctx(&mut counter));
321        assert!(!w.has_fab);
322
323        let next: BottomAppBarView<()> = bottom_app_bar()
324            .actions(vec![leaf_any(24.0, 24.0)])
325            .fab(leaf_any(56.0, 56.0));
326        let flags = View::<()>::rebuild(&next, &prev, &mut w, &mut ctx(&mut counter));
327        assert!(flags.needs_layout());
328        assert!(w.has_fab);
329        assert_eq!(w.slots.len(), 2);
330    }
331
332    #[test]
333    fn semantics_node_is_a_toolbar_forwarding_every_slot() {
334        // A leaf without its own `semantics()` override (e.g. `leaf_any`)
335        // contributes no node — use `Text` children instead, so the "forwards
336        // every slot" assertion is meaningful (mirrors `toolbar.rs`'s identical
337        // semantics-test note).
338        fn logic(_state: &mut ()) -> BottomAppBarView<()> {
339            bottom_app_bar()
340                .actions(vec![frust::authoring::any::<(), _>(frust::text("One"))])
341                .fab(frust::authoring::any::<(), _>(frust::text("Two")))
342        }
343        let mut root: frust_core::RenderRoot<(), BottomAppBarView<()>> =
344            frust_core::RenderRoot::new();
345        let mut state = ();
346        root.rebuild(&mut logic, &mut state);
347        let mut tcx = frust::authoring::text::TextContext::new();
348        root.layout_with_text(Size::new(300.0, BAND), &mut tcx as &mut dyn std::any::Any);
349        let update = root.semantics();
350        let (_, node) = update
351            .nodes
352            .iter()
353            .find(|(_, n)| n.role() == Role::Toolbar)
354            .expect("a Toolbar node is contributed");
355        assert_eq!(node.children().len(), 2, "actions + fab forwarded");
356    }
357}