Skip to main content

waft_material/
navigation_drawer.rs

1//! Flutter counterpart: material_ui's `navigation_drawer.dart` (and its part
2//! `generated/navigation_drawer_defaults_m3.g.dart`).
3
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{AnimationBehavior, AnimationController, AnimationRef, AnyAnimation};
9use waft_embedder::Color;
10use waft_foundation::{App, Handle, Listener, OptionRetained, Ref, ValueChanged};
11use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, ShapeBorderRef, TextStyle};
12use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
13use waft_widgets::{
14    BuildContext, Column, DefaultTextStyle, Expanded, IconTheme, IconThemeData, InheritedWidget,
15    IntoWidget, KeyRef, ListView, Padding, Row, SafeArea, Semantics,
16    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, SizedBox, Stack, State,
17    StateData, StatefulWidget, StatelessWidget, StatusTransitionWidget, TransitionBuilder,
18    WidgetBuilder, WidgetRef, WidgetState, WidgetStates, downcast_widget,
19};
20
21use crate::colors::Colors;
22use crate::drawer::Drawer;
23use crate::generated::navigation_drawer_defaults_m3::NavigationDrawerDefaultsM3;
24use crate::ink_decoration::Ink;
25use crate::ink_well::InkWell;
26use crate::material::{Material, MaterialType};
27use crate::material_localizations::MaterialLocalizations;
28use crate::navigation_bar::NavigationIndicator;
29use crate::navigation_drawer_theme::{NavigationDrawerTheme, NavigationDrawerThemeDataGetters};
30
31/// Material Design Navigation Drawer component.
32///
33/// On top of `Drawer`s, Navigation drawers offer a persistent and convenient way to switch
34/// between primary destinations in an app.
35///
36/// The style for the icons and text are not affected by parent
37/// `DefaultTextStyle`s or `IconTheme`s but rather controlled by parameters or
38/// the `NavigationDrawerThemeData`.
39///
40/// The [`children`](Self::children) are a list of widgets to be displayed in the drawer.
41/// These can be a mixture of any widgets, but there is special handling for
42/// [`NavigationDrawerDestination`]s. They are treated as a group and when one is selected,
43/// the [`on_destination_selected`](Self::on_destination_selected) is called with the index
44/// into the group that corresponds to the selected destination.
45///
46/// See also:
47///
48///  * `Scaffold::drawer`, where one specifies a `Drawer` so that it can be
49///    shown.
50///  * `Scaffold::of`, to obtain the current `ScaffoldState`, which manages the
51///    display and animation of the drawer.
52///  * `ScaffoldState::open_drawer`, which displays its `Drawer`, if any.
53///  * <https://material.io/design/components/navigation-drawer.html>
54pub struct NavigationDrawer {
55    pub key: Option<KeyRef>,
56
57    /// The background color of the `Material` that holds the [`NavigationDrawer`]'s
58    /// contents.
59    ///
60    /// If this is null, then `NavigationDrawerThemeData::background_color` is used.
61    /// If that is also null, then it falls back to `ColorScheme::surface_container_low`.
62    pub background_color: Option<Color>,
63
64    /// The color used for the drop shadow to indicate elevation.
65    ///
66    /// If null, `NavigationDrawerThemeData::shadow_color` is used. If that
67    /// is also null, the default value is `Colors::TRANSPARENT` which
68    /// indicates that no drop shadow will be displayed.
69    ///
70    /// See `Material::shadow_color` for more details on drop shadows.
71    pub shadow_color: Option<Color>,
72
73    /// The surface tint of the `Material` that holds the [`NavigationDrawer`]'s
74    /// contents.
75    ///
76    /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
77    /// introduced a set of tone-based surfaces and surface containers in its `ColorScheme`,
78    /// which provide more flexibility. The intention is to eventually remove surface tint color from
79    /// the framework.
80    ///
81    /// If this is null, then `NavigationDrawerThemeData::surface_tint_color` is used.
82    /// If that is also null, the default value is `Colors::TRANSPARENT`.
83    pub surface_tint_color: Option<Color>,
84
85    /// The elevation of the [`NavigationDrawer`] itself.
86    ///
87    /// If null, `NavigationDrawerThemeData::elevation` is used. If that
88    /// is also null, it will be 1.0.
89    pub elevation: Option<f64>,
90
91    /// The color of the [`indicator_shape`](Self::indicator_shape) when this destination is
92    /// selected.
93    ///
94    /// If this is null, `NavigationDrawerThemeData::indicator_color` is used.
95    /// If that is also null, defaults to `ColorScheme::secondary_container`.
96    pub indicator_color: Option<Color>,
97
98    /// The shape of the selected indicator.
99    ///
100    /// If this is null, `NavigationDrawerThemeData::indicator_shape` is used.
101    /// If that is also null, defaults to `StadiumBorder`.
102    pub indicator_shape: Option<ShapeBorderRef>,
103
104    /// Defines the appearance of the items within the navigation drawer.
105    ///
106    /// The list contains [`NavigationDrawerDestination`] widgets and/or customized
107    /// widgets like headlines and dividers.
108    pub children: Vec<WidgetRef>,
109
110    /// A widget to display at the top of the layout.
111    ///
112    /// Typically used for titles, navigation bars, or other header content.
113    pub header: Option<WidgetRef>,
114
115    /// A widget to display at the bottom of the layout.
116    ///
117    /// Typically used for actions, navigation controls, or other footer content.
118    pub footer: Option<WidgetRef>,
119
120    /// The index into destinations for the current selected
121    /// [`NavigationDrawerDestination`] or null if no destination is selected.
122    ///
123    /// A valid [`selected_index`](Self::selected_index) satisfies
124    /// 0 <= [`selected_index`](Self::selected_index) < number of
125    /// [`NavigationDrawerDestination`]. For an invalid
126    /// [`selected_index`](Self::selected_index) like `-1`, all destinations will appear
127    /// unselected.
128    pub selected_index: Option<i32>,
129
130    /// Called when one of the [`NavigationDrawerDestination`] children is selected.
131    ///
132    /// This callback usually updates the int passed to
133    /// [`selected_index`](Self::selected_index).
134    ///
135    /// Upon updating [`selected_index`](Self::selected_index), the [`NavigationDrawer`] will be
136    /// rebuilt.
137    pub on_destination_selected: Option<ValueChanged<i32>>,
138
139    /// Defines the padding for [`NavigationDrawerDestination`] widgets (Drawer items).
140    ///
141    /// Defaults to `EdgeInsets.symmetric(horizontal: 12.0)`.
142    pub tile_padding: EdgeInsetsGeometry,
143}
144
145impl NavigationDrawer {
146    /// Creates a Material Design Navigation Drawer component.
147    pub fn new(children: impl IntoIterator<Item = WidgetRef>) -> NavigationDrawer {
148        NavigationDrawer {
149            key: None,
150            background_color: None,
151            shadow_color: None,
152            surface_tint_color: None,
153            elevation: None,
154            indicator_color: None,
155            indicator_shape: None,
156            children: children.into_iter().collect(),
157            header: None,
158            footer: None,
159            selected_index: Some(0),
160            on_destination_selected: None,
161            tile_padding: EdgeInsetsGeometry::symmetric(0.0, 12.0),
162        }
163    }
164
165    /// Dart `NavigationDrawer(key:)`.
166    pub fn key(mut self, key: KeyRef) -> NavigationDrawer {
167        self.key = Some(key);
168        self
169    }
170
171    /// Dart `NavigationDrawer(header:)`.
172    #[cfg_attr(debug_assertions, track_caller)]
173    pub fn header<K>(mut self, header: impl IntoWidget<K>) -> NavigationDrawer {
174        self.header = Some(header.into_widget());
175        self
176    }
177
178    /// Dart `NavigationDrawer(footer:)`.
179    #[cfg_attr(debug_assertions, track_caller)]
180    pub fn footer<K>(mut self, footer: impl IntoWidget<K>) -> NavigationDrawer {
181        self.footer = Some(footer.into_widget());
182        self
183    }
184
185    /// Dart `NavigationDrawer(backgroundColor:)`.
186    pub fn background_color(mut self, background_color: Color) -> NavigationDrawer {
187        self.background_color = Some(background_color);
188        self
189    }
190
191    /// Dart `NavigationDrawer(shadowColor:)`.
192    pub fn shadow_color(mut self, shadow_color: Color) -> NavigationDrawer {
193        self.shadow_color = Some(shadow_color);
194        self
195    }
196
197    /// Dart `NavigationDrawer(surfaceTintColor:)`.
198    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> NavigationDrawer {
199        self.surface_tint_color = Some(surface_tint_color);
200        self
201    }
202
203    /// Dart `NavigationDrawer(elevation:)`.
204    pub fn elevation(mut self, elevation: f64) -> NavigationDrawer {
205        self.elevation = Some(elevation);
206        self
207    }
208
209    /// Dart `NavigationDrawer(indicatorColor:)`.
210    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationDrawer {
211        self.indicator_color = Some(indicator_color);
212        self
213    }
214
215    /// Dart `NavigationDrawer(indicatorShape:)`.
216    pub fn indicator_shape(
217        mut self,
218        indicator_shape: impl Into<ShapeBorderRef>,
219    ) -> NavigationDrawer {
220        self.indicator_shape = Some(indicator_shape.into());
221        self
222    }
223
224    /// Dart `NavigationDrawer(onDestinationSelected:)`.
225    pub fn on_destination_selected(
226        mut self,
227        on_destination_selected: ValueChanged<i32>,
228    ) -> NavigationDrawer {
229        self.on_destination_selected = Some(on_destination_selected);
230        self
231    }
232
233    /// Dart `NavigationDrawer(selectedIndex:)`; `None` selects no destination.
234    pub fn selected_index(mut self, selected_index: Option<i32>) -> NavigationDrawer {
235        self.selected_index = selected_index;
236        self
237    }
238
239    /// Dart `NavigationDrawer(tilePadding:)`.
240    pub fn tile_padding(mut self, tile_padding: impl Into<EdgeInsetsGeometry>) -> NavigationDrawer {
241        self.tile_padding = tile_padding.into();
242        self
243    }
244}
245
246impl Debug for NavigationDrawer {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.debug_struct("NavigationDrawer")
249            .field("background_color", &self.background_color)
250            .field("shadow_color", &self.shadow_color)
251            .field("surface_tint_color", &self.surface_tint_color)
252            .field("elevation", &self.elevation)
253            .field("indicator_color", &self.indicator_color)
254            .field("indicator_shape", &self.indicator_shape)
255            .field("children", &self.children)
256            .field("header", &self.header)
257            .field("footer", &self.footer)
258            .field("selected_index", &self.selected_index)
259            .field("tile_padding", &self.tile_padding)
260            .finish_non_exhaustive()
261    }
262}
263
264impl StatelessWidget for NavigationDrawer {
265    fn key(&self) -> Option<&KeyRef> {
266        self.key.as_ref()
267    }
268
269    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
270        let total_number_of_destinations = self
271            .children
272            .iter()
273            .filter(|child| downcast_widget::<NavigationDrawerDestination>(&***child).is_some())
274            .count() as i32;
275
276        let mut destination_index = 0;
277        let wrap_child = |child: WidgetRef, index: i32| {
278            let indicator_color = self.indicator_color;
279            let indicator_shape = self.indicator_shape.clone();
280            let tile_padding = self.tile_padding;
281            let on_destination_selected = self.on_destination_selected.clone();
282            SelectableAnimatedBuilder::new(
283                Some(index) == self.selected_index,
284                move |_app, _context, animation| {
285                    let on_destination_selected = on_destination_selected.clone();
286                    NavigationDrawerDestinationInfo {
287                        index,
288                        total_number_of_destinations,
289                        selected_animation: animation,
290                        indicator_color,
291                        indicator_shape: indicator_shape.clone(),
292                        on_tap: Listener::new(move |app| {
293                            if let Some(on_destination_selected) = &on_destination_selected {
294                                on_destination_selected(app, index);
295                            }
296                        }),
297                        child: child.clone(),
298                        tile_padding,
299                    }
300                    .into_widget()
301                },
302            )
303            .duration(Duration::from_millis(500))
304            .into_widget()
305        };
306
307        let wrapped_children: Vec<WidgetRef> = self
308            .children
309            .iter()
310            .map(|child| {
311                if downcast_widget::<NavigationDrawerDestination>(&**child).is_none() {
312                    child.clone()
313                } else {
314                    let index = destination_index;
315                    destination_index += 1;
316                    wrap_child(child.clone(), index)
317                }
318            })
319            .collect();
320        let navigation_drawer_theme = NavigationDrawerTheme::of(app, context);
321
322        let mut drawer = Drawer::new().child(
323            SafeArea::new(
324                Column::new().children(
325                    self.header
326                        .clone()
327                        .into_iter()
328                        .chain([Expanded::new(
329                            Material::new()
330                                .r#type(MaterialType::Transparency)
331                                .child(ListView::new().children(wrapped_children)),
332                        )
333                        .into_widget()])
334                        .chain(self.footer.clone()),
335                ),
336            )
337            .bottom(false),
338        );
339        drawer.background_color = self
340            .background_color
341            .or(navigation_drawer_theme.background_color);
342        drawer.shadow_color = self.shadow_color.or(navigation_drawer_theme.shadow_color);
343        drawer.surface_tint_color = self
344            .surface_tint_color
345            .or(navigation_drawer_theme.surface_tint_color);
346        drawer.elevation = self.elevation.or(navigation_drawer_theme.elevation);
347        drawer.into_widget()
348    }
349}
350
351/// A Material Design [`NavigationDrawer`] destination.
352///
353/// Displays an icon with a label, for use in [`NavigationDrawer::children`].
354pub struct NavigationDrawerDestination {
355    pub key: Option<KeyRef>,
356
357    /// The background color of the destination.
358    ///
359    /// If this is null, no background is set and [`NavigationDrawer::background_color`] will
360    /// be visible.
361    ///
362    /// This is the background color of the whole rectangular area behind the drawer
363    /// destination. To customize only the indicator color consider using
364    /// [`NavigationDrawer::indicator_color`].
365    pub background_color: Option<Color>,
366
367    /// The `Widget` (usually an `Icon`) that's displayed for this
368    /// `NavigationDestination`.
369    ///
370    /// The icon will use `NavigationDrawerThemeData::icon_theme`. If this is
371    /// null, the default `IconThemeData` would use a size of 24.0 and
372    /// `ColorScheme::on_surface_variant`.
373    pub icon: WidgetRef,
374
375    /// The optional `Widget` (usually an `Icon`) that's displayed when this
376    /// `NavigationDestination` is selected.
377    ///
378    /// If [`selected_icon`](Self::selected_icon) is non-null, the destination will fade from
379    /// [`icon`](Self::icon) to [`selected_icon`](Self::selected_icon) when this destination
380    /// goes from unselected to selected.
381    ///
382    /// The icon will use `NavigationDrawerThemeData::icon_theme` with
383    /// `WidgetState::Selected`. If this is null, the default `IconThemeData`
384    /// would use a size of 24.0 and `ColorScheme::on_secondary_container`.
385    pub selected_icon: Option<WidgetRef>,
386
387    /// The text label that appears on the right of the icon
388    ///
389    /// The accompanying `Text` widget will use
390    /// `NavigationDrawerThemeData::label_text_style`. If this are null, the default
391    /// text style would use `TextTheme::label_large` with `ColorScheme::on_surface_variant`.
392    pub label: WidgetRef,
393
394    /// Indicates that this destination is selectable.
395    ///
396    /// Defaults to true.
397    pub enabled: bool,
398}
399
400impl NavigationDrawerDestination {
401    /// Creates a navigation drawer destination.
402    #[cfg_attr(debug_assertions, track_caller)]
403    pub fn new<I, L>(
404        icon: impl IntoWidget<I>,
405        label: impl IntoWidget<L>,
406    ) -> NavigationDrawerDestination {
407        NavigationDrawerDestination {
408            key: None,
409            background_color: None,
410            icon: icon.into_widget(),
411            selected_icon: None,
412            label: label.into_widget(),
413            enabled: true,
414        }
415    }
416
417    /// Dart `NavigationDrawerDestination(key:)`.
418    pub fn key(mut self, key: KeyRef) -> NavigationDrawerDestination {
419        self.key = Some(key);
420        self
421    }
422
423    /// Dart `NavigationDrawerDestination(backgroundColor:)`.
424    pub fn background_color(mut self, background_color: Color) -> NavigationDrawerDestination {
425        self.background_color = Some(background_color);
426        self
427    }
428
429    /// Dart `NavigationDrawerDestination(selectedIcon:)`.
430    #[cfg_attr(debug_assertions, track_caller)]
431    pub fn selected_icon<K>(
432        mut self,
433        selected_icon: impl IntoWidget<K>,
434    ) -> NavigationDrawerDestination {
435        self.selected_icon = Some(selected_icon.into_widget());
436        self
437    }
438
439    /// Dart `NavigationDrawerDestination(enabled:)`.
440    pub fn enabled(mut self, enabled: bool) -> NavigationDrawerDestination {
441        self.enabled = enabled;
442        self
443    }
444}
445
446impl Debug for NavigationDrawerDestination {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        f.debug_struct("NavigationDrawerDestination")
449            .field("background_color", &self.background_color)
450            .field("icon", &self.icon)
451            .field("selected_icon", &self.selected_icon)
452            .field("label", &self.label)
453            .field("enabled", &self.enabled)
454            .finish()
455    }
456}
457
458impl StatelessWidget for NavigationDrawerDestination {
459    fn key(&self) -> Option<&KeyRef> {
460        self.key.as_ref()
461    }
462
463    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
464        let selected_state = WidgetStates::from([WidgetState::Selected]);
465        let unselected_state = WidgetStates::new();
466        let disabled_state = WidgetStates::from([WidgetState::Disabled]);
467
468        let navigation_drawer_theme = NavigationDrawerTheme::of(app, context);
469        let defaults = Rc::new(NavigationDrawerDefaultsM3::new(context));
470
471        let animation = NavigationDrawerDestinationInfo::of(app, context).selected_animation;
472        let icon_animation = animation.clone();
473
474        let enabled = self.enabled;
475        let icon = self.icon.clone();
476        let selected_icon = self.selected_icon.clone();
477        let label = self.label.clone();
478        let (icon_theme, label_theme) = (navigation_drawer_theme.clone(), navigation_drawer_theme);
479        let (icon_defaults, label_defaults) = (Rc::clone(&defaults), defaults);
480        let (icon_selected, icon_unselected, icon_disabled) = (
481            selected_state.clone(),
482            unselected_state.clone(),
483            disabled_state.clone(),
484        );
485        NavigationDestinationBuilder {
486            build_icon: Rc::new(move |app, _context| {
487                let resolve = |app: &mut App, states: &WidgetStates| -> IconThemeData {
488                    icon_theme
489                        .icon_theme
490                        .as_ref()
491                        .and_then(|icon_theme| icon_theme.resolve(states))
492                        .unwrap_or_else(|| {
493                            icon_defaults
494                                .icon_theme(app)
495                                .expect("the defaults give an icon theme")
496                                .resolve(states)
497                                .expect("the defaults resolve every state")
498                        })
499                };
500                let selected_icon_widget = IconTheme::merge(
501                    None,
502                    resolve(
503                        app,
504                        if enabled {
505                            &icon_selected
506                        } else {
507                            &icon_disabled
508                        },
509                    ),
510                    selected_icon.clone().unwrap_or_else(|| icon.clone()),
511                );
512                let unselected_icon_widget = IconTheme::merge(
513                    None,
514                    resolve(
515                        app,
516                        if enabled {
517                            &icon_unselected
518                        } else {
519                            &icon_disabled
520                        },
521                    ),
522                    icon.clone(),
523                );
524
525                if icon_animation.is_forward_or_completed(app) {
526                    selected_icon_widget
527                } else {
528                    unselected_icon_widget
529                }
530            }),
531            build_label: Rc::new(move |app, _context| {
532                let resolve = |app: &mut App, states: &WidgetStates| -> Option<TextStyle> {
533                    label_theme
534                        .label_text_style
535                        .as_ref()
536                        .and_then(|label_text_style| label_text_style.resolve(states))
537                        .or_else(|| {
538                            label_defaults
539                                .label_text_style(app)
540                                .expect("the defaults give a label text style")
541                                .resolve(states)
542                        })
543                };
544                let effective_selected_label_text_style = resolve(
545                    app,
546                    if enabled {
547                        &selected_state
548                    } else {
549                        &disabled_state
550                    },
551                );
552                let effective_unselected_label_text_style = resolve(
553                    app,
554                    if enabled {
555                        &unselected_state
556                    } else {
557                        &disabled_state
558                    },
559                );
560
561                DefaultTextStyle::new(
562                    if animation.is_forward_or_completed(app) {
563                        effective_selected_label_text_style.expect("a selected label text style")
564                    } else {
565                        effective_unselected_label_text_style
566                            .expect("an unselected label text style")
567                    },
568                    label.clone(),
569                )
570                .into_widget()
571            }),
572            enabled: self.enabled,
573            background_color: self.background_color,
574        }
575        .into_widget()
576    }
577}
578
579/// Widget that handles the semantics and layout of a navigation drawer
580/// destination.
581///
582/// Prefer `NavigationDestination` over this widget, as it is a simpler
583/// (although less customizable) way to get navigation drawer destinations.
584///
585/// The icon and label of this destination are built with
586/// [`build_icon`](Self::build_icon) and [`build_label`](Self::build_label). They should build
587/// the unselected and selected icon and label according to
588/// [`NavigationDrawerDestinationInfo::selected_animation`], where an animation value of 0 is
589/// unselected and 1 is selected.
590///
591/// See `NavigationDestination` for an example.
592struct NavigationDestinationBuilder {
593    /// Builds the icon for a destination in a [`NavigationDrawer`].
594    ///
595    /// To animate between unselected and selected, build the icon based on
596    /// [`NavigationDrawerDestinationInfo::selected_animation`]. When the animation is 0,
597    /// the destination is unselected, when the animation is 1, the destination is
598    /// selected.
599    ///
600    /// The destination is considered selected as soon as the animation is
601    /// increasing or completed, and it is considered unselected as soon as the
602    /// animation is decreasing or dismissed.
603    build_icon: WidgetBuilder,
604
605    /// Builds the label for a destination in a [`NavigationDrawer`].
606    ///
607    /// To animate between unselected and selected, build the icon based on
608    /// [`NavigationDrawerDestinationInfo::selected_animation`]. When the animation is
609    /// 0, the destination is unselected, when the animation is 1, the destination
610    /// is selected.
611    ///
612    /// The destination is considered selected as soon as the animation is
613    /// increasing or completed, and it is considered unselected as soon as the
614    /// animation is decreasing or dismissed.
615    build_label: WidgetBuilder,
616
617    /// Indicates that this destination is selectable.
618    ///
619    /// Defaults to true.
620    enabled: bool,
621
622    /// The background color of the destination.
623    background_color: Option<Color>,
624}
625
626impl Debug for NavigationDestinationBuilder {
627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628        f.debug_struct("_NavigationDestinationBuilder")
629            .field("enabled", &self.enabled)
630            .field("background_color", &self.background_color)
631            .finish_non_exhaustive()
632    }
633}
634
635impl StatelessWidget for NavigationDestinationBuilder {
636    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
637        let info = NavigationDrawerDestinationInfo::of(app, context);
638        let navigation_drawer_theme = NavigationDrawerTheme::of(app, context);
639        let defaults = NavigationDrawerDefaultsM3::new(context);
640
641        let indicator_shape = |app: &mut App| {
642            info.indicator_shape
643                .clone()
644                .or_else(|| navigation_drawer_theme.indicator_shape.clone())
645                .or_else(|| defaults.indicator_shape(app))
646                .expect("the defaults give an indicator shape")
647        };
648        let indicator_size = navigation_drawer_theme
649            .indicator_size
650            .or_else(|| defaults.indicator_size(app))
651            .expect("the defaults give an indicator size");
652        let mut ink_well = InkWell::new()
653            .highlight_color(Colors::TRANSPARENT)
654            .custom_border(indicator_shape(app));
655        if self.enabled {
656            ink_well = ink_well.on_tap(info.on_tap.clone());
657        }
658        let indicator_color = info
659            .indicator_color
660            .or(navigation_drawer_theme.indicator_color)
661            .or_else(|| defaults.indicator_color(app))
662            .expect("the defaults give an indicator color");
663        let indicator_shape = indicator_shape(app);
664        let ink_well = ink_well.child(
665            Stack::new().alignment(AlignmentGeometry::CENTER).children([
666                NavigationIndicator::new(info.selected_animation)
667                    .color(indicator_color)
668                    .shape(indicator_shape)
669                    .width(indicator_size.width())
670                    .height(indicator_size.height())
671                    .into_widget(),
672                Row::new()
673                    .children([
674                        SizedBox::new().width(16.0).into_widget(),
675                        (self.build_icon)(app, context),
676                        SizedBox::new().width(12.0).into_widget(),
677                        (self.build_label)(app, context),
678                    ])
679                    .into_widget(),
680            ]),
681        );
682
683        let mut tile = SizedBox::new().child(ink_well);
684        tile.height = navigation_drawer_theme
685            .tile_height
686            .or_else(|| defaults.tile_height(app));
687        let destination = Padding::new(info.tile_padding)
688            .child(NavigationDestinationSemantics {
689                child: tile.into_widget(),
690            })
691            .into_widget();
692
693        if let Some(background_color) = self.background_color {
694            return Ink::new()
695                .color(background_color)
696                .child(destination)
697                .into_widget();
698        }
699        destination
700    }
701}
702
703/// Semantics widget for a navigation drawer destination.
704///
705/// Requires a [`NavigationDrawerDestinationInfo`] parent (normally provided by the
706/// [`NavigationDrawer`] by default).
707///
708/// Provides localized semantic labels to the destination, for example, it will
709/// read "Home, Tab 1 of 3".
710///
711/// Used by [`NavigationDestinationBuilder`].
712#[derive(Debug)]
713struct NavigationDestinationSemantics {
714    /// The widget that should receive the destination semantics.
715    child: WidgetRef,
716}
717
718impl StatelessWidget for NavigationDestinationSemantics {
719    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
720        let localizations = <dyn MaterialLocalizations>::of(app, context);
721        let destination_info = NavigationDrawerDestinationInfo::of(app, context);
722        let selected_animation = destination_info.selected_animation.clone();
723        // The AnimationStatusBuilder will make sure that the semantics update to
724        // "selected" when the animation status changes.
725        StatusTransitionWidgetBuilder::new(
726            selected_animation.clone(),
727            move |app, _context, child| {
728                let mut semantics = Semantics::new()
729                    .selected(selected_animation.is_forward_or_completed(app))
730                    .container(true);
731                if let Some(child) = child {
732                    semantics = semantics.child(child.clone());
733                }
734                semantics.into_widget()
735            },
736        )
737        .child(
738            Stack::new().alignment(AlignmentGeometry::CENTER).children([
739                self.child.clone(),
740                Semantics::new()
741                    .label(localizations.tab_label(
742                        destination_info.index + 1,
743                        destination_info.total_number_of_destinations,
744                    ))
745                    .into_widget(),
746            ]),
747        )
748        .into_widget()
749    }
750}
751
752/// Widget that listens to an animation, and rebuilds when the animation changes
753/// `AnimationStatus`.
754///
755/// This can be more efficient than just using an `AnimatedBuilder` when you
756/// only need to rebuild when the `Animation::status` changes, since
757/// `AnimatedBuilder` rebuilds every time the animation ticks.
758struct StatusTransitionWidgetBuilder {
759    animation: AnimationRef<f64>,
760
761    /// Called every time the animation changes `AnimationStatus`.
762    builder: TransitionBuilder,
763
764    /// The child widget to pass to the [`builder`](Self::builder).
765    ///
766    /// If a [`builder`](Self::builder) callback's return value contains a subtree that does
767    /// not depend on the animation, it's more efficient to build that subtree once
768    /// instead of rebuilding it on every animation status change.
769    ///
770    /// Using this pre-built child is entirely optional, but can improve
771    /// performance in some cases and is therefore a good practice.
772    ///
773    /// See: `AnimatedBuilder::child`
774    child: Option<WidgetRef>,
775}
776
777impl StatusTransitionWidgetBuilder {
778    /// Creates a widget that rebuilds when the given animation changes status.
779    fn new(
780        animation: AnimationRef<f64>,
781        builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
782    ) -> StatusTransitionWidgetBuilder {
783        StatusTransitionWidgetBuilder {
784            animation,
785            builder: Rc::new(builder),
786            child: None,
787        }
788    }
789
790    /// Dart `_StatusTransitionWidgetBuilder(child:)`.
791    #[cfg_attr(debug_assertions, track_caller)]
792    fn child<K>(mut self, child: impl IntoWidget<K>) -> StatusTransitionWidgetBuilder {
793        self.child = Some(child.into_widget());
794        self
795    }
796}
797
798impl Debug for StatusTransitionWidgetBuilder {
799    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800        f.debug_struct("_StatusTransitionWidgetBuilder")
801            .field("animation", &self.animation)
802            .field("child", &self.child)
803            .finish_non_exhaustive()
804    }
805}
806
807impl StatusTransitionWidget for StatusTransitionWidgetBuilder {
808    fn animation(&self) -> AnyAnimation<f64> {
809        self.animation.handle()
810    }
811
812    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
813        (self.builder)(app, context, self.child.as_ref())
814    }
815}
816
817/// Inherited widget for passing data from the [`NavigationDrawer`] to the
818/// [`NavigationDrawerDestination`] child widgets.
819///
820/// Useful for building navigation destinations using:
821/// `NavigationDrawerDestinationInfo::of(app, context)`.
822#[derive(Clone)]
823struct NavigationDrawerDestinationInfo {
824    /// Which destination index is this in the navigation drawer.
825    ///
826    /// For example:
827    ///
828    /// ```text
829    /// NavigationDrawer::new([
830    ///     Text::new("Headline").into_widget(), // This doesn't have index.
831    ///     // This is destination index 0.
832    ///     NavigationDrawerDestination::new(Icon::new(Some(Icons::surfing())), Text::new("Surfing")).into_widget(),
833    ///     // This is destination index 1.
834    ///     NavigationDrawerDestination::new(Icon::new(Some(Icons::support())), Text::new("Support")).into_widget(),
835    ///     // This is destination index 2.
836    ///     NavigationDrawerDestination::new(Icon::new(Some(Icons::local_hospital())), Text::new("Hospital")).into_widget(),
837    /// ])
838    /// ```
839    ///
840    /// This is required for semantics, so that each destination can have a label
841    /// "Tab 1 of 3", for example.
842    index: i32,
843
844    /// How many total destinations are in this navigation drawer.
845    ///
846    /// This is required for semantics, so that each destination can have a label
847    /// "Tab 1 of 4", for example.
848    total_number_of_destinations: i32,
849
850    /// Indicates whether or not this destination is selected, from 0 (unselected)
851    /// to 1 (selected).
852    selected_animation: AnimationRef<f64>,
853
854    /// The color of the indicator.
855    ///
856    /// This is used by destinations to override the indicator color.
857    indicator_color: Option<Color>,
858
859    /// The shape of the indicator.
860    ///
861    /// This is used by destinations to override the indicator shape.
862    indicator_shape: Option<ShapeBorderRef>,
863
864    /// The callback that should be called when this destination is tapped.
865    ///
866    /// This is computed by calling [`NavigationDrawer::on_destination_selected`]
867    /// with [`index`](Self::index) passed in.
868    on_tap: Listener,
869
870    child: WidgetRef,
871
872    /// Defines the padding for [`NavigationDrawerDestination`] widgets (Drawer items).
873    ///
874    /// Defaults to `EdgeInsets.symmetric(horizontal: 12.0)`.
875    tile_padding: EdgeInsetsGeometry,
876}
877
878impl NavigationDrawerDestinationInfo {
879    /// Returns a non null [`NavigationDrawerDestinationInfo`].
880    ///
881    /// This will return an error if called with no [`NavigationDrawerDestinationInfo`]
882    /// ancestor.
883    ///
884    /// Used by widgets that are implementing a navigation destination info to
885    /// get information like the selected animation and destination number.
886    fn of(app: &mut App, context: BuildContext) -> NavigationDrawerDestinationInfo {
887        context
888            .depend_on_inherited_widget_of_exact_type::<NavigationDrawerDestinationInfo>(app)
889            .cloned()
890            .expect(
891                "Navigation destinations need a _NavigationDrawerDestinationInfo parent, which \
892                 is usually provided by NavigationDrawer.",
893            )
894    }
895}
896
897impl Debug for NavigationDrawerDestinationInfo {
898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899        f.debug_struct("_NavigationDrawerDestinationInfo")
900            .field("index", &self.index)
901            .field(
902                "total_number_of_destinations",
903                &self.total_number_of_destinations,
904            )
905            .field("selected_animation", &self.selected_animation)
906            .field("indicator_color", &self.indicator_color)
907            .field("indicator_shape", &self.indicator_shape)
908            .field("child", &self.child)
909            .field("tile_padding", &self.tile_padding)
910            .finish_non_exhaustive()
911    }
912}
913
914impl InheritedWidget for NavigationDrawerDestinationInfo {
915    fn child(&self) -> &WidgetRef {
916        &self.child
917    }
918
919    fn update_should_notify(&self, old_widget: &NavigationDrawerDestinationInfo) -> bool {
920        self.index != old_widget.index
921            || self.total_number_of_destinations != old_widget.total_number_of_destinations
922            || self.selected_animation != old_widget.selected_animation
923            || self.on_tap != old_widget.on_tap
924    }
925}
926
927/// Dart's `Widget Function(BuildContext, Animation<double>)` builder of
928/// [`SelectableAnimatedBuilder`].
929type AnimationWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;
930
931// Builder widget for widgets that need to be animated from 0 (unselected) to
932// 1.0 (selected).
933//
934// This widget creates and manages an `AnimationController` that it passes down
935// to the child through the `builder` function.
936//
937// When `is_selected` is `true`, the animation controller will animate from
938// 0 to 1 (for `duration` time).
939//
940// When `is_selected` is `false`, the animation controller will animate from
941// 1 to 0 (for `duration` time).
942//
943// If `is_selected` is updated while the widget is animating, the animation will
944// be reversed until it is either 0 or 1 again.
945struct SelectableAnimatedBuilder {
946    /// When true, the widget will animate an animation controller from 0 to 1.
947    ///
948    /// The animation controller is passed to the child widget through
949    /// [`builder`](Self::builder).
950    is_selected: bool,
951
952    /// How long the animation controller should animate for when
953    /// [`is_selected`](Self::is_selected) is updated.
954    ///
955    /// If the animation is currently running and [`is_selected`](Self::is_selected) is
956    /// updated, only the [`duration`](Self::duration) left to finish the animation will be
957    /// run.
958    duration: Duration,
959
960    /// Builds the child widget based on the current animation status.
961    ///
962    /// When [`is_selected`](Self::is_selected) is updated to true, this builder will be called
963    /// and the animation will animate up to 1. When [`is_selected`](Self::is_selected) is
964    /// updated to `false`, this will be called and the animation will animate down to 0.
965    builder: AnimationWidgetBuilder,
966}
967
968impl SelectableAnimatedBuilder {
969    /// Builds and maintains an `AnimationController` that will animate from 0 to
970    /// 1 and back depending on when [`is_selected`](Self::is_selected) is true.
971    fn new(
972        is_selected: bool,
973        builder: impl Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef + 'static,
974    ) -> SelectableAnimatedBuilder {
975        SelectableAnimatedBuilder {
976            is_selected,
977            duration: Duration::from_millis(200),
978            builder: Rc::new(builder),
979        }
980    }
981
982    /// Dart `_SelectableAnimatedBuilder(duration:)`.
983    fn duration(mut self, duration: Duration) -> SelectableAnimatedBuilder {
984        self.duration = duration;
985        self
986    }
987}
988
989impl Debug for SelectableAnimatedBuilder {
990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991        f.debug_struct("_SelectableAnimatedBuilder")
992            .field("is_selected", &self.is_selected)
993            .field("duration", &self.duration)
994            .finish_non_exhaustive()
995    }
996}
997
998impl StatefulWidget for SelectableAnimatedBuilder {
999    type State = SelectableAnimatedBuilderState;
1000
1001    fn create_state(&self) -> SelectableAnimatedBuilderState {
1002        SelectableAnimatedBuilderState {
1003            state: StateData::new(),
1004            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1005            controller: None,
1006        }
1007    }
1008}
1009
1010/// State that manages the `AnimationController` that is passed to
1011/// [`SelectableAnimatedBuilder::builder`].
1012struct SelectableAnimatedBuilderState {
1013    state: StateData<SelectableAnimatedBuilder>,
1014    single_ticker_provider: SingleTickerProviderStateMixinData,
1015    controller: Option<Ref<AnimationController>>,
1016}
1017
1018impl SelectableAnimatedBuilderState {
1019    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1020        app.get(self)
1021            .controller
1022            .handle()
1023            .expect("created in init_state")
1024    }
1025}
1026
1027impl SingleTickerProviderStateMixin for SelectableAnimatedBuilderState {
1028    fn single_ticker_provider_data(
1029        self: Handle<Self>,
1030        app: &App,
1031    ) -> &SingleTickerProviderStateMixinData {
1032        &app.get(self).single_ticker_provider
1033    }
1034
1035    fn single_ticker_provider_data_mut(
1036        self: Handle<Self>,
1037        app: &mut App,
1038    ) -> &mut SingleTickerProviderStateMixinData {
1039        &mut app.get_mut(self).single_ticker_provider
1040    }
1041}
1042
1043impl TickerProviderObject for SelectableAnimatedBuilderState {
1044    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1045        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1046    }
1047}
1048
1049impl State for SelectableAnimatedBuilderState {
1050    type Widget = SelectableAnimatedBuilder;
1051    waft_widgets::state_accessors!();
1052
1053    fn init_state(self: Handle<Self>, app: &mut App) {
1054        let controller = AnimationController::new(
1055            app,
1056            None,
1057            None,
1058            None,
1059            0.0,
1060            1.0,
1061            AnimationBehavior::Normal,
1062            self,
1063        );
1064        app.get_mut(self).controller = Some(controller.clone());
1065        let widget = self.widget(app);
1066        let duration = widget.duration;
1067        let value = if widget.is_selected { 1.0 } else { 0.0 };
1068        app.get_mut(&controller).duration = Some(duration);
1069        controller.set_value(app, value);
1070    }
1071
1072    fn did_update_widget(
1073        self: Handle<Self>,
1074        app: &mut App,
1075        old_widget: &SelectableAnimatedBuilder,
1076    ) {
1077        let controller = self.controller(app);
1078        let widget = self.widget(app);
1079        let duration = widget.duration;
1080        let is_selected = widget.is_selected;
1081        if old_widget.duration != duration {
1082            app.get_mut(controller).duration = Some(duration);
1083        }
1084        if old_widget.is_selected != is_selected {
1085            if is_selected {
1086                controller.forward(app, None);
1087            } else {
1088                controller.reverse(app, None);
1089            }
1090        }
1091    }
1092
1093    fn activate(self: Handle<Self>, app: &mut App) {
1094        SingleTickerProviderStateMixin::activate(self, app);
1095    }
1096
1097    fn dispose(self: Handle<Self>, app: &mut App) {
1098        let controller = self.controller(app);
1099        controller.dispose(app);
1100        SingleTickerProviderStateMixin::dispose(self, app);
1101    }
1102
1103    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1104        let builder = Rc::clone(&self.widget(app).builder);
1105        let controller = app
1106            .get(self)
1107            .controller
1108            .as_ref()
1109            .expect("created in init_state")
1110            .erase();
1111        builder(app, context, controller)
1112    }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    //! The cases of `test/navigation_drawer_test.dart` and the widget cases of
1118    //! `test/navigation_drawer_theme_test.dart`.
1119
1120    use std::cell::{Cell, RefCell};
1121    use waft_painting::ShapeBorder;
1122
1123    use waft_embedder::{Offset, Radius, Rect, Size};
1124    use waft_painting::{
1125        BorderRadius, BorderRadiusGeometry, BorderSide, BoxDecoration, CircleBorder, EdgeInsets,
1126        RoundedRectangleBorder, ShapeDecoration, StadiumBorder,
1127    };
1128    use waft_rendering::{AnyRenderBox, AnyRenderObject};
1129
1130    use waft_widgets::{
1131        AnyElement, Center, Container, GlobalKey, Icon, IconData, MediaQuery, MediaQueryData,
1132        StatefulBuilder, Text, WidgetStatePropertyAll, WidgetsBinding,
1133    };
1134
1135    use waft_widgets::testing::{
1136        WidgetTester, expect, find, finds_n_widgets, finds_one_widget, test_widgets,
1137    };
1138
1139    use super::*;
1140    use crate::app::MaterialApp;
1141    use crate::drawer_header::DrawerHeader;
1142    use crate::icons::Icons;
1143    use crate::list_tile::ListTile;
1144    use crate::material::RenderInkFeatures;
1145    use crate::navigation_drawer_theme::NavigationDrawerThemeData;
1146    use crate::scaffold::{Scaffold, ScaffoldState};
1147    use crate::test_support::material_app;
1148    use crate::theme_data::ThemeData;
1149    use crate::tooltip::tests::{m3, pump_app};
1150
1151    /// Dart's `widgetSetup(tester, viewWidth, viewHeight: viewHeight)`: a 2x view of that
1152    /// logical size.
1153    fn widget_setup(tester: &WidgetTester, view_width: f64, view_height: f64) {
1154        tester.view().set_device_pixel_ratio(2.0);
1155        let dpi = tester.device_pixel_ratio();
1156        tester
1157            .view()
1158            .set_physical_size(Size::new(view_width * dpi, view_height * dpi));
1159    }
1160
1161    /// Dart's `_buildWidget(scaffoldKey, child)`: a `MaterialApp` whose home is a scaffold
1162    /// keyed `key` with the drawer `drawer`.
1163    fn pump_drawer(
1164        tester: &mut WidgetTester,
1165        theme: impl FnOnce(&App) -> ThemeData,
1166        key: &GlobalKey,
1167        drawer: impl FnOnce(&mut App) -> WidgetRef,
1168    ) {
1169        let key = key.clone();
1170        pump_app(tester, theme, move |app| {
1171            Scaffold::new()
1172                .key(key.into())
1173                .drawer(drawer(app))
1174                .body(Container::new())
1175                .into_widget()
1176        });
1177    }
1178
1179    /// Dart's `scaffoldKey.currentState!.openDrawer()`.
1180    fn open_drawer(tester: &WidgetTester, key: &GlobalKey) {
1181        let mut app = tester.cell.borrow_mut();
1182        let state = key
1183            .current_state::<ScaffoldState>(&app)
1184            .expect("a mounted scaffold");
1185        state.open_drawer(&mut app);
1186    }
1187
1188    fn destination(icon: IconData, label: &str) -> WidgetRef {
1189        NavigationDrawerDestination::new(Icon::new(Some(icon)), Text::new(label)).into_widget()
1190    }
1191
1192    /// The headline and the two destinations most cases build.
1193    fn headline_and_two_destinations() -> Vec<WidgetRef> {
1194        vec![
1195            Text::new("Headline").into_widget(),
1196            destination(Icons::ac_unit(), "AC"),
1197            destination(Icons::access_alarm(), "Alarm"),
1198        ]
1199    }
1200
1201    fn select_nothing() -> ValueChanged<i32> {
1202        Rc::new(|_app, _index| {})
1203    }
1204
1205    fn found(tester: &WidgetTester, text: &str) -> usize {
1206        find::text(text).evaluate(tester).len()
1207    }
1208
1209    fn text_center(tester: &WidgetTester, text: &str) -> Offset {
1210        let text = *find::text(text).evaluate(tester).first().expect("the text");
1211        tester.get_rect(text).center()
1212    }
1213
1214    fn icon_center(tester: &WidgetTester, icon: &IconData) -> Offset {
1215        let icon = tester.element(find::by_icon(icon).first());
1216        tester.get_rect(icon).center()
1217    }
1218
1219    fn navigation_drawer(tester: &WidgetTester) -> AnyElement {
1220        *find::by_type::<NavigationDrawer>()
1221            .evaluate(tester)
1222            .first()
1223            .expect("a NavigationDrawer")
1224    }
1225
1226    /// Dart's `_getMaterial(tester)`: the first `Material` in the drawer.
1227    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
1228        let material = *tester
1229            .descendants_of_type::<Material>(navigation_drawer(tester))
1230            .first()
1231            .expect("a Material in the drawer");
1232        tester.widget(material, read)
1233    }
1234
1235    /// Dart's `_getInkWell(tester)?.customBorder`: the first `InkWell` in the drawer.
1236    fn ink_well_custom_border(tester: &WidgetTester) -> Option<ShapeBorderRef> {
1237        let ink_well = *tester
1238            .descendants_of_type::<InkWell>(navigation_drawer(tester))
1239            .first()
1240            .expect("an InkWell in the drawer");
1241        tester.widget(ink_well, |ink_well: &InkWell| {
1242            ink_well.ink_response.custom_border.clone()
1243        })
1244    }
1245
1246    /// Dart's `_getIndicatorDecoration(tester)`: the `ShapeDecoration` of the first `Ink`
1247    /// under a `NavigationIndicator`, as its color and shape.
1248    fn indicator_decoration(tester: &WidgetTester) -> (Option<Color>, ShapeBorderRef) {
1249        let ink = find::by_type::<NavigationIndicator>()
1250            .evaluate(tester)
1251            .into_iter()
1252            .flat_map(|indicator| tester.descendants_of_type::<Ink>(indicator))
1253            .next()
1254            .expect("an Ink under a NavigationIndicator");
1255        tester.widget(ink, |ink: &Ink| {
1256            let decoration = ink
1257                .decoration
1258                .as_deref()
1259                .expect("the indicator's decoration");
1260            let decoration = decoration
1261                .as_any()
1262                .downcast_ref::<ShapeDecoration>()
1263                .expect("a ShapeDecoration");
1264            (
1265                decoration.color.as_deref().copied(),
1266                decoration.shape.clone(),
1267            )
1268        })
1269    }
1270
1271    /// Dart's `_iconStyle(tester, icon)?.color`.
1272    fn icon_color(tester: &WidgetTester, icon: &IconData) -> Option<Color> {
1273        tester
1274            .glyph_style(tester.element(find::by_icon(icon).first()))
1275            .color
1276            .as_deref()
1277            .copied()
1278    }
1279
1280    /// Dart's `_labelStyle(tester, label)`.
1281    fn label_style(tester: &WidgetTester, label: &str) -> TextStyle {
1282        let text = *find::text(label)
1283            .evaluate(tester)
1284            .first()
1285            .expect("the label");
1286        tester.glyph_style(text)
1287    }
1288
1289    fn label_color(tester: &WidgetTester, label: &str) -> Option<Color> {
1290        label_style(tester, label).color.as_deref().copied()
1291    }
1292
1293    fn shape_eq(a: &dyn ShapeBorder, b: &dyn ShapeBorder) -> bool {
1294        a == b
1295    }
1296
1297    /// Dart has no case measuring this, but `Drawer` lays the drawer out at its `_kWidth`, 304,
1298    /// and the destination's indicator takes the width of its padded tile. The theme's 336 is
1299    /// wider than the 280 that leaves, so it is clamped to the row's own rect.
1300    #[test]
1301    fn a_destinations_indicator_covers_its_row() {
1302        test_widgets(|tester| {
1303            let key = GlobalKey::new();
1304            widget_setup(tester, 800.0, 1000.0);
1305            pump_drawer(tester, m3, &key, move |_app| {
1306                NavigationDrawer::new([
1307                    destination(Icons::explore(), "Explore"),
1308                    destination(Icons::chat(), "Chats"),
1309                ])
1310                .on_destination_selected(select_nothing())
1311                .into_widget()
1312            });
1313            open_drawer(tester, &key);
1314            tester.pump_by(Duration::from_secs(1));
1315
1316            let drawer = navigation_drawer(tester);
1317            let drawer_rect = tester.get_rect(drawer);
1318            assert_eq!(drawer_rect.width(), 304.0, "Drawer._kWidth");
1319            let row = *tester
1320                .descendants_of_type::<InkWell>(drawer)
1321                .first()
1322                .expect("the destination's row");
1323            let row_rect = tester.get_rect(row);
1324            assert_eq!(row_rect.left, drawer_rect.left + 12.0, "tilePadding");
1325            assert_eq!(row_rect.width(), 304.0 - 2.0 * 12.0);
1326            assert_eq!(row_rect.height(), 56.0, "tileHeight");
1327
1328            let indicator = *tester
1329                .descendants_of_type::<NavigationIndicator>(drawer)
1330                .first()
1331                .expect("the selected indicator");
1332            let indicator_ink = *tester
1333                .descendants_of_type::<Ink>(indicator)
1334                .first()
1335                .expect("the indicator's ink");
1336            assert_eq!(tester.get_rect(indicator_ink), row_rect);
1337
1338            let label = *find::text("Explore")
1339                .evaluate(tester)
1340                .first()
1341                .expect("the label");
1342            assert_eq!(
1343                tester.get_rect(label).left,
1344                row_rect.left + 16.0 + 24.0 + 12.0,
1345                "the row's leading inset"
1346            );
1347        });
1348    }
1349
1350    // 'Navigation drawer updates destinations when tapped'.
1351    #[test]
1352    fn navigation_drawer_updates_destinations_when_tapped() {
1353        test_widgets(|tester| {
1354            let mutated_index = Rc::new(Cell::new(-1));
1355            let key = GlobalKey::new();
1356            widget_setup(tester, 3000.0, 3000.0);
1357            let mutated = Rc::clone(&mutated_index);
1358            pump_drawer(tester, m3, &key, move |_app| {
1359                NavigationDrawer::new(headline_and_two_destinations())
1360                    .on_destination_selected(Rc::new(move |_app, i| mutated.set(i)))
1361                    .into_widget()
1362            });
1363            open_drawer(tester, &key);
1364            tester.pump();
1365
1366            assert_eq!(found(tester, "Headline"), 1);
1367            assert_eq!(found(tester, "AC"), 1);
1368            assert_eq!(found(tester, "Alarm"), 1);
1369
1370            tester.pump_by(Duration::from_secs(1)); // animation done
1371
1372            let at = text_center(tester, "Alarm");
1373            tester.tap_at(at, 1);
1374            assert_eq!(mutated_index.get(), 1);
1375
1376            let at = text_center(tester, "AC");
1377            tester.tap_at(at, 2);
1378            assert_eq!(mutated_index.get(), 0);
1379        });
1380    }
1381
1382    // 'NavigationDrawer can update background color'.
1383    #[test]
1384    fn navigation_drawer_can_update_background_color() {
1385        test_widgets(|tester| {
1386            let color = Colors::YELLOW.primary();
1387            let key = GlobalKey::new();
1388            pump_drawer(tester, m3, &key, move |_app| {
1389                NavigationDrawer::new(headline_and_two_destinations())
1390                    .background_color(color)
1391                    .on_destination_selected(select_nothing())
1392                    .into_widget()
1393            });
1394
1395            open_drawer(tester, &key);
1396            tester.pump_by(Duration::from_secs(1)); // animation done
1397
1398            assert_eq!(material(tester, |material| material.color), Some(color));
1399        });
1400    }
1401
1402    // 'NavigationDestinationDrawer background color is customizable'.
1403    #[test]
1404    fn navigation_drawer_destination_background_color_is_customizable() {
1405        test_widgets(|tester| {
1406            let color = Colors::YELLOW.primary();
1407            let key = GlobalKey::new();
1408            pump_drawer(tester, m3, &key, move |_app| {
1409                NavigationDrawer::new([
1410                    Text::new("Headline").into_widget(),
1411                    destination(Icons::ac_unit(), "AC"),
1412                    NavigationDrawerDestination::new(
1413                        Icon::new(Some(Icons::access_alarm())),
1414                        Text::new("Alarm"),
1415                    )
1416                    .background_color(color)
1417                    .into_widget(),
1418                ])
1419                .on_destination_selected(select_nothing())
1420                .into_widget()
1421            });
1422
1423            let find_destination_ink = |tester: &WidgetTester, label: &str| -> Vec<AnyElement> {
1424                let text = *find::text(label)
1425                    .evaluate(tester)
1426                    .first()
1427                    .expect("the label");
1428                let destination = tester.ancestor_of_type::<NavigationDrawerDestination>(text);
1429                tester.descendants_of_type::<Ink>(destination)
1430            };
1431
1432            open_drawer(tester, &key);
1433            tester.pump();
1434            tester.pump_by(Duration::from_secs(1)); // Animation done.
1435
1436            // Destination with no custom background color.
1437            let at = text_center(tester, "AC");
1438            tester.tap_at(at, 1);
1439            tester.pump();
1440
1441            // When no background color is set, only the non-visible indicator Ink is expected.
1442            assert_eq!(find_destination_ink(tester, "AC").len(), 1);
1443
1444            // Destination with a custom background color.
1445            let at = icon_center(tester, &Icons::access_alarm());
1446            tester.tap_at(at, 2);
1447            tester.pump();
1448
1449            // A Material is added with the custom color.
1450            let alarm_inks = find_destination_ink(tester, "Alarm");
1451            assert_eq!(alarm_inks.len(), 2);
1452            let destination_color = tester.widget(alarm_inks[0], |ink: &Ink| {
1453                let decoration = ink
1454                    .effective_decoration()
1455                    .expect("the destination's decoration");
1456                decoration
1457                    .as_any()
1458                    .downcast_ref::<BoxDecoration>()
1459                    .expect("a BoxDecoration")
1460                    .color
1461                    .as_deref()
1462                    .copied()
1463            });
1464            assert_eq!(destination_color, Some(color));
1465        });
1466    }
1467
1468    // 'NavigationDrawer can update elevation'.
1469    #[test]
1470    fn navigation_drawer_can_update_elevation() {
1471        test_widgets(|tester| {
1472            let elevation = 42.0;
1473            let key = GlobalKey::new();
1474            pump_drawer(tester, m3, &key, move |_app| {
1475                NavigationDrawer::new(headline_and_two_destinations())
1476                    .elevation(elevation)
1477                    .into_widget()
1478            });
1479            open_drawer(tester, &key);
1480            tester.pump_by(Duration::from_secs(1));
1481
1482            assert_eq!(material(tester, |material| material.elevation), elevation);
1483        });
1484    }
1485
1486    // 'NavigationDrawer uses proper defaults when no parameters are given'.
1487    #[test]
1488    fn navigation_drawer_uses_proper_defaults_when_no_parameters_are_given() {
1489        test_widgets(|tester| {
1490            let key = GlobalKey::new();
1491            pump_drawer(tester, m3, &key, move |_app| {
1492                NavigationDrawer::new(headline_and_two_destinations())
1493                    .on_destination_selected(select_nothing())
1494                    .into_widget()
1495            });
1496            open_drawer(tester, &key);
1497            tester.pump_by(Duration::from_secs(1));
1498            let theme = ThemeData::new(&tester.cell.borrow());
1499            let colors = &theme.color_scheme;
1500
1501            // Test drawer Material.
1502            assert_eq!(
1503                material(tester, |material| material.color),
1504                Some(colors.surface_container_low())
1505            );
1506            assert_eq!(
1507                material(tester, |material| material.surface_tint_color),
1508                Some(Colors::TRANSPARENT)
1509            );
1510            assert_eq!(
1511                material(tester, |material| material.shadow_color),
1512                Some(Colors::TRANSPARENT)
1513            );
1514            assert_eq!(material(tester, |material| material.elevation), 1.0);
1515            // Test indicator decoration.
1516            let (color, shape) = indicator_decoration(tester);
1517            assert_eq!(color, Some(colors.secondary_container()));
1518            assert!(shape_eq(&*shape, &StadiumBorder::new(BorderSide::NONE)));
1519            // Test selected and unselected icon colors.
1520            assert_eq!(
1521                icon_color(tester, &Icons::ac_unit()),
1522                Some(colors.on_secondary_container())
1523            );
1524            assert_eq!(
1525                icon_color(tester, &Icons::access_alarm()),
1526                Some(colors.on_surface_variant())
1527            );
1528            // Test selected and unselected label colors.
1529            assert_eq!(
1530                label_color(tester, "AC"),
1531                Some(colors.on_secondary_container())
1532            );
1533            assert_eq!(
1534                label_color(tester, "Alarm"),
1535                Some(colors.on_surface_variant())
1536            );
1537            // Test that the icon and label are the correct size.
1538            let icon_box =
1539                tester.render_box_of(tester.element(find::by_icon(&Icons::ac_unit()).first()));
1540            assert_eq!(icon_box.size(&tester.cell.borrow()), Size::new(24.0, 24.0));
1541            let icon_box =
1542                tester.render_box_of(tester.element(find::by_icon(&Icons::access_alarm()).first()));
1543            assert_eq!(icon_box.size(&tester.cell.borrow()), Size::new(24.0, 24.0));
1544        });
1545    }
1546
1547    /// Dart's `find.text(label)` (which skips offstage) for a destination of the drawer's
1548    /// `ListView`: the text is built, and its sliver child lies in the viewport, as
1549    /// `SliverMultiBoxAdaptorElement.debugVisitOnstageChildren` lets the finder see only the
1550    /// children between the scroll offset and the end of the remaining paint extent.
1551    fn onstage_label(tester: &WidgetTester, label: &str) -> bool {
1552        let Some(&text) = find::text(label).evaluate(tester).first() else {
1553            return false;
1554        };
1555        let list = *find::by_type::<ListView>()
1556            .evaluate(tester)
1557            .first()
1558            .expect("the ListView");
1559        let viewport = tester.get_rect(list);
1560        let destination = tester.ancestor_of_type::<NavigationDrawerDestination>(text);
1561        let item = tester.get_rect(destination);
1562        item.top < viewport.bottom && item.bottom > viewport.top
1563    }
1564
1565    // 'Navigation drawer is scrollable'.
1566    #[test]
1567    fn navigation_drawer_is_scrollable() {
1568        test_widgets(|tester| {
1569            let key = GlobalKey::new();
1570            widget_setup(tester, 500.0, 300.0);
1571            pump_drawer(tester, m3, &key, move |_app| {
1572                NavigationDrawer::new(
1573                    (0..100).map(|i| destination(Icons::ac_unit(), &format!("Label{i}"))),
1574                )
1575                .on_destination_selected(select_nothing())
1576                .into_widget()
1577            });
1578            open_drawer(tester, &key);
1579            tester.pump_by(Duration::from_secs(1));
1580
1581            for i in 0..=5 {
1582                assert!(onstage_label(tester, &format!("Label{i}")), "Label{i}");
1583            }
1584            for i in 6..=8 {
1585                assert!(!onstage_label(tester, &format!("Label{i}")), "Label{i}");
1586            }
1587
1588            tester.drag_from(Offset::new(0.0, 200.0), Offset::new(0.0, -200.0), 1);
1589            tester.pump();
1590
1591            for i in 0..=2 {
1592                assert!(!onstage_label(tester, &format!("Label{i}")), "Label{i}");
1593            }
1594            for i in 3..=8 {
1595                assert!(onstage_label(tester, &format!("Label{i}")), "Label{i}");
1596            }
1597            for i in 9..=10 {
1598                assert!(!onstage_label(tester, &format!("Label{i}")), "Label{i}");
1599            }
1600        });
1601    }
1602
1603    // 'Safe Area test'.
1604    #[test]
1605    fn safe_area_test() {
1606        test_widgets(|tester| {
1607            let key = GlobalKey::new();
1608            let view_height = 300.0;
1609            widget_setup(tester, 500.0, view_height);
1610            let scaffold_key = key.clone();
1611            #[allow(deprecated)]
1612            let app = MaterialApp::new().use_inherited_media_query(true).home(
1613                Scaffold::new()
1614                    .key(scaffold_key.into())
1615                    .drawer(
1616                        NavigationDrawer::new(
1617                            (0..10).map(|i| destination(Icons::ac_unit(), &format!("Label{i}"))),
1618                        )
1619                        .on_destination_selected(select_nothing()),
1620                    )
1621                    .body(Container::new()),
1622            );
1623            tester.pump_widget(
1624                MediaQuery::new(MediaQueryData::new().padding(EdgeInsets::all(20.0)), app)
1625                    .into_widget(),
1626            );
1627            open_drawer(tester, &key);
1628            tester.pump();
1629            tester.pump_by(Duration::from_secs(1));
1630
1631            let destination_rect = |label: &str| -> Rect {
1632                let text = *find::text(label)
1633                    .evaluate(tester)
1634                    .first()
1635                    .expect("the label");
1636                let destination = tester.ancestor_of_type::<NavigationDrawerDestination>(text);
1637                tester.get_rect(destination)
1638            };
1639
1640            // Safe area padding on the top and sides.
1641            assert_eq!(
1642                destination_rect("Label0").top_left(),
1643                Offset::new(20.0, 20.0)
1644            );
1645
1646            // No Safe area padding at the bottom.
1647            assert_eq!(destination_rect("Label4").bottom, view_height);
1648        });
1649    }
1650
1651    // 'Navigation destination updates indicator color and shape'.
1652    #[test]
1653    fn navigation_destination_updates_indicator_color_and_shape() {
1654        test_widgets(|tester| {
1655            let key = GlobalKey::new();
1656            let color = Color::new(0xff0000ff);
1657            let shape = RoundedRectangleBorder::default();
1658
1659            let build_navigation_drawer =
1660                |tester: &mut WidgetTester, indicator: Option<(Color, RoundedRectangleBorder)>| {
1661                    let key = key.clone();
1662                    pump_app(tester, m3, move |_app| {
1663                        let mut drawer = NavigationDrawer::new(headline_and_two_destinations())
1664                            .on_destination_selected(select_nothing());
1665                        if let Some((indicator_color, indicator_shape)) = indicator {
1666                            drawer = drawer
1667                                .indicator_color(indicator_color)
1668                                .indicator_shape(indicator_shape);
1669                        }
1670                        Scaffold::new()
1671                            .key(key.into())
1672                            .drawer(drawer)
1673                            .body(Container::new())
1674                            .into_widget()
1675                    });
1676                };
1677
1678            build_navigation_drawer(tester, None);
1679            open_drawer(tester, &key);
1680            tester.pump_and_settle();
1681
1682            let theme = ThemeData::new(&tester.cell.borrow());
1683            // Test default indicator color and shape.
1684            let (indicator_color, indicator_shape) = indicator_decoration(tester);
1685            assert_eq!(
1686                indicator_color,
1687                Some(theme.color_scheme.secondary_container())
1688            );
1689            assert!(shape_eq(
1690                &*indicator_shape,
1691                &StadiumBorder::new(BorderSide::NONE)
1692            ));
1693            // Test that InkWell for hover, focus and pressed use default shape.
1694            assert!(shape_eq(
1695                &*ink_well_custom_border(tester).expect("a custom border"),
1696                &StadiumBorder::new(BorderSide::NONE)
1697            ));
1698
1699            build_navigation_drawer(tester, Some((color, shape)));
1700
1701            // Test custom indicator color and shape.
1702            let (indicator_color, indicator_shape) = indicator_decoration(tester);
1703            assert_eq!(indicator_color, Some(color));
1704            assert!(shape_eq(&*indicator_shape, &shape));
1705            // Test that InkWell for hover, focus and pressed use custom shape.
1706            assert!(shape_eq(
1707                &*ink_well_custom_border(tester).expect("a custom border"),
1708                &shape
1709            ));
1710        });
1711    }
1712
1713    // 'NavigationDrawer.tilePadding defaults to EdgeInsets.symmetric(horizontal: 12.0)'.
1714    #[test]
1715    fn navigation_drawer_tile_padding_defaults_to_symmetric_horizontal_12() {
1716        test_widgets(|tester| {
1717            let key = GlobalKey::new();
1718            widget_setup(tester, 3000.0, 3000.0);
1719            pump_drawer(tester, m3, &key, move |_app| {
1720                NavigationDrawer::new([destination(Icons::ac_unit(), "AC")])
1721                    .on_destination_selected(select_nothing())
1722                    .into_widget()
1723            });
1724            open_drawer(tester, &key);
1725            tester.pump();
1726            let tile_padding = tester
1727                .widget(navigation_drawer(tester), |drawer: &NavigationDrawer| {
1728                    drawer.tile_padding
1729                });
1730            assert_eq!(tile_padding, EdgeInsetsGeometry::symmetric(0.0, 12.0));
1731        });
1732    }
1733
1734    // 'Destinations respect their disabled state'.
1735    #[test]
1736    fn destinations_respect_their_disabled_state() {
1737        test_widgets(|tester| {
1738            let key = GlobalKey::new();
1739            let selected_index = Rc::new(Cell::new(0));
1740            widget_setup(tester, 800.0, 1000.0);
1741            let selected = Rc::clone(&selected_index);
1742            pump_drawer(tester, m3, &key, move |_app| {
1743                NavigationDrawer::new([
1744                    destination(Icons::ac_unit(), "AC"),
1745                    destination(Icons::access_alarm(), "Alarm"),
1746                    NavigationDrawerDestination::new(
1747                        Icon::new(Some(Icons::accessible())),
1748                        Text::new("Accessible"),
1749                    )
1750                    .enabled(false)
1751                    .into_widget(),
1752                ])
1753                .on_destination_selected(Rc::new(move |_app, i| selected.set(i)))
1754                .into_widget()
1755            });
1756            open_drawer(tester, &key);
1757            tester.pump();
1758
1759            assert_eq!(found(tester, "AC"), 1);
1760            assert_eq!(found(tester, "Alarm"), 1);
1761            assert_eq!(found(tester, "Accessible"), 1);
1762
1763            tester.pump_by(Duration::from_secs(1));
1764
1765            assert_eq!(selected_index.get(), 0);
1766
1767            let at = text_center(tester, "Alarm");
1768            tester.tap_at(at, 1);
1769            assert_eq!(selected_index.get(), 1);
1770
1771            let at = text_center(tester, "Accessible");
1772            tester.tap_at(at, 2);
1773            assert_eq!(selected_index.get(), 1);
1774
1775            tester.pump_and_settle();
1776        });
1777    }
1778
1779    /// Stands in for Dart's `FlutterLogo`, which Waft does not have; the case only counts
1780    /// them.
1781    #[derive(Debug)]
1782    struct FlutterLogo;
1783
1784    impl StatelessWidget for FlutterLogo {
1785        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1786            SizedBox::new().width(24.0).height(24.0).into_widget()
1787        }
1788    }
1789
1790    // 'NavigationDrawer can display header and footer'.
1791    #[test]
1792    fn navigation_drawer_can_display_header_and_footer() {
1793        test_widgets(|tester| {
1794            let key = GlobalKey::new();
1795            widget_setup(tester, 3000.0, 3000.0);
1796            pump_drawer(tester, m3, &key, move |_app| {
1797                NavigationDrawer::new(
1798                    (0..10).map(|i| destination(Icons::home(), &format!("Item {i}"))),
1799                )
1800                .header(DrawerHeader::new(Some(
1801                    Center::new()
1802                        .child(
1803                            Column::new()
1804                                .main_axis_alignment(waft_rendering::MainAxisAlignment::Center)
1805                                .spacing(8.0)
1806                                .children([
1807                                    FlutterLogo.into_widget(),
1808                                    Text::new("Header").into_widget(),
1809                                ]),
1810                        )
1811                        .into_widget(),
1812                )))
1813                .footer(
1814                    ListTile::new()
1815                        .leading(FlutterLogo)
1816                        .title(Text::new("Footer"))
1817                        .trailing(Icon::new(Some(Icons::settings())))
1818                        .on_tap(Listener::new(|_app| {})),
1819                )
1820                .into_widget()
1821            });
1822            open_drawer(tester, &key);
1823            tester.pump_by(Duration::from_secs(1));
1824
1825            expect(tester, &find::by_type::<DrawerHeader>(), finds_one_widget());
1826            assert_eq!(found(tester, "Header"), 1);
1827            expect(tester, &find::by_type::<FlutterLogo>(), finds_n_widgets(2));
1828            expect(tester, &find::by_type::<ListTile>(), finds_one_widget());
1829            assert_eq!(found(tester, "Footer"), 1);
1830            tester.element(find::by_icon(&Icons::settings()).first());
1831        });
1832    }
1833
1834    // 'NavigationDrawer does not crash at zero area'.
1835    #[test]
1836    fn navigation_drawer_does_not_crash_at_zero_area() {
1837        test_widgets(|tester| {
1838            pump_app(tester, m3, |_app| {
1839                Center::new()
1840                    .child(SizedBox::shrink().child(NavigationDrawer::new([destination(
1841                        Icons::inbox(),
1842                        "Inbox",
1843                    )])))
1844                    .into_widget()
1845            });
1846            let drawer = tester.render_box_of(navigation_drawer(tester));
1847            assert_eq!(drawer.size(&tester.cell.borrow()), Size::ZERO);
1848        });
1849    }
1850
1851    /// The render object of the `Material` nearest above `element`: Dart's
1852    /// `Material.of(tester.element(finder)) as RenderBox`.
1853    fn ink_material_of(tester: &WidgetTester, element: AnyElement) -> AnyRenderObject {
1854        let app = tester.cell.borrow();
1855        let mut object = element
1856            .find_render_object(&app)
1857            .expect("the element has a render object");
1858        loop {
1859            object = object.parent(&app).expect("a Material above the element");
1860            if object.downcast::<RenderInkFeatures>(&app).is_some() {
1861                return object;
1862            }
1863        }
1864    }
1865
1866    // Regression test for https://github.com/flutter/flutter/issues/180233
1867    // 'NavigationDrawer ink effects are bounded within scrollable area when footer is present'.
1868    #[test]
1869    fn navigation_drawer_ink_effects_are_bounded_within_scrollable_area_when_footer_is_present() {
1870        test_widgets(|tester| {
1871            let key = GlobalKey::new();
1872            widget_setup(tester, 800.0, 400.0);
1873            pump_drawer(tester, m3, &key, move |_app| {
1874                NavigationDrawer::new(
1875                    (0..10).map(|i| destination(Icons::home(), &format!("Item {i}"))),
1876                )
1877                .footer(Padding::new(EdgeInsetsGeometry::all(16.0)).child(Text::new("Footer")))
1878                .into_widget()
1879            });
1880
1881            open_drawer(tester, &key);
1882            tester.pump_and_settle();
1883
1884            let footer_text = *find::text("Footer")
1885                .evaluate(tester)
1886                .first()
1887                .expect("the footer");
1888            let footer = tester.ancestor_of_type::<Padding>(footer_text);
1889            let footer_rect = tester.get_rect(tester.render_box_of(footer));
1890
1891            let first_destination = *find::by_type::<NavigationDrawerDestination>()
1892                .evaluate(tester)
1893                .first()
1894                .expect("a destination");
1895            let ink_wells = tester.descendants_of_type::<InkWell>(first_destination);
1896            assert_eq!(ink_wells.len(), 1);
1897
1898            let ink_material: AnyRenderBox = ink_material_of(tester, ink_wells[0])
1899                .as_box()
1900                .expect("a render box");
1901            let ink_material_rect = tester.get_rect(ink_material);
1902
1903            // Equal at f32 precision: `local_to_global` maps through valo's f32 `Matrix4`.
1904            assert_eq!(ink_material_rect.bottom as f32, footer_rect.top as f32);
1905        });
1906    }
1907
1908    // Regression test for https://github.com/flutter/flutter/issues/180359.
1909    // 'Indicator repaints when selectedIndex changes without pointer interaction'.
1910    #[test]
1911    fn indicator_repaints_when_selected_index_changes_without_pointer_interaction() {
1912        test_widgets(|tester| {
1913            let key = GlobalKey::new();
1914            let selected_index = Rc::new(Cell::new(0));
1915            let set_selected_index: Rc<RefCell<Option<waft_widgets::StateSetter>>> = Rc::default();
1916            let (scaffold_key, selected, setter) = (
1917                key.clone(),
1918                Rc::clone(&selected_index),
1919                Rc::clone(&set_selected_index),
1920            );
1921            let theme = ThemeData::new(&tester.cell.borrow());
1922            tester.pump_widget(material_app(
1923                theme,
1924                StatefulBuilder::new(move |_app, _context, set_state| {
1925                    *setter.borrow_mut() = Some(set_state);
1926                    Scaffold::new()
1927                        .key(scaffold_key.clone().into())
1928                        .drawer(
1929                            NavigationDrawer::new([
1930                                destination(Icons::ac_unit(), "AC"),
1931                                destination(Icons::access_alarm(), "Alarm"),
1932                            ])
1933                            .selected_index(Some(selected.get())),
1934                        )
1935                        .body(Container::new())
1936                        .into_widget()
1937                })
1938                .into_widget(),
1939            ));
1940
1941            open_drawer(tester, &key);
1942            tester.pump_and_settle();
1943
1944            // The indicator is painted by an Ink widget, which paints on the nearest
1945            // ancestor Material rather than on its own render object.
1946            let indicator = *find::by_type::<NavigationIndicator>()
1947                .evaluate(tester)
1948                .first()
1949                .expect("an indicator");
1950            let indicator_ink = *tester
1951                .descendants_of_type::<Ink>(indicator)
1952                .first()
1953                .expect("the indicator's Ink");
1954            let ink_controller = ink_material_of(tester, indicator_ink);
1955
1956            // Change the selected index without any pointer interaction and advance
1957            // one frame, stopping before the paint phase: the Material that hosts the
1958            // indicator's ink must have been marked as needing paint, otherwise it
1959            // keeps showing the indicator's previous frame.
1960            {
1961                let set_state = set_selected_index.borrow().clone().expect("built");
1962                let mut app = tester.cell.borrow_mut();
1963                set_state(&mut app, &mut |_app| selected_index.set(1));
1964            }
1965            pump_to_layout(tester);
1966            assert!(ink_controller.debug_needs_paint(&tester.cell.borrow()));
1967            finish_frame(tester);
1968
1969            // Let the indicator animation run to completion normally.
1970            tester.pump_and_settle();
1971        });
1972    }
1973
1974    /// The first half of Dart's `tester.pump_by(null, EnginePhase.layout)`: begins a frame at the
1975    /// last frame's time stamp, then builds and lays out without painting.
1976    fn pump_to_layout(tester: &WidgetTester) {
1977        let mut app = tester.cell.borrow_mut();
1978        let views: Vec<_> = app
1979            .platform()
1980            .views()
1981            .iter()
1982            .map(|view| view.id())
1983            .collect();
1984        waft_scheduler::SchedulerBinding::handle_begin_frame(&mut app, &views, None);
1985        app.drain_microtasks();
1986        let binding = WidgetsBinding::instance(&mut app);
1987        let root_element = binding.root_element(&app).expect("a root element");
1988        binding
1989            .build_owner(&app)
1990            .build_scope(&mut app, root_element, None);
1991        waft_rendering::RendererBinding::instance(&mut app)
1992            .root_pipeline_owner(&app)
1993            .flush_layout(&mut app);
1994    }
1995
1996    /// Ends the frame [`pump_to_layout`] began, as Dart's pump ends it after its phase.
1997    fn finish_frame(tester: &WidgetTester) {
1998        let mut app = tester.cell.borrow_mut();
1999        let views: Vec<_> = app
2000            .platform()
2001            .views()
2002            .iter()
2003            .map(|view| view.id())
2004            .collect();
2005        waft_scheduler::SchedulerBinding::handle_draw_frame(&mut app, &views);
2006        app.drain_microtasks();
2007        drop(app);
2008        tester.cell.checkpoint();
2009    }
2010
2011    // navigation_drawer_theme_test.dart
2012
2013    /// The theme the theme cases give `ThemeData(navigationDrawerTheme:)`.
2014    fn navigation_drawer_theme() -> NavigationDrawerThemeData {
2015        NavigationDrawerThemeData::new()
2016            .background_color(Color::new(0x00000001))
2017            .elevation(7.0)
2018            .shadow_color(Color::new(0x00000002))
2019            .surface_tint_color(Color::new(0x00000003))
2020            .indicator_color(Color::new(0x00000004))
2021            .indicator_shape(RoundedRectangleBorder::new(
2022                BorderSide::NONE,
2023                BorderRadius::only(
2024                    Radius::ZERO,
2025                    Radius::circular(16.0),
2026                    Radius::ZERO,
2027                    Radius::ZERO,
2028                )
2029                .into(),
2030            ))
2031            .label_text_style(Rc::new(WidgetStatePropertyAll::new(Some(
2032                TextStyle::new().font_size(7.0),
2033            ))))
2034            .icon_theme(Rc::new(WidgetStatePropertyAll::new(Some(
2035                IconThemeData::new().color(Color::new(0x00000005)),
2036            ))))
2037    }
2038
2039    fn pump_themed_drawer(
2040        tester: &mut WidgetTester,
2041        key: &GlobalKey,
2042        theme_data_theme: NavigationDrawerThemeData,
2043        drawer: impl FnOnce(&mut App) -> WidgetRef,
2044    ) {
2045        pump_drawer(
2046            tester,
2047            move |app| {
2048                ThemeData::builder()
2049                    .navigation_drawer_theme(theme_data_theme)
2050                    .build(app)
2051            },
2052            key,
2053            drawer,
2054        );
2055    }
2056
2057    // 'NavigationDrawerThemeData values are used when no NavigationDrawer properties are
2058    // specified'.
2059    #[test]
2060    fn navigation_drawer_theme_data_values_are_used_when_no_navigation_drawer_properties_are_specified()
2061     {
2062        test_widgets(|tester| {
2063            let key = GlobalKey::new();
2064            let theme = navigation_drawer_theme();
2065            pump_themed_drawer(tester, &key, theme.clone(), |_app| {
2066                NavigationDrawer::new(headline_and_two_destinations())
2067                    .on_destination_selected(select_nothing())
2068                    .into_widget()
2069            });
2070            open_drawer(tester, &key);
2071            tester.pump_by(Duration::from_secs(1));
2072
2073            // Test drawer Material.
2074            assert_eq!(
2075                material(tester, |material| material.color),
2076                theme.background_color
2077            );
2078            assert_eq!(
2079                material(tester, |material| material.surface_tint_color),
2080                theme.surface_tint_color
2081            );
2082            assert_eq!(
2083                material(tester, |material| material.shadow_color),
2084                theme.shadow_color
2085            );
2086            assert_eq!(material(tester, |material| material.elevation), 7.0);
2087            // Test indicator decoration.
2088            let (indicator_color, indicator_shape) = indicator_decoration(tester);
2089            assert_eq!(indicator_color, theme.indicator_color);
2090            assert!(shape_eq(
2091                &*indicator_shape,
2092                theme.indicator_shape.as_deref().expect("a shape")
2093            ));
2094            // Test icon.
2095            let themed_icon_color = theme
2096                .icon_theme
2097                .as_ref()
2098                .and_then(|icon_theme| icon_theme.resolve(&WidgetStates::new()))
2099                .and_then(|icon_theme| icon_theme.color.as_deref().copied());
2100            assert_eq!(icon_color(tester, &Icons::ac_unit()), themed_icon_color);
2101            assert_eq!(
2102                icon_color(tester, &Icons::access_alarm()),
2103                themed_icon_color
2104            );
2105            // Test label.
2106            let themed_label_style = theme
2107                .label_text_style
2108                .as_ref()
2109                .and_then(|label_text_style| label_text_style.resolve(&WidgetStates::new()));
2110            assert_eq!(Some(label_style(tester, "AC")), themed_label_style);
2111            assert_eq!(Some(label_style(tester, "Alarm")), themed_label_style);
2112        });
2113    }
2114
2115    // 'NavigationDrawer values take priority over NavigationDrawerThemeData values when both
2116    // properties are specified'.
2117    #[test]
2118    fn navigation_drawer_values_take_priority_over_navigation_drawer_theme_data_values() {
2119        test_widgets(|tester| {
2120            let key = GlobalKey::new();
2121            let background_color = Color::new(0x00000009);
2122            let elevation = 14.0;
2123            let shadow_color = Color::new(0x00000008);
2124            let surface_tint_color = Color::new(0x00000007);
2125            let indicator_shape =
2126                RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(32.0));
2127            let indicator_color = Color::new(0x00000006);
2128            let shape = indicator_shape;
2129            pump_themed_drawer(tester, &key, navigation_drawer_theme(), move |_app| {
2130                NavigationDrawer::new(headline_and_two_destinations())
2131                    .background_color(background_color)
2132                    .elevation(elevation)
2133                    .shadow_color(shadow_color)
2134                    .surface_tint_color(surface_tint_color)
2135                    .indicator_shape(shape)
2136                    .indicator_color(indicator_color)
2137                    .on_destination_selected(select_nothing())
2138                    .into_widget()
2139            });
2140            open_drawer(tester, &key);
2141            tester.pump_by(Duration::from_secs(1));
2142
2143            // Test drawer Material.
2144            assert_eq!(
2145                material(tester, |material| material.color),
2146                Some(background_color)
2147            );
2148            assert_eq!(
2149                material(tester, |material| material.surface_tint_color),
2150                Some(surface_tint_color)
2151            );
2152            assert_eq!(
2153                material(tester, |material| material.shadow_color),
2154                Some(shadow_color)
2155            );
2156            assert_eq!(material(tester, |material| material.elevation), elevation);
2157            // Test indicator decoration.
2158            let (color, shape) = indicator_decoration(tester);
2159            assert_eq!(color, Some(indicator_color));
2160            assert!(shape_eq(&*shape, &indicator_shape));
2161        });
2162    }
2163
2164    // 'Local NavigationDrawerTheme takes priority over ThemeData.navigationDrawerTheme'.
2165    #[test]
2166    fn local_navigation_drawer_theme_takes_priority_over_theme_data_navigation_drawer_theme() {
2167        test_widgets(|tester| {
2168            let key = GlobalKey::new();
2169            let background_color = Color::new(0x00000009);
2170            let elevation = 7.0;
2171            let shadow_color = Color::new(0x00000008);
2172            let surface_tint_color = Color::new(0x00000007);
2173            let icon_color_value = Color::new(0x00000006);
2174            let label_style_value = TextStyle::new().font_size(7.0);
2175            let indicator_color = Color::new(0x00000005);
2176            pump_themed_drawer(tester, &key, navigation_drawer_theme(), move |_app| {
2177                NavigationDrawerTheme::new(
2178                    NavigationDrawerThemeData::new()
2179                        .background_color(background_color)
2180                        .elevation(elevation)
2181                        .shadow_color(shadow_color)
2182                        .surface_tint_color(surface_tint_color)
2183                        .indicator_shape(CircleBorder::default())
2184                        .indicator_color(indicator_color)
2185                        .label_text_style(Rc::new(WidgetStatePropertyAll::new(Some(
2186                            TextStyle::new().font_size(7.0),
2187                        ))))
2188                        .icon_theme(Rc::new(WidgetStatePropertyAll::new(Some(
2189                            IconThemeData::new().color(icon_color_value),
2190                        )))),
2191                    NavigationDrawer::new(headline_and_two_destinations())
2192                        .on_destination_selected(select_nothing()),
2193                )
2194                .into_widget()
2195            });
2196            open_drawer(tester, &key);
2197            tester.pump_by(Duration::from_secs(1));
2198
2199            // Test drawer Material.
2200            assert_eq!(
2201                material(tester, |material| material.color),
2202                Some(background_color)
2203            );
2204            assert_eq!(
2205                material(tester, |material| material.surface_tint_color),
2206                Some(surface_tint_color)
2207            );
2208            assert_eq!(
2209                material(tester, |material| material.shadow_color),
2210                Some(shadow_color)
2211            );
2212            assert_eq!(material(tester, |material| material.elevation), elevation);
2213            // Test indicator decoration.
2214            let (color, shape) = indicator_decoration(tester);
2215            assert_eq!(color, Some(indicator_color));
2216            assert!(shape_eq(&*shape, &CircleBorder::default()));
2217            // Test icon.
2218            assert_eq!(
2219                icon_color(tester, &Icons::ac_unit()),
2220                Some(icon_color_value)
2221            );
2222            assert_eq!(
2223                icon_color(tester, &Icons::access_alarm()),
2224                Some(icon_color_value)
2225            );
2226            // Test label.
2227            assert_eq!(label_style(tester, "AC"), label_style_value);
2228            assert_eq!(label_style(tester, "Alarm"), label_style_value);
2229        });
2230    }
2231
2232    // navigation_drawer_theme_test.dart 'NavigationDrawerThemeData copyWith, ==, hashCode,
2233    // basics'.
2234    #[test]
2235    fn navigation_drawer_theme_data_copy_with_equality_basics() {
2236        assert_eq!(
2237            NavigationDrawerThemeData::new(),
2238            NavigationDrawerThemeData::new().copy_with()
2239        );
2240    }
2241
2242    // navigation_drawer_theme_test.dart 'NavigationDrawerThemeData lerp special cases'.
2243    #[test]
2244    fn navigation_drawer_theme_data_lerp_special_cases() {
2245        assert_eq!(NavigationDrawerThemeData::lerp(None, None, 0.0), None);
2246        let data = NavigationDrawerThemeData::new();
2247        assert_eq!(
2248            NavigationDrawerThemeData::lerp(Some(&data), Some(&data), 0.5),
2249            Some(data)
2250        );
2251    }
2252
2253    #[test]
2254    fn navigation_drawer_theme_data_null_fields_by_default() {
2255        let theme = NavigationDrawerThemeData::new();
2256        assert_eq!(theme.tile_height, None);
2257        assert_eq!(theme.background_color, None);
2258        assert_eq!(theme.elevation, None);
2259        assert_eq!(theme.shadow_color, None);
2260        assert_eq!(theme.surface_tint_color, None);
2261        assert_eq!(theme.indicator_color, None);
2262        assert!(theme.indicator_shape.is_none());
2263        assert_eq!(theme.indicator_size, None);
2264        assert!(theme.label_text_style.is_none());
2265        assert!(theme.icon_theme.is_none());
2266    }
2267
2268    #[test]
2269    fn navigation_drawer_theme_data_lerps_each_field_as_dart_does() {
2270        let a = NavigationDrawerThemeData::new()
2271            .tile_height(40.0)
2272            .background_color(Colors::BLACK)
2273            .elevation(2.0)
2274            .indicator_size(Size::new(100.0, 40.0));
2275        let b = NavigationDrawerThemeData::new()
2276            .tile_height(60.0)
2277            .background_color(Colors::WHITE)
2278            .elevation(6.0)
2279            .indicator_size(Size::new(300.0, 60.0));
2280        let halfway = NavigationDrawerThemeData::lerp(Some(&a), Some(&b), 0.5).expect("both");
2281        assert_eq!(halfway.tile_height, Some(50.0));
2282        assert_eq!(
2283            halfway.background_color,
2284            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
2285        );
2286        assert_eq!(halfway.elevation, Some(4.0));
2287        // Dart lerps `a.indicatorSize` with itself.
2288        assert_eq!(halfway.indicator_size, Some(Size::new(100.0, 40.0)));
2289    }
2290
2291    #[test]
2292    fn theme_data_holds_the_navigation_drawer_theme() {
2293        test_widgets(|tester| {
2294            let app = tester.cell.borrow();
2295            let theme = ThemeData::new(&app);
2296            assert_eq!(
2297                theme.navigation_drawer_theme,
2298                NavigationDrawerThemeData::new()
2299            );
2300
2301            let tall = ThemeData::builder()
2302                .navigation_drawer_theme(NavigationDrawerThemeData::new().tile_height(60.0))
2303                .build(&app);
2304            assert_eq!(tall.navigation_drawer_theme.tile_height, Some(60.0));
2305            assert_ne!(theme, tall);
2306            assert_eq!(
2307                theme
2308                    .copy_with()
2309                    .navigation_drawer_theme(tall.navigation_drawer_theme.clone())
2310                    .build(),
2311                tall
2312            );
2313            let short = ThemeData::builder()
2314                .navigation_drawer_theme(NavigationDrawerThemeData::new().tile_height(40.0))
2315                .build(&app);
2316            assert_eq!(
2317                ThemeData::lerp(&short, &tall, 0.5)
2318                    .navigation_drawer_theme
2319                    .tile_height,
2320                Some(50.0)
2321            );
2322        });
2323    }
2324
2325    #[test]
2326    fn navigation_drawer_theme_of_prefers_the_closest_theme_over_theme_data() {
2327        test_widgets(|tester| {
2328            let widget_theme = NavigationDrawerThemeData::new().tile_height(30.0);
2329            let expected = widget_theme.clone();
2330            let seen = crate::drawer_theme::tests::probe(
2331                tester,
2332                move |app, child| {
2333                    let data = ThemeData::builder()
2334                        .navigation_drawer_theme(NavigationDrawerThemeData::new().tile_height(70.0))
2335                        .build(app);
2336                    crate::theme::Theme::new(
2337                        data,
2338                        NavigationDrawerTheme::new(widget_theme.clone(), child),
2339                    )
2340                    .into_widget()
2341                },
2342                NavigationDrawerTheme::of,
2343            );
2344            assert_eq!(seen, expected);
2345
2346            let seen = crate::drawer_theme::tests::probe(
2347                tester,
2348                move |app, child| {
2349                    let data = ThemeData::builder()
2350                        .navigation_drawer_theme(NavigationDrawerThemeData::new().tile_height(70.0))
2351                        .build(app);
2352                    crate::theme::Theme::new(data, child).into_widget()
2353                },
2354                NavigationDrawerTheme::of,
2355            );
2356            assert_eq!(seen.tile_height, Some(70.0));
2357        });
2358    }
2359}