Skip to main content

waft_material/
action_buttons.rs

1//! Flutter counterpart: material_ui's `action_buttons.dart`.
2
3use waft_embedder::{Color, TargetPlatform};
4use waft_foundation::{App, K_IS_WEB, Listener};
5use waft_widgets::{
6    BuildContext, Icon, IconData, IntoWidget, KeyRef, Navigator, Semantics, StandardComponentType,
7    StatelessWidget, WidgetBuilder, WidgetRef,
8};
9
10use crate::action_icons_theme::{ActionIconTheme, ActionIconThemeData};
11use crate::button_style::ButtonStyle;
12use crate::debug::debug_check_has_material_localizations;
13use crate::icon_button::IconButton;
14use crate::icons::Icons;
15use crate::material_localizations::MaterialLocalizations;
16use crate::scaffold::{Scaffold, scaffold_drawer_expanded_of, scaffold_end_drawer_expanded_of};
17use crate::theme::Theme;
18
19/// What `_ActionButton` reads of its subclass: the fields Dart's constructor passes to
20/// `IconButton` through `super`.
21struct ActionButtonFields<'a> {
22    color: Option<Color>,
23    style: &'a Option<ButtonStyle>,
24    on_pressed: &'a Option<Listener>,
25    icon: &'a WidgetRef,
26    standard_component: Option<StandardComponentType>,
27}
28
29/// Dart's abstract `_ActionButton extends IconButton`: a Material Design icon button whose
30/// subclasses name the tooltip and the default behaviour of a press.
31///
32/// A subclass is a widget that builds through [`ActionButton::build`]; the base class's
33/// `build` never returns the subclass itself but a plain `IconButton`.
34trait ActionButton: Sized {
35    fn fields(&self) -> ActionButtonFields<'_>;
36
37    /// This returns the appropriate tooltip text for this action button.
38    fn get_tooltip(app: &mut App, context: BuildContext) -> String;
39
40    /// This is the default function that is called when `on_pressed` is set
41    /// to null.
42    fn on_pressed_callback(app: &mut App, context: BuildContext);
43
44    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
45        debug_assert!(debug_check_has_material_localizations(app, context));
46        let fields = self.fields();
47        let on_pressed = fields.on_pressed.clone();
48        let mut button = IconButton::new(
49            Some(Listener::new(move |app| match &on_pressed {
50                Some(on_pressed) => on_pressed.call(app),
51                None => Self::on_pressed_callback(app, context),
52            })),
53            fields.icon.clone(),
54        )
55        .tooltip(Self::get_tooltip(app, context));
56        if let Some(standard_component) = fields.standard_component {
57            button = button.key(standard_component.key());
58        }
59        if let Some(style) = fields.style {
60            button = button.style(style.clone());
61        }
62        if let Some(color) = fields.color {
63            button = button.color(color);
64        }
65        button.into_widget()
66    }
67}
68
69/// Dart's `_ActionIcon`.
70#[derive(Debug)]
71struct ActionIcon {
72    icon_builder_callback: fn(&ActionIconThemeData) -> &Option<WidgetBuilder>,
73    get_icon: fn(&mut App, BuildContext) -> IconData,
74    get_android_semantics_label: fn(&dyn MaterialLocalizations) -> String,
75}
76
77impl StatelessWidget for ActionIcon {
78    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
79        let action_icon_theme = ActionIconTheme::of(app, context);
80        let icon_builder = action_icon_theme
81            .as_ref()
82            .and_then(|theme| (self.icon_builder_callback)(theme).clone());
83        if let Some(icon_builder) = icon_builder {
84            return icon_builder(app, context);
85        }
86
87        let data = (self.get_icon)(app, context);
88        // This can't use the platform from Theme because it is the Android OS that
89        // expects the duplicated tooltip and label.
90        let semantics_label = match app.platform().target_platform() {
91            TargetPlatform::Android => Some((self.get_android_semantics_label)(
92                &*<dyn MaterialLocalizations>::of(app, context),
93            )),
94            TargetPlatform::Fuchsia
95            | TargetPlatform::Linux
96            | TargetPlatform::Windows
97            | TargetPlatform::IOS
98            | TargetPlatform::MacOS => None,
99        };
100
101        let mut icon = Icon::new(Some(data));
102        if let Some(semantics_label) = semantics_label {
103            icon = icon.semantic_label(semantics_label);
104        }
105        icon.into_widget()
106    }
107}
108
109/// Defines one of Dart's `_ActionButton` subclasses: a widget with `IconButton`'s `key`,
110/// `color`, `style` and `onPressed`, and the icon its constructor passes to `super`.
111macro_rules! action_button_widget {
112    (
113        $(#[$meta:meta])*
114        $name:ident, icon: $icon:ident, standard_component: $standard_component:expr,
115        tooltip: $tooltip:ident, on_pressed: |$app:ident, $context:ident| $on_pressed:expr
116    ) => {
117        $(#[$meta])*
118        #[derive(Debug)]
119        pub struct $name {
120            pub key: Option<KeyRef>,
121            pub color: Option<Color>,
122            pub style: Option<ButtonStyle>,
123            pub on_pressed: Option<Listener>,
124            icon: WidgetRef,
125            standard_component: Option<StandardComponentType>,
126        }
127
128        impl $name {
129            #[doc = concat!("Dart `", stringify!($name), "()`.")]
130            pub fn new() -> $name {
131                $name {
132                    key: None,
133                    color: None,
134                    style: None,
135                    on_pressed: None,
136                    icon: $icon::new().into_widget(),
137                    standard_component: $standard_component,
138                }
139            }
140
141            #[doc = concat!("Dart `", stringify!($name), "(key:)`.")]
142            pub fn key(mut self, key: KeyRef) -> $name {
143                self.key = Some(key);
144                self
145            }
146
147            #[doc = concat!("Dart `", stringify!($name), "(color:)`.")]
148            pub fn color(mut self, color: Color) -> $name {
149                self.color = Some(color);
150                self
151            }
152
153            #[doc = concat!("Dart `", stringify!($name), "(style:)`.")]
154            pub fn style(mut self, style: ButtonStyle) -> $name {
155                self.style = Some(style);
156                self
157            }
158
159            #[doc = concat!("Dart `", stringify!($name), "(onPressed:)`.")]
160            pub fn on_pressed(mut self, on_pressed: Listener) -> $name {
161                self.on_pressed = Some(on_pressed);
162                self
163            }
164        }
165
166        impl Default for $name {
167            fn default() -> $name {
168                $name::new()
169            }
170        }
171
172        impl ActionButton for $name {
173            fn fields(&self) -> ActionButtonFields<'_> {
174                ActionButtonFields {
175                    color: self.color,
176                    style: &self.style,
177                    on_pressed: &self.on_pressed,
178                    icon: &self.icon,
179                    standard_component: self.standard_component,
180                }
181            }
182
183            fn get_tooltip(app: &mut App, context: BuildContext) -> String {
184                <dyn MaterialLocalizations>::of(app, context).$tooltip()
185            }
186
187            fn on_pressed_callback($app: &mut App, $context: BuildContext) {
188                $on_pressed
189            }
190        }
191
192        impl StatelessWidget for $name {
193            fn key(&self) -> Option<&KeyRef> {
194                self.key.as_ref()
195            }
196
197            fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
198                ActionButton::build(self, app, context)
199            }
200        }
201    };
202}
203
204/// Dart's `Semantics(expanded:)` around `DrawerButtonIcon`'s and `EndDrawerButtonIcon`'s
205/// `_ActionIcon`, from the scaffold read `expanded_of`.
206fn with_expanded_semantics(
207    app: &mut App,
208    context: BuildContext,
209    expanded_of: fn(&mut App, BuildContext) -> Option<bool>,
210    action_icon: ActionIcon,
211) -> WidgetRef {
212    let mut semantics = Semantics::new();
213    if let Some(expanded) = expanded_of(app, context) {
214        semantics = semantics.expanded(expanded);
215    }
216    semantics.child(action_icon).into_widget()
217}
218
219/// Defines one of Dart's `*ButtonIcon` widgets, each a `_ActionIcon` whose builder comes from
220/// the action icon theme, and whose Android semantics label is the localized `$label`. The
221/// drawer icons name `expanded:`, the scaffold read Dart's `Semantics(expanded:)` around them
222/// takes.
223macro_rules! action_icon_widget {
224    (@wrap $app:ident, $context:ident, $action_icon:ident) => {
225        $action_icon.into_widget()
226    };
227    (@wrap $app:ident, $context:ident, $action_icon:ident, $expanded:path) => {
228        with_expanded_semantics($app, $context, $expanded, $action_icon)
229    };
230    (
231        $(#[$meta:meta])*
232        $name:ident, builder: $builder:ident, get_icon: |$app:ident, $context:ident| $get_icon:expr,
233        android_semantics_label: $label:ident $(, expanded: $expanded:path)?
234    ) => {
235        $(#[$meta])*
236        #[derive(Debug, Default)]
237        pub struct $name {
238            pub key: Option<KeyRef>,
239        }
240
241        impl $name {
242            #[doc = concat!("Dart `", stringify!($name), "()`.")]
243            pub fn new() -> $name {
244                $name::default()
245            }
246
247            #[doc = concat!("Dart `", stringify!($name), "(key:)`.")]
248            pub fn key(mut self, key: KeyRef) -> $name {
249                self.key = Some(key);
250                self
251            }
252        }
253
254        impl StatelessWidget for $name {
255            fn key(&self) -> Option<&KeyRef> {
256                self.key.as_ref()
257            }
258
259            fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
260                let action_icon = ActionIcon {
261                    icon_builder_callback: |action_icon_theme| &action_icon_theme.$builder,
262                    get_icon: |$app, $context| $get_icon,
263                    get_android_semantics_label: |material_localization| {
264                        material_localization.$label()
265                    },
266                };
267                action_icon_widget!(@wrap _app, _context, action_icon $(, $expanded)?)
268            }
269        }
270    };
271}
272
273action_icon_widget!(
274    /// A "back" icon that's appropriate for the current [`TargetPlatform`].
275    ///
276    /// The current platform is determined by querying for the ambient `Theme`.
277    ///
278    /// See also:
279    ///
280    ///  * [`BackButton`], an `IconButton` with a [`BackButtonIcon`] that calls
281    ///    `Navigator::maybe_pop` to return to the previous route.
282    ///  * `IconButton`, which is a more general widget for creating buttons
283    ///    with icons.
284    ///  * `Icon`, a Material Design icon.
285    ///  * `ThemeData::platform`, which specifies the current platform.
286    BackButtonIcon,
287    builder: back_button_icon_builder,
288    get_icon: |app, context| {
289        if K_IS_WEB {
290            // Always use 'Icons.arrow_back' as a back_button icon in web.
291            return Icons::arrow_back();
292        }
293        match Theme::of(app, context).platform {
294            TargetPlatform::Android
295            | TargetPlatform::Fuchsia
296            | TargetPlatform::Linux
297            | TargetPlatform::Windows => Icons::arrow_back(),
298            TargetPlatform::IOS | TargetPlatform::MacOS => Icons::arrow_back_ios_new_rounded(),
299        }
300    },
301    android_semantics_label: back_button_tooltip
302);
303
304action_button_widget!(
305    /// A Material Design back icon button.
306    ///
307    /// A [`BackButton`] is an `IconButton` with a "back" icon appropriate for the
308    /// current [`TargetPlatform`]. When pressed, the back button calls
309    /// `Navigator::maybe_pop` to return to the previous route unless a custom
310    /// [`on_pressed`](Self::on_pressed) callback is provided.
311    ///
312    /// The [`on_pressed`](Self::on_pressed) callback can, for instance, be used to pop the
313    /// platform's navigation stack via `SystemNavigator` instead of Flutter's `Navigator` in
314    /// add-to-app situations.
315    ///
316    /// In Material Design 3, both [`style`](Self::style)'s `ButtonStyle::icon_color` and
317    /// [`color`](Self::color) are used to override the default icon color of [`BackButton`]. If
318    /// both exist, the `ButtonStyle::icon_color` will override [`color`](Self::color) for states
319    /// where `ButtonStyle::foreground_color` resolves to non-null.
320    ///
321    /// When deciding to display a [`BackButton`], consider using
322    /// `ModalRoute::can_pop_of(context)` to check whether the current route can be
323    /// popped. If that value is false (e.g., because the current route is the
324    /// initial route), the [`BackButton`] will not have any effect when pressed,
325    /// which could frustrate the user.
326    ///
327    /// Requires one of its ancestors to be a `Material` widget.
328    ///
329    /// See also:
330    ///
331    ///  * `AppBar`, which automatically uses a [`BackButton`] in its
332    ///    `AppBar::leading` slot when the `Scaffold` has no `Drawer` and the
333    ///    current `Route` is not the `Navigator`'s first route.
334    ///  * [`BackButtonIcon`], which is useful if you need to create a back button
335    ///    that responds differently to being pressed.
336    ///  * `IconButton`, which is a more general widget for creating buttons with
337    ///    icons.
338    ///  * [`CloseButton`], an alternative which may be more appropriate for leaf
339    ///    node pages in the navigation tree.
340    BackButton,
341    icon: BackButtonIcon,
342    standard_component: Some(StandardComponentType::BackButton),
343    tooltip: back_button_tooltip,
344    on_pressed: |app, context| {
345        Navigator::maybe_pop(app, context, None);
346    }
347);
348
349action_icon_widget!(
350    /// A "close" icon that's appropriate for the current [`TargetPlatform`].
351    ///
352    /// The current platform is determined by querying for the ambient `Theme`.
353    ///
354    /// See also:
355    ///
356    ///  * [`CloseButton`], an `IconButton` with a [`CloseButtonIcon`] that calls
357    ///    `Navigator::maybe_pop` to return to the previous route.
358    ///  * `IconButton`, which is a more general widget for creating buttons
359    ///    with icons.
360    ///  * `Icon`, a Material Design icon.
361    ///  * `ThemeData::platform`, which specifies the current platform.
362    CloseButtonIcon,
363    builder: close_button_icon_builder,
364    get_icon: |_app, _context| Icons::close(),
365    android_semantics_label: close_button_tooltip
366);
367
368action_button_widget!(
369    /// A Material Design close icon button.
370    ///
371    /// A [`CloseButton`] is an `IconButton` with a "close" icon. When pressed, the
372    /// close button calls `Navigator::maybe_pop` to return to the previous route.
373    ///
374    /// The [`on_pressed`](Self::on_pressed) callback can, for instance, be used to pop the
375    /// platform's navigation stack via `SystemNavigator` instead of Flutter's `Navigator` in
376    /// add-to-app situations.
377    ///
378    /// In Material Design 3, both [`style`](Self::style)'s `ButtonStyle::icon_color` and
379    /// [`color`](Self::color) are used to override the default icon color of [`CloseButton`]. If
380    /// both exist, the `ButtonStyle::icon_color` will override [`color`](Self::color) for states
381    /// where `ButtonStyle::foreground_color` resolves to non-null.
382    ///
383    /// Use a [`CloseButton`] instead of a [`BackButton`] on fullscreen dialogs or
384    /// pages that may solicit additional actions to close.
385    ///
386    /// See also:
387    ///
388    ///  * `AppBar`, which automatically uses a [`CloseButton`] in its
389    ///    `AppBar::leading` slot when appropriate.
390    ///  * [`BackButton`], which is more appropriate for middle nodes in the
391    ///    navigation tree or where pages can be popped instantaneously with
392    ///    no user data consequence.
393    ///  * `IconButton`, to create other Material Design icon buttons.
394    CloseButton,
395    icon: CloseButtonIcon,
396    standard_component: Some(StandardComponentType::CloseButton),
397    tooltip: close_button_tooltip,
398    on_pressed: |app, context| {
399        Navigator::maybe_pop(app, context, None);
400    }
401);
402
403action_icon_widget!(
404    /// A "drawer" icon that's appropriate for the current [`TargetPlatform`].
405    ///
406    /// The current platform is determined by querying for the ambient `Theme`.
407    ///
408    /// See also:
409    ///
410    ///  * [`DrawerButton`], an `IconButton` with a [`DrawerButtonIcon`] that calls
411    ///    `ScaffoldState::open_drawer` to open the `Scaffold::drawer`.
412    ///  * [`EndDrawerButton`], an `IconButton` with an [`EndDrawerButtonIcon`] that
413    ///    calls `ScaffoldState::open_end_drawer` to open the `Scaffold::end_drawer`.
414    ///  * `IconButton`, which is a more general widget for creating buttons
415    ///    with icons.
416    ///  * `Icon`, a Material Design icon.
417    ///  * `ThemeData::platform`, which specifies the current platform.
418    DrawerButtonIcon,
419    builder: drawer_button_icon_builder,
420    get_icon: |_app, _context| Icons::menu(),
421    android_semantics_label: open_app_drawer_tooltip,
422    expanded: scaffold_drawer_expanded_of
423);
424
425action_button_widget!(
426    /// A Material Design drawer icon button.
427    ///
428    /// A [`DrawerButton`] is an `IconButton` with a "drawer" icon. When pressed, the
429    /// close button calls `ScaffoldState::open_drawer` to the `Scaffold::drawer`.
430    ///
431    /// The default behaviour on press can be overridden with
432    /// [`on_pressed`](Self::on_pressed).
433    ///
434    /// See also:
435    ///
436    ///  * [`EndDrawerButton`], an `IconButton` with an [`EndDrawerButtonIcon`] that
437    ///    calls `ScaffoldState::open_end_drawer` to open the `Scaffold::end_drawer`.
438    ///  * `IconButton`, which is a more general widget for creating buttons
439    ///    with icons.
440    ///  * `Icon`, a Material Design icon.
441    ///  * `ThemeData::platform`, which specifies the current platform.
442    DrawerButton,
443    icon: DrawerButtonIcon,
444    standard_component: Some(StandardComponentType::DrawerButton),
445    tooltip: open_app_drawer_tooltip,
446    on_pressed: |app, context| {
447        Scaffold::of(app, context).open_drawer(app);
448    }
449);
450
451action_icon_widget!(
452    /// A "end drawer" icon that's appropriate for the current [`TargetPlatform`].
453    ///
454    /// The current platform is determined by querying for the ambient `Theme`.
455    ///
456    /// See also:
457    ///
458    ///  * [`DrawerButton`], an `IconButton` with a [`DrawerButtonIcon`] that calls
459    ///    `ScaffoldState::open_drawer` to open the `Scaffold::drawer`.
460    ///  * [`EndDrawerButton`], an `IconButton` with an [`EndDrawerButtonIcon`] that
461    ///    calls `ScaffoldState::open_end_drawer` to open the `Scaffold::end_drawer`
462    ///  * `IconButton`, which is a more general widget for creating buttons
463    ///    with icons.
464    ///  * `Icon`, a Material Design icon.
465    ///  * `ThemeData::platform`, which specifies the current platform.
466    EndDrawerButtonIcon,
467    builder: end_drawer_button_icon_builder,
468    get_icon: |_app, _context| Icons::menu(),
469    android_semantics_label: open_app_drawer_tooltip,
470    expanded: scaffold_end_drawer_expanded_of
471);
472
473action_button_widget!(
474    /// A Material Design end drawer icon button.
475    ///
476    /// A [`EndDrawerButton`] is an `IconButton` with a "drawer" icon. When pressed, the
477    /// end drawer button calls `ScaffoldState::open_end_drawer` to open the
478    /// `Scaffold::end_drawer`.
479    ///
480    /// The default behaviour on press can be overridden with
481    /// [`on_pressed`](Self::on_pressed).
482    ///
483    /// See also:
484    ///
485    ///  * [`DrawerButton`], an `IconButton` with a [`DrawerButtonIcon`] that calls
486    ///    `ScaffoldState::open_drawer` to open a drawer.
487    ///  * `IconButton`, which is a more general widget for creating buttons
488    ///    with icons.
489    ///  * `Icon`, a Material Design icon.
490    ///  * `ThemeData::platform`, which specifies the current platform.
491    EndDrawerButton,
492    icon: EndDrawerButtonIcon,
493    standard_component: None,
494    tooltip: open_app_drawer_tooltip,
495    on_pressed: |app, context| {
496        Scaffold::of(app, context).open_end_drawer(app);
497    }
498);
499
500#[cfg(test)]
501mod tests {
502    //! The cases of `back_button_test.dart` and `drawer_button_test.dart` that pin behaviour; the
503    //! semantics and the semantics-tree cases wait on accessibility.
504
505    use std::cell::Cell;
506    use std::rc::Rc;
507
508    use waft_embedder::{Offset, Size, TargetPlatform};
509    use waft_foundation::Handle;
510    use waft_services::{MouseCursorRef, SystemMouseCursors};
511    use waft_widgets::{
512        AnyElement, Builder, Center, Column, GlobalKey, PageRouteBuilder, RoutePageBuilder,
513        SizedBox, Text, WidgetStatePropertyAll,
514    };
515
516    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
517
518    use super::*;
519    use crate::colors::Colors;
520    use crate::drawer::Drawer;
521    use crate::material::Material;
522    use crate::scaffold::{Scaffold, ScaffoldState};
523    use crate::test_support::material_app;
524    use crate::theme::Theme;
525    use crate::theme_data::ThemeData;
526
527    fn pump_app(tester: &mut WidgetTester, home: WidgetRef) {
528        let root = {
529            let app = tester.cell.borrow();
530            material_app(ThemeData::new(&app), home)
531        };
532        tester.pump_widget(root);
533    }
534
535    fn app_scaffold(tester: &mut WidgetTester, scaffold: Scaffold) {
536        pump_app(tester, scaffold.into_widget());
537    }
538
539    fn material<K>(child: impl IntoWidget<K>) -> WidgetRef {
540        Material::new().child(child).into_widget()
541    }
542
543    fn tap(tester: &mut WidgetTester, element: AnyElement) {
544        let center = tester.get_center(element);
545        tester.tap_at(center, 1);
546    }
547
548    fn only<W: 'static>(tester: &WidgetTester) -> AnyElement {
549        let found = find::by_type::<W>().evaluate(tester);
550        assert_eq!(found.len(), 1);
551        found[0]
552    }
553
554    fn counter(count: &Rc<Cell<usize>>) -> Listener {
555        let count = Rc::clone(count);
556        Listener::new(move |_app| count.set(count.get() + 1))
557    }
558
559    fn red_icon_color() -> ButtonStyle {
560        ButtonStyle::new().icon_color(Rc::new(WidgetStatePropertyAll::new(Some(
561            Colors::RED.primary(),
562        ))))
563    }
564
565    /// The colour of the glyph the button's `Icon` paints: Dart's `tester.firstWidget<RichText>(
566    /// find.descendant(of: find.byType(Button), matching: find.byType(RichText))).text.style!.color`.
567    fn glyph_color(tester: &WidgetTester) -> Option<Color> {
568        let icon = find::by_type::<Icon>().evaluate(tester)[0];
569        tester
570            .glyph_style(icon)
571            .color
572            .as_ref()
573            .map(|color| color.color())
574    }
575
576    /// The context of the home page, to push a route from.
577    #[derive(Clone, Default)]
578    struct Home(Rc<Cell<Option<BuildContext>>>);
579
580    impl Home {
581        fn page(&self) -> WidgetRef {
582            let slot = Rc::clone(&self.0);
583            Builder::new(move |_app, context| {
584                slot.set(Some(context));
585                material(Text::new("Home"))
586            })
587            .into_widget()
588        }
589
590        /// Dart's `navigator.pushNamed('/next')` of a route that builds `next`.
591        fn push(&self, tester: &WidgetTester, next: impl Fn() -> WidgetRef + 'static) {
592            let mut app = tester.cell.borrow_mut();
593            let page_builder: RoutePageBuilder = Rc::new(move |_app, _context, _, _| next());
594            let route = PageRouteBuilder::new(&mut app, page_builder);
595            let context = self.0.get().expect("the home page built");
596            drop(Navigator::push(&mut app, context, route.erase()));
597        }
598    }
599
600    /// The tester, on the page `next` builds above the home page.
601    fn on_next_page(tester: &mut WidgetTester, next: impl Fn() -> WidgetRef + 'static) -> Home {
602        let home = Home::default();
603        pump_app(tester, home.page());
604        home.push(tester, next);
605        tester.pump_and_settle();
606        home
607    }
608
609    fn on_home(tester: &WidgetTester) -> bool {
610        !find::text("Home").evaluate(tester).is_empty()
611    }
612
613    // 'BackButton control test'
614    #[test]
615    fn a_back_button_pops_the_route() {
616        test_widgets(|tester| {
617            let _home = on_next_page(tester, || material(Center::new().child(BackButton::new())));
618
619            let button = only::<BackButton>(tester);
620            tap(tester, button);
621            tester.pump_and_settle();
622
623            assert_eq!(find::text("Home").evaluate(tester).len(), 1);
624        });
625    }
626
627    // 'BackButton onPressed overrides default pop behavior'
628    #[test]
629    fn a_back_buttons_on_pressed_overrides_the_pop() {
630        test_widgets(|tester| {
631            let calls = Rc::new(Cell::new(0));
632            let _home = on_next_page(tester, {
633                let calls = Rc::clone(&calls);
634                move || material(Center::new().child(BackButton::new().on_pressed(counter(&calls))))
635            });
636
637            assert!(!on_home(tester)); // Start off on the second page.
638            assert_eq!(calls.get(), 0);
639            let button = only::<BackButton>(tester);
640            tap(tester, button);
641            tester.pump_and_settle();
642
643            // We're still on the second page.
644            assert!(!on_home(tester));
645            // But the custom callback is called.
646            assert_eq!(calls.get(), 1);
647        });
648    }
649
650    // 'CloseButton onPressed overrides default pop behavior'
651    #[test]
652    fn a_close_buttons_on_pressed_overrides_the_pop() {
653        test_widgets(|tester| {
654            let calls = Rc::new(Cell::new(0));
655            let _home = on_next_page(tester, {
656                let calls = Rc::clone(&calls);
657                move || {
658                    material(Center::new().child(CloseButton::new().on_pressed(counter(&calls))))
659                }
660            });
661
662            assert!(!on_home(tester));
663            assert_eq!(calls.get(), 0);
664            let button = only::<CloseButton>(tester);
665            tap(tester, button);
666            tester.pump_and_settle();
667
668            assert!(!on_home(tester));
669            assert_eq!(calls.get(), 1);
670        });
671    }
672
673    // The default pop of 'BackButton control test', for the close button.
674    #[test]
675    fn a_close_button_pops_the_route() {
676        test_widgets(|tester| {
677            let _home = on_next_page(tester, || material(Center::new().child(CloseButton::new())));
678
679            let button = only::<CloseButton>(tester);
680            tap(tester, button);
681            tester.pump_and_settle();
682
683            assert_eq!(find::text("Home").evaluate(tester).len(), 1);
684        });
685    }
686
687    /// The icons of the `Icon`s the tester found, in tree order.
688    fn icons(tester: &WidgetTester) -> Vec<Option<IconData>> {
689        find::by_type::<Icon>()
690            .evaluate(tester)
691            .into_iter()
692            .map(|element| tester.widget(element, |icon: &Icon| icon.icon.clone()))
693            .collect()
694    }
695
696    /// Dart's `Theme(data: ThemeData(platform: platform), child: icon)` for the five platforms,
697    /// in Dart's order: Android, iOS, Linux, macOS, Windows.
698    fn icon_on_each_platform(tester: &mut WidgetTester, icon: impl Fn() -> WidgetRef) {
699        let platforms = [
700            TargetPlatform::Android,
701            TargetPlatform::IOS,
702            TargetPlatform::Linux,
703            TargetPlatform::MacOS,
704            TargetPlatform::Windows,
705        ];
706        let children: Vec<WidgetRef> = {
707            let app = tester.cell.borrow();
708            platforms
709                .into_iter()
710                .map(|platform| {
711                    Theme::new(ThemeData::builder().platform(platform).build(&app), icon())
712                        .into_widget()
713                })
714                .collect()
715        };
716        pump_app(tester, Column::new().children(children).into_widget());
717    }
718
719    // 'BackButton icon'
720    #[test]
721    fn a_back_button_icon_is_the_ios_arrow_on_ios_and_macos() {
722        test_widgets(|tester| {
723            icon_on_each_platform(tester, || BackButtonIcon::new().into_widget());
724
725            let [android, ios, linux, macos, windows] = &icons(tester)[..] else {
726                panic!("one icon for each platform");
727            };
728            assert_eq!(ios == android, K_IS_WEB);
729            assert!(linux == android);
730            assert_eq!(macos == android, K_IS_WEB);
731            assert!(macos == ios);
732            assert!(windows == android);
733        });
734    }
735
736    // 'DrawerButton icon'
737    #[test]
738    fn a_drawer_button_icon_is_the_same_on_every_platform() {
739        test_widgets(|tester| {
740            icon_on_each_platform(tester, || DrawerButtonIcon::new().into_widget());
741
742            let icons = icons(tester);
743            assert!(icons.iter().all(|icon| *icon == icons[0]));
744            assert_eq!(icons[0], Some(Icons::menu()));
745        });
746    }
747
748    // The platform choice of `CloseButtonIcon` and `EndDrawerButtonIcon`.
749    #[test]
750    fn a_close_icon_and_an_end_drawer_icon_are_the_same_on_every_platform() {
751        test_widgets(|tester| {
752            icon_on_each_platform(tester, || CloseButtonIcon::new().into_widget());
753            let close_icons = icons(tester);
754            assert!(close_icons.iter().all(|icon| *icon == Some(Icons::close())));
755
756            icon_on_each_platform(tester, || EndDrawerButtonIcon::new().into_widget());
757            let end_drawer_icons = icons(tester);
758            assert!(
759                end_drawer_icons
760                    .iter()
761                    .all(|icon| *icon == Some(Icons::menu()))
762            );
763        });
764    }
765
766    // The tooltip each button gives its `IconButton`, which Dart's semantics cases read as
767    // 'Back', 'Close' and 'Open navigation menu'.
768    #[test]
769    fn each_action_button_gives_its_icon_button_the_localized_tooltip() {
770        test_widgets(|tester| {
771            let buttons: Vec<WidgetRef> = vec![
772                BackButton::new().into_widget(),
773                CloseButton::new().into_widget(),
774                DrawerButton::new().into_widget(),
775                EndDrawerButton::new().into_widget(),
776            ];
777            pump_app(tester, material(Column::new().children(buttons)));
778
779            let tooltips: Vec<Option<String>> = find::by_type::<IconButton>()
780                .evaluate(tester)
781                .into_iter()
782                .map(|element| tester.widget(element, |button: &IconButton| button.tooltip.clone()))
783                .collect();
784            assert_eq!(
785                tooltips,
786                vec![
787                    Some("Back".to_string()),
788                    Some("Close".to_string()),
789                    Some("Open navigation menu".to_string()),
790                    Some("Open navigation menu".to_string()),
791                ]
792            );
793        });
794    }
795
796    // The keys that mark a standard component, which each button gives its `IconButton`.
797    #[test]
798    fn action_buttons_mark_their_icon_button_as_a_standard_component() {
799        test_widgets(|tester| {
800            let buttons: Vec<WidgetRef> = vec![
801                BackButton::new().into_widget(),
802                CloseButton::new().into_widget(),
803                DrawerButton::new().into_widget(),
804                EndDrawerButton::new().into_widget(),
805            ];
806            pump_app(tester, material(Column::new().children(buttons)));
807
808            let keys: Vec<Option<KeyRef>> = find::by_type::<IconButton>()
809                .evaluate(tester)
810                .into_iter()
811                .map(|element| tester.widget(element, |button: &IconButton| button.key.clone()))
812                .collect();
813            assert_eq!(
814                keys,
815                vec![
816                    Some(StandardComponentType::BackButton.key()),
817                    Some(StandardComponentType::CloseButton.key()),
818                    Some(StandardComponentType::DrawerButton.key()),
819                    None,
820                ]
821            );
822        });
823    }
824
825    /// Dart's `MaterialApp(home: Material(child: button))` with the glyph colour read back.
826    fn glyph_color_of<K>(tester: &mut WidgetTester, button: impl IntoWidget<K>) -> Option<Color> {
827        pump_app(tester, material(button));
828        glyph_color(tester)
829    }
830
831    // 'BackButton color'
832    #[test]
833    fn a_back_buttons_color_colors_its_icon() {
834        test_widgets(|tester| {
835            assert_eq!(
836                glyph_color_of(tester, BackButton::new().color(Colors::RED.primary())),
837                Some(Colors::RED.primary())
838            );
839        });
840    }
841
842    // 'BackButton color with ButtonStyle'
843    #[test]
844    fn a_back_buttons_style_icon_color_colors_its_icon() {
845        test_widgets(|tester| {
846            assert_eq!(
847                glyph_color_of(tester, BackButton::new().style(red_icon_color())),
848                Some(Colors::RED.primary())
849            );
850        });
851    }
852
853    // 'BackButton.style.iconColor parameter overrides BackButton.color'
854    #[test]
855    fn a_back_buttons_style_icon_color_overrides_its_color() {
856        test_widgets(|tester| {
857            assert_eq!(
858                glyph_color_of(
859                    tester,
860                    BackButton::new()
861                        .color(Colors::GREEN.primary())
862                        .style(red_icon_color())
863                ),
864                Some(Colors::RED.primary())
865            );
866        });
867    }
868
869    // 'CloseButton color'
870    #[test]
871    fn a_close_buttons_color_colors_its_icon() {
872        test_widgets(|tester| {
873            assert_eq!(
874                glyph_color_of(tester, CloseButton::new().color(Colors::RED.primary())),
875                Some(Colors::RED.primary())
876            );
877        });
878    }
879
880    // 'CloseButton color with ButtonStyle'
881    #[test]
882    fn a_close_buttons_style_icon_color_colors_its_icon() {
883        test_widgets(|tester| {
884            assert_eq!(
885                glyph_color_of(tester, CloseButton::new().style(red_icon_color())),
886                Some(Colors::RED.primary())
887            );
888        });
889    }
890
891    // 'CloseButton.style.iconColor parameter overrides CloseButton.color'
892    #[test]
893    fn a_close_buttons_style_icon_color_overrides_its_color() {
894        test_widgets(|tester| {
895            assert_eq!(
896                glyph_color_of(
897                    tester,
898                    CloseButton::new()
899                        .color(Colors::GREEN.primary())
900                        .style(red_icon_color())
901                ),
902                Some(Colors::RED.primary())
903            );
904        });
905    }
906
907    // 'DrawerButton color'
908    #[test]
909    fn a_drawer_buttons_color_colors_its_icon() {
910        test_widgets(|tester| {
911            assert_eq!(
912                glyph_color_of(tester, DrawerButton::new().color(Colors::RED.primary())),
913                Some(Colors::RED.primary())
914            );
915        });
916    }
917
918    // 'DrawerButton color with ButtonStyle'
919    #[test]
920    fn a_drawer_buttons_style_icon_color_colors_its_icon() {
921        test_widgets(|tester| {
922            assert_eq!(
923                glyph_color_of(tester, DrawerButton::new().style(red_icon_color())),
924                Some(Colors::RED.primary())
925            );
926        });
927    }
928
929    // 'EndDrawerButton color'
930    #[test]
931    fn an_end_drawer_buttons_color_colors_its_icon() {
932        test_widgets(|tester| {
933            assert_eq!(
934                glyph_color_of(tester, EndDrawerButton::new().color(Colors::RED.primary())),
935                Some(Colors::RED.primary())
936            );
937        });
938    }
939
940    // 'EndDrawerButton color with ButtonStyle'
941    #[test]
942    fn an_end_drawer_buttons_style_icon_color_colors_its_icon() {
943        test_widgets(|tester| {
944            assert_eq!(
945                glyph_color_of(tester, EndDrawerButton::new().style(red_icon_color())),
946                Some(Colors::RED.primary())
947            );
948        });
949    }
950
951    // 'DrawerButton control test'
952    #[test]
953    fn a_drawer_button_opens_the_drawer() {
954        test_widgets(|tester| {
955            app_scaffold(
956                tester,
957                Scaffold::new()
958                    .body(DrawerButton::new())
959                    .drawer(Drawer::new()),
960            );
961            tester.pump_and_settle();
962
963            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
964
965            let button = only::<DrawerButton>(tester);
966            tap(tester, button);
967            tester.pump_and_settle();
968
969            assert_eq!(find::by_type::<Drawer>().evaluate(tester).len(), 1);
970        });
971    }
972
973    // 'EndDrawerButton control test'
974    #[test]
975    fn an_end_drawer_button_opens_the_end_drawer() {
976        test_widgets(|tester| {
977            app_scaffold(
978                tester,
979                Scaffold::new()
980                    .body(EndDrawerButton::new())
981                    .end_drawer(Drawer::new()),
982            );
983            tester.pump_and_settle();
984
985            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
986
987            let button = only::<EndDrawerButton>(tester);
988            tap(tester, button);
989            tester.pump_and_settle();
990
991            assert_eq!(find::by_type::<Drawer>().evaluate(tester).len(), 1);
992        });
993    }
994
995    // 'DrawerButton onPressed overrides default end drawer open behaviour'
996    #[test]
997    fn a_drawer_buttons_on_pressed_overrides_opening_the_drawer() {
998        test_widgets(|tester| {
999            let calls = Rc::new(Cell::new(0));
1000            app_scaffold(
1001                tester,
1002                Scaffold::new()
1003                    .body(Center::new().child(DrawerButton::new().on_pressed(counter(&calls))))
1004                    .drawer(Drawer::new()),
1005            );
1006            tester.pump_and_settle();
1007
1008            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
1009            assert_eq!(calls.get(), 0);
1010            let button = only::<DrawerButton>(tester);
1011            tap(tester, button);
1012            tester.pump_and_settle();
1013
1014            // Drawer is still closed
1015            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
1016            // The custom callback is called.
1017            assert_eq!(calls.get(), 1);
1018        });
1019    }
1020
1021    // 'EndDrawerButton onPressed overrides default end drawer open behaviour'
1022    #[test]
1023    fn an_end_drawer_buttons_on_pressed_overrides_opening_the_end_drawer() {
1024        test_widgets(|tester| {
1025            let calls = Rc::new(Cell::new(0));
1026            app_scaffold(
1027                tester,
1028                Scaffold::new()
1029                    .body(Center::new().child(EndDrawerButton::new().on_pressed(counter(&calls))))
1030                    .end_drawer(Drawer::new()),
1031            );
1032            tester.pump_and_settle();
1033
1034            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
1035            assert_eq!(calls.get(), 0);
1036            let button = only::<EndDrawerButton>(tester);
1037            tap(tester, button);
1038            tester.pump_and_settle();
1039
1040            assert!(find::by_type::<Drawer>().evaluate(tester).is_empty());
1041            assert_eq!(calls.get(), 1);
1042        });
1043    }
1044
1045    /// A scaffold with both drawers and both drawer buttons in its body.
1046    fn scaffold_with_both_drawers(
1047        tester: &mut WidgetTester,
1048        buttons: Vec<WidgetRef>,
1049    ) -> Handle<ScaffoldState> {
1050        let key = GlobalKey::new();
1051        app_scaffold(
1052            tester,
1053            Scaffold::new()
1054                .key(key.clone().into())
1055                .body(Center::new().child(Column::new().children(buttons)))
1056                .drawer(Drawer::new())
1057                .end_drawer(Drawer::new()),
1058        );
1059        tester.pump_and_settle();
1060        key.current_state::<ScaffoldState>(&tester.cell.borrow_mut())
1061            .expect("a mounted scaffold")
1062    }
1063
1064    // The `openDrawer` each drawer button calls, against the scaffold's state.
1065    #[test]
1066    fn a_drawer_button_opens_only_the_drawer() {
1067        test_widgets(|tester| {
1068            let state = scaffold_with_both_drawers(
1069                tester,
1070                vec![
1071                    EndDrawerButton::new().into_widget(),
1072                    DrawerButton::new().into_widget(),
1073                ],
1074            );
1075
1076            let button = only::<DrawerButton>(tester);
1077            tap(tester, button);
1078            tester.pump_and_settle();
1079
1080            assert!(state.is_drawer_open(&tester.cell.borrow()));
1081            assert!(!state.is_end_drawer_open(&tester.cell.borrow()));
1082        });
1083    }
1084
1085    // The `openEndDrawer` each drawer button calls, against the scaffold's state.
1086    #[test]
1087    fn an_end_drawer_button_opens_only_the_end_drawer() {
1088        test_widgets(|tester| {
1089            let state = scaffold_with_both_drawers(
1090                tester,
1091                vec![
1092                    DrawerButton::new().into_widget(),
1093                    EndDrawerButton::new().into_widget(),
1094                ],
1095            );
1096
1097            let button = only::<EndDrawerButton>(tester);
1098            tap(tester, button);
1099            tester.pump_and_settle();
1100
1101            assert!(!state.is_drawer_open(&tester.cell.borrow()));
1102            assert!(state.is_end_drawer_open(&tester.cell.borrow()));
1103        });
1104    }
1105
1106    /// Dart's `MaterialApp(home: Center(child: SizedBox.shrink(child: Scaffold(body: button))))`.
1107    fn size_at_zero_area<W: 'static, K>(
1108        tester: &mut WidgetTester,
1109        button: impl IntoWidget<K>,
1110    ) -> Size {
1111        pump_app(
1112            tester,
1113            Center::new()
1114                .child(SizedBox::shrink().child(Scaffold::new().body(button)))
1115                .into_widget(),
1116        );
1117        let element = only::<W>(tester);
1118        tester.get_size(element)
1119    }
1120
1121    // 'EndDrawerButton does not crash at zero area'
1122    #[test]
1123    fn an_end_drawer_button_has_no_size_at_zero_area() {
1124        test_widgets(|tester| {
1125            assert_eq!(
1126                size_at_zero_area::<EndDrawerButton, _>(tester, EndDrawerButton::new()),
1127                Size::ZERO
1128            );
1129        });
1130    }
1131
1132    // 'CloseButton does not crash at zero area'
1133    #[test]
1134    fn a_close_button_has_no_size_at_zero_area() {
1135        test_widgets(|tester| {
1136            assert_eq!(
1137                size_at_zero_area::<CloseButton, _>(tester, CloseButton::new()),
1138                Size::ZERO
1139            );
1140        });
1141    }
1142
1143    // 'DrawerButton does not crash at zero area'
1144    #[test]
1145    fn a_drawer_button_has_no_size_at_zero_area() {
1146        test_widgets(|tester| {
1147            assert_eq!(
1148                size_at_zero_area::<DrawerButton, _>(tester, DrawerButton::new()),
1149                Size::ZERO
1150            );
1151        });
1152    }
1153
1154    // 'BackButton renders at zero area'
1155    #[test]
1156    fn a_back_button_icon_is_empty_at_zero_area() {
1157        test_widgets(|tester| {
1158            let _ = size_at_zero_area::<BackButton, _>(tester, BackButton::new());
1159            pump_app(
1160                tester,
1161                Center::new()
1162                    .child(SizedBox::shrink().child(Scaffold::new().body(BackButton::new())))
1163                    .into_widget(),
1164            );
1165            let icon = only::<BackButtonIcon>(tester);
1166            let size = tester.get_size(icon);
1167            assert!(size.is_empty());
1168        });
1169    }
1170
1171    /// The cursor under a mouse the tester moved onto the centre of the button.
1172    fn cursor_over<W: 'static, K>(
1173        tester: &mut WidgetTester,
1174        button: impl IntoWidget<K>,
1175    ) -> MouseCursorRef {
1176        pump_app(tester, material(button));
1177        let mut mouse = TestPointer::mouse(1, 0);
1178        tester.add_pointer(&mut mouse, Offset::new(1000.0, 1000.0));
1179        let center = tester.get_center(only::<W>(tester));
1180        tester.move_to(&mut mouse, center, false);
1181        tester.pump_by(std::time::Duration::ZERO);
1182        tester.active_cursor(1)
1183    }
1184
1185    fn default_cursor() -> MouseCursorRef {
1186        if K_IS_WEB {
1187            SystemMouseCursors::CLICK.into()
1188        } else {
1189            SystemMouseCursors::BASIC.into()
1190        }
1191    }
1192
1193    fn cell_cursor_style() -> ButtonStyle {
1194        let cell: MouseCursorRef = SystemMouseCursors::CELL.into();
1195        ButtonStyle::new().mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(cell))))
1196    }
1197
1198    // 'BackButton has expected default mouse cursor on hover'
1199    #[test]
1200    fn a_back_button_has_the_default_mouse_cursor_on_hover() {
1201        test_widgets(|tester| {
1202            assert!(*cursor_over::<BackButton, _>(tester, BackButton::new()) == *default_cursor());
1203        });
1204    }
1205
1206    // 'CloseButton has expected default mouse cursor on hover'
1207    #[test]
1208    fn a_close_button_has_the_default_mouse_cursor_on_hover() {
1209        test_widgets(|tester| {
1210            assert!(
1211                *cursor_over::<CloseButton, _>(tester, CloseButton::new()) == *default_cursor()
1212            );
1213        });
1214    }
1215
1216    // 'DrawerButton has expected default mouse cursor on hover'
1217    #[test]
1218    fn a_drawer_button_has_the_default_mouse_cursor_on_hover() {
1219        test_widgets(|tester| {
1220            assert!(
1221                *cursor_over::<DrawerButton, _>(tester, DrawerButton::new()) == *default_cursor()
1222            );
1223        });
1224    }
1225
1226    // 'EndDrawerButton has expected default mouse cursor on hover'
1227    #[test]
1228    fn an_end_drawer_button_has_the_default_mouse_cursor_on_hover() {
1229        test_widgets(|tester| {
1230            assert!(
1231                *cursor_over::<EndDrawerButton, _>(tester, EndDrawerButton::new())
1232                    == *default_cursor()
1233            );
1234        });
1235    }
1236
1237    // 'BackButton has expected mouse cursor when explicitly configured'
1238    #[test]
1239    fn a_back_button_uses_the_mouse_cursor_its_style_gives() {
1240        test_widgets(|tester| {
1241            let cell: MouseCursorRef = SystemMouseCursors::CELL.into();
1242            assert!(
1243                *cursor_over::<BackButton, _>(tester, BackButton::new().style(cell_cursor_style()))
1244                    == *cell
1245            );
1246        });
1247    }
1248
1249    // 'CloseButton has expected mouse cursor when explicitly configured'
1250    #[test]
1251    fn a_close_button_uses_the_mouse_cursor_its_style_gives() {
1252        test_widgets(|tester| {
1253            let cell: MouseCursorRef = SystemMouseCursors::CELL.into();
1254            assert!(
1255                *cursor_over::<CloseButton, _>(
1256                    tester,
1257                    CloseButton::new().style(cell_cursor_style())
1258                ) == *cell
1259            );
1260        });
1261    }
1262
1263    // 'DrawerButton has expected mouse cursor when explicitly configured'
1264    #[test]
1265    fn a_drawer_button_uses_the_mouse_cursor_its_style_gives() {
1266        test_widgets(|tester| {
1267            let cell: MouseCursorRef = SystemMouseCursors::CELL.into();
1268            assert!(
1269                *cursor_over::<DrawerButton, _>(
1270                    tester,
1271                    DrawerButton::new().style(cell_cursor_style())
1272                ) == *cell
1273            );
1274        });
1275    }
1276
1277    // 'EndDrawerButton has expected mouse cursor when explicitly configured'
1278    #[test]
1279    fn an_end_drawer_button_uses_the_mouse_cursor_its_style_gives() {
1280        test_widgets(|tester| {
1281            let cell: MouseCursorRef = SystemMouseCursors::CELL.into();
1282            assert!(
1283                *cursor_over::<EndDrawerButton, _>(
1284                    tester,
1285                    EndDrawerButton::new().style(cell_cursor_style())
1286                ) == *cell
1287            );
1288        });
1289    }
1290}