Skip to main content

waft_widgets/widgets/
navigation_toolbar.rs

1//! Flutter counterpart: `widgets/navigation_toolbar.dart`.
2
3use std::any::Any;
4use std::rc::Rc;
5
6use waft_embedder::{Offset, Size, TextDirection};
7use waft_foundation::{App, ValueKey};
8use waft_rendering::{
9    BoxConstraints, ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
10};
11
12use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
13use crate::widgets::basic::{CustomMultiChildLayout, Directionality, LayoutId};
14
15/// [`NavigationToolbar`] is a layout helper to position 3 widgets or groups of
16/// widgets along a horizontal axis that's sensible for an application's
17/// navigation bar such as in Material Design and in iOS.
18///
19/// The [`leading`](Self::leading) and [`trailing`](Self::trailing) widgets occupy the edges of
20/// the widget with reasonable size constraints while the [`middle`](Self::middle) widget
21/// occupies the remaining space in either a center aligned or start aligned fashion.
22///
23/// Either directly use the themed app bars such as the iOS `CupertinoNavigationBar` or wrap
24/// this widget with more theming specifications for your own custom app bar.
25#[derive(Debug)]
26pub struct NavigationToolbar {
27    pub key: Option<KeyRef>,
28    /// Widget to place at the start of the horizontal toolbar.
29    pub leading: Option<WidgetRef>,
30    /// Widget to place in the middle of the horizontal toolbar, occupying
31    /// as much remaining space as possible.
32    pub middle: Option<WidgetRef>,
33    /// Widget to place at the end of the horizontal toolbar.
34    pub trailing: Option<WidgetRef>,
35    /// Whether to align the [`middle`](Self::middle) widget to the center of this widget or
36    /// next to the [`leading`](Self::leading) widget when false.
37    pub center_middle: bool,
38    /// The spacing around the [`middle`](Self::middle) widget on horizontal axis.
39    ///
40    /// Defaults to [`K_MIDDLE_SPACING`](Self::K_MIDDLE_SPACING).
41    pub middle_spacing: f64,
42}
43
44impl NavigationToolbar {
45    /// The default spacing around the [`middle`](Self::middle) widget in dp.
46    pub const K_MIDDLE_SPACING: f64 = 16.0;
47
48    /// Creates a widget that lays out its children in a manner suitable for a
49    /// toolbar; Dart's named arguments are the setters.
50    pub fn new() -> NavigationToolbar {
51        NavigationToolbar {
52            key: None,
53            leading: None,
54            middle: None,
55            trailing: None,
56            center_middle: true,
57            middle_spacing: NavigationToolbar::K_MIDDLE_SPACING,
58        }
59    }
60
61    /// Dart `NavigationToolbar(key:)`.
62    pub fn key(mut self, key: KeyRef) -> NavigationToolbar {
63        self.key = Some(key);
64        self
65    }
66
67    /// Dart `NavigationToolbar(leading:)`.
68    #[cfg_attr(debug_assertions, track_caller)]
69    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> NavigationToolbar {
70        self.leading = Some(leading.into_widget());
71        self
72    }
73
74    /// Dart `NavigationToolbar(middle:)`.
75    #[cfg_attr(debug_assertions, track_caller)]
76    pub fn middle<K>(mut self, middle: impl IntoWidget<K>) -> NavigationToolbar {
77        self.middle = Some(middle.into_widget());
78        self
79    }
80
81    /// Dart `NavigationToolbar(trailing:)`.
82    #[cfg_attr(debug_assertions, track_caller)]
83    pub fn trailing<K>(mut self, trailing: impl IntoWidget<K>) -> NavigationToolbar {
84        self.trailing = Some(trailing.into_widget());
85        self
86    }
87
88    /// Dart `NavigationToolbar(centerMiddle:)`.
89    pub fn center_middle(mut self, center_middle: bool) -> NavigationToolbar {
90        self.center_middle = center_middle;
91        self
92    }
93
94    /// Dart `NavigationToolbar(middleSpacing:)`.
95    pub fn middle_spacing(mut self, middle_spacing: f64) -> NavigationToolbar {
96        self.middle_spacing = middle_spacing;
97        self
98    }
99}
100
101impl Default for NavigationToolbar {
102    fn default() -> NavigationToolbar {
103        NavigationToolbar::new()
104    }
105}
106
107impl StatelessWidget for NavigationToolbar {
108    fn key(&self) -> Option<&KeyRef> {
109        self.key.as_ref()
110    }
111
112    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
113        // Dart's `debugCheckHasDirectionality` is `Directionality::of`'s own panic.
114        let text_direction = Directionality::of(app, context);
115        let mut children = Vec::new();
116        if let Some(leading) = self.leading.clone() {
117            children.push(LayoutId::new(ToolbarSlot::Leading.id(), leading).into_widget());
118        }
119        if let Some(middle) = self.middle.clone() {
120            children.push(LayoutId::new(ToolbarSlot::Middle.id(), middle).into_widget());
121        }
122        if let Some(trailing) = self.trailing.clone() {
123            children.push(LayoutId::new(ToolbarSlot::Trailing.id(), trailing).into_widget());
124        }
125        CustomMultiChildLayout::new(Rc::new(ToolbarLayout {
126            center_middle: self.center_middle,
127            middle_spacing: self.middle_spacing,
128            text_direction,
129        }))
130        .children(children)
131        .into_widget()
132    }
133}
134
135/// Dart's `_ToolbarSlot`.
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
137enum ToolbarSlot {
138    Leading,
139    Middle,
140    Trailing,
141}
142
143impl ToolbarSlot {
144    /// The [`ChildLayoutId`] this slot is known by, Dart's enum value as the `LayoutId.id`.
145    fn id(self) -> ChildLayoutId {
146        Rc::new(ValueKey::new(self))
147    }
148}
149
150/// Dart's `_ToolbarLayout`.
151#[derive(Debug)]
152struct ToolbarLayout {
153    /// If false the middle widget should be start-justified within the space between the
154    /// leading and trailing widgets. If true the middle widget is centered within the toolbar
155    /// (not within the horizontal space between the leading and trailing widgets).
156    center_middle: bool,
157    /// The spacing around middle widget on horizontal axis.
158    middle_spacing: f64,
159    text_direction: TextDirection,
160}
161
162impl MultiChildLayoutDelegate for ToolbarLayout {
163    fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size) {
164        let mut leading_width = 0.0;
165        let mut trailing_width = 0.0;
166
167        if children.has_child(&ToolbarSlot::Leading.id()) {
168            let constraints = BoxConstraints::new()
169                .max_width(size.width())
170                // The height should be exactly the height of the bar.
171                .min_height(size.height())
172                .max_height(size.height());
173            leading_width = children
174                .layout_child(app, &ToolbarSlot::Leading.id(), constraints)
175                .width();
176            let leading_x = match self.text_direction {
177                TextDirection::Rtl => size.width() - leading_width,
178                TextDirection::Ltr => 0.0,
179            };
180            children.position_child(app, &ToolbarSlot::Leading.id(), Offset::new(leading_x, 0.0));
181        }
182
183        if children.has_child(&ToolbarSlot::Trailing.id()) {
184            let constraints = BoxConstraints::loose(size);
185            let trailing_size =
186                children.layout_child(app, &ToolbarSlot::Trailing.id(), constraints);
187            let trailing_x = match self.text_direction {
188                TextDirection::Rtl => 0.0,
189                TextDirection::Ltr => size.width() - trailing_size.width(),
190            };
191            let trailing_y = (size.height() - trailing_size.height()) / 2.0;
192            trailing_width = trailing_size.width();
193            children.position_child(
194                app,
195                &ToolbarSlot::Trailing.id(),
196                Offset::new(trailing_x, trailing_y),
197            );
198        }
199
200        if children.has_child(&ToolbarSlot::Middle.id()) {
201            let max_width =
202                (size.width() - leading_width - trailing_width - self.middle_spacing * 2.0)
203                    .max(0.0);
204            let constraints = BoxConstraints::loose(size).max_width(max_width);
205            let middle_size = children.layout_child(app, &ToolbarSlot::Middle.id(), constraints);
206
207            let middle_start_margin = leading_width + self.middle_spacing;
208            let mut middle_start = middle_start_margin;
209            let middle_y = (size.height() - middle_size.height()) / 2.0;
210            // If the centered middle will not fit between the leading and trailing
211            // widgets, then align its left or right edge with the adjacent boundary.
212            if self.center_middle {
213                middle_start = (size.width() - middle_size.width()) / 2.0;
214                if middle_start + middle_size.width() > size.width() - trailing_width {
215                    middle_start =
216                        size.width() - trailing_width - middle_size.width() - self.middle_spacing;
217                } else if middle_start < middle_start_margin {
218                    middle_start = middle_start_margin;
219                }
220            }
221
222            let middle_x = match self.text_direction {
223                TextDirection::Rtl => size.width() - middle_size.width() - middle_start,
224                TextDirection::Ltr => middle_start,
225            };
226
227            children.position_child(
228                app,
229                &ToolbarSlot::Middle.id(),
230                Offset::new(middle_x, middle_y),
231            );
232        }
233    }
234
235    fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
236        let old_delegate = old_delegate
237            .as_any()
238            .downcast_ref::<ToolbarLayout>()
239            .expect("the delegate types matched");
240        old_delegate.center_middle != self.center_middle
241            || old_delegate.middle_spacing != self.middle_spacing
242            || old_delegate.text_direction != self.text_direction
243    }
244
245    fn as_any(&self) -> &dyn Any {
246        self
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use waft_foundation::AppCell;
253    use waft_rendering::{
254        AnyRenderBox, ContainerBoxParentData, ContainerRenderObjectMixin,
255        MultiChildLayoutParentData, RenderCustomMultiChildLayoutBox,
256    };
257
258    use super::*;
259    use crate::test_harness::Harness;
260    use crate::widgets::basic::SizedBox;
261
262    fn sized(width: f64, height: f64) -> WidgetRef {
263        SizedBox {
264            width: Some(width),
265            height: Some(height),
266            ..Default::default()
267        }
268        .into_widget()
269    }
270
271    /// The toolbar's children, with the size and offset the delegate gave each.
272    fn placements(harness: &Harness, app: &App) -> Vec<(Size, Offset)> {
273        let toolbar: waft_rendering::RenderHandle<RenderCustomMultiChildLayoutBox> = harness
274            .render_root(app)
275            .child(app)
276            .expect("a child")
277            .as_object()
278            .downcast::<RenderCustomMultiChildLayoutBox>(app)
279            .expect("a RenderCustomMultiChildLayoutBox");
280        let mut placements = Vec::new();
281        let mut child: Option<AnyRenderBox> = toolbar.first_child(app);
282        while let Some(current) = child {
283            let parent_data = current
284                .as_object()
285                .parent_data_of::<MultiChildLayoutParentData>(app);
286            placements.push((current.size(app), parent_data.offset()));
287            child = toolbar.child_after(app, current);
288        }
289        placements
290    }
291
292    /// A toolbar with fixed-size children under the given direction, mounted and laid out.
293    fn toolbar(
294        app: &mut App,
295        text_direction: TextDirection,
296        center_middle: bool,
297        leading: Option<(f64, f64)>,
298        middle: Option<(f64, f64)>,
299        trailing: Option<(f64, f64)>,
300    ) -> Harness {
301        let mut bar = NavigationToolbar::new().center_middle(center_middle);
302        if let Some((width, height)) = leading {
303            bar = bar.leading(sized(width, height));
304        }
305        if let Some((width, height)) = middle {
306            bar = bar.middle(sized(width, height));
307        }
308        if let Some((width, height)) = trailing {
309            bar = bar.trailing(sized(width, height));
310        }
311        let harness = Harness::mount(app, Directionality::new(text_direction, bar).into_widget());
312        harness.pump(app);
313        harness
314    }
315
316    /// The view is 300 x 200, so `size.height` is 200 and the leading widget is stretched to it.
317    #[test]
318    fn a_centered_middle_sits_in_the_middle_of_the_bar_in_both_directions() {
319        let cell = AppCell::new();
320        let mut app = cell.borrow_mut();
321        let harness = toolbar(
322            &mut app,
323            TextDirection::Ltr,
324            true,
325            Some((50.0, 20.0)),
326            Some((60.0, 20.0)),
327            Some((40.0, 20.0)),
328        );
329        assert_eq!(
330            placements(&harness, &app),
331            vec![
332                (Size::new(50.0, 200.0), Offset::new(0.0, 0.0)),
333                (Size::new(60.0, 20.0), Offset::new(120.0, 90.0)),
334                (Size::new(40.0, 20.0), Offset::new(260.0, 90.0)),
335            ]
336        );
337
338        let cell = AppCell::new();
339        let mut app = cell.borrow_mut();
340        let harness = toolbar(
341            &mut app,
342            TextDirection::Rtl,
343            true,
344            Some((50.0, 20.0)),
345            Some((60.0, 20.0)),
346            Some((40.0, 20.0)),
347        );
348        assert_eq!(
349            placements(&harness, &app),
350            vec![
351                (Size::new(50.0, 200.0), Offset::new(250.0, 0.0)),
352                (Size::new(60.0, 20.0), Offset::new(120.0, 90.0)),
353                (Size::new(40.0, 20.0), Offset::new(0.0, 90.0)),
354            ]
355        );
356    }
357
358    #[test]
359    fn an_uncentered_middle_starts_next_to_the_leading_widget_in_both_directions() {
360        let cell = AppCell::new();
361        let mut app = cell.borrow_mut();
362        let harness = toolbar(
363            &mut app,
364            TextDirection::Ltr,
365            false,
366            Some((50.0, 20.0)),
367            Some((60.0, 20.0)),
368            Some((40.0, 20.0)),
369        );
370        assert_eq!(
371            placements(&harness, &app)[1],
372            (Size::new(60.0, 20.0), Offset::new(66.0, 90.0)),
373            "leading width plus the middle spacing"
374        );
375
376        let cell = AppCell::new();
377        let mut app = cell.borrow_mut();
378        let harness = toolbar(
379            &mut app,
380            TextDirection::Rtl,
381            false,
382            Some((50.0, 20.0)),
383            Some((60.0, 20.0)),
384            Some((40.0, 20.0)),
385        );
386        assert_eq!(
387            placements(&harness, &app)[1],
388            (Size::new(60.0, 20.0), Offset::new(174.0, 90.0)),
389            "the same margin measured from the right edge"
390        );
391    }
392
393    #[test]
394    fn a_centered_middle_that_would_overlap_the_leading_widget_is_pushed_off_it() {
395        let cell = AppCell::new();
396        let mut app = cell.borrow_mut();
397        let harness = toolbar(
398            &mut app,
399            TextDirection::Ltr,
400            true,
401            Some((200.0, 20.0)),
402            Some((100.0, 20.0)),
403            Some((40.0, 20.0)),
404        );
405        assert_eq!(
406            placements(&harness, &app)[1],
407            (Size::new(28.0, 20.0), Offset::new(216.0, 90.0)),
408            "the middle is capped at the free width and aligned with the leading edge"
409        );
410    }
411
412    #[test]
413    fn a_centered_middle_that_would_overlap_the_trailing_widget_is_pushed_off_it() {
414        let cell = AppCell::new();
415        let mut app = cell.borrow_mut();
416        let harness = toolbar(
417            &mut app,
418            TextDirection::Ltr,
419            true,
420            None,
421            Some((100.0, 20.0)),
422            Some((200.0, 20.0)),
423        );
424        assert_eq!(
425            placements(&harness, &app),
426            vec![
427                (Size::new(68.0, 20.0), Offset::new(16.0, 90.0)),
428                (Size::new(200.0, 20.0), Offset::new(100.0, 90.0)),
429            ],
430            "with no leading widget the middle is the first child"
431        );
432    }
433
434    #[test]
435    fn a_toolbar_lays_out_only_the_children_it_was_given() {
436        let cell = AppCell::new();
437        let mut app = cell.borrow_mut();
438        let harness = toolbar(
439            &mut app,
440            TextDirection::Ltr,
441            true,
442            None,
443            Some((60.0, 20.0)),
444            None,
445        );
446        assert_eq!(
447            placements(&harness, &app),
448            vec![(Size::new(60.0, 20.0), Offset::new(120.0, 90.0))]
449        );
450    }
451}