Skip to main content

waft_material/compose/
navigation_suite_scaffold.rs

1//! One list of destinations shown as a bar, a rail or a drawer for the window's size.
2
3use std::rc::Rc;
4
5use waft_embedder::{Color, TextDirection};
6use waft_foundation::{App, ValueChanged};
7use waft_painting::RoundedRectangleBorder;
8use waft_widgets::{
9    BuildContext, Column, Directionality, Expanded, IntoWidget, KeyRef, MediaQuery, Positioned,
10    Row, SizedBox, Stack, StatelessWidget, Text, WidgetRef,
11};
12
13use crate::compose::{WindowHeightSizeClass, WindowSizeClass, WindowWidthSizeClass};
14use crate::drawer_theme::DrawerTheme;
15use crate::material::Material;
16use crate::navigation_bar::{NavigationBar, NavigationDestination};
17use crate::navigation_drawer::{NavigationDrawer, NavigationDrawerDestination};
18use crate::navigation_rail::{NavigationRail, NavigationRailDestination, NavigationRailLabelType};
19use crate::theme::Theme;
20
21/// Compose's `PrimaryActionContentPadding`: the primary action's gap to the bar and the end edge.
22const PRIMARY_ACTION_CONTENT_PADDING: f64 = 16.0;
23
24/// What a [`NavigationSuiteScaffold`] shows its destinations in.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum NavigationSuiteType {
27    /// A bottom bar.
28    NavigationBar,
29    /// A rail with icons and optional labels.
30    NavigationRail,
31    /// Flutter's extended rail: icons with labels, 256 wide.
32    ExtendedNavigationRail,
33    /// A permanent drawer beside the content.
34    NavigationDrawer,
35    /// No navigation widget; the app shows its own.
36    None,
37}
38
39impl NavigationSuiteType {
40    /// A bar when the width or height is Compact; the extended rail from Large; the rail
41    /// otherwise.
42    pub fn from_window_size_class(size_class: WindowSizeClass) -> NavigationSuiteType {
43        if size_class.width == WindowWidthSizeClass::Compact
44            || size_class.height == WindowHeightSizeClass::Compact
45        {
46            NavigationSuiteType::NavigationBar
47        } else {
48            match size_class.width {
49                WindowWidthSizeClass::Large | WindowWidthSizeClass::ExtraLarge => {
50                    NavigationSuiteType::ExtendedNavigationRail
51                }
52                _ => NavigationSuiteType::NavigationRail,
53            }
54        }
55    }
56}
57
58/// Compose's `NavigationSuiteColors`: the container colour of each navigation widget the suite
59/// can show. `None` keeps the widget's own, from its theme or Material's defaults, as Compose's
60/// `NavigationSuiteDefaults.colors()` does; `Colors::TRANSPARENT` shows the suite's container.
61#[derive(Clone, Copy, Debug, Default, PartialEq)]
62pub struct NavigationSuiteColors {
63    /// The bar's background.
64    pub navigation_bar_container_color: Option<Color>,
65    /// The rail's background, extended or not.
66    pub navigation_rail_container_color: Option<Color>,
67    /// The permanent drawer's background.
68    pub navigation_drawer_container_color: Option<Color>,
69}
70
71/// Compose's `navigationItemVerticalArrangement`: where a rail's destinations sit along its
72/// height.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub enum NavigationItemVerticalArrangement {
75    /// Under the primary action, Compose's `NavigationSuiteDefaults.verticalArrangement`.
76    #[default]
77    Top,
78    /// In the middle of the room the primary action leaves.
79    Center,
80    /// At the bottom.
81    Bottom,
82}
83
84impl NavigationItemVerticalArrangement {
85    /// The rail's `group_alignment` for this arrangement.
86    fn group_alignment(self) -> f64 {
87        match self {
88            NavigationItemVerticalArrangement::Top => -1.0,
89            NavigationItemVerticalArrangement::Center => 0.0,
90            NavigationItemVerticalArrangement::Bottom => 1.0,
91        }
92    }
93}
94
95/// One destination in a navigation suite.
96#[derive(Clone)]
97pub struct NavigationSuiteDestination {
98    /// The icon shown when the destination is not selected.
99    pub icon: WidgetRef,
100    /// The icon shown when it is selected.
101    pub selected_icon: Option<WidgetRef>,
102    /// Its label.
103    pub label: String,
104    /// Whether it can be selected.
105    pub enabled: bool,
106}
107
108impl NavigationSuiteDestination {
109    /// Creates a destination with an icon and a label.
110    #[cfg_attr(debug_assertions, track_caller)]
111    pub fn new<K>(
112        icon: impl IntoWidget<K>,
113        label: impl Into<String>,
114    ) -> NavigationSuiteDestination {
115        NavigationSuiteDestination {
116            icon: icon.into_widget(),
117            selected_icon: None,
118            label: label.into(),
119            enabled: true,
120        }
121    }
122
123    /// The icon shown when the destination is selected.
124    #[cfg_attr(debug_assertions, track_caller)]
125    pub fn selected_icon<K>(
126        mut self,
127        selected_icon: impl IntoWidget<K>,
128    ) -> NavigationSuiteDestination {
129        self.selected_icon = Some(selected_icon.into_widget());
130        self
131    }
132
133    /// Whether the destination can be selected. Defaults to `true`.
134    pub fn enabled(mut self, enabled: bool) -> NavigationSuiteDestination {
135        self.enabled = enabled;
136        self
137    }
138}
139
140/// Content beside a bar, rail or drawer built from one list of destinations.
141pub struct NavigationSuiteScaffold {
142    /// The scaffold's key.
143    pub key: Option<KeyRef>,
144    /// The destinations, in order.
145    pub destinations: Vec<NavigationSuiteDestination>,
146    /// The selected destination.
147    pub selected_index: usize,
148    /// Called with a selected destination's index.
149    pub on_destination_selected: Option<ValueChanged<usize>>,
150    /// What to show the destinations in; `None` follows the window's size class.
151    pub navigation_suite_type: Option<NavigationSuiteType>,
152    /// The rail's leading widget, the drawer's header, or a button above the bar's end.
153    pub primary_action: Option<WidgetRef>,
154    /// The background of each navigation widget.
155    pub navigation_suite_colors: NavigationSuiteColors,
156    /// Where a rail's destinations sit along its height.
157    pub navigation_item_vertical_arrangement: NavigationItemVerticalArrangement,
158    /// The background behind the navigation widget and the content; `None` is the scheme's
159    /// surface, Compose's `colorScheme.background`.
160    pub container_color: Option<Color>,
161    /// The content beside the navigation widget.
162    pub content: WidgetRef,
163}
164
165impl NavigationSuiteScaffold {
166    /// Creates a suite around `content`.
167    #[cfg_attr(debug_assertions, track_caller)]
168    pub fn new<K>(
169        destinations: Vec<NavigationSuiteDestination>,
170        content: impl IntoWidget<K>,
171    ) -> NavigationSuiteScaffold {
172        NavigationSuiteScaffold {
173            key: None,
174            destinations,
175            selected_index: 0,
176            on_destination_selected: None,
177            navigation_suite_type: None,
178            primary_action: None,
179            navigation_suite_colors: NavigationSuiteColors::default(),
180            navigation_item_vertical_arrangement: NavigationItemVerticalArrangement::Top,
181            container_color: None,
182            content: content.into_widget(),
183        }
184    }
185
186    /// Sets the selected destination.
187    pub fn selected_index(mut self, selected_index: usize) -> NavigationSuiteScaffold {
188        self.selected_index = selected_index;
189        self
190    }
191
192    /// Sets the callback for a selected destination.
193    pub fn on_destination_selected(
194        mut self,
195        on_destination_selected: ValueChanged<usize>,
196    ) -> NavigationSuiteScaffold {
197        self.on_destination_selected = Some(on_destination_selected);
198        self
199    }
200
201    /// Sets what to show the destinations in.
202    pub fn navigation_suite_type(
203        mut self,
204        navigation_suite_type: NavigationSuiteType,
205    ) -> NavigationSuiteScaffold {
206        self.navigation_suite_type = Some(navigation_suite_type);
207        self
208    }
209
210    /// Sets the rail's leading widget, the drawer's header, or the button above the bar's end.
211    #[cfg_attr(debug_assertions, track_caller)]
212    pub fn primary_action<K>(
213        mut self,
214        primary_action: impl IntoWidget<K>,
215    ) -> NavigationSuiteScaffold {
216        self.primary_action = Some(primary_action.into_widget());
217        self
218    }
219
220    /// Sets the background of each navigation widget.
221    pub fn navigation_suite_colors(
222        mut self,
223        navigation_suite_colors: NavigationSuiteColors,
224    ) -> NavigationSuiteScaffold {
225        self.navigation_suite_colors = navigation_suite_colors;
226        self
227    }
228
229    /// Sets where a rail's destinations sit along its height.
230    pub fn navigation_item_vertical_arrangement(
231        mut self,
232        navigation_item_vertical_arrangement: NavigationItemVerticalArrangement,
233    ) -> NavigationSuiteScaffold {
234        self.navigation_item_vertical_arrangement = navigation_item_vertical_arrangement;
235        self
236    }
237
238    /// Sets the background behind the navigation widget and the content.
239    pub fn container_color(mut self, container_color: Color) -> NavigationSuiteScaffold {
240        self.container_color = Some(container_color);
241        self
242    }
243
244    /// Sets the scaffold's key.
245    pub fn key(mut self, key: KeyRef) -> NavigationSuiteScaffold {
246        self.key = Some(key);
247        self
248    }
249
250    fn bar(&self) -> WidgetRef {
251        let destinations = self
252            .destinations
253            .iter()
254            .map(|destination| {
255                let mut item =
256                    NavigationDestination::new(destination.icon.clone(), destination.label.clone())
257                        .enabled(destination.enabled);
258                if let Some(selected_icon) = &destination.selected_icon {
259                    item = item.selected_icon(selected_icon.clone());
260                }
261                item.into_widget()
262            })
263            .collect::<Vec<_>>();
264        let mut bar = NavigationBar::new(destinations).selected_index(self.selected_index);
265        if let Some(color) = self.navigation_suite_colors.navigation_bar_container_color {
266            bar = bar.background_color(color);
267        }
268        if let Some(on_selected) = &self.on_destination_selected {
269            let on_selected = on_selected.clone();
270            bar = bar.on_destination_selected(move |app, index| on_selected(app, index));
271        }
272        bar.into_widget()
273    }
274
275    fn rail(&self, extended: bool) -> WidgetRef {
276        let destinations = self
277            .destinations
278            .iter()
279            .map(|destination| {
280                let selected_icon = destination
281                    .selected_icon
282                    .clone()
283                    .unwrap_or_else(|| destination.icon.clone());
284                NavigationRailDestination::new(
285                    destination.icon.clone(),
286                    Text::new(destination.label.clone()),
287                )
288                .selected_icon(selected_icon)
289                .disabled(!destination.enabled)
290            })
291            .collect::<Vec<_>>();
292        let mut rail = NavigationRail::new(destinations, Some(self.selected_index))
293            .label_type(NavigationRailLabelType::All)
294            .group_alignment(self.navigation_item_vertical_arrangement.group_alignment());
295        if extended {
296            rail = rail
297                .extended(true)
298                .label_type(NavigationRailLabelType::None)
299                .min_extended_width(256.0);
300        }
301        if let Some(color) = self.navigation_suite_colors.navigation_rail_container_color {
302            rail = rail.background_color(color);
303        }
304        if let Some(primary_action) = &self.primary_action {
305            rail = rail.leading(primary_action.clone());
306        }
307        if let Some(on_selected) = &self.on_destination_selected {
308            let on_selected = on_selected.clone();
309            rail = rail.on_destination_selected(move |app, index| on_selected(app, index));
310        }
311        rail.into_widget()
312    }
313
314    /// Compose's `PermanentDrawerSheet`: the drawer with square corners and no elevation.
315    fn drawer(&self, app: &mut App, context: BuildContext) -> WidgetRef {
316        let destinations = self
317            .destinations
318            .iter()
319            .map(|destination| {
320                let mut item = NavigationDrawerDestination::new(
321                    destination.icon.clone(),
322                    Text::new(destination.label.clone()),
323                )
324                .enabled(destination.enabled);
325                if let Some(selected_icon) = &destination.selected_icon {
326                    item = item.selected_icon(selected_icon.clone());
327                }
328                item.into_widget()
329            })
330            .collect::<Vec<_>>();
331        let mut drawer = NavigationDrawer::new(destinations)
332            .selected_index(Some(self.selected_index as i32))
333            .elevation(0.0);
334        if let Some(color) = self
335            .navigation_suite_colors
336            .navigation_drawer_container_color
337        {
338            drawer = drawer.background_color(color);
339        }
340        if let Some(primary_action) = &self.primary_action {
341            drawer = drawer.header(primary_action.clone());
342        }
343        if let Some(on_selected) = &self.on_destination_selected {
344            let on_selected = on_selected.clone();
345            drawer = drawer.on_destination_selected(Rc::new(move |app, index| {
346                on_selected(app, index as usize);
347            }));
348        }
349        let sheet = DrawerTheme::of(app, context).shape(RoundedRectangleBorder::default());
350        DrawerTheme::new(sheet, SizedBox::new().width(360.0).child(drawer)).into_widget()
351    }
352
353    /// The content with the primary action floated above its bottom end, as over a bar.
354    fn content_with_primary_action(
355        &self,
356        app: &mut App,
357        context: BuildContext,
358        content: WidgetRef,
359    ) -> WidgetRef {
360        let Some(primary_action) = &self.primary_action else {
361            return content;
362        };
363        let text_direction = Directionality::of(app, context);
364        Stack::new()
365            .children([
366                Positioned::fill(content).into_widget(),
367                Positioned::directional(
368                    text_direction,
369                    None,
370                    Some(PRIMARY_ACTION_CONTENT_PADDING),
371                    primary_action.clone(),
372                )
373                .bottom(PRIMARY_ACTION_CONTENT_PADDING)
374                .into_widget(),
375            ])
376            .into_widget()
377    }
378
379    fn content_without_padding(
380        &self,
381        app: &mut App,
382        context: BuildContext,
383        suite_type: NavigationSuiteType,
384    ) -> WidgetRef {
385        let remove_start = matches!(
386            suite_type,
387            NavigationSuiteType::NavigationRail
388                | NavigationSuiteType::ExtendedNavigationRail
389                | NavigationSuiteType::NavigationDrawer
390        );
391        let remove_bottom = suite_type == NavigationSuiteType::NavigationBar;
392        if !remove_start && !remove_bottom {
393            return self.content.clone();
394        }
395        let rtl = Directionality::of(app, context) == TextDirection::Rtl;
396        let data = MediaQuery::of(app, context).remove_padding(
397            remove_start && !rtl,
398            false,
399            remove_start && rtl,
400            remove_bottom,
401        );
402        MediaQuery::new(data, self.content.clone()).into_widget()
403    }
404}
405
406impl std::fmt::Debug for NavigationSuiteScaffold {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        f.debug_struct("NavigationSuiteScaffold")
409            .field("key", &self.key)
410            .field("selected_index", &self.selected_index)
411            .field("navigation_suite_type", &self.navigation_suite_type)
412            .finish_non_exhaustive()
413    }
414}
415
416impl StatelessWidget for NavigationSuiteScaffold {
417    fn key(&self) -> Option<&KeyRef> {
418        self.key.as_ref()
419    }
420
421    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
422        let suite_type = self.navigation_suite_type.unwrap_or_else(|| {
423            NavigationSuiteType::from_window_size_class(WindowSizeClass::of(app, context))
424        });
425        let content = self.content_without_padding(app, context, suite_type);
426        let container_color = self
427            .container_color
428            .unwrap_or_else(|| Theme::of(app, context).color_scheme.surface());
429        let suite = match suite_type {
430            NavigationSuiteType::None => content,
431            NavigationSuiteType::NavigationBar => {
432                let content = self.content_with_primary_action(app, context, content);
433                Column::new()
434                    .children([Expanded::new(content).into_widget(), self.bar()])
435                    .into_widget()
436            }
437            NavigationSuiteType::NavigationRail => Row::new()
438                .children([self.rail(false), Expanded::new(content).into_widget()])
439                .into_widget(),
440            NavigationSuiteType::ExtendedNavigationRail => Row::new()
441                .children([self.rail(true), Expanded::new(content).into_widget()])
442                .into_widget(),
443            NavigationSuiteType::NavigationDrawer => Row::new()
444                .children([
445                    self.drawer(app, context),
446                    Expanded::new(content).into_widget(),
447                ])
448                .into_widget(),
449        };
450        // Compose's `Surface(color = containerColor)` around the suite and its content.
451        Material::new()
452            .color(container_color)
453            .child(suite)
454            .into_widget()
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use std::cell::Cell;
461
462    use waft_embedder::Size;
463    use waft_foundation::{App, ValueKey};
464    use waft_widgets::testing::{WidgetTester, find, test_widgets};
465    use waft_widgets::{MediaQueryData, Text};
466
467    use super::*;
468    use crate::compose::WindowHeightSizeClass;
469    use crate::test_support::material_app;
470    use crate::theme_data::ThemeData;
471
472    fn size_class(width: WindowWidthSizeClass, height: WindowHeightSizeClass) -> WindowSizeClass {
473        WindowSizeClass { width, height }
474    }
475
476    fn destination(label: &str) -> NavigationSuiteDestination {
477        NavigationSuiteDestination::new(Text::new(format!("{label} icon")), label)
478    }
479
480    fn suite() -> NavigationSuiteScaffold {
481        NavigationSuiteScaffold::new(
482            vec![destination("A"), destination("B")],
483            Text::new("content"),
484        )
485    }
486
487    fn pump(tester: &mut WidgetTester, width: f64, height: f64, suite: NavigationSuiteScaffold) {
488        tester.set_surface_size(Some(Size::new(width, height)));
489        let theme = ThemeData::new(&tester.cell.borrow());
490        let home = MediaQuery::new(MediaQueryData::new().size(Size::new(width, height)), suite);
491        tester.pump_widget(material_app(theme, home.into_widget()));
492    }
493
494    #[test]
495    fn the_suite_type_follows_the_window() {
496        assert_eq!(
497            NavigationSuiteType::from_window_size_class(size_class(
498                WindowWidthSizeClass::Compact,
499                WindowHeightSizeClass::Expanded
500            )),
501            NavigationSuiteType::NavigationBar
502        );
503        assert_eq!(
504            NavigationSuiteType::from_window_size_class(size_class(
505                WindowWidthSizeClass::Expanded,
506                WindowHeightSizeClass::Compact
507            )),
508            NavigationSuiteType::NavigationBar
509        );
510        assert_eq!(
511            NavigationSuiteType::from_window_size_class(size_class(
512                WindowWidthSizeClass::Medium,
513                WindowHeightSizeClass::Expanded
514            )),
515            NavigationSuiteType::NavigationRail
516        );
517        assert_eq!(
518            NavigationSuiteType::from_window_size_class(size_class(
519                WindowWidthSizeClass::Expanded,
520                WindowHeightSizeClass::Expanded
521            )),
522            NavigationSuiteType::NavigationRail
523        );
524        assert_eq!(
525            NavigationSuiteType::from_window_size_class(size_class(
526                WindowWidthSizeClass::Large,
527                WindowHeightSizeClass::Expanded
528            )),
529            NavigationSuiteType::ExtendedNavigationRail
530        );
531        assert_eq!(
532            NavigationSuiteType::from_window_size_class(size_class(
533                WindowWidthSizeClass::ExtraLarge,
534                WindowHeightSizeClass::Expanded
535            )),
536            NavigationSuiteType::ExtendedNavigationRail
537        );
538    }
539
540    #[test]
541    fn a_compact_window_shows_a_navigation_bar() {
542        test_widgets(|tester| {
543            pump(tester, 400.0, 700.0, suite());
544            assert_eq!(find::by_type::<NavigationBar>().evaluate(tester).len(), 1);
545            assert_eq!(find::by_type::<NavigationRail>().evaluate(tester).len(), 0);
546            assert!(!find::text("A").evaluate(tester).is_empty());
547        });
548    }
549
550    #[test]
551    fn a_short_window_keeps_the_bar() {
552        test_widgets(|tester| {
553            pump(tester, 800.0, 400.0, suite());
554            assert_eq!(find::by_type::<NavigationBar>().evaluate(tester).len(), 1);
555            assert_eq!(find::by_type::<NavigationRail>().evaluate(tester).len(), 0);
556        });
557    }
558
559    #[test]
560    fn a_medium_window_shows_a_rail_with_labels() {
561        test_widgets(|tester| {
562            pump(tester, 800.0, 700.0, suite());
563            assert_eq!(find::by_type::<NavigationRail>().evaluate(tester).len(), 1);
564            let (extended, labels) = tester.widget(
565                find::by_type::<NavigationRail>(),
566                |rail: &NavigationRail| (rail.extended, rail.label_type),
567            );
568            assert!(!extended);
569            assert_eq!(labels, Some(NavigationRailLabelType::All));
570        });
571    }
572
573    #[test]
574    fn a_large_window_shows_the_extended_rail() {
575        test_widgets(|tester| {
576            pump(tester, 1300.0, 700.0, suite());
577            let (extended, width, labels) = tester.widget(
578                find::by_type::<NavigationRail>(),
579                |rail: &NavigationRail| (rail.extended, rail.min_extended_width, rail.label_type),
580            );
581            assert!(extended);
582            assert_eq!(width, Some(256.0));
583            assert_eq!(labels, Some(NavigationRailLabelType::None));
584        });
585    }
586
587    #[test]
588    fn an_app_can_choose_the_drawer() {
589        test_widgets(|tester| {
590            pump(
591                tester,
592                1300.0,
593                700.0,
594                suite().navigation_suite_type(NavigationSuiteType::NavigationDrawer),
595            );
596            assert_eq!(
597                find::by_type::<NavigationDrawer>().evaluate(tester).len(),
598                1
599            );
600            assert_eq!(find::by_type::<NavigationRail>().evaluate(tester).len(), 0);
601        });
602    }
603
604    #[test]
605    fn the_suite_sits_on_its_container_color_and_the_rail_takes_its_own() {
606        test_widgets(|tester| {
607            let container = Color::from_argb(255, 1, 2, 3);
608            let rail = Color::from_argb(0, 0, 0, 0);
609            pump(
610                tester,
611                800.0,
612                700.0,
613                suite()
614                    .container_color(container)
615                    .navigation_suite_colors(NavigationSuiteColors {
616                        navigation_rail_container_color: Some(rail),
617                        ..NavigationSuiteColors::default()
618                    }),
619            );
620            let suite_color = tester.widget(
621                find::ancestor(
622                    find::by_type::<NavigationRail>(),
623                    find::by_type::<Material>(),
624                )
625                .last(),
626                |material: &Material| material.color,
627            );
628            assert_eq!(suite_color, Some(container));
629            let rail_color = tester.widget(
630                find::by_type::<NavigationRail>(),
631                |navigation_rail: &NavigationRail| navigation_rail.background_color,
632            );
633            assert_eq!(rail_color, Some(rail));
634        });
635    }
636
637    #[test]
638    fn a_centred_arrangement_centres_the_rail_s_destinations() {
639        test_widgets(|tester| {
640            pump(
641                tester,
642                800.0,
643                700.0,
644                suite().navigation_item_vertical_arrangement(
645                    NavigationItemVerticalArrangement::Center,
646                ),
647            );
648            let alignment = tester.widget(
649                find::by_type::<NavigationRail>(),
650                |rail: &NavigationRail| rail.group_alignment,
651            );
652            assert_eq!(alignment, Some(0.0));
653        });
654    }
655
656    #[test]
657    fn the_container_defaults_to_the_scheme_s_surface() {
658        test_widgets(|tester| {
659            pump(tester, 400.0, 700.0, suite());
660            let surface = ThemeData::new(&tester.cell.borrow()).color_scheme.surface();
661            let suite_color = tester.widget(
662                find::ancestor(find::text("content"), find::by_type::<Material>()).last(),
663                |material: &Material| material.color,
664            );
665            assert_eq!(suite_color, Some(surface));
666        });
667    }
668
669    #[test]
670    fn selecting_a_destination_reports_its_index() {
671        test_widgets(|tester| {
672            let selected = Rc::new(Cell::new(None));
673            let callback = Rc::clone(&selected);
674            pump(
675                tester,
676                800.0,
677                700.0,
678                suite().on_destination_selected(Rc::new(move |_app: &mut App, index: usize| {
679                    callback.set(Some(index));
680                })),
681            );
682            tester.tap(find::text("B"));
683            assert_eq!(selected.get(), Some(1));
684        });
685    }
686
687    #[test]
688    fn the_primary_action_leads_the_rail() {
689        test_widgets(|tester| {
690            pump(
691                tester,
692                800.0,
693                700.0,
694                suite().primary_action(Text::new("compose")),
695            );
696            let leading = tester.widget(
697                find::by_type::<NavigationRail>(),
698                |rail: &NavigationRail| rail.leading.is_some(),
699            );
700            assert!(leading);
701            assert!(!find::text("compose").evaluate(tester).is_empty());
702        });
703    }
704
705    #[test]
706    fn the_primary_action_floats_above_the_bar_s_end_in_either_direction() {
707        test_widgets(|tester| {
708            for (direction, expected_left) in
709                [(TextDirection::Ltr, 334.0), (TextDirection::Rtl, 16.0)]
710            {
711                let action = SizedBox::new()
712                    .key(ValueKey::new("action").into())
713                    .width(50.0)
714                    .height(50.0);
715                let suite = Directionality::new(direction, suite().primary_action(action));
716                tester.set_surface_size(Some(Size::new(400.0, 700.0)));
717                let theme = ThemeData::new(&tester.cell.borrow());
718                let home =
719                    MediaQuery::new(MediaQueryData::new().size(Size::new(400.0, 700.0)), suite);
720                tester.pump_widget(material_app(theme, home.into_widget()));
721
722                let action = tester.get_rect(find::by_key(ValueKey::new("action")));
723                let bar = tester.get_rect(find::by_type::<NavigationBar>());
724                assert_eq!(action.left, expected_left, "{direction:?}");
725                assert_eq!(action.bottom, bar.top - 16.0, "{direction:?}");
726            }
727        });
728    }
729}