Skip to main content

waft_material/
navigation_rail.rs

1//! Flutter counterpart: material_ui's `navigation_rail.dart` (and its part
2//! `generated/navigation_rail_defaults_m3.g.dart`).
3
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6
7use waft_animation::{
8    Animation, AnimationBehavior, AnimationController, AnimationRef, AnyAnimation, CurveTween,
9    CurvedAnimation, Curves, Drive, Interval, ReverseAnimation,
10};
11use waft_embedder::SemanticsRole;
12use waft_embedder::{Color, Offset, Radius, Rect, lerp_double};
13use waft_foundation::{App, Handle, K_IS_WEB, Listener, OptionRetained, Ref, ValueChanged};
14use waft_painting::{
15    Alignment, AlignmentGeometry, BorderRadius, BoxShape, EdgeInsetsGeometry, ShapeBorderRef,
16    TextDirection, TextStyle,
17};
18use waft_rendering::{BoxConstraints, MainAxisAlignment, MainAxisSize};
19use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
20use waft_widgets::{
21    Align, BuildContext, Center, ClipRect, Column, ConstrainedBox, DefaultTextStyle,
22    Directionality, FadeTransition, Flexible, IconTheme, IconThemeData, InheritedWidget,
23    IntoWidget, KeyRef, MergeSemantics, Padding, Row, SafeArea, Semantics, SingleChildScrollView,
24    SizedBox, Stack, State, StateData, StatefulWidget, StatelessWidget, TickerProviderStateMixin,
25    TickerProviderStateMixinData, Visibility, WidgetRef,
26};
27
28use crate::generated::navigation_rail_defaults_m3::NavigationRailDefaultsM3;
29use crate::ink_well::InkResponse;
30use crate::material::{Material, MaterialType, RectCallback};
31use crate::material_localizations::MaterialLocalizations;
32use crate::navigation_bar::NavigationIndicator;
33use crate::navigation_rail_theme::{
34    NavigationRailTheme, NavigationRailThemeData, NavigationRailThemeDataGetters,
35};
36use crate::theme::{K_THEME_ANIMATION_DURATION, Theme};
37use crate::theme_data_getters::DefaultsContext;
38
39const K_CIRCULAR_INDICATOR_DIAMETER: f64 = 56.0;
40const K_INDICATOR_HEIGHT: f64 = 32.0;
41
42/// A Material Design widget that is meant to be displayed at the left or right of an
43/// app to navigate between a small number of views, typically between three and
44/// five.
45///
46/// Learn more about [`NavigationRail`] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=y9xchtVTtqQ).
47///
48/// The navigation rail is meant for layouts with wide viewports, such as a
49/// desktop web or tablet landscape layout. For smaller layouts, like mobile
50/// portrait, a `BottomNavigationBar` should be used instead.
51///
52/// A navigation rail is usually used as the first or last element of a `Row`
53/// which defines the app's `Scaffold` body.
54///
55/// The appearance of all of the [`NavigationRail`]s within an app can be
56/// specified with [`NavigationRailTheme`]. The default values for null theme
57/// properties are based on the `Theme`'s `ThemeData::text_theme`,
58/// `ThemeData::icon_theme`, and `ThemeData::color_scheme`.
59///
60/// Adaptive layouts can build different instances of the `Scaffold` in order to
61/// have a navigation rail for more horizontal layouts and a bottom navigation
62/// bar for more vertical layouts. See
63/// [the adaptive_scaffold.dart sample](https://github.com/flutter/demos/blob/main/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart)
64/// for an example.
65///
66/// See also:
67///
68///  * `Scaffold`, which can display the navigation rail within a `Row` of the
69///    `Scaffold::body` slot.
70///  * [`NavigationRailDestination`], which is used as a model to create tappable
71///    destinations in the navigation rail.
72///  * `BottomNavigationBar`, which is a similar navigation widget that's laid
73///    out horizontally.
74///  * <https://material.io/components/navigation-rail/>
75///  * <https://m3.material.io/components/navigation-rail>
76pub struct NavigationRail {
77    pub key: Option<KeyRef>,
78
79    /// Sets the color of the Container that holds all of the [`NavigationRail`]'s
80    /// contents.
81    ///
82    /// The default value is `NavigationRailThemeData::background_color`. If
83    /// `NavigationRailThemeData::background_color` is null, then the default value
84    /// is based on `ColorScheme::surface` of `ThemeData::color_scheme`.
85    pub background_color: Option<Color>,
86
87    /// Indicates that the [`NavigationRail`] should be in the extended state.
88    ///
89    /// The extended state has a wider rail container, and the labels are
90    /// positioned next to the icons. [`min_extended_width`](Self::min_extended_width) can be
91    /// used to set the minimum width of the rail when it is in this state.
92    ///
93    /// The rail will implicitly animate between the extended and normal state.
94    ///
95    /// If the rail is going to be in the extended state, then the
96    /// [`label_type`](Self::label_type) must be set to [`NavigationRailLabelType::None`].
97    ///
98    /// The default value is false.
99    pub extended: bool,
100
101    /// The leading widget in the rail that is placed above the destinations.
102    ///
103    /// It is placed at the top of the rail, above the [`destinations`](Self::destinations).
104    /// Its location is not affected by [`group_alignment`](Self::group_alignment).
105    ///
106    /// This is commonly a `FloatingActionButton`, but may also be a non-button,
107    /// such as a logo.
108    ///
109    /// The default value is null.
110    pub leading: Option<WidgetRef>,
111
112    /// The trailing widget in the rail that is placed below the destinations.
113    ///
114    /// The trailing widget is placed below the last [`NavigationRailDestination`].
115    /// It's location is affected by [`group_alignment`](Self::group_alignment).
116    ///
117    /// This is commonly a list of additional options or destinations that is
118    /// usually only rendered when [`extended`](Self::extended) is true.
119    ///
120    /// The default value is null.
121    pub trailing: Option<WidgetRef>,
122
123    /// Defines the appearance of the button items that are arrayed within the
124    /// navigation rail.
125    ///
126    /// The value must be a list of zero or more [`NavigationRailDestination`]
127    /// values.
128    pub destinations: Vec<NavigationRailDestination>,
129
130    /// The index into [`destinations`](Self::destinations) for the current selected
131    /// [`NavigationRailDestination`] or null if no destination is selected.
132    pub selected_index: Option<usize>,
133
134    /// Called when one of the [`destinations`](Self::destinations) is selected.
135    ///
136    /// The stateful widget that creates the navigation rail needs to keep
137    /// track of the index of the selected [`NavigationRailDestination`] and call
138    /// `set_state` to rebuild the navigation rail with the new
139    /// [`selected_index`](Self::selected_index).
140    pub on_destination_selected: Option<ValueChanged<usize>>,
141
142    /// The rail's elevation or z-coordinate.
143    ///
144    /// If `Directionality` is `TextDirection::Ltr`, the inner side is the
145    /// right side, and if `Directionality` is `TextDirection::Rtl`, it is
146    /// the left side.
147    ///
148    /// The default value is 0.
149    pub elevation: Option<f64>,
150
151    /// The vertical alignment for the group of [`destinations`](Self::destinations) within
152    /// the rail.
153    ///
154    /// The [`NavigationRailDestination`]s are by default grouped together with the
155    /// [`trailing`](Self::trailing) widget, due to
156    /// [`trailing_at_bottom`](Self::trailing_at_bottom) being `false`. The
157    /// [`leading`](Self::leading) widget, can also be in the aligned group by setting
158    /// [`leading_at_top`](Self::leading_at_top) to `false`. If these widgets are not
159    /// included in the group, they are placed at the top and bottom, respectively, of the
160    /// rail and only the space between them is considered for the alignment.
161    ///
162    /// The value must be between -1.0 and 1.0.
163    ///
164    /// If [`group_alignment`](Self::group_alignment) is -1.0, then the items are aligned to
165    /// the top. If [`group_alignment`](Self::group_alignment) is 0.0, then the items are
166    /// aligned to the center. If [`group_alignment`](Self::group_alignment) is 1.0, then the
167    /// items are aligned to the bottom.
168    ///
169    /// The default is -1.0.
170    ///
171    /// See also:
172    ///   * `Alignment::y`
173    ///
174    pub group_alignment: Option<f64>,
175
176    /// Defines the layout and behavior of the labels for the default, unextended
177    /// [`NavigationRail`].
178    ///
179    /// When a navigation rail is [`extended`](Self::extended), the labels are always shown.
180    ///
181    /// The default value is `NavigationRailThemeData::label_type`. If
182    /// `NavigationRailThemeData::label_type` is null, then the default value is
183    /// [`NavigationRailLabelType::None`].
184    ///
185    /// See also:
186    ///
187    ///   * [`NavigationRailLabelType`] for information on the meaning of different
188    ///     types.
189    pub label_type: Option<NavigationRailLabelType>,
190
191    /// The `TextStyle` of a destination's label when it is unselected.
192    ///
193    /// When one of the [`destinations`](Self::destinations) is selected the
194    /// [`selected_label_text_style`](Self::selected_label_text_style) will be used instead.
195    ///
196    /// The default value is based on the `Theme`'s `TextTheme::body_large`. The
197    /// default color is based on the `Theme`'s `ColorScheme::on_surface`.
198    ///
199    /// Properties from this text style, or
200    /// `NavigationRailThemeData::unselected_label_text_style` if this is null, are
201    /// merged into the defaults.
202    pub unselected_label_text_style: Option<TextStyle>,
203
204    /// The `TextStyle` of a destination's label when it is selected.
205    ///
206    /// When a [`NavigationRailDestination`] is not selected,
207    /// [`unselected_label_text_style`](Self::unselected_label_text_style) will be used.
208    ///
209    /// The default value is based on the `TextTheme::body_large` of
210    /// `ThemeData::text_theme`. The default color is based on the `Theme`'s
211    /// `ColorScheme::primary`.
212    ///
213    /// Properties from this text style,
214    /// or `NavigationRailThemeData::selected_label_text_style` if this is null, are
215    /// merged into the defaults.
216    pub selected_label_text_style: Option<TextStyle>,
217
218    /// The visual properties of the icon in the unselected destination.
219    ///
220    /// If this field is not provided, or provided with any null properties, then
221    /// a copy of the `IconThemeData::fallback` with a custom [`NavigationRail`]
222    /// specific color will be used.
223    ///
224    /// The default value is the `Theme`'s `ThemeData::icon_theme` with a color
225    /// of the `Theme`'s `ColorScheme::on_surface` with an opacity of 0.64.
226    /// Properties from this icon theme, or
227    /// `NavigationRailThemeData::unselected_icon_theme` if this is null, are
228    /// merged into the defaults.
229    pub unselected_icon_theme: Option<IconThemeData>,
230
231    /// The visual properties of the icon in the selected destination.
232    ///
233    /// When a [`NavigationRailDestination`] is not selected,
234    /// [`unselected_icon_theme`](Self::unselected_icon_theme) will be used.
235    ///
236    /// The default value is the `Theme`'s `ThemeData::icon_theme` with a color
237    /// of the `Theme`'s `ColorScheme::primary`. Properties from this icon theme,
238    /// or `NavigationRailThemeData::selected_icon_theme` if this is null, are
239    /// merged into the defaults.
240    pub selected_icon_theme: Option<IconThemeData>,
241
242    /// The smallest possible width for the rail regardless of the destination's
243    /// icon or label size.
244    ///
245    /// The default is 72.
246    ///
247    /// This value also defines the min width and min height of the destinations.
248    ///
249    /// To make a compact rail, set this to 56 and use
250    /// [`NavigationRailLabelType::None`].
251    pub min_width: Option<f64>,
252
253    /// The final width when the animation is complete for setting
254    /// [`extended`](Self::extended) to true.
255    ///
256    /// This is only used when [`extended`](Self::extended) is set to true.
257    ///
258    /// The default value is 256.
259    pub min_extended_width: Option<f64>,
260
261    /// If `true`, adds a rounded [`NavigationIndicator`] behind the selected
262    /// destination's icon.
263    ///
264    /// The indicator's shape will be circular if [`label_type`](Self::label_type) is
265    /// [`NavigationRailLabelType::None`], or a `StadiumBorder` if
266    /// [`label_type`](Self::label_type) is [`NavigationRailLabelType::All`] or
267    /// [`NavigationRailLabelType::Selected`].
268    ///
269    /// If `null`, defaults to `NavigationRailThemeData::use_indicator`. If that is
270    /// `null`, defaults to `ThemeData::use_material3`.
271    pub use_indicator: Option<bool>,
272
273    /// Overrides the default value of [`NavigationRail`]'s selection indicator color,
274    /// when [`use_indicator`](Self::use_indicator) is true.
275    ///
276    /// If this is null, `NavigationRailThemeData::indicator_color` is used. If
277    /// that is null, defaults to `ColorScheme::secondary_container`.
278    pub indicator_color: Option<Color>,
279
280    /// Overrides the default value of [`NavigationRail`]'s selection indicator shape,
281    /// when [`use_indicator`](Self::use_indicator) is true.
282    ///
283    /// If this is null, `NavigationRailThemeData::indicator_shape` is used. If
284    /// that is null, defaults to `StadiumBorder`.
285    pub indicator_shape: Option<ShapeBorderRef>,
286
287    /// Pin the [`leading`](Self::leading) widget to the top.
288    ///
289    /// If `true`, the [`leading`](Self::leading) widget is pinned to the top of the
290    /// [`NavigationRail`]. Otherwise it precedes directly the main group of
291    /// [`destinations`](Self::destinations).
292    ///
293    /// See also [`scrollable`](Self::scrollable) for a description of the interplay of
294    /// these parameters.
295    pub leading_at_top: bool,
296
297    /// Pin the [`trailing`](Self::trailing) widget to the bottom.
298    ///
299    /// If `true`, the [`trailing`](Self::trailing) widget is pinned to the bottom of the
300    /// [`NavigationRail`]. Otherwise it follows directly the main group of
301    /// [`destinations`](Self::destinations).
302    ///
303    /// See also [`scrollable`](Self::scrollable) for a description of the interplay of
304    /// these parameters.
305    pub trailing_at_bottom: bool,
306
307    /// Whether the main group of items should be scrollable when vertical space
308    /// is insufficient to show all of [`destinations`](Self::destinations),
309    /// [`leading`](Self::leading) and [`trailing`](Self::trailing).
310    ///
311    /// If [`leading_at_top`](Self::leading_at_top) or
312    /// [`trailing_at_bottom`](Self::trailing_at_bottom) are false,
313    /// [`leading`](Self::leading) or [`trailing`](Self::trailing) widgets, respectively,
314    /// are part of the main group in addition to [`destinations`](Self::destinations).
315    /// Otherwise these are statical at the top or bottom, respectively.
316    pub scrollable: bool,
317
318    /// How the [`destinations`](Self::destinations) should be placed along the vertical
319    /// axis.
320    ///
321    /// When there is extra vertical space in the [`NavigationRail`], this
322    /// property controls the alignment and spacing of the items. For example,
323    /// setting this to `MainAxisAlignment::SpaceEvenly` will distribute the
324    /// destinations equally along the available vertical space.
325    ///
326    /// When this property is not null, [`group_alignment`](Self::group_alignment) is
327    /// ignored.
328    ///
329    /// If null, the layout behaves as if `MainAxisAlignment::Start` was
330    /// specified.
331    ///
332    /// See also:
333    ///
334    ///  * `Column::main_axis_alignment`, which describes the different values and
335    ///    their effects on the layout.
336    pub main_axis_alignment: Option<MainAxisAlignment>,
337}
338
339impl NavigationRail {
340    /// Creates a Material Design navigation rail.
341    ///
342    /// The value of [`destinations`](Self::destinations) must be a list of zero or more
343    /// [`NavigationRailDestination`] values.
344    ///
345    /// If [`elevation`](Self::elevation) is specified, it must be non-negative.
346    ///
347    /// If [`min_width`](Self::min_width) is specified, it must be non-negative, and if
348    /// [`min_extended_width`](Self::min_extended_width) is specified, it must be
349    /// non-negative and greater than [`min_width`](Self::min_width).
350    ///
351    /// The [`extended`](Self::extended) argument can only be set to true when the
352    /// [`label_type`](Self::label_type) is null or [`NavigationRailLabelType::None`].
353    ///
354    /// If [`background_color`](Self::background_color), [`elevation`](Self::elevation),
355    /// [`group_alignment`](Self::group_alignment), [`label_type`](Self::label_type),
356    /// [`unselected_label_text_style`](Self::unselected_label_text_style),
357    /// [`selected_label_text_style`](Self::selected_label_text_style),
358    /// [`unselected_icon_theme`](Self::unselected_icon_theme), or
359    /// [`selected_icon_theme`](Self::selected_icon_theme) are null, then their
360    /// [`NavigationRailThemeData`] values will be used. If the corresponding
361    /// [`NavigationRailThemeData`] property is null, then the navigation rail
362    /// defaults are used. See the individual properties for more information.
363    ///
364    /// Typically used within a `Row` that defines the `Scaffold::body` property.
365    pub fn new(
366        destinations: Vec<NavigationRailDestination>,
367        selected_index: Option<usize>,
368    ) -> NavigationRail {
369        debug_assert!(selected_index.is_none_or(|index| index < destinations.len()));
370        NavigationRail {
371            key: None,
372            background_color: None,
373            extended: false,
374            leading: None,
375            trailing: None,
376            destinations,
377            selected_index,
378            on_destination_selected: None,
379            elevation: None,
380            group_alignment: None,
381            label_type: None,
382            unselected_label_text_style: None,
383            selected_label_text_style: None,
384            unselected_icon_theme: None,
385            selected_icon_theme: None,
386            min_width: None,
387            min_extended_width: None,
388            use_indicator: None,
389            indicator_color: None,
390            indicator_shape: None,
391            leading_at_top: true,
392            trailing_at_bottom: false,
393            scrollable: false,
394            main_axis_alignment: None,
395        }
396    }
397
398    /// Dart `NavigationRail(key:)`.
399    pub fn key(mut self, key: KeyRef) -> NavigationRail {
400        self.key = Some(key);
401        self
402    }
403
404    /// Dart `NavigationRail(backgroundColor:)`.
405    pub fn background_color(mut self, background_color: Color) -> NavigationRail {
406        self.background_color = Some(background_color);
407        self
408    }
409
410    /// Dart `NavigationRail(extended:)`.
411    pub fn extended(mut self, extended: bool) -> NavigationRail {
412        self.extended = extended;
413        self
414    }
415
416    /// Dart `NavigationRail(leading:)`.
417    #[cfg_attr(debug_assertions, track_caller)]
418    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> NavigationRail {
419        self.leading = Some(leading.into_widget());
420        self
421    }
422
423    /// Dart `NavigationRail(trailing:)`.
424    #[cfg_attr(debug_assertions, track_caller)]
425    pub fn trailing<K>(mut self, trailing: impl IntoWidget<K>) -> NavigationRail {
426        self.trailing = Some(trailing.into_widget());
427        self
428    }
429
430    /// Dart `NavigationRail(onDestinationSelected:)`.
431    pub fn on_destination_selected(
432        mut self,
433        on_destination_selected: impl Fn(&mut App, usize) + 'static,
434    ) -> NavigationRail {
435        self.on_destination_selected = Some(Rc::new(on_destination_selected));
436        self
437    }
438
439    /// Dart `NavigationRail(elevation:)`.
440    pub fn elevation(mut self, elevation: f64) -> NavigationRail {
441        debug_assert!(elevation > 0.0);
442        self.elevation = Some(elevation);
443        self
444    }
445
446    /// Dart `NavigationRail(groupAlignment:)`.
447    pub fn group_alignment(mut self, group_alignment: f64) -> NavigationRail {
448        self.group_alignment = Some(group_alignment);
449        self
450    }
451
452    /// Dart `NavigationRail(labelType:)`.
453    pub fn label_type(mut self, label_type: NavigationRailLabelType) -> NavigationRail {
454        self.label_type = Some(label_type);
455        self
456    }
457
458    /// Dart `NavigationRail(unselectedLabelTextStyle:)`.
459    pub fn unselected_label_text_style(
460        mut self,
461        unselected_label_text_style: TextStyle,
462    ) -> NavigationRail {
463        self.unselected_label_text_style = Some(unselected_label_text_style);
464        self
465    }
466
467    /// Dart `NavigationRail(selectedLabelTextStyle:)`.
468    pub fn selected_label_text_style(
469        mut self,
470        selected_label_text_style: TextStyle,
471    ) -> NavigationRail {
472        self.selected_label_text_style = Some(selected_label_text_style);
473        self
474    }
475
476    /// Dart `NavigationRail(unselectedIconTheme:)`.
477    pub fn unselected_icon_theme(mut self, unselected_icon_theme: IconThemeData) -> NavigationRail {
478        self.unselected_icon_theme = Some(unselected_icon_theme);
479        self
480    }
481
482    /// Dart `NavigationRail(selectedIconTheme:)`.
483    pub fn selected_icon_theme(mut self, selected_icon_theme: IconThemeData) -> NavigationRail {
484        self.selected_icon_theme = Some(selected_icon_theme);
485        self
486    }
487
488    /// Dart `NavigationRail(minWidth:)`.
489    pub fn min_width(mut self, min_width: f64) -> NavigationRail {
490        debug_assert!(min_width > 0.0);
491        self.min_width = Some(min_width);
492        self
493    }
494
495    /// Dart `NavigationRail(minExtendedWidth:)`.
496    pub fn min_extended_width(mut self, min_extended_width: f64) -> NavigationRail {
497        debug_assert!(min_extended_width > 0.0);
498        self.min_extended_width = Some(min_extended_width);
499        self
500    }
501
502    /// Dart `NavigationRail(useIndicator:)`.
503    pub fn use_indicator(mut self, use_indicator: bool) -> NavigationRail {
504        self.use_indicator = Some(use_indicator);
505        self
506    }
507
508    /// Dart `NavigationRail(indicatorColor:)`.
509    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationRail {
510        self.indicator_color = Some(indicator_color);
511        self
512    }
513
514    /// Dart `NavigationRail(indicatorShape:)`.
515    pub fn indicator_shape(mut self, indicator_shape: impl Into<ShapeBorderRef>) -> NavigationRail {
516        self.indicator_shape = Some(indicator_shape.into());
517        self
518    }
519
520    /// Dart `NavigationRail(leadingAtTop:)`.
521    pub fn leading_at_top(mut self, leading_at_top: bool) -> NavigationRail {
522        self.leading_at_top = leading_at_top;
523        self
524    }
525
526    /// Dart `NavigationRail(trailingAtBottom:)`.
527    pub fn trailing_at_bottom(mut self, trailing_at_bottom: bool) -> NavigationRail {
528        self.trailing_at_bottom = trailing_at_bottom;
529        self
530    }
531
532    /// Dart `NavigationRail(scrollable:)`.
533    pub fn scrollable(mut self, scrollable: bool) -> NavigationRail {
534        self.scrollable = scrollable;
535        self
536    }
537
538    /// Dart `NavigationRail(mainAxisAlignment:)`.
539    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> NavigationRail {
540        self.main_axis_alignment = Some(main_axis_alignment);
541        self
542    }
543
544    /// Returns the animation that controls the [`NavigationRail::extended`] state.
545    ///
546    /// This can be used to synchronize animations in the [`leading`](Self::leading) or
547    /// [`trailing`](Self::trailing) widget, such as an animated menu or a
548    /// `FloatingActionButton` animation.
549    pub fn extended_animation(app: &mut App, context: BuildContext) -> AnyAnimation<f64> {
550        context
551            .depend_on_inherited_widget_of_exact_type::<ExtendedNavigationRailAnimation>(app)
552            .expect("a NavigationRail above the context")
553            .animation
554            .handle()
555    }
556}
557
558impl Debug for NavigationRail {
559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560        f.debug_struct("NavigationRail")
561            .field("extended", &self.extended)
562            .field("destinations", &self.destinations.len())
563            .field("selected_index", &self.selected_index)
564            .field("label_type", &self.label_type)
565            .finish_non_exhaustive()
566    }
567}
568
569impl StatefulWidget for NavigationRail {
570    type State = NavigationRailState;
571
572    fn key(&self) -> Option<&KeyRef> {
573        self.key.as_ref()
574    }
575
576    fn debug_check_constructor(&self) {
577        debug_assert!(
578            self.min_width.is_none()
579                || self.min_extended_width.is_none()
580                || self.min_extended_width >= self.min_width
581        );
582        debug_assert!(
583            !self.extended
584                || self.label_type.is_none()
585                || self.label_type == Some(NavigationRailLabelType::None)
586        );
587    }
588
589    fn create_state(&self) -> NavigationRailState {
590        NavigationRailState {
591            state: StateData::new(),
592            ticker_provider: TickerProviderStateMixinData::new(),
593            destination_controllers: Vec::new(),
594            destination_animations: Vec::new(),
595            extended_controller: None,
596            extended_animation: None,
597        }
598    }
599}
600
601/// Dart's `_NavigationRailState`.
602pub struct NavigationRailState {
603    state: StateData<NavigationRail>,
604    ticker_provider: TickerProviderStateMixinData,
605    destination_controllers: Vec<Ref<AnimationController>>,
606    destination_animations: Vec<AnimationRef<f64>>,
607    extended_controller: Option<Ref<AnimationController>>,
608    extended_animation: Option<Ref<CurvedAnimation>>,
609}
610
611impl TickerProviderStateMixin for NavigationRailState {
612    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
613        &app.get(self).ticker_provider
614    }
615
616    fn ticker_provider_data_mut(
617        self: Handle<Self>,
618        app: &mut App,
619    ) -> &mut TickerProviderStateMixinData {
620        &mut app.get_mut(self).ticker_provider
621    }
622}
623
624impl TickerProviderObject for NavigationRailState {
625    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
626        TickerProviderStateMixin::create_ticker(self, app, on_tick)
627    }
628}
629
630impl State for NavigationRailState {
631    type Widget = NavigationRail;
632    waft_widgets::state_accessors!();
633
634    fn init_state(self: Handle<Self>, app: &mut App) {
635        self.init_controllers(app);
636    }
637
638    fn activate(self: Handle<Self>, app: &mut App) {
639        TickerProviderStateMixin::activate(self, app);
640    }
641
642    fn dispose(self: Handle<Self>, app: &mut App) {
643        self.dispose_controllers(app);
644        TickerProviderStateMixin::dispose(self, app);
645    }
646
647    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &NavigationRail) {
648        let widget = self.widget(app);
649        let extended = widget.extended;
650        let destinations_len = widget.destinations.len();
651        let selected_index = widget.selected_index;
652        if extended != old_widget.extended {
653            let extended_controller = self.extended_controller(app);
654            if extended {
655                extended_controller.forward(app, None);
656            } else {
657                extended_controller.reverse(app, None);
658            }
659        }
660
661        // No animated segue if the length of the items list changes.
662        if destinations_len != old_widget.destinations.len() {
663            self.reset_state(app);
664            return;
665        }
666
667        if selected_index != old_widget.selected_index {
668            if let Some(old_selected_index) = old_widget.selected_index {
669                app.get(self).destination_controllers[old_selected_index].reverse(app, None);
670            }
671            if let Some(selected_index) = selected_index {
672                app.get(self).destination_controllers[selected_index].forward(app, None);
673            }
674        }
675    }
676
677    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
678        let navigation_rail_theme = NavigationRailTheme::of(app, context);
679        let defaults: Box<dyn NavigationRailThemeDataGetters> =
680            if Theme::of(app, context).use_material3 {
681                Box::new(NavigationRailDefaultsM3::new(context))
682            } else {
683                Box::new(NavigationRailDefaultsM2::new(app, context))
684            };
685        let localizations = <dyn MaterialLocalizations>::of(app, context);
686
687        let widget_ref = context.widget(app).clone();
688        let widget = waft_widgets::downcast_widget::<NavigationRail>(&*widget_ref)
689            .expect("a NavigationRailState builds its NavigationRail");
690        let background_color = widget
691            .background_color
692            .or(navigation_rail_theme.background_color)
693            .or_else(|| defaults.background_color(app))
694            .expect("the defaults give a background color");
695        let elevation = widget
696            .elevation
697            .or(navigation_rail_theme.elevation)
698            .or_else(|| defaults.elevation(app))
699            .expect("the defaults give an elevation");
700        let min_width = widget
701            .min_width
702            .or(navigation_rail_theme.min_width)
703            .or_else(|| defaults.min_width(app))
704            .expect("the defaults give a min width");
705        let min_extended_width = widget
706            .min_extended_width
707            .or(navigation_rail_theme.min_extended_width)
708            .or_else(|| defaults.min_extended_width(app))
709            .expect("the defaults give a min extended width");
710        let unselected_label_text_style = widget
711            .unselected_label_text_style
712            .clone()
713            .or(navigation_rail_theme.unselected_label_text_style.clone())
714            .or_else(|| defaults.unselected_label_text_style(app))
715            .expect("the defaults give an unselected label text style");
716        let selected_label_text_style = widget
717            .selected_label_text_style
718            .clone()
719            .or(navigation_rail_theme.selected_label_text_style.clone())
720            .or_else(|| defaults.selected_label_text_style(app))
721            .expect("the defaults give a selected label text style");
722        let unselected_icon_theme = widget
723            .unselected_icon_theme
724            .clone()
725            .or(navigation_rail_theme.unselected_icon_theme.clone())
726            .or_else(|| defaults.unselected_icon_theme(app))
727            .expect("the defaults give an unselected icon theme");
728        let selected_icon_theme = widget
729            .selected_icon_theme
730            .clone()
731            .or(navigation_rail_theme.selected_icon_theme.clone())
732            .or_else(|| defaults.selected_icon_theme(app))
733            .expect("the defaults give a selected icon theme");
734        let group_alignment = widget
735            .group_alignment
736            .or(navigation_rail_theme.group_alignment)
737            .or_else(|| defaults.group_alignment(app))
738            .expect("the defaults give a group alignment");
739        let label_type = widget
740            .label_type
741            .or(navigation_rail_theme.label_type)
742            .or_else(|| defaults.label_type(app))
743            .expect("the defaults give a label type");
744        let use_indicator = widget
745            .use_indicator
746            .or(navigation_rail_theme.use_indicator)
747            .or_else(|| defaults.use_indicator(app))
748            .expect("the defaults give use_indicator");
749        let indicator_color = widget
750            .indicator_color
751            .or(navigation_rail_theme.indicator_color)
752            .or_else(|| defaults.indicator_color(app));
753        let indicator_shape = widget
754            .indicator_shape
755            .clone()
756            .or(navigation_rail_theme.indicator_shape.clone())
757            .or_else(|| defaults.indicator_shape(app));
758
759        // For backwards compatibility, in M2 the opacity of the unselected icons needs
760        // to be set to the default if it isn't in the given theme. This can be removed
761        // when Material 3 is the default.
762        let effective_unselected_icon_theme = if Theme::of(app, context).use_material3 {
763            unselected_icon_theme
764        } else {
765            let opacity = unselected_icon_theme.opacity.or_else(|| {
766                defaults
767                    .unselected_icon_theme(app)
768                    .expect("the M2 defaults give an unselected icon theme")
769                    .opacity
770            });
771            match opacity {
772                Some(opacity) => unselected_icon_theme.copy_with().opacity(opacity),
773                None => unselected_icon_theme.copy_with(),
774            }
775        };
776
777        let is_rtl_direction = Directionality::of(app, context) == TextDirection::Rtl;
778
779        let state = app.get(self);
780        let extended_animation: AnimationRef<f64> = state
781            .extended_animation
782            .as_ref()
783            .expect("created in init_state")
784            .erase();
785        let destination_animations = state.destination_animations.clone();
786        let widget = self.widget(app);
787        let destinations_len = widget.destinations.len();
788
789        let mut main_group_children = Vec::new();
790        if !widget.leading_at_top
791            && let Some(leading) = &widget.leading
792        {
793            main_group_children.push(leading.clone());
794            main_group_children.push(vertical_spacer());
795        }
796        let rail_destinations: Vec<WidgetRef> = widget
797            .destinations
798            .iter()
799            .enumerate()
800            .map(|(i, destination)| {
801                let selected = widget.selected_index == Some(i);
802                let on_destination_selected = widget.on_destination_selected.clone();
803                RailDestination {
804                    min_width,
805                    min_extended_width,
806                    extended_transition_animation: extended_animation.clone(),
807                    selected,
808                    icon: if selected {
809                        destination.selected_icon.clone()
810                    } else {
811                        destination.icon.clone()
812                    },
813                    label: destination.label.clone(),
814                    destination_animation: destination_animations[i].clone(),
815                    label_type,
816                    icon_theme: if selected {
817                        selected_icon_theme.clone()
818                    } else {
819                        effective_unselected_icon_theme.clone()
820                    },
821                    label_text_style: if selected {
822                        selected_label_text_style.clone()
823                    } else {
824                        unselected_label_text_style.clone()
825                    },
826                    padding: destination.padding,
827                    use_indicator,
828                    indicator_color: if use_indicator { indicator_color } else { None },
829                    indicator_shape: if use_indicator {
830                        indicator_shape.clone()
831                    } else {
832                        None
833                    },
834                    on_tap: Listener::new(move |app| {
835                        if let Some(on_destination_selected) = &on_destination_selected {
836                            on_destination_selected(app, i);
837                        }
838                    }),
839                    index_label: localizations.tab_label(i as i32 + 1, destinations_len as i32),
840                    disabled: destination.disabled,
841                }
842                .into_widget()
843            })
844            .collect();
845        main_group_children.push(
846            Semantics::new()
847                .role(SemanticsRole::TabBar)
848                .explicit_child_nodes(true)
849                .container(true)
850                .child(
851                    Column::new()
852                        .main_axis_size(MainAxisSize::Min)
853                        .children(rail_destinations),
854                )
855                .into_widget(),
856        );
857        if !widget.trailing_at_bottom
858            && let Some(trailing) = &widget.trailing
859        {
860            main_group_children.push(trailing.clone());
861        }
862        let mut main_group = Column::new()
863            .main_axis_size(if widget.main_axis_alignment.is_some() {
864                MainAxisSize::Max
865            } else {
866                MainAxisSize::Min
867            })
868            .main_axis_alignment(
869                widget
870                    .main_axis_alignment
871                    .unwrap_or(MainAxisAlignment::Start),
872            )
873            .children(main_group_children)
874            .into_widget();
875
876        if widget.scrollable {
877            main_group = SingleChildScrollView::new().child(main_group).into_widget();
878        }
879
880        let mut column_children = vec![vertical_spacer()];
881        if widget.leading_at_top
882            && let Some(leading) = &widget.leading
883        {
884            column_children.push(leading.clone());
885            column_children.push(vertical_spacer());
886        }
887        column_children.push(
888            Flexible::new(
889                Align::new()
890                    .alignment(AlignmentGeometry::Alignment(Alignment::new(
891                        0.0,
892                        group_alignment,
893                    )))
894                    .child(main_group),
895            )
896            .into_widget(),
897        );
898        if widget.trailing_at_bottom
899            && let Some(trailing) = &widget.trailing
900        {
901            column_children.push(trailing.clone());
902        }
903
904        Semantics::new()
905            .container(true)
906            .child(ExtendedNavigationRailAnimation {
907                animation: extended_animation.clone(),
908                child: Semantics::new()
909                    .explicit_child_nodes(true)
910                    .child(
911                        Material::new()
912                            .elevation(elevation)
913                            .color(background_color)
914                            .child(
915                                SafeArea::new(Column::new().children(column_children))
916                                    .right(is_rtl_direction)
917                                    .left(!is_rtl_direction),
918                            ),
919                    )
920                    .into_widget(),
921            })
922            .into_widget()
923    }
924}
925
926impl NavigationRailState {
927    fn extended_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
928        app.get(self)
929            .extended_controller
930            .handle()
931            .expect("created in init_state")
932    }
933
934    fn dispose_controllers(self: Handle<Self>, app: &mut App) {
935        let state = app.get(self);
936        let destination_controllers = state.destination_controllers.clone();
937        let extended_controller = state
938            .extended_controller
939            .handle()
940            .expect("created in init_state");
941        let extended_animation = state
942            .extended_animation
943            .handle()
944            .expect("created in init_state");
945        for controller in destination_controllers {
946            controller.dispose(app);
947        }
948        extended_controller.dispose(app);
949        extended_animation.dispose(app);
950    }
951
952    fn init_controllers(self: Handle<Self>, app: &mut App) {
953        let destinations_len = self.widget(app).destinations.len();
954        let destination_controllers: Vec<Ref<AnimationController>> = (0..destinations_len)
955            .map(|_| {
956                let controller = AnimationController::new(
957                    app,
958                    None,
959                    Some(K_THEME_ANIMATION_DURATION),
960                    None,
961                    0.0,
962                    1.0,
963                    AnimationBehavior::Normal,
964                    self,
965                );
966                Animation::add_listener(
967                    controller.handle(),
968                    app,
969                    Listener::handle_method(self, Self::rebuild),
970                );
971                controller
972            })
973            .collect();
974        let destination_animations = destination_controllers
975            .iter()
976            .map(|controller| controller.erase())
977            .collect();
978        if let Some(selected_index) = self.widget(app).selected_index {
979            destination_controllers[selected_index].set_value(app, 1.0);
980        }
981        let extended = self.widget(app).extended;
982        let extended_controller = AnimationController::new(
983            app,
984            Some(if extended { 1.0 } else { 0.0 }),
985            Some(K_THEME_ANIMATION_DURATION),
986            None,
987            0.0,
988            1.0,
989            AnimationBehavior::Normal,
990            self,
991        );
992        let extended_animation = CurvedAnimation::new(
993            app,
994            extended_controller.erase(),
995            Curves::ease_in_out(),
996            None,
997        );
998        Animation::add_listener(
999            extended_controller.handle(),
1000            app,
1001            Listener::handle_method(self, Self::rebuild),
1002        );
1003        let state = app.get_mut(self);
1004        state.destination_controllers = destination_controllers;
1005        state.destination_animations = destination_animations;
1006        state.extended_controller = Some(extended_controller);
1007        state.extended_animation = Some(extended_animation);
1008    }
1009
1010    fn reset_state(self: Handle<Self>, app: &mut App) {
1011        self.dispose_controllers(app);
1012        self.init_controllers(app);
1013    }
1014
1015    fn rebuild(self: Handle<Self>, app: &mut App) {
1016        self.set_state(app, |_| {
1017            // Rebuilding when any of the controllers tick, i.e. when the items are
1018            // animating.
1019        });
1020    }
1021}
1022
1023/// Dart's `_RailDestination`.
1024struct RailDestination {
1025    min_width: f64,
1026    min_extended_width: f64,
1027    icon: WidgetRef,
1028    label: WidgetRef,
1029    destination_animation: AnimationRef<f64>,
1030    label_type: NavigationRailLabelType,
1031    selected: bool,
1032    extended_transition_animation: AnimationRef<f64>,
1033    icon_theme: IconThemeData,
1034    label_text_style: TextStyle,
1035    on_tap: Listener,
1036    index_label: String,
1037    padding: Option<EdgeInsetsGeometry>,
1038    use_indicator: bool,
1039    indicator_color: Option<Color>,
1040    indicator_shape: Option<ShapeBorderRef>,
1041    disabled: bool,
1042}
1043
1044impl Debug for RailDestination {
1045    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1046        f.debug_struct("_RailDestination")
1047            .field("label_type", &self.label_type)
1048            .field("selected", &self.selected)
1049            .field("disabled", &self.disabled)
1050            .finish_non_exhaustive()
1051    }
1052}
1053
1054impl StatefulWidget for RailDestination {
1055    type State = RailDestinationState;
1056
1057    fn create_state(&self) -> RailDestinationState {
1058        RailDestinationState {
1059            state: StateData::new(),
1060            position_animation: None,
1061        }
1062    }
1063}
1064
1065/// Dart's `_RailDestinationState`.
1066struct RailDestinationState {
1067    state: StateData<RailDestination>,
1068    /// Dart's `_positionAnimation`, a `CurvedAnimation` over a `ReverseAnimation`.
1069    position_animation: Option<Ref<CurvedAnimation>>,
1070}
1071
1072impl RailDestinationState {
1073    fn set_position_animation(self: Handle<Self>, app: &mut App) {
1074        let destination_animation = self.widget(app).destination_animation.clone();
1075        let reversed = ReverseAnimation::new(app, destination_animation);
1076        let curved = CurvedAnimation::new(
1077            app,
1078            reversed.erase(),
1079            Curves::ease_in_out(),
1080            Some(Rc::new(Curves::ease_in_out().flipped())),
1081        );
1082        app.get_mut(self).position_animation = Some(curved);
1083    }
1084
1085    fn dispose_position_animation(self: Handle<Self>, app: &mut App) {
1086        let position_animation = app
1087            .get_mut(self)
1088            .position_animation
1089            .take()
1090            .expect("set in init_state");
1091        position_animation.dispose(app);
1092    }
1093
1094    fn position_animation_value(self: Handle<Self>, app: &App) -> f64 {
1095        app.get(self)
1096            .position_animation
1097            .as_ref()
1098            .expect("set in init_state")
1099            .value(app)
1100    }
1101
1102    /// Dart's `parent.drive(CurveTween(curve: Interval(begin, end)))`.
1103    fn label_fade_animation(
1104        app: &mut App,
1105        parent: AnimationRef<f64>,
1106        begin: f64,
1107        end: f64,
1108    ) -> AnimationRef<f64> {
1109        let curve_tween =
1110            CurveTween::new(app, Rc::new(Interval::new(begin, end, Curves::linear())));
1111        parent.drive(app, curve_tween)
1112    }
1113}
1114
1115impl State for RailDestinationState {
1116    type Widget = RailDestination;
1117    waft_widgets::state_accessors!();
1118
1119    fn init_state(self: Handle<Self>, app: &mut App) {
1120        self.set_position_animation(app);
1121    }
1122
1123    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RailDestination) {
1124        if self.widget(app).destination_animation != old_widget.destination_animation {
1125            self.dispose_position_animation(app);
1126            self.set_position_animation(app);
1127        }
1128    }
1129
1130    fn dispose(self: Handle<Self>, app: &mut App) {
1131        self.dispose_position_animation(app);
1132    }
1133
1134    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1135    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1136        {
1137            let widget = self.widget(app);
1138            debug_assert!(
1139                widget.use_indicator || widget.indicator_color.is_none(),
1140                "[NavigationRail.indicatorColor] does not have an effect when \
1141                 [NavigationRail.useIndicator] is false"
1142            );
1143        }
1144
1145        let theme = Theme::of(app, context);
1146        let text_direction = Directionality::of(app, context);
1147        let material3 = theme.use_material3;
1148        let m2_min_width = NavigationRailDefaultsM2::new(app, context)
1149            .min_width(app)
1150            .expect("the M2 defaults give a min width");
1151        let position_animation_value = self.position_animation_value(app);
1152        let extended_transition_value = self.widget(app).extended_transition_animation.value(app);
1153
1154        let widget = self.widget(app);
1155        let destination_padding = widget
1156            .padding
1157            .unwrap_or(EdgeInsetsGeometry::ZERO)
1158            .resolve(Some(text_direction));
1159        let indicator_offset: Offset;
1160        let mut apply_x_offset = false;
1161
1162        let themed_icon = IconTheme::new(
1163            if widget.disabled {
1164                widget
1165                    .icon_theme
1166                    .copy_with()
1167                    .color(theme.color_scheme.on_surface().with_opacity(0.38))
1168            } else {
1169                widget.icon_theme.clone()
1170            },
1171            widget.icon.clone(),
1172        )
1173        .into_widget();
1174        let styled_label = DefaultTextStyle::new(
1175            if widget.disabled {
1176                widget
1177                    .label_text_style
1178                    .copy_with()
1179                    .color(theme.color_scheme.on_surface().with_opacity(0.38))
1180            } else {
1181                widget.label_text_style.clone()
1182            },
1183            widget.label.clone(),
1184        )
1185        .into_widget();
1186
1187        let content: WidgetRef;
1188
1189        // The indicator height is fixed and equal to _kIndicatorHeight.
1190        // When the icon height is larger than the indicator height the indicator
1191        // vertical offset is used to vertically center the indicator.
1192        let is_large_icon_size = widget
1193            .icon_theme
1194            .size
1195            .is_some_and(|size| size > K_INDICATOR_HEIGHT);
1196        let indicator_vertical_offset = if is_large_icon_size {
1197            (widget.icon_theme.size.expect("checked above") - K_INDICATOR_HEIGHT) / 2.0
1198        } else {
1199            0.0
1200        };
1201
1202        let add_indicator = |is_circular: bool, child: WidgetRef| AddIndicator {
1203            add_indicator: widget.use_indicator,
1204            indicator_color: widget.indicator_color,
1205            indicator_shape: widget.indicator_shape.clone(),
1206            is_circular,
1207            indicator_animation: widget.destination_animation.clone(),
1208            child,
1209        };
1210
1211        match widget.label_type {
1212            NavigationRailLabelType::None => {
1213                // Split the destination spacing across the top and bottom to keep the icon
1214                // centered.
1215                let spacing = material3.then(|| {
1216                    SizedBox::new()
1217                        .height(VERTICAL_DESTINATION_SPACING_M3 / 2.0)
1218                        .into_widget()
1219                });
1220                indicator_offset = Offset::new(
1221                    widget.min_width / 2.0 + destination_padding.left,
1222                    VERTICAL_DESTINATION_SPACING_M3 / 2.0
1223                        + destination_padding.top
1224                        + indicator_vertical_offset,
1225                );
1226                let mut icon_box = SizedBox::new().width(widget.min_width);
1227                if !material3 {
1228                    icon_box = icon_box.height(widget.min_width);
1229                }
1230                let icon_part = Column::new()
1231                    .children(
1232                        spacing
1233                            .clone()
1234                            .into_iter()
1235                            .chain([icon_box
1236                                .child(Center::new().child(add_indicator(!material3, themed_icon)))
1237                                .into_widget()])
1238                            .chain(spacing),
1239                    )
1240                    .into_widget();
1241                if extended_transition_value == 0.0 {
1242                    content = Padding::new(widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO))
1243                        .child(
1244                            Stack::new().children([
1245                                icon_part,
1246                                // For semantics when label is not showing,
1247                                SizedBox::shrink()
1248                                    .child(
1249                                        Visibility::maintain(widget.label.clone()).visible(false),
1250                                    )
1251                                    .into_widget(),
1252                            ]),
1253                        )
1254                        .into_widget();
1255                } else {
1256                    let extended_transition_animation =
1257                        widget.extended_transition_animation.clone();
1258                    let min_width = widget.min_width;
1259                    let min_extended_width = widget.min_extended_width;
1260                    let padding = widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO);
1261                    let label_fade_animation = RailDestinationState::label_fade_animation(
1262                        app,
1263                        extended_transition_animation,
1264                        0.0,
1265                        0.25,
1266                    );
1267                    apply_x_offset = true;
1268                    content = Padding::new(padding)
1269                        .child(
1270                            ConstrainedBox::new(
1271                                BoxConstraints::new().min_width(
1272                                    lerp_double(
1273                                        Some(min_width),
1274                                        Some(min_extended_width),
1275                                        extended_transition_value,
1276                                    )
1277                                    .expect("both ends given"),
1278                                ),
1279                            )
1280                            .child(
1281                                ClipRect::new().child(
1282                                    Row::new().main_axis_size(MainAxisSize::Min).children([
1283                                        icon_part,
1284                                        Flexible::new(
1285                                            Align::new()
1286                                                .height_factor(1.0)
1287                                                .width_factor(extended_transition_value)
1288                                                .alignment(AlignmentGeometry::CENTER_START)
1289                                                .child(
1290                                                    FadeTransition::new(label_fade_animation)
1291                                                        .child(styled_label),
1292                                                ),
1293                                        )
1294                                        .into_widget(),
1295                                        SizedBox::new()
1296                                            .width(
1297                                                HORIZONTAL_DESTINATION_PADDING
1298                                                    * extended_transition_value,
1299                                            )
1300                                            .into_widget(),
1301                                    ]),
1302                                ),
1303                            ),
1304                        )
1305                        .into_widget();
1306                }
1307            }
1308            NavigationRailLabelType::Selected => {
1309                let appearing_animation_value = 1.0 - position_animation_value;
1310                let vertical_padding = lerp_double(
1311                    Some(VERTICAL_DESTINATION_PADDING_NO_LABEL),
1312                    Some(VERTICAL_DESTINATION_PADDING_WITH_LABEL),
1313                    appearing_animation_value,
1314                )
1315                .expect("both ends given");
1316                let (interval_begin, interval_end) = if widget.selected {
1317                    (0.25, 0.75)
1318                } else {
1319                    (0.75, 1.0)
1320                };
1321                let min_height = if material3 { 0.0 } else { widget.min_width };
1322                let top_spacing = SizedBox::new()
1323                    .height(if material3 { 0.0 } else { vertical_padding })
1324                    .into_widget();
1325                let label_spacing = SizedBox::new()
1326                    .height(if material3 {
1327                        lerp_double(
1328                            Some(0.0),
1329                            Some(VERTICAL_ICON_LABEL_SPACING_M3),
1330                            appearing_animation_value,
1331                        )
1332                        .expect("both ends given")
1333                    } else {
1334                        0.0
1335                    })
1336                    .into_widget();
1337                let bottom_spacing = SizedBox::new()
1338                    .height(if material3 {
1339                        VERTICAL_DESTINATION_SPACING_M3
1340                    } else {
1341                        vertical_padding
1342                    })
1343                    .into_widget();
1344                let indicator_horizontal_padding =
1345                    (destination_padding.left / 2.0) - (destination_padding.right / 2.0);
1346                let indicator_vertical_padding = destination_padding.top;
1347                let mut offset = Offset::new(
1348                    widget.min_width / 2.0 + indicator_horizontal_padding,
1349                    indicator_vertical_padding + indicator_vertical_offset,
1350                );
1351                if widget.min_width < m2_min_width {
1352                    offset = Offset::new(
1353                        widget.min_width / 2.0 + HORIZONTAL_DESTINATION_SPACING_M3,
1354                        indicator_vertical_padding + indicator_vertical_offset,
1355                    );
1356                }
1357                indicator_offset = offset;
1358                let indicator = add_indicator(false, themed_icon).into_widget();
1359                let min_width = widget.min_width;
1360                let padding = widget.padding.unwrap_or(EdgeInsetsGeometry::symmetric(
1361                    0.0,
1362                    HORIZONTAL_DESTINATION_PADDING,
1363                ));
1364                let destination_animation = widget.destination_animation.clone();
1365                let label_fade_animation = RailDestinationState::label_fade_animation(
1366                    app,
1367                    destination_animation,
1368                    interval_begin,
1369                    interval_end,
1370                );
1371                content = ConstrainedBox::new(
1372                    BoxConstraints::new()
1373                        .min_width(min_width)
1374                        .min_height(min_height),
1375                )
1376                .child(
1377                    Padding::new(padding).child(
1378                        ClipRect::new().child(
1379                            Column::new()
1380                                .main_axis_size(MainAxisSize::Min)
1381                                .main_axis_alignment(MainAxisAlignment::Center)
1382                                .children([
1383                                    top_spacing,
1384                                    indicator,
1385                                    label_spacing,
1386                                    Align::new()
1387                                        .alignment(AlignmentGeometry::TOP_CENTER)
1388                                        .height_factor(appearing_animation_value)
1389                                        .width_factor(1.0)
1390                                        .child(
1391                                            FadeTransition::new(label_fade_animation)
1392                                                .child(styled_label),
1393                                        )
1394                                        .into_widget(),
1395                                    bottom_spacing,
1396                                ]),
1397                        ),
1398                    ),
1399                )
1400                .into_widget();
1401            }
1402            NavigationRailLabelType::All => {
1403                let min_height = if material3 { 0.0 } else { widget.min_width };
1404                let top_spacing = SizedBox::new()
1405                    .height(if material3 {
1406                        0.0
1407                    } else {
1408                        VERTICAL_DESTINATION_PADDING_WITH_LABEL
1409                    })
1410                    .into_widget();
1411                let label_spacing = SizedBox::new()
1412                    .height(if material3 {
1413                        VERTICAL_ICON_LABEL_SPACING_M3
1414                    } else {
1415                        0.0
1416                    })
1417                    .into_widget();
1418                let bottom_spacing = SizedBox::new()
1419                    .height(if material3 {
1420                        VERTICAL_DESTINATION_SPACING_M3
1421                    } else {
1422                        VERTICAL_DESTINATION_PADDING_WITH_LABEL
1423                    })
1424                    .into_widget();
1425                let indicator_horizontal_padding =
1426                    (destination_padding.left / 2.0) - (destination_padding.right / 2.0);
1427                let indicator_vertical_padding = destination_padding.top;
1428                let mut offset = Offset::new(
1429                    widget.min_width / 2.0 + indicator_horizontal_padding,
1430                    indicator_vertical_padding + indicator_vertical_offset,
1431                );
1432                if widget.min_width < m2_min_width {
1433                    offset = Offset::new(
1434                        widget.min_width / 2.0 + HORIZONTAL_DESTINATION_SPACING_M3,
1435                        indicator_vertical_padding + indicator_vertical_offset,
1436                    );
1437                }
1438                indicator_offset = offset;
1439                content = ConstrainedBox::new(
1440                    BoxConstraints::new()
1441                        .min_width(widget.min_width)
1442                        .min_height(min_height),
1443                )
1444                .child(
1445                    Padding::new(widget.padding.unwrap_or(EdgeInsetsGeometry::symmetric(
1446                        0.0,
1447                        HORIZONTAL_DESTINATION_PADDING,
1448                    )))
1449                    .child(Column::new().children([
1450                        top_spacing,
1451                        add_indicator(false, themed_icon).into_widget(),
1452                        label_spacing,
1453                        styled_label,
1454                        bottom_spacing,
1455                    ])),
1456                )
1457                .into_widget();
1458            }
1459        }
1460
1461        let colors = &Theme::of(app, context).color_scheme;
1462        let primary_color_alpha_modified = (colors.primary().alpha() as f64) < 255.0;
1463        let effective_splash_color = if primary_color_alpha_modified {
1464            colors.primary()
1465        } else {
1466            colors.primary().with_opacity(0.12)
1467        };
1468        let effective_hover_color = if primary_color_alpha_modified {
1469            colors.primary()
1470        } else {
1471            colors.primary().with_opacity(0.04)
1472        };
1473        let widget = self.widget(app);
1474        let mut stack_children = vec![
1475            Material::new()
1476                .r#type(MaterialType::Transparency)
1477                .child(indicator_ink_well(IndicatorInkWell {
1478                    child: content,
1479                    on_tap: (!widget.disabled).then(|| widget.on_tap.clone()),
1480                    border_radius: BorderRadius::all(Radius::circular(widget.min_width / 2.0)),
1481                    custom_border: widget.indicator_shape.clone(),
1482                    splash_color: effective_splash_color,
1483                    hover_color: effective_hover_color,
1484                    use_material3: material3,
1485                    indicator_offset,
1486                    apply_x_offset,
1487                    text_direction,
1488                }))
1489                .into_widget(),
1490        ];
1491        if !K_IS_WEB {
1492            stack_children.push(
1493                Semantics::new()
1494                    .label(widget.index_label.clone())
1495                    .into_widget(),
1496            );
1497        }
1498        let mut semantics = Semantics::new()
1499            .role(SemanticsRole::Tab)
1500            .selected(widget.selected);
1501        if widget.disabled {
1502            semantics = semantics.enabled(false);
1503        }
1504        MergeSemantics::new()
1505            .child(semantics.child(Stack::new().children(stack_children)))
1506            .into_widget()
1507    }
1508}
1509
1510/// The arguments of Dart's `_IndicatorInkWell`, an `InkResponse` subclass.
1511struct IndicatorInkWell {
1512    child: WidgetRef,
1513    on_tap: Option<Listener>,
1514    custom_border: Option<ShapeBorderRef>,
1515    border_radius: BorderRadius,
1516    splash_color: Color,
1517    hover_color: Color,
1518    use_material3: bool,
1519    // The offset used to position Ink highlight.
1520    indicator_offset: Offset,
1521    // Whether the horizontal offset from indicatorOffset should be used to position Ink
1522    // highlight. If true, Ink highlight uses the indicator horizontal offset. If false, Ink
1523    // highlight is centered horizontally.
1524    apply_x_offset: bool,
1525    // The text direction used to adjust the indicator horizontal offset.
1526    text_direction: TextDirection,
1527}
1528
1529/// Dart's `_IndicatorInkWell`: the `InkResponse` its constructor makes, with its
1530/// `getRectCallback` override.
1531fn indicator_ink_well(ink_well: IndicatorInkWell) -> InkResponse {
1532    let IndicatorInkWell {
1533        child,
1534        on_tap,
1535        custom_border,
1536        border_radius,
1537        splash_color,
1538        hover_color,
1539        use_material3,
1540        indicator_offset,
1541        apply_x_offset,
1542        text_direction,
1543    } = ink_well;
1544    let mut response = InkResponse::new()
1545        .child(child)
1546        .splash_color(splash_color)
1547        .hover_color(hover_color)
1548        .contained_ink_well(true)
1549        .highlight_shape(BoxShape::Rectangle)
1550        .override_get_rect_callback(move |app, reference_box| -> Option<RectCallback> {
1551            if use_material3 {
1552                let box_width = reference_box.size(app).width();
1553                let mut indicator_horizontal_center = if apply_x_offset {
1554                    indicator_offset.dx()
1555                } else {
1556                    box_width / 2.0
1557                };
1558                if text_direction == TextDirection::Rtl {
1559                    indicator_horizontal_center = box_width - indicator_horizontal_center;
1560                }
1561                return Some(Rc::new(move |_app| {
1562                    Rect::from_ltwh(
1563                        indicator_horizontal_center - (K_CIRCULAR_INDICATOR_DIAMETER / 2.0),
1564                        indicator_offset.dy(),
1565                        K_CIRCULAR_INDICATOR_DIAMETER,
1566                        K_INDICATOR_HEIGHT,
1567                    )
1568                }));
1569            }
1570            None
1571        });
1572    if let Some(on_tap) = on_tap {
1573        response = response.on_tap(on_tap);
1574    }
1575    if !use_material3 {
1576        response = response.border_radius(border_radius);
1577    }
1578    if use_material3 && let Some(custom_border) = custom_border {
1579        response = response.custom_border(custom_border);
1580    }
1581    response
1582}
1583
1584/// When `add_indicator` is `true`, puts `child` center aligned in a `Stack` with
1585/// a [`NavigationIndicator`] behind it, otherwise returns `child`.
1586///
1587/// When `is_circular` is true, the indicator will be a circle, otherwise the
1588/// indicator will be a stadium shape.
1589struct AddIndicator {
1590    add_indicator: bool,
1591    is_circular: bool,
1592    indicator_color: Option<Color>,
1593    indicator_shape: Option<ShapeBorderRef>,
1594    indicator_animation: AnimationRef<f64>,
1595    child: WidgetRef,
1596}
1597
1598impl Debug for AddIndicator {
1599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1600        f.debug_struct("_AddIndicator")
1601            .field("add_indicator", &self.add_indicator)
1602            .field("is_circular", &self.is_circular)
1603            .field("indicator_color", &self.indicator_color)
1604            .field("indicator_shape", &self.indicator_shape)
1605            .field("child", &self.child)
1606            .finish_non_exhaustive()
1607    }
1608}
1609
1610impl StatelessWidget for AddIndicator {
1611    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1612        if !self.add_indicator {
1613            return self.child.clone();
1614        }
1615        let indicator = if self.is_circular {
1616            let mut indicator = NavigationIndicator::new(self.indicator_animation.clone())
1617                .height(K_CIRCULAR_INDICATOR_DIAMETER)
1618                .width(K_CIRCULAR_INDICATOR_DIAMETER)
1619                .border_radius(BorderRadius::all(Radius::circular(
1620                    K_CIRCULAR_INDICATOR_DIAMETER / 2.0,
1621                )));
1622            if let Some(color) = self.indicator_color {
1623                indicator = indicator.color(color);
1624            }
1625            indicator
1626        } else {
1627            let mut indicator = NavigationIndicator::new(self.indicator_animation.clone())
1628                .width(K_CIRCULAR_INDICATOR_DIAMETER);
1629            if let Some(shape) = self.indicator_shape.clone() {
1630                indicator = indicator.shape(shape);
1631            }
1632            if let Some(color) = self.indicator_color {
1633                indicator = indicator.color(color);
1634            }
1635            indicator
1636        };
1637
1638        Stack::new()
1639            .alignment(AlignmentGeometry::CENTER)
1640            .children([indicator.into_widget(), self.child.clone()])
1641            .into_widget()
1642    }
1643}
1644
1645/// Defines the behavior of the labels of a [`NavigationRail`].
1646///
1647/// See also:
1648///
1649///   * [`NavigationRail`]
1650#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1651pub enum NavigationRailLabelType {
1652    /// Only the [`NavigationRailDestination`]s are shown.
1653    None,
1654
1655    /// Only the selected [`NavigationRailDestination`] will show its label.
1656    ///
1657    /// The label will animate in and out as new [`NavigationRailDestination`]s are
1658    /// selected.
1659    Selected,
1660
1661    /// All [`NavigationRailDestination`]s will show their label.
1662    All,
1663}
1664
1665/// Defines a [`NavigationRail`] button that represents one "destination" view.
1666///
1667/// See also:
1668///
1669///  * [`NavigationRail`]
1670#[derive(Clone, Debug)]
1671pub struct NavigationRailDestination {
1672    /// The icon of the destination.
1673    ///
1674    /// Typically the icon is an `Icon` or an `ImageIcon` widget. If another type
1675    /// of widget is provided then it should configure itself to match the current
1676    /// `IconTheme` size and color.
1677    ///
1678    /// If [`selected_icon`](Self::selected_icon) is provided, this will only be displayed
1679    /// when the destination is not selected.
1680    ///
1681    /// To make the [`NavigationRail`] more accessible, consider choosing an
1682    /// icon with a stroked and filled version, such as `Icons::cloud` and
1683    /// `Icons::cloud_queue`. The [`icon`](Self::icon) should be set to the stroked version
1684    /// and [`selected_icon`](Self::selected_icon) to the filled version.
1685    pub icon: WidgetRef,
1686
1687    /// An alternative icon displayed when this destination is selected.
1688    ///
1689    /// If this icon is not provided, the [`NavigationRail`] will display
1690    /// [`icon`](Self::icon) in either state. The size, color, and opacity of the
1691    /// [`NavigationRail::selected_icon_theme`] will still apply.
1692    ///
1693    /// See also:
1694    ///
1695    ///  * [`NavigationRailDestination::icon`], for a description of how to pair
1696    ///    icons.
1697    pub selected_icon: WidgetRef,
1698
1699    /// The color of the [`indicator_shape`](Self::indicator_shape) when this destination is
1700    /// selected.
1701    pub indicator_color: Option<Color>,
1702
1703    /// The shape of the selection indicator.
1704    pub indicator_shape: Option<ShapeBorderRef>,
1705
1706    /// The label for the destination.
1707    ///
1708    /// The label must be provided when used with the [`NavigationRail`]. When the
1709    /// [`NavigationRail::label_type`] is [`NavigationRailLabelType::None`], the label is
1710    /// still used for semantics, and may still be used if
1711    /// [`NavigationRail::extended`] is true.
1712    pub label: WidgetRef,
1713
1714    /// The amount of space to inset the destination item.
1715    pub padding: Option<EdgeInsetsGeometry>,
1716
1717    /// Indicates that this destination is inaccessible.
1718    pub disabled: bool,
1719}
1720
1721impl NavigationRailDestination {
1722    /// Creates a destination that is used with [`NavigationRail::destinations`].
1723    ///
1724    /// When the [`NavigationRail::label_type`] is [`NavigationRailLabelType::None`], the
1725    /// label is still used for semantics, and may still be used if
1726    /// [`NavigationRail::extended`] is true.
1727    #[cfg_attr(debug_assertions, track_caller)]
1728    pub fn new<I, L>(
1729        icon: impl IntoWidget<I>,
1730        label: impl IntoWidget<L>,
1731    ) -> NavigationRailDestination {
1732        let icon = icon.into_widget();
1733        NavigationRailDestination {
1734            selected_icon: icon.clone(),
1735            icon,
1736            indicator_color: None,
1737            indicator_shape: None,
1738            label: label.into_widget(),
1739            padding: None,
1740            disabled: false,
1741        }
1742    }
1743
1744    /// Dart `NavigationRailDestination(selectedIcon:)`.
1745    #[cfg_attr(debug_assertions, track_caller)]
1746    pub fn selected_icon<K>(
1747        mut self,
1748        selected_icon: impl IntoWidget<K>,
1749    ) -> NavigationRailDestination {
1750        self.selected_icon = selected_icon.into_widget();
1751        self
1752    }
1753
1754    /// Dart `NavigationRailDestination(indicatorColor:)`.
1755    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationRailDestination {
1756        self.indicator_color = Some(indicator_color);
1757        self
1758    }
1759
1760    /// Dart `NavigationRailDestination(indicatorShape:)`.
1761    pub fn indicator_shape(
1762        mut self,
1763        indicator_shape: impl Into<ShapeBorderRef>,
1764    ) -> NavigationRailDestination {
1765        self.indicator_shape = Some(indicator_shape.into());
1766        self
1767    }
1768
1769    /// Dart `NavigationRailDestination(padding:)`.
1770    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> NavigationRailDestination {
1771        self.padding = Some(padding.into());
1772        self
1773    }
1774
1775    /// Dart `NavigationRailDestination(disabled:)`.
1776    pub fn disabled(mut self, disabled: bool) -> NavigationRailDestination {
1777        self.disabled = disabled;
1778        self
1779    }
1780}
1781
1782/// Dart's `_ExtendedNavigationRailAnimation`.
1783#[derive(Debug)]
1784struct ExtendedNavigationRailAnimation {
1785    animation: AnimationRef<f64>,
1786    child: WidgetRef,
1787}
1788
1789impl InheritedWidget for ExtendedNavigationRailAnimation {
1790    fn child(&self) -> &WidgetRef {
1791        &self.child
1792    }
1793
1794    fn update_should_notify(&self, old: &ExtendedNavigationRailAnimation) -> bool {
1795        self.animation != old.animation
1796    }
1797}
1798
1799// There don't appear to be tokens for these values, but they are
1800// shown in the spec.
1801const HORIZONTAL_DESTINATION_PADDING: f64 = 8.0;
1802const VERTICAL_DESTINATION_PADDING_NO_LABEL: f64 = 24.0;
1803const VERTICAL_DESTINATION_PADDING_WITH_LABEL: f64 = 16.0;
1804/// Dart's `const Widget _verticalSpacer = SizedBox(height: 8.0)`.
1805fn vertical_spacer() -> WidgetRef {
1806    SizedBox::new().height(8.0).into_widget()
1807}
1808const VERTICAL_ICON_LABEL_SPACING_M3: f64 = 4.0;
1809const VERTICAL_DESTINATION_SPACING_M3: f64 = 12.0;
1810const HORIZONTAL_DESTINATION_SPACING_M3: f64 = 12.0;
1811
1812/// Dart's `_NavigationRailDefaultsM2`.
1813struct NavigationRailDefaultsM2 {
1814    /// Dart's `super(..)` arguments.
1815    navigation_rail_theme_data: NavigationRailThemeData,
1816    context: DefaultsContext,
1817}
1818
1819impl NavigationRailDefaultsM2 {
1820    fn new(app: &mut App, context: BuildContext) -> NavigationRailDefaultsM2 {
1821        NavigationRailDefaultsM2 {
1822            navigation_rail_theme_data: NavigationRailThemeData::new()
1823                .elevation(0.0)
1824                .group_alignment(-1.0)
1825                .label_type(NavigationRailLabelType::None)
1826                .use_indicator(false)
1827                .min_width(72.0)
1828                .min_extended_width(256.0),
1829            context: DefaultsContext::with_theme(app, context),
1830        }
1831    }
1832}
1833
1834#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1835impl NavigationRailThemeDataGetters for NavigationRailDefaultsM2 {
1836    fn navigation_rail_theme_data(&self) -> &NavigationRailThemeData {
1837        &self.navigation_rail_theme_data
1838    }
1839
1840    fn background_color(&self, app: &mut App) -> Option<Color> {
1841        let theme = self.context.theme(app);
1842        let colors = &theme.color_scheme;
1843        Some(colors.surface())
1844    }
1845
1846    fn unselected_label_text_style(&self, app: &mut App) -> Option<TextStyle> {
1847        let theme = self.context.theme(app);
1848        let colors = &theme.color_scheme;
1849        Some(
1850            theme
1851                .text_theme
1852                .body_large
1853                .as_ref()
1854                .expect("the text theme has bodyLarge")
1855                .copy_with()
1856                .color(colors.on_surface().with_opacity(0.64)),
1857        )
1858    }
1859
1860    fn selected_label_text_style(&self, app: &mut App) -> Option<TextStyle> {
1861        let theme = self.context.theme(app);
1862        let colors = &theme.color_scheme;
1863        Some(
1864            theme
1865                .text_theme
1866                .body_large
1867                .as_ref()
1868                .expect("the text theme has bodyLarge")
1869                .copy_with()
1870                .color(colors.primary()),
1871        )
1872    }
1873
1874    fn unselected_icon_theme(&self, app: &mut App) -> Option<IconThemeData> {
1875        let theme = self.context.theme(app);
1876        let colors = &theme.color_scheme;
1877        Some(
1878            IconThemeData::new()
1879                .size(24.0)
1880                .color(colors.on_surface())
1881                .opacity(0.64),
1882        )
1883    }
1884
1885    fn selected_icon_theme(&self, app: &mut App) -> Option<IconThemeData> {
1886        let theme = self.context.theme(app);
1887        let colors = &theme.color_scheme;
1888        Some(
1889            IconThemeData::new()
1890                .size(24.0)
1891                .color(colors.primary())
1892                .opacity(1.0),
1893        )
1894    }
1895}
1896
1897#[cfg(test)]
1898mod tests {
1899    //! Ported from `test/navigation_rail_test.dart` and laid out in FlutterTest, whose glyphs
1900    //! are squares of the font size (`install_platform_fonts`).
1901
1902    use std::time::Duration;
1903    use waft_painting::ShapeBorder;
1904
1905    use waft_embedder::{FontWeight, Size};
1906    use waft_rendering::{AnyRenderBox, RenderParagraph};
1907    use waft_widgets::{
1908        AnyElement, Builder, Expanded, GlobalKey, Icon, IconData, MediaQuery, RichText, Text,
1909    };
1910
1911    use waft_painting::EdgeInsets;
1912
1913    use waft_widgets::testing::{
1914        TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget, finds_widgets,
1915        test_widgets,
1916    };
1917
1918    use super::*;
1919    use crate::colors::Colors;
1920    use crate::floating_action_button::FloatingActionButton;
1921    use crate::icons::Icons;
1922    use crate::scaffold::Scaffold;
1923    use crate::test_support::material_app;
1924    use crate::theme_data::ThemeData;
1925
1926    fn destination(
1927        icon: IconData,
1928        selected_icon: IconData,
1929        label: &str,
1930    ) -> NavigationRailDestination {
1931        NavigationRailDestination::new(Icon::new(Some(icon)), Text::new(label))
1932            .selected_icon(Icon::new(Some(selected_icon)))
1933    }
1934
1935    /// Dart's `_destinations()`.
1936    fn destinations() -> Vec<NavigationRailDestination> {
1937        vec![
1938            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
1939            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
1940            destination(Icons::star_border(), Icons::star(), "Ghi"),
1941            destination(Icons::hotel(), Icons::home(), "Jkl"),
1942        ]
1943    }
1944
1945    /// The arguments of Dart's `_pumpNavigationRail` besides the rail.
1946    struct Pump {
1947        text_scale_factor: f64,
1948        use_material3: bool,
1949        navigation_rail_theme: Option<NavigationRailThemeData>,
1950    }
1951
1952    impl Default for Pump {
1953        fn default() -> Pump {
1954            Pump {
1955                text_scale_factor: 1.0,
1956                use_material3: true,
1957                navigation_rail_theme: None,
1958            }
1959        }
1960    }
1961
1962    fn theme(app: &App, use_material3: bool) -> ThemeData {
1963        ThemeData::builder().use_material3(use_material3).build(app)
1964    }
1965
1966    /// Dart's `_pumpNavigationRail`.
1967    fn pump_navigation_rail_with(
1968        tester: &mut WidgetTester,
1969        navigation_rail: NavigationRail,
1970        pump: Pump,
1971    ) {
1972        let root = {
1973            let app = tester.cell.borrow();
1974            let mut builder = ThemeData::builder().use_material3(pump.use_material3);
1975            if let Some(navigation_rail_theme) = pump.navigation_rail_theme {
1976                builder = builder.navigation_rail_theme(navigation_rail_theme);
1977            }
1978            let theme = builder.build(&app);
1979            let rail = navigation_rail.into_widget();
1980            let text_scale_factor = pump.text_scale_factor;
1981            material_app(
1982                theme,
1983                Builder::new(move |_app, _context| {
1984                    MediaQuery::with_clamped_text_scaling(
1985                        None,
1986                        text_scale_factor,
1987                        text_scale_factor,
1988                        Scaffold::new().body(Row::new().children([
1989                            rail.clone(),
1990                            Expanded::new(Text::new("body")).into_widget(),
1991                        ])),
1992                    )
1993                })
1994                .into_widget(),
1995            )
1996        };
1997        tester.pump_widget(root);
1998    }
1999
2000    fn pump_navigation_rail(tester: &mut WidgetTester, navigation_rail: NavigationRail) {
2001        pump_navigation_rail_with(tester, navigation_rail, Pump::default());
2002    }
2003
2004    /// Dart's `_buildWidget`.
2005    fn build_widget(app: &App, child: WidgetRef, use_material3: bool, is_rtl: bool) -> WidgetRef {
2006        material_app(
2007            theme(app, use_material3),
2008            Directionality::new(
2009                if is_rtl {
2010                    TextDirection::Rtl
2011                } else {
2012                    TextDirection::Ltr
2013                },
2014                Scaffold::new().body(
2015                    Row::new().children([child, Expanded::new(Text::new("body")).into_widget()]),
2016                ),
2017            )
2018            .into_widget(),
2019        )
2020    }
2021
2022    fn pump_built_widget<K>(
2023        tester: &mut WidgetTester,
2024        child: impl IntoWidget<K>,
2025        use_material3: bool,
2026        is_rtl: bool,
2027    ) {
2028        let child = child.into_widget();
2029        let root = build_widget(&tester.cell.borrow(), child, use_material3, is_rtl);
2030        tester.pump_widget(root);
2031    }
2032
2033    fn rail_box(tester: &WidgetTester) -> AnyRenderBox {
2034        tester.render_box_of(find::by_type::<NavigationRail>().evaluate(tester)[0])
2035    }
2036
2037    fn global_top_left(tester: &WidgetTester, render: AnyRenderBox) -> Offset {
2038        render.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
2039    }
2040
2041    /// The `RichText` below `element`.
2042    fn rich_text_below(tester: &WidgetTester, element: AnyElement) -> AnyElement {
2043        tester.descendants_of_type::<RichText>(element)[0]
2044    }
2045
2046    /// Dart's `_iconRenderBox`.
2047    fn icon_render_box(tester: &WidgetTester, icon: IconData) -> AnyRenderBox {
2048        let icon = tester.element(find::by_icon(&icon).first());
2049        tester.render_box_of(rich_text_below(tester, icon))
2050    }
2051
2052    /// Dart's `_labelRenderBox`.
2053    fn label_render_box(tester: &WidgetTester, text: &str) -> AnyRenderBox {
2054        let text = find::text(text).evaluate(tester)[0];
2055        tester.render_box_of(rich_text_below(tester, text))
2056    }
2057
2058    /// Dart's `_iconStyle`.
2059    fn icon_style(tester: &WidgetTester, icon: IconData) -> TextStyle {
2060        tester.glyph_style(tester.element(find::by_icon(&icon).first()))
2061    }
2062
2063    /// Dart's `tester.renderObject<RenderParagraph>(find.text(text)).text.style!`.
2064    fn paragraph_style(tester: &WidgetTester, text: &str) -> TextStyle {
2065        let render = label_render_box(tester, text);
2066        let app = tester.cell.borrow();
2067        render
2068            .as_object()
2069            .downcast::<RenderParagraph>(&app)
2070            .expect("a Text renders a paragraph")
2071            .text(&app)
2072            .style()
2073            .cloned()
2074            .expect("the paragraph's text has a style")
2075    }
2076
2077    /// Dart's `_labelOpacity`. Only valid when labelType != all.
2078    fn label_opacity(tester: &WidgetTester, text: &str) -> f64 {
2079        let text = find::text(text).evaluate(tester)[0];
2080        let ancestors = tester.ancestors(text);
2081        let app = tester.cell.borrow();
2082        // We search for both Visibility and FadeTransition since in some
2083        // cases opacity is animated, in other it's not.
2084        if let Some(visibility) = ancestors.iter().find_map(|element| {
2085            waft_widgets::downcast_widget::<Visibility>(&**element.widget(&app))
2086        }) {
2087            return if visibility.visible { 1.0 } else { 0.0 };
2088        }
2089        // first because there's also a FadeTransition from the MaterialPageRoute, which is
2090        // up the tree
2091        let fade = ancestors
2092            .iter()
2093            .find_map(|element| {
2094                waft_widgets::downcast_widget::<FadeTransition>(&**element.widget(&app))
2095                    .map(|fade| fade.opacity.clone())
2096            })
2097            .expect("a FadeTransition above the label");
2098        fade.value(&app)
2099    }
2100
2101    /// Dart's `_opacityAboveLabel(text)` found anything.
2102    fn has_opacity_above_label(tester: &WidgetTester, text: &str) -> bool {
2103        let text = find::text(text).evaluate(tester)[0];
2104        let ancestors = tester.ancestors(text);
2105        let app = tester.cell.borrow();
2106        ancestors.iter().any(|element| {
2107            waft_widgets::downcast_widget::<waft_widgets::Opacity>(&**element.widget(&app))
2108                .is_some()
2109        })
2110    }
2111
2112    /// Dart's `_railMaterial`: the first material is for the rail, and the rest are for the
2113    /// destinations.
2114    fn rail_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
2115        let rail = find::by_type::<NavigationRail>().evaluate(tester)[0];
2116        let material = tester.descendants_of_type::<Material>(rail)[0];
2117        tester.widget(material, read)
2118    }
2119
2120    /// Dart's `expect(offset, equals(expected))` for a position Waft works out through
2121    /// valo's `f32` matrices: equal within `f32` precision.
2122    fn assert_offset(actual: Offset, expected: Offset) {
2123        let near = |a: f64, b: f64| (a - b).abs() <= 1e-4 * b.abs().max(1.0);
2124        assert!(
2125            near(actual.dx(), expected.dx()) && near(actual.dy(), expected.dy()),
2126            "{actual:?} (dx {}, dy {}) is not {expected:?} (dx {}, dy {})",
2127            actual.dx(),
2128            actual.dy(),
2129            expected.dx(),
2130            expected.dy()
2131        );
2132    }
2133
2134    /// Asserts that the icon `render` is centred in a destination `destination_width` wide
2135    /// whose 32 high indicator starts at `next_destination_y`.
2136    fn expect_icon_at(
2137        tester: &WidgetTester,
2138        render: AnyRenderBox,
2139        destination_width: f64,
2140        destination_height: f64,
2141        next_destination_y: f64,
2142    ) {
2143        let size = tester.get_size(render);
2144        assert_offset(
2145            global_top_left(tester, render),
2146            Offset::new(
2147                (destination_width - size.width()) / 2.0,
2148                next_destination_y + (destination_height - size.height()) / 2.0,
2149            ),
2150        );
2151    }
2152
2153    #[test]
2154    fn custom_selected_and_unselected_text_styles_are_honored() {
2155        test_widgets(|tester| {
2156            let selected_text_style = TextStyle::new()
2157                .font_weight(FontWeight::W300)
2158                .font_size(17.0);
2159            let unselected_text_style = TextStyle::new()
2160                .font_weight(FontWeight::W800)
2161                .font_size(11.0);
2162            pump_navigation_rail(
2163                tester,
2164                NavigationRail::new(destinations(), Some(0))
2165                    .label_type(NavigationRailLabelType::All)
2166                    .selected_label_text_style(selected_text_style.clone())
2167                    .unselected_label_text_style(unselected_text_style.clone()),
2168            );
2169
2170            let actual_selected_text_style = paragraph_style(tester, "Abc");
2171            let actual_unselected_text_style = paragraph_style(tester, "Def");
2172            assert_eq!(
2173                actual_selected_text_style.font_size,
2174                selected_text_style.font_size
2175            );
2176            assert_eq!(
2177                actual_selected_text_style.font_weight,
2178                selected_text_style.font_weight
2179            );
2180            assert_eq!(
2181                actual_unselected_text_style.font_size,
2182                actual_unselected_text_style.font_size
2183            );
2184            assert_eq!(
2185                actual_unselected_text_style.font_weight,
2186                actual_unselected_text_style.font_weight
2187            );
2188        });
2189    }
2190
2191    #[test]
2192    fn custom_selected_and_unselected_icon_themes_are_honored() {
2193        test_widgets(|tester| {
2194            let selected_icon_theme = IconThemeData::new()
2195                .size(36.0)
2196                .color(Color::new(0x00000001));
2197            let unselected_icon_theme = IconThemeData::new()
2198                .size(18.0)
2199                .color(Color::new(0x00000002));
2200            pump_navigation_rail(
2201                tester,
2202                NavigationRail::new(destinations(), Some(0))
2203                    .label_type(NavigationRailLabelType::All)
2204                    .selected_icon_theme(selected_icon_theme.clone())
2205                    .unselected_icon_theme(unselected_icon_theme.clone()),
2206            );
2207
2208            let actual_selected_icon_theme = icon_style(tester, Icons::favorite());
2209            let actual_unselected_icon_theme = icon_style(tester, Icons::bookmark_border());
2210            assert_eq!(actual_selected_icon_theme.color, selected_icon_theme.color);
2211            assert_eq!(
2212                actual_selected_icon_theme.font_size,
2213                selected_icon_theme.size
2214            );
2215            assert_eq!(
2216                actual_unselected_icon_theme.color,
2217                unselected_icon_theme.color
2218            );
2219            assert_eq!(
2220                actual_unselected_icon_theme.font_size,
2221                unselected_icon_theme.size
2222            );
2223        });
2224    }
2225
2226    #[test]
2227    fn no_selected_destination_when_selected_index_is_null() {
2228        test_widgets(|tester| {
2229            pump_navigation_rail(tester, NavigationRail::new(destinations(), None));
2230
2231            let selected = find::by_type::<Semantics>()
2232                .evaluate(tester)
2233                .into_iter()
2234                .filter(|element| {
2235                    tester.widget(*element, |semantics: &Semantics| {
2236                        semantics.properties.selected.unwrap_or(false)
2237                    })
2238                })
2239                .count();
2240            assert_eq!(selected, 0);
2241        });
2242    }
2243
2244    #[test]
2245    fn background_color_can_be_changed() {
2246        test_widgets(|tester| {
2247            pump_navigation_rail(
2248                tester,
2249                NavigationRail::new(destinations(), Some(0))
2250                    .label_type(NavigationRailLabelType::All),
2251            );
2252
2253            // default surface color in M3 colorScheme
2254            assert_eq!(
2255                rail_material(tester, |material| material.color),
2256                Some(Color::new(0xfffef7ff))
2257            );
2258
2259            pump_navigation_rail(
2260                tester,
2261                NavigationRail::new(destinations(), Some(0))
2262                    .label_type(NavigationRailLabelType::All)
2263                    .background_color(Colors::GREEN.primary()),
2264            );
2265
2266            assert_eq!(
2267                rail_material(tester, |material| material.color),
2268                Some(Colors::GREEN.primary())
2269            );
2270        });
2271    }
2272
2273    #[test]
2274    fn elevation_can_be_changed() {
2275        test_widgets(|tester| {
2276            pump_navigation_rail(
2277                tester,
2278                NavigationRail::new(destinations(), Some(0))
2279                    .label_type(NavigationRailLabelType::All),
2280            );
2281
2282            assert_eq!(rail_material(tester, |material| material.elevation), 0.0);
2283
2284            pump_navigation_rail(
2285                tester,
2286                NavigationRail::new(destinations(), Some(0))
2287                    .label_type(NavigationRailLabelType::All)
2288                    .elevation(7.0),
2289            );
2290
2291            assert_eq!(rail_material(tester, |material| material.elevation), 7.0);
2292        });
2293    }
2294
2295    #[test]
2296    fn renders_at_the_correct_default_width_label_type_none_default() {
2297        test_widgets(|tester| {
2298            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));
2299
2300            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
2301        });
2302    }
2303
2304    #[test]
2305    fn renders_at_the_correct_default_width_label_type_selected() {
2306        test_widgets(|tester| {
2307            pump_navigation_rail(
2308                tester,
2309                NavigationRail::new(destinations(), Some(0))
2310                    .label_type(NavigationRailLabelType::Selected),
2311            );
2312
2313            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
2314        });
2315    }
2316
2317    #[test]
2318    fn renders_at_the_correct_default_width_label_type_all() {
2319        test_widgets(|tester| {
2320            pump_navigation_rail(
2321                tester,
2322                NavigationRail::new(destinations(), Some(0))
2323                    .label_type(NavigationRailLabelType::All),
2324            );
2325
2326            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
2327        });
2328    }
2329
2330    /// The `MaterialApp(home: Scaffold(body: Row([NavigationRail(..), Expanded(Text('body'))])))`
2331    /// that Dart's `StatefulBuilder` cases rebuild.
2332    fn pump_rail_in_app(tester: &mut WidgetTester, rail: NavigationRail) {
2333        pump_rail_in_app_with(tester, rail, true);
2334    }
2335
2336    /// [`pump_rail_in_app`] under `ThemeData(useMaterial3: use_material3)`.
2337    fn pump_rail_in_app_with(tester: &mut WidgetTester, rail: NavigationRail, use_material3: bool) {
2338        let root = {
2339            let app = tester.cell.borrow();
2340            material_app(
2341                theme(&app, use_material3),
2342                Scaffold::new()
2343                    .body(Row::new().children([
2344                        rail.into_widget(),
2345                        Expanded::new(Text::new("body")).into_widget(),
2346                    ]))
2347                    .into_widget(),
2348            )
2349        };
2350        tester.pump_widget(root);
2351    }
2352
2353    fn render_box_of_key(tester: &WidgetTester, key: &GlobalKey) -> AnyRenderBox {
2354        tester.render_object(key).as_box().expect("a render box")
2355    }
2356
2357    #[test]
2358    fn leading_and_trailing_spacing_is_correct_with_0_2_destinations() {
2359        test_widgets(|tester| {
2360            // Padding at the top of the rail.
2361            let top_padding = 8.0;
2362            // Padding at after the leading widget.
2363            let spacer_padding = 8.0;
2364            // Width of a destination.
2365            let destination_width = 80.0;
2366            // Height of a destination indicator with icon.
2367            let destination_height = 32.0;
2368            // Space between destinations.
2369            let destination_spacing = 12.0;
2370            // Height of the leading and trailing widgets.
2371            let fab_height = 56.0;
2372
2373            let leading_widget_key = GlobalKey::new();
2374            let trailing_widget_key = GlobalKey::new();
2375            let fab = |key: &GlobalKey| {
2376                FloatingActionButton::new(Some(Listener::new(|_| {})))
2377                    .key(KeyRef::from(key.clone()))
2378                    .into_widget()
2379            };
2380            let one = || {
2381                vec![destination(
2382                    Icons::favorite_border(),
2383                    Icons::favorite(),
2384                    "Abc",
2385                )]
2386            };
2387            let two = || {
2388                vec![
2389                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
2390                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
2391                ]
2392            };
2393            let match_expect = |tester: &WidgetTester, render: AnyRenderBox, y: f64| {
2394                expect_icon_at(tester, render, destination_width, destination_height, y)
2395            };
2396            let leading_at = |tester: &WidgetTester, key: &GlobalKey| {
2397                let render = render_box_of_key(tester, key);
2398                (global_top_left(tester, render), tester.get_size(render))
2399            };
2400
2401            pump_rail_in_app(tester, NavigationRail::new(Vec::new(), None));
2402
2403            // empty destinations and leading widget
2404            pump_rail_in_app(
2405                tester,
2406                NavigationRail::new(Vec::new(), None).leading(fab(&leading_widget_key)),
2407            );
2408            tester.pump_and_settle();
2409            assert_eq!(
2410                leading_at(tester, &leading_widget_key).0,
2411                Offset::new(0.0, top_padding)
2412            );
2413
2414            // one destination and leading widget
2415            pump_rail_in_app(
2416                tester,
2417                NavigationRail::new(one(), None).leading(fab(&leading_widget_key)),
2418            );
2419            tester.pump_and_settle();
2420            let mut next_destination_y = top_padding;
2421            let (position, size) = leading_at(tester, &leading_widget_key);
2422            assert_eq!(
2423                position,
2424                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
2425            );
2426
2427            next_destination_y += fab_height + spacer_padding + destination_spacing / 2.0;
2428            match_expect(
2429                tester,
2430                icon_render_box(tester, Icons::favorite_border()),
2431                next_destination_y,
2432            );
2433
2434            // two destinations and leading widget
2435            pump_rail_in_app(
2436                tester,
2437                NavigationRail::new(two(), None).leading(fab(&leading_widget_key)),
2438            );
2439            tester.pump_and_settle();
2440            next_destination_y = top_padding;
2441            let (position, size) = leading_at(tester, &leading_widget_key);
2442            assert_eq!(
2443                position,
2444                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
2445            );
2446
2447            next_destination_y += fab_height + spacer_padding + destination_spacing / 2.0;
2448            match_expect(
2449                tester,
2450                icon_render_box(tester, Icons::favorite_border()),
2451                next_destination_y,
2452            );
2453
2454            next_destination_y += destination_height + destination_spacing;
2455            match_expect(
2456                tester,
2457                icon_render_box(tester, Icons::bookmark_border()),
2458                next_destination_y,
2459            );
2460
2461            // empty destinations and trailing widget
2462            pump_rail_in_app(
2463                tester,
2464                NavigationRail::new(Vec::new(), None).trailing(fab(&trailing_widget_key)),
2465            );
2466            tester.pump_and_settle();
2467            assert_eq!(
2468                leading_at(tester, &trailing_widget_key).0,
2469                Offset::new(0.0, top_padding)
2470            );
2471
2472            // one destination and trailing widget
2473            pump_rail_in_app(
2474                tester,
2475                NavigationRail::new(one(), None).trailing(fab(&trailing_widget_key)),
2476            );
2477            tester.pump_and_settle();
2478            next_destination_y = top_padding + destination_spacing / 2.0;
2479            match_expect(
2480                tester,
2481                icon_render_box(tester, Icons::favorite_border()),
2482                next_destination_y,
2483            );
2484
2485            next_destination_y += destination_height + destination_spacing / 2.0;
2486            let (position, size) = leading_at(tester, &trailing_widget_key);
2487            assert_eq!(
2488                position,
2489                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
2490            );
2491
2492            // two destinations and trailing widget
2493            pump_rail_in_app(
2494                tester,
2495                NavigationRail::new(two(), None).trailing(fab(&trailing_widget_key)),
2496            );
2497            tester.pump_and_settle();
2498            next_destination_y = top_padding + destination_spacing / 2.0;
2499            match_expect(
2500                tester,
2501                icon_render_box(tester, Icons::favorite_border()),
2502                next_destination_y,
2503            );
2504
2505            next_destination_y += destination_height + destination_spacing;
2506            match_expect(
2507                tester,
2508                icon_render_box(tester, Icons::bookmark_border()),
2509                next_destination_y,
2510            );
2511
2512            next_destination_y += destination_height + destination_spacing / 2.0;
2513            let (position, size) = leading_at(tester, &trailing_widget_key);
2514            assert_eq!(
2515                position,
2516                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
2517            );
2518        });
2519    }
2520
2521    fn rail_widget<R>(tester: &WidgetTester, read: impl FnOnce(&NavigationRail) -> R) -> R {
2522        tester.widget(find::by_type::<NavigationRail>().evaluate(tester)[0], read)
2523    }
2524
2525    #[test]
2526    fn change_destinations_and_selected_index() {
2527        test_widgets(|tester| {
2528            pump_rail_in_app(tester, NavigationRail::new(Vec::new(), None));
2529
2530            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 0);
2531            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);
2532
2533            let two = || {
2534                vec![
2535                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
2536                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
2537                ]
2538            };
2539            pump_rail_in_app(tester, NavigationRail::new(two(), None));
2540            tester.pump_and_settle();
2541
2542            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
2543            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);
2544
2545            pump_rail_in_app(tester, NavigationRail::new(two(), Some(0)));
2546            tester.pump_and_settle();
2547
2548            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
2549            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
2550
2551            pump_rail_in_app(
2552                tester,
2553                NavigationRail::new(
2554                    vec![destination(
2555                        Icons::favorite_border(),
2556                        Icons::favorite(),
2557                        "Abc",
2558                    )],
2559                    Some(0),
2560                ),
2561            );
2562            tester.pump_and_settle();
2563
2564            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 1);
2565            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
2566        });
2567    }
2568
2569    #[test]
2570    fn renders_wider_for_a_destination_with_a_long_label_label_type_all() {
2571        test_widgets(|tester| {
2572            pump_navigation_rail(
2573                tester,
2574                NavigationRail::new(
2575                    vec![
2576                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
2577                        destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
2578                    ],
2579                    Some(0),
2580                )
2581                .label_type(NavigationRailLabelType::All),
2582            );
2583
2584            // Total padding is 16 (8 on each side).
2585            assert_eq!(
2586                tester.get_size(rail_box(tester)).width(),
2587                tester
2588                    .get_size(label_render_box(tester, "Longer Label"))
2589                    .width()
2590                    + 16.0
2591            );
2592        });
2593    }
2594
2595    fn finds_one_icon(tester: &WidgetTester, icon: IconData) -> bool {
2596        find::by_type::<Icon>()
2597            .evaluate(tester)
2598            .into_iter()
2599            .filter(|element| {
2600                tester.widget(*element, |widget: &Icon| {
2601                    widget.icon.as_ref() == Some(&icon)
2602                })
2603            })
2604            .count()
2605            == 1
2606    }
2607
2608    #[test]
2609    fn renders_only_icons_label_type_none_default() {
2610        test_widgets(|tester| {
2611            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));
2612
2613            assert!(finds_one_icon(tester, Icons::favorite()));
2614            assert!(finds_one_icon(tester, Icons::bookmark_border()));
2615            assert!(finds_one_icon(tester, Icons::star_border()));
2616            assert!(finds_one_icon(tester, Icons::hotel()));
2617
2618            // When there are no labels, a 0 opacity label is still shown for semantics.
2619            assert_eq!(label_opacity(tester, "Abc"), 0.0);
2620            assert_eq!(label_opacity(tester, "Def"), 0.0);
2621            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
2622            assert_eq!(label_opacity(tester, "Jkl"), 0.0);
2623        });
2624    }
2625
2626    #[test]
2627    fn renders_icons_and_labels_label_type_all() {
2628        test_widgets(|tester| {
2629            pump_navigation_rail(
2630                tester,
2631                NavigationRail::new(destinations(), Some(0))
2632                    .label_type(NavigationRailLabelType::All),
2633            );
2634
2635            assert!(finds_one_icon(tester, Icons::favorite()));
2636            assert!(finds_one_icon(tester, Icons::bookmark_border()));
2637            assert!(finds_one_icon(tester, Icons::star_border()));
2638            assert!(finds_one_icon(tester, Icons::hotel()));
2639
2640            for label in ["Abc", "Def", "Ghi", "Jkl"] {
2641                expect(tester, &find::text(label), finds_one_widget());
2642                // When displaying all labels, there is no opacity.
2643                assert!(!has_opacity_above_label(tester, label));
2644            }
2645        });
2646    }
2647
2648    #[test]
2649    fn renders_icons_and_selected_label_label_type_selected() {
2650        test_widgets(|tester| {
2651            pump_navigation_rail(
2652                tester,
2653                NavigationRail::new(destinations(), Some(0))
2654                    .label_type(NavigationRailLabelType::Selected),
2655            );
2656
2657            assert!(finds_one_icon(tester, Icons::favorite()));
2658            assert!(finds_one_icon(tester, Icons::bookmark_border()));
2659            assert!(finds_one_icon(tester, Icons::star_border()));
2660            assert!(finds_one_icon(tester, Icons::hotel()));
2661
2662            // Only the selected label is visible.
2663            assert_eq!(label_opacity(tester, "Abc"), 1.0);
2664            assert_eq!(label_opacity(tester, "Def"), 0.0);
2665            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
2666            assert_eq!(label_opacity(tester, "Jkl"), 0.0);
2667        });
2668    }
2669
2670    /// The icons of [`destinations`] in order: the first selected.
2671    fn icons_in_order() -> [IconData; 4] {
2672        [
2673            Icons::favorite(),
2674            Icons::bookmark_border(),
2675            Icons::star_border(),
2676            Icons::hotel(),
2677        ]
2678    }
2679
2680    #[test]
2681    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_1_0_default() {
2682        test_widgets(|tester| {
2683            // Padding at the top of the rail.
2684            let top_padding = 8.0;
2685            // Width of a destination.
2686            let destination_width = 80.0;
2687            // Height of a destination indicator with icon.
2688            let destination_height = 32.0;
2689            // Space between destinations.
2690            let destination_padding = 12.0;
2691
2692            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));
2693
2694            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);
2695
2696            // The first destination below the rail top by some padding.
2697            let mut next_destination_y = top_padding + destination_padding / 2.0;
2698            for icon in icons_in_order() {
2699                expect_icon_at(
2700                    tester,
2701                    icon_render_box(tester, icon),
2702                    destination_width,
2703                    destination_height,
2704                    next_destination_y,
2705                );
2706                // The next destination is one height below this destination.
2707                next_destination_y += destination_height + destination_padding;
2708            }
2709        });
2710    }
2711
2712    /// Asserts each icon of [`icons_in_order`] centred `destination_width` wide in its 32 high
2713    /// indicator, the first at `first_y` and each next one `steps[i]` below the one before.
2714    fn expect_icon_column(
2715        tester: &WidgetTester,
2716        destination_width: f64,
2717        first_y: f64,
2718        steps: [f64; 3],
2719    ) {
2720        expect_icon_column_in(tester, destination_width, 32.0, first_y, steps);
2721    }
2722
2723    /// [`expect_icon_column`] in destinations `destination_height` high.
2724    fn expect_icon_column_in(
2725        tester: &WidgetTester,
2726        destination_width: f64,
2727        destination_height: f64,
2728        first_y: f64,
2729        steps: [f64; 3],
2730    ) {
2731        let mut next_destination_y = first_y;
2732        for (i, icon) in icons_in_order().into_iter().enumerate() {
2733            expect_icon_at(
2734                tester,
2735                icon_render_box(tester, icon),
2736                destination_width,
2737                destination_height,
2738                next_destination_y,
2739            );
2740            if i < 3 {
2741                next_destination_y += steps[i];
2742            }
2743        }
2744    }
2745
2746    /// Asserts the label `text` centred `destination_width` wide with its top at `y`.
2747    fn expect_label_at(tester: &WidgetTester, text: &str, destination_width: f64, y: f64) {
2748        let render = label_render_box(tester, text);
2749        let size = tester.get_size(render);
2750        assert_offset(
2751            global_top_left(tester, render),
2752            Offset::new((destination_width - size.width()) / 2.0, y),
2753        );
2754    }
2755
2756    /// The icon-only destination spacing cases at `text_scale_factor`, `min_width` wide.
2757    fn icon_only_spacing(text_scale_factor: f64, min_width: Option<f64>) {
2758        test_widgets(|tester| {
2759            // Since the rail is icon only, its destinations should not be affected by
2760            // textScaleFactor.
2761
2762            // Padding at the top of the rail.
2763            let top_padding = 8.0;
2764            // Width of a destination.
2765            let destination_width = min_width.unwrap_or(80.0);
2766            // Height of a destination indicator with icon.
2767            let destination_height = 32.0;
2768            // Space between destinations.
2769            let destination_padding = 12.0;
2770
2771            let mut rail = NavigationRail::new(destinations(), Some(0));
2772            if let Some(min_width) = min_width {
2773                rail = rail.min_width(min_width);
2774            }
2775            pump_navigation_rail_with(
2776                tester,
2777                rail,
2778                Pump {
2779                    text_scale_factor,
2780                    ..Pump::default()
2781                },
2782            );
2783
2784            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);
2785
2786            // The first destination below the rail top by some padding; each next one is
2787            // one height below the one before.
2788            let step = destination_height + destination_padding;
2789            expect_icon_column(
2790                tester,
2791                destination_width,
2792                top_padding + destination_padding / 2.0,
2793                [step; 3],
2794            );
2795        });
2796    }
2797
2798    #[test]
2799    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_3_0() {
2800        icon_only_spacing(3.0, None);
2801    }
2802
2803    #[test]
2804    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_0_75() {
2805        icon_only_spacing(0.75, None);
2806    }
2807
2808    #[test]
2809    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_1_0_default()
2810     {
2811        icon_only_spacing(1.0, Some(56.0));
2812    }
2813
2814    #[test]
2815    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_3_0()
2816    {
2817        icon_only_spacing(3.0, Some(56.0));
2818    }
2819
2820    #[test]
2821    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_0_75()
2822    {
2823        icon_only_spacing(0.75, Some(56.0));
2824    }
2825
2826    /// The labelled destination spacing cases: `label_type` at `text_scale_factor`, whose
2827    /// destinations are `destination_width` wide.
2828    fn labelled_spacing(
2829        label_type: NavigationRailLabelType,
2830        text_scale_factor: f64,
2831        destination_width: f64,
2832    ) {
2833        test_widgets(|tester| {
2834            // Padding at the top of the rail.
2835            let top_padding = 8.0;
2836            // Height of a destination indicator with icon.
2837            let destination_height = 32.0;
2838            // Space between the indicator and label.
2839            let destination_label_spacing = 4.0;
2840            // Height of the label.
2841            let label_height = 16.0 * text_scale_factor;
2842            // Height of a destination with both icon and label.
2843            let destination_height_with_label =
2844                destination_height + destination_label_spacing + label_height;
2845            // Space between destinations.
2846            let destination_spacing = 12.0;
2847
2848            pump_navigation_rail_with(
2849                tester,
2850                NavigationRail::new(destinations(), Some(0)).label_type(label_type),
2851                Pump {
2852                    text_scale_factor,
2853                    ..Pump::default()
2854                },
2855            );
2856
2857            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);
2858
2859            // The first destination topPadding below the rail top.
2860            let next_destination_y = top_padding;
2861            expect_label_at(
2862                tester,
2863                "Abc",
2864                destination_width,
2865                next_destination_y + destination_height + destination_label_spacing,
2866            );
2867
2868            // Each destination is below the one before with some spacing; with
2869            // [labelType]=selected, only the first shows its label.
2870            let labelled = destination_height_with_label + destination_spacing;
2871            let unlabelled = match label_type {
2872                NavigationRailLabelType::Selected => destination_height + destination_spacing,
2873                _ => labelled,
2874            };
2875            expect_icon_column(
2876                tester,
2877                destination_width,
2878                next_destination_y,
2879                [labelled, unlabelled, unlabelled],
2880            );
2881        });
2882    }
2883
2884    #[test]
2885    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_1_0_default() {
2886        labelled_spacing(NavigationRailLabelType::Selected, 1.0, 80.0);
2887    }
2888
2889    #[test]
2890    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_3_0() {
2891        labelled_spacing(NavigationRailLabelType::Selected, 3.0, 125.5);
2892    }
2893
2894    #[test]
2895    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_0_75() {
2896        labelled_spacing(NavigationRailLabelType::Selected, 0.75, 80.0);
2897    }
2898
2899    #[test]
2900    fn destination_spacing_is_correct_label_type_all_text_scale_factor_1_0_default() {
2901        labelled_spacing(NavigationRailLabelType::All, 1.0, 80.0);
2902    }
2903
2904    #[test]
2905    fn destination_spacing_is_correct_label_type_all_text_scale_factor_3_0() {
2906        labelled_spacing(NavigationRailLabelType::All, 3.0, 125.5);
2907    }
2908
2909    #[test]
2910    fn destination_spacing_is_correct_label_type_all_text_scale_factor_0_75() {
2911        labelled_spacing(NavigationRailLabelType::All, 0.75, 80.0);
2912    }
2913
2914    /// The group alignment cases: the destinations `offset` below where they start at the top.
2915    fn group_alignment(group_alignment: Option<f64>, offset: f64) {
2916        test_widgets(|tester| {
2917            // Padding at the top of the rail.
2918            let top_padding = 8.0;
2919            // Width of a destination.
2920            let destination_width = 80.0;
2921            // Height of a destination indicator with icon.
2922            let destination_height = 32.0;
2923            // Space between destinations.
2924            let destination_padding = 12.0;
2925
2926            let mut rail = NavigationRail::new(destinations(), Some(0));
2927            if let Some(group_alignment) = group_alignment {
2928                rail = rail.group_alignment(group_alignment);
2929            }
2930            pump_navigation_rail(tester, rail);
2931
2932            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);
2933
2934            // The first destination below the rail top by some padding with an offset for the
2935            // alignment.
2936            let step = destination_height + destination_padding;
2937            expect_icon_column(
2938                tester,
2939                destination_width,
2940                top_padding + destination_padding / 2.0 + offset,
2941                [step; 3],
2942            );
2943        });
2944    }
2945
2946    #[test]
2947    fn group_alignment_works_group_alignment_minus_1_0_default() {
2948        group_alignment(None, 0.0);
2949    }
2950
2951    #[test]
2952    fn group_alignment_works_group_alignment_0_0() {
2953        group_alignment(Some(0.0), 208.0);
2954    }
2955
2956    #[test]
2957    fn group_alignment_works_group_alignment_1_0() {
2958        group_alignment(Some(1.0), 416.0);
2959    }
2960
2961    fn fab() -> WidgetRef {
2962        FloatingActionButton::new(Some(Listener::new(|_| {}))).into_widget()
2963    }
2964
2965    #[test]
2966    fn leading_and_trailing_appear_in_the_correct_places() {
2967        test_widgets(|tester| {
2968            pump_navigation_rail(
2969                tester,
2970                NavigationRail::new(destinations(), Some(0))
2971                    .leading(fab())
2972                    .trailing(fab()),
2973            );
2974
2975            let fabs = find::by_type::<FloatingActionButton>().evaluate(tester);
2976            let leading = tester.render_box_of(fabs[0]);
2977            let trailing = tester.render_box_of(fabs[1]);
2978            assert_eq!(
2979                global_top_left(tester, leading),
2980                Offset::new((80.0 - tester.get_size(leading).width()) / 2.0, 8.0)
2981            );
2982            assert_eq!(
2983                global_top_left(tester, trailing),
2984                Offset::new((80.0 - tester.get_size(trailing).width()) / 2.0, 248.0)
2985            );
2986        });
2987    }
2988
2989    /// What Dart's `stateSetter` cases pump: `rail` in the app, then the frame
2990    /// `tester.pump()` runs.
2991    fn set_rail(tester: &mut WidgetTester, rail: NavigationRail) {
2992        pump_rail_in_app(tester, rail);
2993    }
2994
2995    #[test]
2996    fn extended_rail_animates_the_width_and_labels_appear_text_direction_ltr() {
2997        test_widgets(|tester| {
2998            // Padding at the top of the rail.
2999            let top_padding = 8.0;
3000            // Width of a destination.
3001            let destination_width = 80.0;
3002            // Height of a destination indicator with icon.
3003            let destination_height = 32.0;
3004            // Space between destinations.
3005            let destination_padding = 12.0;
3006
3007            pump_rail_in_app(tester, NavigationRail::new(destinations(), Some(0)));
3008
3009            let rail = rail_box(tester);
3010            assert_eq!(tester.get_size(rail).width(), destination_width);
3011
3012            set_rail(
3013                tester,
3014                NavigationRail::new(destinations(), Some(0)).extended(true),
3015            );
3016            tester.pump_by(Duration::from_millis(100));
3017            assert_eq!(tester.get_size(rail).width(), 168.0);
3018
3019            tester.pump_and_settle();
3020            assert_eq!(tester.get_size(rail).width(), 256.0);
3021
3022            // The first destination below the rail top by some padding.
3023            let mut next_destination_y = top_padding + destination_padding / 2.0;
3024            for (icon, label) in icons_in_order()
3025                .into_iter()
3026                .zip(["Abc", "Def", "Ghi", "Jkl"])
3027            {
3028                expect_icon_at(
3029                    tester,
3030                    icon_render_box(tester, icon),
3031                    destination_width,
3032                    destination_height,
3033                    next_destination_y,
3034                );
3035                let label = label_render_box(tester, label);
3036                assert_offset(
3037                    global_top_left(tester, label),
3038                    Offset::new(
3039                        destination_width,
3040                        next_destination_y
3041                            + (destination_height - tester.get_size(label).height()) / 2.0,
3042                    ),
3043                );
3044                // The next destination is one height below this destination.
3045                next_destination_y += destination_height + destination_padding;
3046            }
3047        });
3048    }
3049
3050    /// The `Directionality(rtl, Scaffold(body: Row(textDirection: rtl, [rail, body])))` of the
3051    /// RTL extended case.
3052    fn pump_rtl_rail(tester: &mut WidgetTester, rail: NavigationRail) {
3053        pump_rtl_rail_with(tester, rail, true);
3054    }
3055
3056    /// [`pump_rtl_rail`] under `ThemeData(useMaterial3: use_material3)`.
3057    fn pump_rtl_rail_with(tester: &mut WidgetTester, rail: NavigationRail, use_material3: bool) {
3058        let root = {
3059            let app = tester.cell.borrow();
3060            material_app(
3061                theme(&app, use_material3),
3062                Directionality::new(
3063                    TextDirection::Rtl,
3064                    Scaffold::new().body(Row::new().text_direction(TextDirection::Rtl).children([
3065                        rail.into_widget(),
3066                        Expanded::new(Text::new("body")).into_widget(),
3067                    ])),
3068                )
3069                .into_widget(),
3070            )
3071        };
3072        tester.pump_widget(root);
3073    }
3074
3075    #[test]
3076    fn extended_rail_animates_the_width_and_labels_appear_text_direction_rtl() {
3077        test_widgets(|tester| {
3078            // Padding at the top of the rail.
3079            let top_padding = 8.0;
3080            // Width of a destination.
3081            let destination_width = 80.0;
3082            // Height of a destination indicator with icon.
3083            let destination_height = 32.0;
3084            // Space between destinations.
3085            let destination_padding = 12.0;
3086
3087            pump_rtl_rail(tester, NavigationRail::new(destinations(), Some(0)));
3088
3089            let rail = rail_box(tester);
3090            assert_eq!(tester.get_size(rail).width(), destination_width);
3091            assert_eq!(global_top_left(tester, rail), Offset::new(720.0, 0.0));
3092
3093            pump_rtl_rail(
3094                tester,
3095                NavigationRail::new(destinations(), Some(0)).extended(true),
3096            );
3097            tester.pump_by(Duration::from_millis(100));
3098            assert_eq!(tester.get_size(rail).width(), 168.0);
3099            assert_eq!(global_top_left(tester, rail), Offset::new(632.0, 0.0));
3100
3101            tester.pump_and_settle();
3102            assert_eq!(tester.get_size(rail).width(), 256.0);
3103            assert_eq!(global_top_left(tester, rail), Offset::new(544.0, 0.0));
3104
3105            // The first destination below the rail top by some padding.
3106            let mut next_destination_y = top_padding + destination_padding / 2.0;
3107            for (icon, label) in icons_in_order()
3108                .into_iter()
3109                .zip(["Abc", "Def", "Ghi", "Jkl"])
3110            {
3111                let icon = icon_render_box(tester, icon);
3112                let icon_size = tester.get_size(icon);
3113                assert_offset(
3114                    global_top_left(tester, icon),
3115                    Offset::new(
3116                        800.0 - (destination_width + icon_size.width()) / 2.0,
3117                        next_destination_y + (destination_height - icon_size.height()) / 2.0,
3118                    ),
3119                );
3120                let label = label_render_box(tester, label);
3121                let label_size = tester.get_size(label);
3122                assert_offset(
3123                    global_top_left(tester, label),
3124                    Offset::new(
3125                        800.0 - destination_width - label_size.width(),
3126                        next_destination_y + (destination_height - label_size.height()) / 2.0,
3127                    ),
3128                );
3129                // The next destination is one height below this destination.
3130                next_destination_y += destination_height + destination_padding;
3131            }
3132        });
3133    }
3134
3135    fn abc_and_longer_label() -> Vec<NavigationRailDestination> {
3136        vec![
3137            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
3138            destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
3139        ]
3140    }
3141
3142    #[test]
3143    fn extended_rail_gets_wider_with_longer_labels_are_larger_text_scale() {
3144        test_widgets(|tester| {
3145            let pump = |tester: &mut WidgetTester, extended: bool| {
3146                let root = {
3147                    let app = tester.cell.borrow();
3148                    material_app(
3149                        ThemeData::new(&app),
3150                        Scaffold::new()
3151                            .body(
3152                                Row::new().children([
3153                                    MediaQuery::with_clamped_text_scaling(
3154                                        None,
3155                                        3.0,
3156                                        3.0,
3157                                        NavigationRail::new(abc_and_longer_label(), Some(0))
3158                                            .extended(extended),
3159                                    ),
3160                                    Expanded::new(Text::new("body")).into_widget(),
3161                                ]),
3162                            )
3163                            .into_widget(),
3164                    )
3165                };
3166                tester.pump_widget(root);
3167            };
3168            pump(tester, false);
3169
3170            let rail = rail_box(tester);
3171            assert_eq!(tester.get_size(rail).width(), 80.0);
3172
3173            pump(tester, true);
3174            tester.pump_by(Duration::from_millis(100));
3175            assert_eq!(tester.get_size(rail).width(), 303.0);
3176
3177            tester.pump_and_settle();
3178            assert_eq!(tester.get_size(rail).width(), 526.0);
3179        });
3180    }
3181
3182    #[test]
3183    fn extended_rail_final_width_can_be_changed() {
3184        test_widgets(|tester| {
3185            pump_rail_in_app(
3186                tester,
3187                NavigationRail::new(destinations(), Some(0)).min_extended_width(300.0),
3188            );
3189
3190            let rail = rail_box(tester);
3191            assert_eq!(tester.get_size(rail).width(), 80.0);
3192
3193            set_rail(
3194                tester,
3195                NavigationRail::new(destinations(), Some(0))
3196                    .min_extended_width(300.0)
3197                    .extended(true),
3198            );
3199            tester.pump_and_settle();
3200            assert_eq!(tester.get_size(rail).width(), 300.0);
3201        });
3202    }
3203
3204    /// Regression test for https://github.com/flutter/flutter/issues/65657
3205    #[test]
3206    fn extended_rail_transition_does_not_jump_from_the_beginning() {
3207        test_widgets(|tester| {
3208            pump_rail_in_app(tester, NavigationRail::new(abc_and_longer_label(), Some(0)));
3209
3210            // Before starting the animation, the rail has a width of 80.
3211            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
3212
3213            set_rail(
3214                tester,
3215                NavigationRail::new(abc_and_longer_label(), Some(0)).extended(true),
3216            );
3217            // Create very close to 0, but non-zero, animation value.
3218            tester.pump_by(Duration::from_millis(1));
3219            let width = tester.get_size(rail_box(tester)).width();
3220            // Expect that it has started to extend.
3221            assert!(width > 80.0, "{width}");
3222            // Expect that it has only extended by a small amount, or that the first
3223            // frame does not jump. This helps verify that it is a smooth animation.
3224            assert!((width - 80.0).abs() <= 1.0, "{width}");
3225        });
3226    }
3227
3228    #[test]
3229    fn extended_rail_animation_can_be_consumed() {
3230        test_widgets(|tester| {
3231            let animation: Rc<std::cell::Cell<Option<AnyAnimation<f64>>>> = Rc::default();
3232            let rail = |extended: bool| {
3233                let animation = Rc::clone(&animation);
3234                NavigationRail::new(destinations(), Some(0))
3235                    .leading(Builder::new(move |app, context| {
3236                        animation.set(Some(NavigationRail::extended_animation(app, context)));
3237                        fab()
3238                    }))
3239                    .extended(extended)
3240            };
3241            pump_rail_in_app(tester, rail(false));
3242
3243            let read = |tester: &WidgetTester| {
3244                animation
3245                    .get()
3246                    .expect("the leading widget was built")
3247                    .status(&tester.cell.borrow())
3248            };
3249            assert!(read(tester).is_dismissed());
3250
3251            set_rail(tester, rail(true));
3252            tester.pump_and_settle();
3253
3254            assert!(read(tester).is_completed());
3255        });
3256    }
3257
3258    fn center_of_element(tester: &WidgetTester, element: AnyElement) -> Offset {
3259        tester.get_rect(element).center()
3260    }
3261
3262    fn center_of_text(tester: &WidgetTester, text: &str) -> Offset {
3263        center_of_element(tester, find::text(text).evaluate(tester)[0])
3264    }
3265
3266    fn center_of_icon(tester: &WidgetTester, icon: IconData) -> Offset {
3267        center_of_element(tester, tester.element(find::by_icon(&icon).first()))
3268    }
3269
3270    #[test]
3271    fn on_destination_selected_is_called() {
3272        test_widgets(|tester| {
3273            let selected_index = Rc::new(std::cell::Cell::new(None));
3274            let seen = Rc::clone(&selected_index);
3275            pump_navigation_rail(
3276                tester,
3277                NavigationRail::new(destinations(), Some(0))
3278                    .on_destination_selected(move |_app, index| seen.set(Some(index)))
3279                    .label_type(NavigationRailLabelType::All),
3280            );
3281
3282            tester.tap_at(center_of_text(tester, "Def"), 1);
3283            assert_eq!(selected_index.get(), Some(1));
3284
3285            tester.tap_at(center_of_text(tester, "Ghi"), 2);
3286            assert_eq!(selected_index.get(), Some(2));
3287
3288            // Wait for any pending shader compilation.
3289            tester.pump_and_settle();
3290        });
3291    }
3292
3293    #[test]
3294    fn on_destination_selected_is_not_called_if_null() {
3295        test_widgets(|tester| {
3296            let selected_index = 0;
3297            pump_navigation_rail(
3298                tester,
3299                NavigationRail::new(destinations(), Some(selected_index))
3300                    .label_type(NavigationRailLabelType::All),
3301            );
3302
3303            tester.tap_at(center_of_text(tester, "Def"), 1);
3304            assert_eq!(selected_index, 0);
3305
3306            // Wait for any pending shader compilation.
3307            tester.pump_and_settle();
3308        });
3309    }
3310
3311    #[test]
3312    fn changing_destinations_animate_when_label_type_selected() {
3313        test_widgets(|tester| {
3314            let selected_index = Rc::new(std::cell::Cell::new(0_usize));
3315            let root = {
3316                let app = tester.cell.borrow();
3317                let selected_index = Rc::clone(&selected_index);
3318                material_app(
3319                    ThemeData::new(&app),
3320                    waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
3321                        let selected = Rc::clone(&selected_index);
3322                        Scaffold::new()
3323                            .body(
3324                                Row::new().children([
3325                                    NavigationRail::new(destinations(), Some(selected_index.get()))
3326                                        .label_type(NavigationRailLabelType::Selected)
3327                                        .on_destination_selected(move |app, index| {
3328                                            let selected = Rc::clone(&selected);
3329                                            set_state(app, &mut |_app| selected.set(index));
3330                                        })
3331                                        .into_widget(),
3332                                    Expanded::new(Text::new("body")).into_widget(),
3333                                ]),
3334                            )
3335                            .into_widget()
3336                    })
3337                    .into_widget(),
3338                )
3339            };
3340            tester.pump_widget(root);
3341
3342            // Tap the second destination.
3343            tester.tap_at(center_of_icon(tester, Icons::bookmark_border()), 1);
3344            assert_eq!(selected_index.get(), 1);
3345
3346            // The second destination animates in.
3347            assert_eq!(label_opacity(tester, "Def"), 0.0);
3348            tester.pump();
3349            tester.pump_by(Duration::from_millis(100));
3350            assert_eq!(label_opacity(tester, "Def"), 0.5);
3351            tester.pump_and_settle();
3352            assert_eq!(label_opacity(tester, "Def"), 1.0);
3353
3354            // Tap the third destination.
3355            tester.tap_at(center_of_icon(tester, Icons::star_border()), 2);
3356            assert_eq!(selected_index.get(), 2);
3357
3358            // The second destination animates out quickly and the third destination
3359            // animates in.
3360            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
3361            tester.pump();
3362            tester.pump_by(Duration::from_millis(25));
3363            assert_eq!(label_opacity(tester, "Def"), 0.5);
3364            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
3365            tester.pump();
3366            tester.pump_by(Duration::from_millis(25));
3367            assert_eq!(label_opacity(tester, "Def"), 0.0);
3368            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
3369            tester.pump();
3370            tester.pump_by(Duration::from_millis(50));
3371            assert_eq!(label_opacity(tester, "Ghi"), 0.5);
3372            tester.pump_and_settle();
3373            assert_eq!(label_opacity(tester, "Ghi"), 1.0);
3374        });
3375    }
3376
3377    fn selected_rail(selected_index: Option<usize>) -> NavigationRail {
3378        NavigationRail::new(destinations(), selected_index)
3379            .label_type(NavigationRailLabelType::Selected)
3380    }
3381
3382    #[test]
3383    fn changing_destinations_animate_for_selected_index_null() {
3384        test_widgets(|tester| {
3385            pump_rail_in_app(tester, selected_rail(Some(0)));
3386
3387            // Unset the selected index.
3388            set_rail(tester, selected_rail(None));
3389
3390            // The first destination animates out.
3391            assert_eq!(label_opacity(tester, "Abc"), 1.0);
3392            tester.pump_by(Duration::from_millis(25));
3393            assert_eq!(label_opacity(tester, "Abc"), 0.5);
3394            tester.pump_and_settle();
3395            assert_eq!(label_opacity(tester, "Abc"), 0.0);
3396
3397            // Set the selected index to the first destination.
3398            set_rail(tester, selected_rail(Some(0)));
3399
3400            // The first destination animates in.
3401            assert_eq!(label_opacity(tester, "Abc"), 0.0);
3402            tester.pump_by(Duration::from_millis(100));
3403            assert_eq!(label_opacity(tester, "Abc"), 0.5);
3404            tester.pump_and_settle();
3405            assert_eq!(label_opacity(tester, "Abc"), 1.0);
3406        });
3407    }
3408
3409    /// Dart's `StatefulBuilder` over a rail of the `selected_index` it keeps, with the
3410    /// `stateSetter` the case calls without pumping a frame.
3411    struct StatefulRail {
3412        selected_index: Rc<std::cell::Cell<Option<usize>>>,
3413        set_state: Rc<std::cell::RefCell<Option<waft_widgets::StateSetter>>>,
3414    }
3415
3416    impl StatefulRail {
3417        fn pump(
3418            tester: &mut WidgetTester,
3419            selected_index: Option<usize>,
3420            make: fn(Option<usize>) -> NavigationRail,
3421        ) -> StatefulRail {
3422            let rail = StatefulRail {
3423                selected_index: Rc::new(std::cell::Cell::new(selected_index)),
3424                set_state: Rc::default(),
3425            };
3426            let root = {
3427                let app = tester.cell.borrow();
3428                let selected_index = Rc::clone(&rail.selected_index);
3429                let state_setter = Rc::clone(&rail.set_state);
3430                material_app(
3431                    ThemeData::new(&app),
3432                    waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
3433                        *state_setter.borrow_mut() = Some(set_state);
3434                        Scaffold::new()
3435                            .body(Row::new().children([
3436                                make(selected_index.get()).into_widget(),
3437                                Expanded::new(Text::new("body")).into_widget(),
3438                            ]))
3439                            .into_widget()
3440                    })
3441                    .into_widget(),
3442                )
3443            };
3444            tester.pump_widget(root);
3445            rail
3446        }
3447
3448        /// Dart's `stateSetter(() { selectedIndex = selected_index; })`.
3449        fn set_selected_index(&self, tester: &WidgetTester, selected_index: Option<usize>) {
3450            let set_state = self
3451                .set_state
3452                .borrow()
3453                .clone()
3454                .expect("the builder was built");
3455            let selected = Rc::clone(&self.selected_index);
3456            set_state(&mut tester.cell.borrow_mut(), &mut |_app| {
3457                selected.set(selected_index)
3458            });
3459        }
3460    }
3461
3462    #[test]
3463    fn changing_destinations_animate_when_selected_index_null_during_transition() {
3464        test_widgets(|tester| {
3465            let rail = StatefulRail::pump(tester, Some(0), selected_rail);
3466
3467            rail.set_selected_index(tester, Some(1));
3468
3469            tester.pump();
3470            tester.pump_by(Duration::from_millis(175));
3471
3472            // Interrupt while animating from index 0 to 1.
3473            rail.set_selected_index(tester, None);
3474
3475            assert_eq!(label_opacity(tester, "Abc"), 0.0);
3476            assert_eq!(label_opacity(tester, "Def"), 1.0);
3477
3478            tester.pump();
3479            // Create very close to 0, but non-zero, animation value.
3480            tester.pump_by(Duration::from_millis(1));
3481            // Ensure the opacity is animated back towards 0.
3482            let def = label_opacity(tester, "Def");
3483            assert!(def < 0.5, "{def}");
3484            assert!((def - 0.5).abs() <= 0.03, "{def}");
3485
3486            tester.pump_and_settle();
3487            assert_eq!(label_opacity(tester, "Abc"), 0.0);
3488            assert_eq!(label_opacity(tester, "Def"), 0.0);
3489        });
3490    }
3491
3492    fn abc_def_ghi_with_padding() -> Vec<NavigationRailDestination> {
3493        vec![
3494            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
3495            destination(Icons::bookmark_border(), Icons::bookmark(), "Def")
3496                .padding(EdgeInsetsGeometry::symmetric(30.0, 0.0)),
3497            destination(Icons::star_border(), Icons::star(), "Ghi")
3498                .padding(EdgeInsetsGeometry::symmetric(0.0, 10.0)),
3499        ]
3500    }
3501
3502    /// Dart's `tester.widget<Padding>(find.descendant(of: find.widgetWithText(
3503    /// _IndicatorInkWell, text), matching: find.widgetWithText(Padding, text))).padding`: the
3504    /// one `Padding` between the destination's ink well and its label.
3505    fn destination_padding(tester: &WidgetTester, text: &str) -> EdgeInsetsGeometry {
3506        let text = find::text(text).evaluate(tester)[0];
3507        let ancestors = tester.ancestors(text);
3508        let app = tester.cell.borrow();
3509        let below_ink_well: Vec<&AnyElement> = ancestors
3510            .iter()
3511            .take_while(|element| {
3512                waft_widgets::downcast_widget::<InkResponse>(&**element.widget(&app)).is_none()
3513            })
3514            .collect();
3515        assert!(
3516            below_ink_well.len() < ancestors.len(),
3517            "the label is inside an ink well"
3518        );
3519        let paddings: Vec<EdgeInsetsGeometry> = below_ink_well
3520            .into_iter()
3521            .filter_map(|element| {
3522                waft_widgets::downcast_widget::<Padding>(&**element.widget(&app))
3523                    .map(|padding| padding.padding)
3524            })
3525            .collect();
3526        assert_eq!(
3527            paddings.len(),
3528            1,
3529            "one Padding between the ink well and the label"
3530        );
3531        paddings[0]
3532    }
3533
3534    fn padding_properly_applied(
3535        label_type: NavigationRailLabelType,
3536        default_padding: EdgeInsetsGeometry,
3537    ) {
3538        test_widgets(|tester| {
3539            let second_item_padding = EdgeInsetsGeometry::symmetric(30.0, 0.0);
3540            let third_item_padding = EdgeInsetsGeometry::symmetric(0.0, 10.0);
3541
3542            pump_navigation_rail(
3543                tester,
3544                NavigationRail::new(abc_def_ghi_with_padding(), Some(0)).label_type(label_type),
3545            );
3546
3547            assert_eq!(destination_padding(tester, "Abc"), default_padding);
3548            assert_eq!(destination_padding(tester, "Def"), second_item_padding);
3549            assert_eq!(destination_padding(tester, "Ghi"), third_item_padding);
3550        });
3551    }
3552
3553    #[test]
3554    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_all() {
3555        padding_properly_applied(
3556            NavigationRailLabelType::All,
3557            EdgeInsetsGeometry::symmetric(0.0, 8.0),
3558        );
3559    }
3560
3561    #[test]
3562    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_selected() {
3563        padding_properly_applied(
3564            NavigationRailLabelType::Selected,
3565            EdgeInsetsGeometry::symmetric(0.0, 8.0),
3566        );
3567    }
3568
3569    #[test]
3570    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_none() {
3571        padding_properly_applied(NavigationRailLabelType::None, EdgeInsetsGeometry::ZERO);
3572    }
3573
3574    fn abc_def_ghi() -> Vec<NavigationRailDestination> {
3575        vec![
3576            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
3577            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
3578            destination(Icons::star_border(), Icons::star(), "Ghi"),
3579        ]
3580    }
3581
3582    #[test]
3583    fn navigation_rail_destination_adds_indicator_by_default_when_theme_data_use_material3_is_true()
3584    {
3585        test_widgets(|tester| {
3586            pump_navigation_rail(
3587                tester,
3588                NavigationRail::new(abc_def_ghi(), Some(0))
3589                    .label_type(NavigationRailLabelType::Selected),
3590            );
3591
3592            expect(
3593                tester,
3594                &find::by_type::<NavigationIndicator>(),
3595                finds_widgets(),
3596            );
3597        });
3598    }
3599
3600    #[test]
3601    fn navigation_rail_destination_adds_indicator_when_use_indicator_is_true() {
3602        test_widgets(|tester| {
3603            pump_navigation_rail(
3604                tester,
3605                NavigationRail::new(abc_def_ghi(), Some(0))
3606                    .use_indicator(true)
3607                    .label_type(NavigationRailLabelType::Selected),
3608            );
3609
3610            expect(
3611                tester,
3612                &find::by_type::<NavigationIndicator>(),
3613                finds_widgets(),
3614            );
3615        });
3616    }
3617
3618    #[test]
3619    fn navigation_rail_destination_does_not_add_indicator_when_use_indicator_is_false() {
3620        test_widgets(|tester| {
3621            pump_navigation_rail(
3622                tester,
3623                NavigationRail::new(abc_def_ghi(), Some(0))
3624                    .use_indicator(false)
3625                    .label_type(NavigationRailLabelType::Selected),
3626            );
3627
3628            expect(
3629                tester,
3630                &find::by_type::<NavigationIndicator>(),
3631                finds_nothing(),
3632            );
3633        });
3634    }
3635
3636    fn adds_an_oval_indicator(label_type: NavigationRailLabelType) {
3637        test_widgets(|tester| {
3638            pump_navigation_rail(
3639                tester,
3640                NavigationRail::new(abc_def_ghi(), Some(0))
3641                    .use_indicator(true)
3642                    .label_type(label_type),
3643            );
3644
3645            let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[0];
3646            let (width, height) = tester.widget(indicator, |indicator: &NavigationIndicator| {
3647                (indicator.width, indicator.height)
3648            });
3649            assert_eq!(width, 56.0);
3650            assert_eq!(height, 32.0);
3651        });
3652    }
3653
3654    #[test]
3655    fn navigation_rail_destination_adds_an_oval_indicator_when_no_labels_are_present() {
3656        adds_an_oval_indicator(NavigationRailLabelType::None);
3657    }
3658
3659    #[test]
3660    fn navigation_rail_destination_adds_an_oval_indicator_when_selected_labels_are_present() {
3661        adds_an_oval_indicator(NavigationRailLabelType::Selected);
3662    }
3663
3664    #[test]
3665    fn navigation_rail_destination_adds_an_oval_indicator_when_all_labels_are_present() {
3666        adds_an_oval_indicator(NavigationRailLabelType::All);
3667    }
3668
3669    /// The destinations of "has center aligned indicator": the first icon in a `Stack` with a
3670    /// small text over its corner.
3671    fn umbrella_destinations() -> Vec<NavigationRailDestination> {
3672        vec![
3673            NavigationRailDestination::new(
3674                Stack::new().children([
3675                    Icon::new(Some(Icons::umbrella())).into_widget(),
3676                    waft_widgets::Positioned::new(
3677                        Text::new("Text").style(
3678                            TextStyle::new()
3679                                .font_size(10.0)
3680                                .color(Colors::RED.primary()),
3681                        ),
3682                    )
3683                    .top(0.0)
3684                    .right(0.0)
3685                    .into_widget(),
3686                ]),
3687                Text::new("Abc"),
3688            ),
3689            NavigationRailDestination::new(Icon::new(Some(Icons::umbrella())), Text::new("Def")),
3690            NavigationRailDestination::new(
3691                Icon::new(Some(Icons::bookmark_border())),
3692                Text::new("Ghi"),
3693            ),
3694        ]
3695    }
3696
3697    fn has_center_aligned_indicator(use_material3: bool, dx: f64) {
3698        test_widgets(|tester| {
3699            // This is a regression test for
3700            // https://github.com/flutter/flutter/issues/97753
3701            pump_navigation_rail_with(
3702                tester,
3703                NavigationRail::new(umbrella_destinations(), Some(0))
3704                    .label_type(NavigationRailLabelType::None),
3705                Pump {
3706                    use_material3,
3707                    ..Pump::default()
3708                },
3709            );
3710            let icons = find::by_type::<Icon>().evaluate(tester);
3711            // Indicator with Stack widget
3712            let first_indicator = tester.render_box_of(icons[0]);
3713            assert_eq!(global_top_left(tester, first_indicator).dx(), dx);
3714            // Indicator without Stack widget
3715            let last_indicator = tester.render_box_of(*icons.last().expect("icons"));
3716            assert_eq!(global_top_left(tester, last_indicator).dx(), dx);
3717        });
3718    }
3719
3720    #[test]
3721    fn navigation_rail_destination_has_center_aligned_indicator_label_type_none() {
3722        has_center_aligned_indicator(true, 28.0);
3723    }
3724
3725    fn two_destinations() -> Vec<NavigationRailDestination> {
3726        vec![
3727            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
3728            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
3729        ]
3730    }
3731
3732    fn respects_the_notch(use_material3: bool, default_rail_width: f64) {
3733        test_widgets(|tester| {
3734            let safe_area_padding = 40.0;
3735            let with_padding = |padding: EdgeInsets| {
3736                MediaQuery::new(
3737                    waft_widgets::MediaQueryData::new().padding(padding),
3738                    NavigationRail::new(two_destinations(), Some(0)),
3739                )
3740                .into_widget()
3741            };
3742
3743            pump_built_widget(
3744                tester,
3745                NavigationRail::new(two_destinations(), Some(0)),
3746                use_material3,
3747                false,
3748            );
3749            let default_width = tester.get_size(rail_box(tester)).width();
3750            assert_eq!(default_width, default_rail_width);
3751
3752            pump_built_widget(
3753                tester,
3754                with_padding(EdgeInsets::only(safe_area_padding, 0.0, 0.0, 0.0)),
3755                use_material3,
3756                false,
3757            );
3758            let updated_width = tester.get_size(rail_box(tester)).width();
3759            assert_eq!(updated_width, default_width + safe_area_padding);
3760
3761            // test width when text direction is RTL.
3762            pump_built_widget(
3763                tester,
3764                with_padding(EdgeInsets::only(0.0, 0.0, safe_area_padding, 0.0)),
3765                use_material3,
3766                true,
3767            );
3768            let updated_width_rtl = tester.get_size(rail_box(tester)).width();
3769            assert_eq!(updated_width_rtl, default_width + safe_area_padding);
3770        });
3771    }
3772
3773    #[test]
3774    fn navigation_rail_respects_the_notch_system_navigation_bar_in_landscape_mode() {
3775        respects_the_notch(true, 80.0);
3776    }
3777
3778    /// What the ink features of the rail's materials draw, in tree order: Dart's `paints` on
3779    /// the first `_RenderInkFeatures`, the scaffold's, whose paint reaches theirs.
3780    fn rail_ink_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
3781        let rail = rail_box(tester).as_object();
3782        let features = tester.all::<crate::material::RenderInkFeatures>();
3783        let mut ops = Vec::new();
3784        for render in features {
3785            let under_rail = {
3786                let app = tester.cell.borrow();
3787                std::iter::successors(
3788                    Some(waft_rendering::RenderBox::as_object(render)),
3789                    |object| object.parent(&app),
3790                )
3791                .any(|object| object == rail)
3792            };
3793            if under_rail {
3794                let mut canvas = waft_embedder::Canvas::new();
3795                render.paint_ink_features(&mut tester.cell.borrow_mut(), &mut canvas, Offset::ZERO);
3796                ops.extend(canvas.build().ops().iter().cloned());
3797            }
3798        }
3799        ops
3800    }
3801
3802    /// Dart's `paints..clipPath(pathMatcher: isPathThat(includes: [the edge midpoints of
3803    /// indicator_rect], excludes: [those of indicator_rect.inflate(10)]))..rect(rect:
3804    /// indicator_rect, color: Color(0x0a6750a4))..rrect(rrect: rrect, color:
3805    /// Color(0xffe8def8))`: the hover highlight clipped to the indicator, then the selected
3806    /// destination's indicator.
3807    fn paints_indicator_highlight(
3808        ops: &[waft_embedder::valo::Op],
3809        indicator_rect: Rect,
3810        rrect: waft_embedder::RRect,
3811    ) -> bool {
3812        use waft_embedder::valo::{self, Op};
3813        let midpoints = |rect: Rect| {
3814            [
3815                rect.center_left(),
3816                rect.top_center(),
3817                rect.center_right(),
3818                rect.bottom_center(),
3819            ]
3820        };
3821        let contains = |path: &valo::Path, point: Offset| {
3822            path.contains(
3823                valo::Point::new(point.dx() as f32, point.dy() as f32),
3824                valo::FillRule::NonZero,
3825            )
3826        };
3827        let excluded_rect = indicator_rect.inflate(10.0);
3828        let Some(clip_at) = ops.iter().position(|op| match op {
3829            Op::ClipPath { path, .. } => {
3830                midpoints(indicator_rect)
3831                    .iter()
3832                    .all(|point| contains(path, *point))
3833                    && midpoints(excluded_rect)
3834                        .iter()
3835                        .all(|point| !contains(path, *point))
3836            }
3837            _ => false,
3838        }) else {
3839            return false;
3840        };
3841        let near = |a: f32, b: f64| (f64::from(a) - b).abs() < 1e-3;
3842        let highlight_color: valo::Color = Color::new(0x0a6750a4).into();
3843        let Some(rect_at) = ops[clip_at..].iter().position(|op| match op {
3844            Op::DrawRect { rect, paint, .. } => {
3845                paint.color == highlight_color
3846                    && near(rect.x, indicator_rect.left)
3847                    && near(rect.y, indicator_rect.top)
3848                    && near(rect.width, indicator_rect.width())
3849                    && near(rect.height, indicator_rect.height())
3850            }
3851            _ => false,
3852        }) else {
3853            return false;
3854        };
3855        let mut canvas = waft_embedder::Canvas::new();
3856        waft_painting::draw_rrect(&mut canvas, rrect, &waft_embedder::Paint::default());
3857        let expected = canvas.build();
3858        let Some(Op::DrawPath {
3859            path: expected_path,
3860            ..
3861        }) = expected.ops().first()
3862        else {
3863            panic!("draw_rrect records a path");
3864        };
3865        let indicator_color: valo::Color = Color::new(0xffe8def8).into();
3866        ops[clip_at + rect_at..].iter().any(|op| {
3867            matches!(
3868                op,
3869                Op::DrawPath { path, paint, .. }
3870                    if path == expected_path && paint.color == indicator_color
3871            )
3872        })
3873    }
3874
3875    /// Dart's `createGesture(kind: mouse)`, `addPointer()`, `moveTo(center of icon)` and
3876    /// `pumpAndSettle()`.
3877    fn hover_icon(tester: &mut WidgetTester, icon: IconData) {
3878        let at = center_of_icon(tester, icon);
3879        let mut mouse = TestPointer::mouse(1, 0);
3880        tester.add_pointer(&mut mouse, Offset::ZERO);
3881        tester.move_to(&mut mouse, at, false);
3882        tester.pump_and_settle();
3883    }
3884
3885    fn rrect(left: f64, top: f64, right: f64, bottom: f64) -> waft_embedder::RRect {
3886        waft_embedder::RRect::from_ltrbr(left, top, right, bottom, Radius::circular(16.0))
3887    }
3888
3889    #[test]
3890    fn navigation_rail_indicator_renders_ripple() {
3891        test_widgets(|tester| {
3892            pump_navigation_rail(
3893                tester,
3894                NavigationRail::new(two_destinations(), Some(1))
3895                    .label_type(NavigationRailLabelType::All),
3896            );
3897            hover_icon(tester, Icons::favorite_border());
3898
3899            let indicator_rect = Rect::from_ltrb(12.0, 0.0, 68.0, 32.0);
3900            assert!(paints_indicator_highlight(
3901                &rail_ink_ops(tester),
3902                indicator_rect,
3903                rrect(12.0, 0.0, 68.0, 32.0)
3904            ));
3905        });
3906    }
3907
3908    #[test]
3909    fn navigation_rail_indicator_renders_ripple_extended() {
3910        test_widgets(|tester| {
3911            // This is a regression test for https://github.com/flutter/flutter/issues/117126
3912            pump_navigation_rail(
3913                tester,
3914                NavigationRail::new(two_destinations(), Some(1))
3915                    .extended(true)
3916                    .label_type(NavigationRailLabelType::None),
3917            );
3918            hover_icon(tester, Icons::favorite_border());
3919
3920            let indicator_rect = Rect::from_ltrb(12.0, 6.0, 68.0, 38.0);
3921            assert!(paints_indicator_highlight(
3922                &rail_ink_ops(tester),
3923                indicator_rect,
3924                rrect(12.0, 6.0, 68.0, 38.0)
3925            ));
3926        });
3927    }
3928
3929    fn padded_two_destinations() -> Vec<NavigationRailDestination> {
3930        vec![
3931            destination(Icons::favorite_border(), Icons::favorite(), "Abc")
3932                .padding(EdgeInsetsGeometry::all(10.0)),
3933            destination(Icons::bookmark_border(), Icons::bookmark(), "Def")
3934                .padding(EdgeInsetsGeometry::all(18.0)),
3935        ]
3936    }
3937
3938    #[test]
3939    fn navigation_rail_indicator_renders_properly_when_padding_is_applied() {
3940        test_widgets(|tester| {
3941            // This is a regression test for https://github.com/flutter/flutter/issues/117126
3942            pump_navigation_rail(
3943                tester,
3944                NavigationRail::new(padded_two_destinations(), Some(1))
3945                    .extended(true)
3946                    .label_type(NavigationRailLabelType::None),
3947            );
3948            hover_icon(tester, Icons::favorite_border());
3949
3950            let indicator_rect = Rect::from_ltrb(22.0, 16.0, 78.0, 48.0);
3951            assert!(paints_indicator_highlight(
3952                &rail_ink_ops(tester),
3953                indicator_rect,
3954                rrect(30.0, 24.0, 86.0, 56.0)
3955            ));
3956        });
3957    }
3958
3959    #[test]
3960    fn indicator_renders_properly_when_navigation_rai_min_width_less_than_default_min_width() {
3961        test_widgets(|tester| {
3962            // This is a regression test for https://github.com/flutter/flutter/issues/117126
3963            pump_navigation_rail(
3964                tester,
3965                NavigationRail::new(two_destinations(), Some(1))
3966                    .min_width(50.0)
3967                    .extended(true)
3968                    .label_type(NavigationRailLabelType::None),
3969            );
3970            hover_icon(tester, Icons::favorite_border());
3971
3972            let indicator_rect = Rect::from_ltrb(-3.0, 6.0, 53.0, 38.0);
3973            assert!(paints_indicator_highlight(
3974                &rail_ink_ops(tester),
3975                indicator_rect,
3976                rrect(0.0, 6.0, 50.0, 38.0)
3977            ));
3978        });
3979    }
3980
3981    #[test]
3982    fn navigation_rail_indicator_renders_properly_with_custom_padding_and_min_width() {
3983        test_widgets(|tester| {
3984            // This is a regression test for https://github.com/flutter/flutter/issues/117126
3985            pump_navigation_rail(
3986                tester,
3987                NavigationRail::new(padded_two_destinations(), Some(1))
3988                    .min_width(300.0)
3989                    .extended(true)
3990                    .label_type(NavigationRailLabelType::None),
3991            );
3992            hover_icon(tester, Icons::favorite_border());
3993
3994            let indicator_rect = Rect::from_ltrb(132.0, 16.0, 188.0, 48.0);
3995            assert!(paints_indicator_highlight(
3996                &rail_ink_ops(tester),
3997                indicator_rect,
3998                rrect(140.0, 24.0, 196.0, 56.0)
3999            ));
4000        });
4001    }
4002
4003    #[test]
4004    fn navigation_rail_indicator_renders_properly_with_long_labels() {
4005        test_widgets(|tester| {
4006            // This is a regression test for https://github.com/flutter/flutter/issues/128005.
4007            pump_navigation_rail(
4008                tester,
4009                NavigationRail::new(
4010                    vec![
4011                        destination(
4012                            Icons::favorite_border(),
4013                            Icons::favorite(),
4014                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
4015                        ),
4016                        destination(Icons::bookmark_border(), Icons::bookmark(), "ABC"),
4017                    ],
4018                    Some(1),
4019                )
4020                .label_type(NavigationRailLabelType::All),
4021            );
4022            hover_icon(tester, Icons::favorite_border());
4023
4024            // Default values from M3 specification.
4025            let rail_min_width = 80.0;
4026            let indicator_height = 32.0;
4027            let destination_width = 72.0;
4028            let destination_horizontal_padding = 8.0;
4029            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0
4030
4031            // The navigation rail width is larger than default because of the first
4032            // destination long label.
4033            let rail_width = tester.get_size(rail_box(tester)).width();
4034
4035            // Expected indicator position.
4036            let indicator_left = (rail_width - indicator_width) / 2.0;
4037            let indicator_right = (rail_width + indicator_width) / 2.0;
4038            let indicator_rect =
4039                Rect::from_ltrb(indicator_left, 0.0, indicator_right, indicator_height);
4040            let indicator_horizontal_padding = (rail_min_width - indicator_width) / 2.0; // 12.0
4041
4042            assert!(paints_indicator_highlight(
4043                &rail_ink_ops(tester),
4044                indicator_rect,
4045                rrect(
4046                    indicator_horizontal_padding,
4047                    0.0,
4048                    indicator_horizontal_padding + indicator_width,
4049                    indicator_height,
4050                )
4051            ));
4052        });
4053    }
4054
4055    #[test]
4056    fn navigation_rail_indicator_renders_properly_with_large_icon() {
4057        test_widgets(|tester| {
4058            // This is a regression test for https://github.com/flutter/flutter/issues/133799.
4059            let icon_size = 50.0;
4060            pump_navigation_rail_with(
4061                tester,
4062                NavigationRail::new(
4063                    vec![
4064                        destination(Icons::favorite_border(), Icons::favorite(), "ABC"),
4065                        destination(Icons::bookmark_border(), Icons::bookmark(), "DEF"),
4066                    ],
4067                    Some(1),
4068                )
4069                .label_type(NavigationRailLabelType::All),
4070                Pump {
4071                    navigation_rail_theme: Some(
4072                        NavigationRailThemeData::new()
4073                            .selected_icon_theme(IconThemeData::new().size(icon_size))
4074                            .unselected_icon_theme(IconThemeData::new().size(icon_size)),
4075                    ),
4076                    ..Pump::default()
4077                },
4078            );
4079
4080            // Hover the first destination.
4081            hover_icon(tester, Icons::favorite_border());
4082
4083            // Default values from M3 specification.
4084            let rail_min_width = 80.0;
4085            let indicator_height = 32.0;
4086            let destination_width = 72.0;
4087            let destination_horizontal_padding = 8.0;
4088            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0
4089
4090            // The navigation rail width is the default one because labels are short.
4091            let rail_width = tester.get_size(rail_box(tester)).width();
4092            assert_eq!(rail_width, rail_min_width);
4093
4094            // Expected indicator position.
4095            let indicator_left = (rail_width - indicator_width) / 2.0;
4096            let indicator_right = (rail_width + indicator_width) / 2.0;
4097            let indicator_top = (icon_size - indicator_height) / 2.0;
4098            let indicator_bottom = (icon_size + indicator_height) / 2.0;
4099            let indicator_rect = Rect::from_ltrb(
4100                indicator_left,
4101                indicator_top,
4102                indicator_right,
4103                indicator_bottom,
4104            );
4105
4106            // Icon height is greater than indicator height so the indicator has a vertical
4107            // offset.
4108            let second_indicator_vertical_offset = (icon_size - indicator_height) / 2.0;
4109
4110            assert!(paints_indicator_highlight(
4111                &rail_ink_ops(tester),
4112                // Hover highlight for the hovered destination (the one with 'favorite' icon).
4113                indicator_rect,
4114                // Indicator for the selected destination (the one with 'bookmark' icon).
4115                rrect(
4116                    indicator_left,
4117                    second_indicator_vertical_offset,
4118                    indicator_right,
4119                    second_indicator_vertical_offset + indicator_height,
4120                )
4121            ));
4122        });
4123    }
4124
4125    #[test]
4126    fn navigation_rail_indicator_renders_properly_when_text_direction_is_rtl() {
4127        test_widgets(|tester| {
4128            // This is a regression test for https://github.com/flutter/flutter/issues/134361.
4129            pump_built_widget(
4130                tester,
4131                NavigationRail::new(
4132                    vec![
4133                        destination(Icons::favorite_border(), Icons::favorite(), "ABC"),
4134                        destination(Icons::bookmark_border(), Icons::bookmark(), "DEF"),
4135                    ],
4136                    Some(1),
4137                )
4138                .extended(true),
4139                true,
4140                true,
4141            );
4142
4143            // Hover the first destination.
4144            hover_icon(tester, Icons::favorite_border());
4145
4146            // Default values from M3 specification.
4147            let rail_min_extended_width = 256.0;
4148            let indicator_height = 32.0;
4149            let destination_width = 72.0;
4150            let destination_horizontal_padding = 8.0;
4151            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0
4152            let vertical_destination_spacing_m3 = 12.0;
4153
4154            // The navigation rail width is the default one because labels are short.
4155            let rail_width = tester.get_size(rail_box(tester)).width();
4156            assert_eq!(rail_width, rail_min_extended_width);
4157
4158            // Expected indicator position.
4159            let indicator_left =
4160                rail_width - (destination_width - destination_horizontal_padding / 2.0);
4161            let indicator_right = indicator_left + indicator_width;
4162            let indicator_rect = Rect::from_ltrb(
4163                indicator_left,
4164                vertical_destination_spacing_m3 / 2.0,
4165                indicator_right,
4166                vertical_destination_spacing_m3 / 2.0 + indicator_height,
4167            );
4168
4169            // Compute the vertical position for the selected destination (the one with
4170            // 'bookmark' icon).
4171            let second_indicator_vertical_offset = vertical_destination_spacing_m3 / 2.0;
4172
4173            assert!(paints_indicator_highlight(
4174                &rail_ink_ops(tester),
4175                // Hover highlight for the hovered destination (the one with 'favorite' icon).
4176                indicator_rect,
4177                // Indicator for the selected destination (the one with 'bookmark' icon).
4178                rrect(
4179                    indicator_left,
4180                    second_indicator_vertical_offset,
4181                    indicator_right,
4182                    second_indicator_vertical_offset + indicator_height,
4183                )
4184            ));
4185        });
4186    }
4187
4188    #[test]
4189    fn navigation_rail_indicator_scale_transform() {
4190        test_widgets(|tester| {
4191            let build = |tester: &mut WidgetTester, selected_index: usize| {
4192                pump_navigation_rail(
4193                    tester,
4194                    NavigationRail::new(two_destinations(), Some(selected_index))
4195                        .label_type(NavigationRailLabelType::All),
4196                );
4197            };
4198            build(tester, 0);
4199            tester.pump_and_settle();
4200            // Dart's `.last` Transform under the indicators: the second destination's.
4201            let second_scale = |tester: &WidgetTester| {
4202                let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[1];
4203                let transform = *tester
4204                    .descendants_of_type::<waft_widgets::Transform>(indicator)
4205                    .last()
4206                    .expect("a Transform under the indicator");
4207                tester.widget(transform, |transform: &waft_widgets::Transform| {
4208                    f64::from(transform.transform.to_flutter_array()[0])
4209                })
4210            };
4211            assert_eq!(second_scale(tester), 0.0);
4212
4213            build(tester, 1);
4214            tester.pump_by(Duration::from_millis(100));
4215            let scale = second_scale(tester);
4216            // Dart's `closeTo(.., precisionErrorTolerance)`, within the `f32` of valo's matrix.
4217            assert!((scale - 0.970_502_395_629_882_8).abs() < 1e-6, "{scale}");
4218
4219            tester.pump_by(Duration::from_millis(100));
4220            assert_eq!(second_scale(tester), 1.0);
4221        });
4222    }
4223
4224    /// Dart's `_getIndicatorDecoration`: the decoration of the first `Ink` under a
4225    /// `FadeTransition`, as a `ShapeDecoration`.
4226    fn indicator_decoration<R>(
4227        tester: &WidgetTester,
4228        read: impl FnOnce(&waft_painting::ShapeDecoration) -> R,
4229    ) -> R {
4230        let ink = find::by_type::<waft_widgets::FadeTransition>()
4231            .evaluate(tester)
4232            .into_iter()
4233            .find_map(|fade| {
4234                tester
4235                    .descendants_of_type::<crate::ink_decoration::Ink>(fade)
4236                    .first()
4237                    .copied()
4238            })
4239            .expect("an Ink under a FadeTransition");
4240        tester.widget(ink, |ink: &crate::ink_decoration::Ink| {
4241            read(
4242                ink.decoration
4243                    .as_deref()
4244                    .and_then(|decoration| decoration.as_any().downcast_ref())
4245                    .expect("a ShapeDecoration"),
4246            )
4247        })
4248    }
4249
4250    #[test]
4251    fn navigation_destination_updates_indicator_color_and_shape() {
4252        test_widgets(|tester| {
4253            let color = Color::new(0xff0000ff);
4254            let shape = waft_painting::RoundedRectangleBorder::default();
4255            let build_navigation_rail = |tester: &mut WidgetTester,
4256                                         indicator: Option<(
4257                Color,
4258                waft_painting::RoundedRectangleBorder,
4259            )>| {
4260                let mut rail = NavigationRail::new(destinations(), Some(0)).use_indicator(true);
4261                if let Some((color, shape)) = indicator {
4262                    rail = rail.indicator_color(color).indicator_shape(shape);
4263                }
4264                pump_rail_in_app(tester, rail);
4265            };
4266            let theme = ThemeData::new(&tester.cell.borrow());
4267            build_navigation_rail(tester, None);
4268
4269            // Test default indicator color and shape.
4270            assert_eq!(
4271                indicator_decoration(tester, |decoration| decoration.color.clone()),
4272                Some(theme.color_scheme.secondary_container().into())
4273            );
4274            assert!(indicator_decoration(tester, |decoration| {
4275                &*decoration.shape
4276                    == &waft_painting::StadiumBorder::new(waft_painting::BorderSide::NONE)
4277                        as &dyn ShapeBorder
4278            }));
4279
4280            build_navigation_rail(tester, Some((color, shape)));
4281
4282            // Test custom indicator color and shape.
4283            assert_eq!(
4284                indicator_decoration(tester, |decoration| decoration.color.clone()),
4285                Some(color.into())
4286            );
4287            assert!(indicator_decoration(tester, |decoration| {
4288                &*decoration.shape == &shape as &dyn ShapeBorder
4289            }));
4290        });
4291    }
4292
4293    #[test]
4294    fn destination_s_respect_their_disabled_state() {
4295        test_widgets(|tester| {
4296            let selected_index = Rc::new(std::cell::Cell::new(None));
4297            let seen = Rc::clone(&selected_index);
4298            pump_navigation_rail(
4299                tester,
4300                NavigationRail::new(
4301                    vec![
4302                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
4303                        destination(Icons::star_border(), Icons::star(), "Bcd"),
4304                        destination(Icons::bookmark_border(), Icons::bookmark(), "Cde")
4305                            .disabled(true),
4306                    ],
4307                    Some(0),
4308                )
4309                .on_destination_selected(move |_app, index| seen.set(Some(index)))
4310                .label_type(NavigationRailLabelType::All),
4311            );
4312
4313            tester.tap_at(center_of_text(tester, "Abc"), 1);
4314            assert_eq!(selected_index.get(), Some(0));
4315
4316            tester.tap_at(center_of_text(tester, "Bcd"), 2);
4317            assert_eq!(selected_index.get(), Some(1));
4318
4319            tester.tap_at(center_of_text(tester, "Cde"), 3);
4320            assert_eq!(selected_index.get(), Some(1));
4321
4322            // Wait for any pending shader compilation.
4323            tester.pump_and_settle();
4324        });
4325    }
4326
4327    #[test]
4328    #[expect(
4329        deprecated,
4330        reason = "Dart's case reads the deprecated `Color.opacity`"
4331    )]
4332    fn destination_s_label_with_the_right_opacity_while_disabled() {
4333        test_widgets(|tester| {
4334            pump_navigation_rail(
4335                tester,
4336                NavigationRail::new(
4337                    vec![
4338                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
4339                        destination(Icons::bookmark_border(), Icons::bookmark(), "Bcd")
4340                            .disabled(true),
4341                    ],
4342                    Some(0),
4343                )
4344                .on_destination_selected(|_app, _index| {})
4345                .label_type(NavigationRailLabelType::All),
4346            );
4347
4348            tester.pump_and_settle();
4349
4350            let default_text_style_opacity = |text: &str| {
4351                let element = tester
4352                    .ancestor_of_type::<DefaultTextStyle>(find::text(text).evaluate(tester)[0]);
4353                tester.widget(element, |style: &DefaultTextStyle| {
4354                    style.style.color.as_deref().map(|color| color.opacity())
4355                })
4356            };
4357
4358            let abc_label_opacity = default_text_style_opacity("Abc");
4359            let bcd_label_opacity = default_text_style_opacity("Bcd");
4360
4361            assert_eq!(abc_label_opacity, Some(1.0));
4362            let bcd = bcd_label_opacity.expect("a colour");
4363            assert!((bcd - 0.38).abs() <= 0.01, "{bcd}");
4364        });
4365    }
4366
4367    #[test]
4368    fn navigation_rail_indicator_inkwell_can_be_transparent() {
4369        test_widgets(|tester| {
4370            // This is a regression test for https://github.com/flutter/flutter/issues/135866.
4371            let root = {
4372                let app = tester.cell.borrow();
4373                let mut color_scheme = crate::color_scheme::ColorScheme::light();
4374                color_scheme = color_scheme.with_primary(Colors::TRANSPARENT);
4375                let theme = ThemeData::builder()
4376                    .color_scheme(color_scheme)
4377                    // Material 3 defaults to InkSparkle which is not testable using paints.
4378                    .splash_factory(crate::ink_splash::InkSplash::splash_factory())
4379                    .build(&app);
4380                material_app(
4381                    theme,
4382                    Scaffold::new()
4383                        .body(
4384                            Row::new().children([
4385                                NavigationRail::new(
4386                                    vec![
4387                                        destination(
4388                                            Icons::favorite_border(),
4389                                            Icons::favorite(),
4390                                            "ABC",
4391                                        ),
4392                                        destination(
4393                                            Icons::bookmark_border(),
4394                                            Icons::bookmark(),
4395                                            "DEF",
4396                                        ),
4397                                    ],
4398                                    Some(1),
4399                                )
4400                                .label_type(NavigationRailLabelType::All)
4401                                .into_widget(),
4402                                Expanded::new(Text::new("body")).into_widget(),
4403                            ]),
4404                        )
4405                        .into_widget(),
4406                )
4407            };
4408            tester.pump_widget(root);
4409
4410            let at = center_of_icon(tester, Icons::favorite_border());
4411            let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
4412            tester.add_pointer(&mut mouse, Offset::ZERO);
4413            tester.move_to(&mut mouse, at, false);
4414            tester.pump_and_settle();
4415
4416            // Dart's `paints..rect(color: Colors.transparent)`: Valo's canvas drops a draw whose
4417            // paint is transparent, so the hover highlight has no entry; the case asserts that
4418            // no rect is drawn instead, as a hover in the primary colour would draw one.
4419            let draws_rect = |ops: &[waft_embedder::valo::Op]| {
4420                ops.iter()
4421                    .any(|op| matches!(op, waft_embedder::valo::Op::DrawRect { .. }))
4422            };
4423            assert!(!draws_rect(&rail_ink_ops(tester)));
4424
4425            tester.down(&mut mouse, at);
4426            tester.pump(); // Start the splash and highlight animations.
4427            // Wait for splash and highlight to be well under way.
4428            tester.pump_by(Duration::from_millis(800));
4429
4430            // Dart's `paints..circle(color: Colors.transparent)`: likewise no splash circle is
4431            // drawn instead.
4432            let ops = rail_ink_ops(tester);
4433            let draws_circle = ops.iter().any(|op| {
4434                matches!(
4435                    op,
4436                    waft_embedder::valo::Op::DrawPath { path, .. } if path.as_oval().is_some()
4437                )
4438            });
4439            assert!(!draws_circle);
4440        });
4441    }
4442
4443    #[test]
4444    fn navigation_rail_can_have_expanded_widgets_inside() {
4445        test_widgets(|tester| {
4446            pump_navigation_rail(
4447                tester,
4448                NavigationRail::new(
4449                    vec![destination(
4450                        Icons::favorite_border(),
4451                        Icons::favorite(),
4452                        "Abc",
4453                    )],
4454                    Some(0),
4455                )
4456                .trailing(Expanded::new(Icon::new(Some(Icons::search())))),
4457            );
4458
4459            // Dart's `expect(tester.takeException(), isNull)`: the frame did not panic.
4460            tester.pump_and_settle();
4461        });
4462    }
4463
4464    #[test]
4465    fn navigation_rail_labels_shall_not_overflow_if_longer_texts_provided_extended() {
4466        test_widgets(|tester| {
4467            // Regression test for https://github.com/flutter/flutter/issues/110901.
4468            // The navigation rail has a narrow width constraint. The text should wrap.
4469            let normal_label = "Abc";
4470            let long_label = "Very long bookmark text for navigation destination";
4471            let root = {
4472                let app = tester.cell.borrow();
4473                material_app(
4474                    ThemeData::new(&app),
4475                    Scaffold::new()
4476                        .body(
4477                            Row::new().children([
4478                                SizedBox::new()
4479                                    .width(140.0)
4480                                    .child(
4481                                        NavigationRail::new(
4482                                            vec![
4483                                                destination(
4484                                                    Icons::favorite_border(),
4485                                                    Icons::favorite(),
4486                                                    normal_label,
4487                                                ),
4488                                                destination(
4489                                                    Icons::bookmark_border(),
4490                                                    Icons::bookmark(),
4491                                                    long_label,
4492                                                ),
4493                                            ],
4494                                            Some(1),
4495                                        )
4496                                        .extended(true),
4497                                    )
4498                                    .into_widget(),
4499                                Expanded::new(Text::new("body")).into_widget(),
4500                            ]),
4501                        )
4502                        .into_widget(),
4503                )
4504            };
4505            tester.pump_widget(root);
4506
4507            expect(
4508                tester,
4509                &find::by_type::<NavigationRail>(),
4510                finds_one_widget(),
4511            );
4512            expect(tester, &find::text(normal_label), finds_one_widget());
4513            expect(tester, &find::text(long_label), finds_one_widget());
4514
4515            // If the widget manages to layout without throwing an overflow exception,
4516            // the test passes.
4517        });
4518    }
4519
4520    #[test]
4521    fn navigation_rail_can_scroll_in_low_height() {
4522        test_widgets(|tester| {
4523            let root = {
4524                let app = tester.cell.borrow();
4525                material_app(
4526                    ThemeData::new(&app),
4527                    Builder::new(|app, context| {
4528                        MediaQuery::new(
4529                            // Set Screen height with 300
4530                            MediaQuery::of(app, context)
4531                                .copy_with()
4532                                .size(Size::new(800.0, 300.0)),
4533                            Scaffold::new().body(
4534                                Row::new().children([
4535                                    // Set NavigationRail height with 100
4536                                    SizedBox::new()
4537                                        .height(100.0)
4538                                        .child(
4539                                            NavigationRail::new(abc_def_ghi(), Some(0))
4540                                                .scrollable(true),
4541                                        )
4542                                        .into_widget(),
4543                                    Expanded::new(Text::new("body")).into_widget(),
4544                                ]),
4545                            ),
4546                        )
4547                        .into_widget()
4548                    })
4549                    .into_widget(),
4550                )
4551            };
4552            tester.pump_widget(root);
4553
4554            let scrollable = find::by_type::<waft_widgets::Scrollable>().evaluate(tester)[0];
4555            let mut app = tester.cell.borrow_mut();
4556            let state = scrollable
4557                .state_handle::<waft_widgets::ScrollableState>(&app)
4558                .expect("a ScrollableState");
4559            let position = state.position(&app);
4560            position.jump_to(&mut app, 500.0);
4561            assert_eq!(position.pixels(&app), 500.0);
4562        });
4563    }
4564
4565    /// The rail of the leading/trailing placement cases, 140 wide.
4566    fn pump_leading_trailing_rail(
4567        tester: &mut WidgetTester,
4568        configure: impl FnOnce(NavigationRail) -> NavigationRail,
4569    ) -> (GlobalKey, GlobalKey) {
4570        let leading_key = GlobalKey::new();
4571        let trailing_key = GlobalKey::new();
4572        let rail = configure(
4573            NavigationRail::new(
4574                vec![
4575                    NavigationRailDestination::new(
4576                        Icon::new(Some(Icons::favorite())),
4577                        Text::new("Abc"),
4578                    ),
4579                    NavigationRailDestination::new(
4580                        Icon::new(Some(Icons::bookmark())),
4581                        Text::new("Def"),
4582                    ),
4583                    NavigationRailDestination::new(
4584                        Icon::new(Some(Icons::star())),
4585                        Text::new("Ghi"),
4586                    ),
4587                ],
4588                Some(0),
4589            )
4590            .extended(true)
4591            .group_alignment(0.0)
4592            .leading(
4593                SizedBox::new()
4594                    .key(KeyRef::from(leading_key.clone()))
4595                    .height(50.0),
4596            )
4597            .trailing(
4598                SizedBox::new()
4599                    .key(KeyRef::from(trailing_key.clone()))
4600                    .height(50.0),
4601            ),
4602        );
4603        let root = {
4604            let app = tester.cell.borrow();
4605            material_app(
4606                ThemeData::new(&app),
4607                Scaffold::new()
4608                    .body(Row::new().children([
4609                        SizedBox::new().width(140.0).child(rail).into_widget(),
4610                        Expanded::new(Text::new("body")).into_widget(),
4611                    ]))
4612                    .into_widget(),
4613            )
4614        };
4615        tester.pump_widget(root);
4616        (leading_key, trailing_key)
4617    }
4618
4619    /// Dart's `tester.getRect(find.ancestor(of: find.byIcon(icon), matching:
4620    /// find.byType(Semantics)).first)`.
4621    fn destination_rect(tester: &WidgetTester, icon: IconData) -> Rect {
4622        let semantics = tester
4623            .element(find::ancestor(find::by_icon(&icon), find::by_type::<Semantics>()).first());
4624        tester.get_rect(tester.render_box_of(semantics))
4625    }
4626
4627    #[test]
4628    fn navigation_rail_leading_widget_is_at_top_and_trailing_widget_is_at_last_destination_defaults()
4629     {
4630        test_widgets(|tester| {
4631            let (leading_key, trailing_key) = pump_leading_trailing_rail(tester, |rail| rail);
4632
4633            let leading_rect = tester.get_rect(render_box_of_key(tester, &leading_key));
4634            let trailing_rect = tester.get_rect(render_box_of_key(tester, &trailing_key));
4635            let first_dest_rect = destination_rect(tester, Icons::favorite());
4636            let last_dest_rect = destination_rect(tester, Icons::star());
4637
4638            assert_eq!(leading_rect.top, 8.0);
4639            assert!(first_dest_rect.top - leading_rect.bottom > 100.0);
4640            assert_eq!(trailing_rect.top - last_dest_rect.bottom, 0.0);
4641            assert!(trailing_rect.bottom < 500.0);
4642        });
4643    }
4644
4645    #[test]
4646    fn navigation_rail_leading_at_top_set_to_false_and_trailing_at_bottom_to_true() {
4647        test_widgets(|tester| {
4648            let (leading_key, trailing_key) = pump_leading_trailing_rail(tester, |rail| {
4649                rail.leading_at_top(false).trailing_at_bottom(true)
4650            });
4651
4652            let leading_rect = tester.get_rect(render_box_of_key(tester, &leading_key));
4653            let trailing_rect = tester.get_rect(render_box_of_key(tester, &trailing_key));
4654            let first_dest_rect = destination_rect(tester, Icons::favorite());
4655            let last_dest_rect = destination_rect(tester, Icons::star());
4656
4657            assert!(leading_rect.top > 100.0);
4658            assert_eq!(first_dest_rect.top - leading_rect.bottom, 8.0);
4659            assert!(trailing_rect.top - last_dest_rect.bottom > 100.0);
4660            assert_eq!(trailing_rect.bottom, 600.0);
4661        });
4662    }
4663
4664    #[test]
4665    fn navigation_rail_does_not_crash_at_zero_area() {
4666        test_widgets(|tester| {
4667            let root = {
4668                let app = tester.cell.borrow();
4669                material_app(
4670                    ThemeData::new(&app),
4671                    Center::new()
4672                        .child(SizedBox::shrink().child(NavigationRail::new(
4673                            vec![NavigationRailDestination::new(
4674                                Icon::new(Some(Icons::abc())),
4675                                Text::new("X"),
4676                            )],
4677                            Some(0),
4678                        )))
4679                        .into_widget(),
4680                )
4681            };
4682            tester.pump_widget(root);
4683            assert_eq!(tester.get_size(rail_box(tester)), Size::ZERO);
4684        });
4685    }
4686
4687    #[test]
4688    fn navigation_rail_respects_main_axis_alignment() {
4689        test_widgets(|tester| {
4690            pump_navigation_rail(
4691                tester,
4692                NavigationRail::new(destinations(), Some(0))
4693                    .main_axis_alignment(MainAxisAlignment::SpaceEvenly),
4694            );
4695
4696            // Find the exact column by checking both alignment and size
4697            let columns = find::by_type::<Column>()
4698                .evaluate(tester)
4699                .into_iter()
4700                .filter(|element| {
4701                    tester.widget(*element, |column: &Column| {
4702                        column.main_axis_alignment == MainAxisAlignment::SpaceEvenly
4703                            && column.main_axis_size == MainAxisSize::Max
4704                    })
4705                })
4706                .count();
4707            assert_eq!(columns, 1);
4708        });
4709    }
4710
4711    // These tests are only relevant for Material 2. Once Material 2
4712    // support is deprecated and the APIs are removed, these tests
4713    // can be deleted.
4714
4715    fn m2() -> Pump {
4716        Pump {
4717            use_material3: false,
4718            ..Pump::default()
4719        }
4720    }
4721
4722    fn m2_default_width(label_type: Option<NavigationRailLabelType>) {
4723        test_widgets(|tester| {
4724            let mut rail = NavigationRail::new(destinations(), Some(0));
4725            if let Some(label_type) = label_type {
4726                rail = rail.label_type(label_type);
4727            }
4728            pump_navigation_rail_with(tester, rail, m2());
4729
4730            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);
4731        });
4732    }
4733
4734    #[test]
4735    fn material_2_renders_at_the_correct_default_width_label_type_none_default() {
4736        m2_default_width(None);
4737    }
4738
4739    #[test]
4740    fn material_2_renders_at_the_correct_default_width_label_type_selected() {
4741        m2_default_width(Some(NavigationRailLabelType::Selected));
4742    }
4743
4744    #[test]
4745    fn material_2_renders_at_the_correct_default_width_label_type_all() {
4746        m2_default_width(Some(NavigationRailLabelType::All));
4747    }
4748
4749    /// The Material 2 icon-only destination spacing cases at `text_scale_factor`, `min_width`
4750    /// wide: Since the rail is icon only, its destinations should not be affected by
4751    /// textScaleFactor.
4752    fn m2_icon_only_spacing(text_scale_factor: f64, min_width: Option<f64>) {
4753        test_widgets(|tester| {
4754            let destination_width = min_width.unwrap_or(72.0);
4755            let mut rail = NavigationRail::new(destinations(), Some(0));
4756            if let Some(min_width) = min_width {
4757                rail = rail.min_width(min_width);
4758            }
4759            pump_navigation_rail_with(
4760                tester,
4761                rail,
4762                Pump {
4763                    text_scale_factor,
4764                    ..m2()
4765                },
4766            );
4767
4768            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);
4769
4770            // The first destination is 8 from the top because of the default vertical
4771            // padding at the to of the rail; each next one is one width below the one before.
4772            expect_icon_column_in(
4773                tester,
4774                destination_width,
4775                destination_width,
4776                8.0,
4777                [destination_width; 3],
4778            );
4779        });
4780    }
4781
4782    #[test]
4783    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_1_0_default()
4784     {
4785        m2_icon_only_spacing(1.0, None);
4786    }
4787
4788    #[test]
4789    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_3_0() {
4790        m2_icon_only_spacing(3.0, None);
4791    }
4792
4793    #[test]
4794    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_0_75() {
4795        m2_icon_only_spacing(0.75, None);
4796    }
4797
4798    /// The Material 2 selected-label spacing cases whose rail keeps its 72 width (a
4799    /// textScaleFactor of 1.0 and 0.75: a smaller one will not reduce the default width of the
4800    /// rail since there is a minWidth).
4801    fn m2_selected_spacing(text_scale_factor: f64) {
4802        test_widgets(|tester| {
4803            pump_navigation_rail_with(
4804                tester,
4805                NavigationRail::new(destinations(), Some(0))
4806                    .label_type(NavigationRailLabelType::Selected),
4807                Pump {
4808                    text_scale_factor,
4809                    ..m2()
4810                },
4811            );
4812
4813            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);
4814
4815            // The first destination is 8 from the top because of the default vertical
4816            // padding at the to of the rail.
4817            let next_destination_y = 8.0;
4818            let icon = icon_render_box(tester, Icons::favorite());
4819            let label = label_render_box(tester, "Abc");
4820            let icon_size = tester.get_size(icon);
4821            let label_size = tester.get_size(label);
4822            assert_offset(
4823                global_top_left(tester, icon),
4824                Offset::new(
4825                    (72.0 - icon_size.width()) / 2.0,
4826                    next_destination_y + (72.0 - icon_size.height() - label_size.height()) / 2.0,
4827                ),
4828            );
4829            assert_offset(
4830                global_top_left(tester, label),
4831                Offset::new(
4832                    (72.0 - label_size.width()) / 2.0,
4833                    next_destination_y + (72.0 + icon_size.height() - label_size.height()) / 2.0,
4834                ),
4835            );
4836
4837            // The other destinations are 72 below the one before.
4838            let mut next_destination_y = next_destination_y;
4839            for icon in &icons_in_order()[1..] {
4840                next_destination_y += 72.0;
4841                expect_icon_at(
4842                    tester,
4843                    icon_render_box(tester, icon.clone()),
4844                    72.0,
4845                    72.0,
4846                    next_destination_y,
4847                );
4848            }
4849        });
4850    }
4851
4852    #[test]
4853    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_1_0_default()
4854    {
4855        m2_selected_spacing(1.0);
4856    }
4857
4858    #[test]
4859    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_0_75() {
4860        m2_selected_spacing(0.75);
4861    }
4862
4863    /// The Material 2 labelled spacing cases at a textScaleFactor of 3.0: the rail and
4864    /// destinations sizes grow to fit the larger text labels.
4865    fn m2_large_text_labelled_spacing(label_type: NavigationRailLabelType) {
4866        test_widgets(|tester| {
4867            pump_navigation_rail_with(
4868                tester,
4869                NavigationRail::new(destinations(), Some(0)).label_type(label_type),
4870                Pump {
4871                    text_scale_factor: 3.0,
4872                    ..m2()
4873                },
4874            );
4875
4876            assert_eq!(tester.get_size(rail_box(tester)).width(), 142.0);
4877
4878            // The first destination is 8 from the top because of the default vertical
4879            // padding at the to of the rail.
4880            let mut next_destination_y = 8.0;
4881            for (i, (icon, label)) in icons_in_order()
4882                .into_iter()
4883                .zip(["Abc", "Def", "Ghi", "Jkl"])
4884                .enumerate()
4885            {
4886                let icon = icon_render_box(tester, icon);
4887                let icon_size = tester.get_size(icon);
4888                let labelled = i == 0 || label_type == NavigationRailLabelType::All;
4889                if !labelled {
4890                    // An unselected destination is 72 high with its icon 24 below its top.
4891                    assert_offset(
4892                        global_top_left(tester, icon),
4893                        Offset::new((142.0 - icon_size.width()) / 2.0, next_destination_y + 24.0),
4894                    );
4895                    next_destination_y += 72.0;
4896                    continue;
4897                }
4898                assert_offset(
4899                    global_top_left(tester, icon),
4900                    Offset::new((142.0 - icon_size.width()) / 2.0, next_destination_y + 16.0),
4901                );
4902                // The label sits right below the icon.
4903                let label = label_render_box(tester, label);
4904                let label_size = tester.get_size(label);
4905                assert_offset(
4906                    global_top_left(tester, label),
4907                    Offset::new(
4908                        (142.0 - label_size.width()) / 2.0,
4909                        next_destination_y + 16.0 + icon_size.height(),
4910                    ),
4911                );
4912                next_destination_y += 16.0 + icon_size.height() + label_size.height() + 16.0;
4913            }
4914        });
4915    }
4916
4917    #[test]
4918    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_3_0() {
4919        m2_large_text_labelled_spacing(NavigationRailLabelType::Selected);
4920    }
4921
4922    #[test]
4923    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_3_0() {
4924        m2_large_text_labelled_spacing(NavigationRailLabelType::All);
4925    }
4926
4927    #[test]
4928    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_1_0_default() {
4929        m2_all_spacing(1.0);
4930    }
4931
4932    #[test]
4933    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_0_75() {
4934        m2_all_spacing(0.75);
4935    }
4936
4937    /// The Material 2 all-labels spacing cases whose rail keeps its 72 width (a textScaleFactor
4938    /// of 1.0 and 0.75: a smaller one will not reduce the default size of the rail).
4939    fn m2_all_spacing(text_scale_factor: f64) {
4940        test_widgets(|tester| {
4941            pump_navigation_rail_with(
4942                tester,
4943                NavigationRail::new(destinations(), Some(0))
4944                    .label_type(NavigationRailLabelType::All),
4945                Pump {
4946                    text_scale_factor,
4947                    ..m2()
4948                },
4949            );
4950
4951            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);
4952
4953            // The first destination is 8 from the top because of the default vertical
4954            // padding at the to of the rail; each next one is 72 below the one before.
4955            let mut next_destination_y = 8.0;
4956            for (icon, label) in icons_in_order()
4957                .into_iter()
4958                .zip(["Abc", "Def", "Ghi", "Jkl"])
4959            {
4960                let icon = icon_render_box(tester, icon);
4961                let label = label_render_box(tester, label);
4962                let icon_size = tester.get_size(icon);
4963                assert_offset(
4964                    global_top_left(tester, icon),
4965                    Offset::new((72.0 - icon_size.width()) / 2.0, next_destination_y + 16.0),
4966                );
4967                assert_offset(
4968                    global_top_left(tester, label),
4969                    Offset::new(
4970                        (72.0 - tester.get_size(label).width()) / 2.0,
4971                        next_destination_y + 16.0 + icon_size.height(),
4972                    ),
4973                );
4974                next_destination_y += 72.0;
4975            }
4976        });
4977    }
4978
4979    fn m2_group_alignment(group_alignment: Option<f64>, first_y: f64) {
4980        test_widgets(|tester| {
4981            let mut rail = NavigationRail::new(destinations(), Some(0));
4982            if let Some(group_alignment) = group_alignment {
4983                rail = rail.group_alignment(group_alignment);
4984            }
4985            pump_navigation_rail_with(tester, rail, m2());
4986
4987            // Each next destination is 72 below the one before.
4988            expect_icon_column_in(tester, 72.0, 72.0, first_y, [72.0; 3]);
4989        });
4990    }
4991
4992    #[test]
4993    fn material_2_group_alignment_works_group_alignment_minus_1_0_default() {
4994        m2_group_alignment(None, 8.0);
4995    }
4996
4997    #[test]
4998    fn material_2_group_alignment_works_group_alignment_0_0() {
4999        m2_group_alignment(Some(0.0), 160.0);
5000    }
5001
5002    #[test]
5003    fn material_2_group_alignment_works_group_alignment_1_0() {
5004        m2_group_alignment(Some(1.0), 312.0);
5005    }
5006
5007    #[test]
5008    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_1_0_default()
5009     {
5010        m2_icon_only_spacing(1.0, Some(56.0));
5011    }
5012
5013    #[test]
5014    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_3_0()
5015     {
5016        m2_icon_only_spacing(3.0, Some(56.0));
5017    }
5018
5019    /// Dart's case of this name pumps a textScaleFactor of 3.0, not 0.75.
5020    #[test]
5021    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_0_75()
5022     {
5023        m2_icon_only_spacing(3.0, Some(56.0));
5024    }
5025
5026    #[test]
5027    fn material_2_extended_rail_final_width_can_be_changed() {
5028        test_widgets(|tester| {
5029            let rail = |extended: bool| {
5030                NavigationRail::new(destinations(), Some(0))
5031                    .min_extended_width(300.0)
5032                    .extended(extended)
5033            };
5034            pump_navigation_rail_with(tester, rail(false), m2());
5035
5036            let rail_render = rail_box(tester);
5037            assert_eq!(tester.get_size(rail_render).width(), 72.0);
5038
5039            pump_navigation_rail_with(tester, rail(true), m2());
5040            tester.pump_and_settle();
5041            assert_eq!(tester.get_size(rail_render).width(), 300.0);
5042        });
5043    }
5044
5045    #[test]
5046    fn material_2_leading_and_trailing_spacing_is_correct_with_0_2_destinations() {
5047        test_widgets(|tester| {
5048            let leading_widget_key = GlobalKey::new();
5049            let trailing_widget_key = GlobalKey::new();
5050            let fab = |key: &GlobalKey| {
5051                FloatingActionButton::new(Some(Listener::new(|_| {})))
5052                    .key(KeyRef::from(key.clone()))
5053                    .into_widget()
5054            };
5055            let one = || {
5056                vec![destination(
5057                    Icons::favorite_border(),
5058                    Icons::favorite(),
5059                    "Abc",
5060                )]
5061            };
5062            let two = || {
5063                vec![
5064                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
5065                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
5066                ]
5067            };
5068            let key_at = |tester: &WidgetTester, key: &GlobalKey| {
5069                global_top_left(tester, render_box_of_key(tester, key))
5070            };
5071            let icon_at = |tester: &WidgetTester, icon: IconData| {
5072                global_top_left(tester, icon_render_box(tester, icon))
5073            };
5074            let label_at = |tester: &WidgetTester, text: &str| {
5075                global_top_left(tester, label_render_box(tester, text))
5076            };
5077
5078            pump_rail_in_app_with(tester, NavigationRail::new(Vec::new(), None), false);
5079
5080            // empty destinations and leading widget
5081            pump_rail_in_app_with(
5082                tester,
5083                NavigationRail::new(Vec::new(), None).leading(fab(&leading_widget_key)),
5084                false,
5085            );
5086            tester.pump_and_settle();
5087            assert_eq!(key_at(tester, &leading_widget_key), Offset::new(0.0, 8.0));
5088
5089            // one destination and leading widget
5090            pump_rail_in_app_with(
5091                tester,
5092                NavigationRail::new(one(), None).leading(fab(&leading_widget_key)),
5093                false,
5094            );
5095            tester.pump_and_settle();
5096            assert_offset(
5097                icon_at(tester, Icons::favorite_border()),
5098                Offset::new(24.0, 96.0),
5099            );
5100            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 72.0));
5101            assert_offset(key_at(tester, &leading_widget_key), Offset::new(8.0, 8.0));
5102
5103            // two destinations and leading widget
5104            pump_rail_in_app_with(
5105                tester,
5106                NavigationRail::new(two(), None).leading(fab(&leading_widget_key)),
5107                false,
5108            );
5109            tester.pump_and_settle();
5110            assert_offset(
5111                icon_at(tester, Icons::favorite_border()),
5112                Offset::new(24.0, 96.0),
5113            );
5114            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 72.0));
5115            assert_offset(
5116                icon_at(tester, Icons::bookmark_border()),
5117                Offset::new(24.0, 168.0),
5118            );
5119            assert_offset(label_at(tester, "Longer Label"), Offset::new(0.0, 144.0));
5120            assert_offset(key_at(tester, &leading_widget_key), Offset::new(8.0, 8.0));
5121
5122            // empty destinations and trailing widget
5123            pump_rail_in_app_with(
5124                tester,
5125                NavigationRail::new(Vec::new(), None).trailing(fab(&trailing_widget_key)),
5126                false,
5127            );
5128            tester.pump_and_settle();
5129            assert_eq!(key_at(tester, &trailing_widget_key), Offset::new(0.0, 8.0));
5130
5131            // one destination and trailing widget
5132            pump_rail_in_app_with(
5133                tester,
5134                NavigationRail::new(one(), None).trailing(fab(&trailing_widget_key)),
5135                false,
5136            );
5137            tester.pump_and_settle();
5138            assert_offset(
5139                icon_at(tester, Icons::favorite_border()),
5140                Offset::new(24.0, 32.0),
5141            );
5142            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 8.0));
5143            assert_offset(key_at(tester, &trailing_widget_key), Offset::new(8.0, 80.0));
5144
5145            // two destinations and trailing widget
5146            pump_rail_in_app_with(
5147                tester,
5148                NavigationRail::new(two(), None).trailing(fab(&trailing_widget_key)),
5149                false,
5150            );
5151            tester.pump_and_settle();
5152            assert_offset(
5153                icon_at(tester, Icons::favorite_border()),
5154                Offset::new(24.0, 32.0),
5155            );
5156            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 8.0));
5157            assert_offset(
5158                icon_at(tester, Icons::bookmark_border()),
5159                Offset::new(24.0, 104.0),
5160            );
5161            assert_offset(label_at(tester, "Longer Label"), Offset::new(0.0, 80.0));
5162            assert_offset(
5163                key_at(tester, &trailing_widget_key),
5164                Offset::new(8.0, 152.0),
5165            );
5166        });
5167    }
5168
5169    #[test]
5170    fn material_2_change_destinations_and_selected_index() {
5171        test_widgets(|tester| {
5172            let two = || {
5173                vec![
5174                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
5175                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
5176                ]
5177            };
5178            pump_rail_in_app_with(tester, NavigationRail::new(Vec::new(), None), false);
5179
5180            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 0);
5181            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);
5182
5183            pump_rail_in_app_with(tester, NavigationRail::new(two(), None), false);
5184            tester.pump_and_settle();
5185
5186            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
5187            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);
5188
5189            pump_rail_in_app_with(tester, NavigationRail::new(two(), Some(0)), false);
5190            tester.pump_and_settle();
5191
5192            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
5193            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
5194
5195            pump_rail_in_app_with(
5196                tester,
5197                NavigationRail::new(
5198                    vec![destination(
5199                        Icons::favorite_border(),
5200                        Icons::favorite(),
5201                        "Abc",
5202                    )],
5203                    Some(0),
5204                ),
5205                false,
5206            );
5207            tester.pump_and_settle();
5208
5209            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 1);
5210            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
5211        });
5212    }
5213
5214    #[test]
5215    fn material_2_leading_and_trailing_appear_in_the_correct_places() {
5216        test_widgets(|tester| {
5217            pump_navigation_rail_with(
5218                tester,
5219                NavigationRail::new(destinations(), Some(0))
5220                    .leading(fab())
5221                    .trailing(fab()),
5222                m2(),
5223            );
5224
5225            let fabs = find::by_type::<FloatingActionButton>().evaluate(tester);
5226            let leading = tester.render_box_of(fabs[0]);
5227            let trailing = tester.render_box_of(fabs[1]);
5228            assert_eq!(
5229                global_top_left(tester, leading),
5230                Offset::new((72.0 - tester.get_size(leading).width()) / 2.0, 8.0)
5231            );
5232            assert_eq!(
5233                global_top_left(tester, trailing),
5234                Offset::new((72.0 - tester.get_size(trailing).width()) / 2.0, 360.0)
5235            );
5236        });
5237    }
5238
5239    #[test]
5240    fn material_2_extended_rail_animates_the_width_and_labels_appear_text_direction_rtl() {
5241        test_widgets(|tester| {
5242            pump_rtl_rail_with(tester, NavigationRail::new(destinations(), Some(0)), false);
5243
5244            let rail = rail_box(tester);
5245            assert_eq!(tester.get_size(rail).width(), 72.0);
5246            assert_eq!(global_top_left(tester, rail), Offset::new(728.0, 0.0));
5247
5248            pump_rtl_rail_with(
5249                tester,
5250                NavigationRail::new(destinations(), Some(0)).extended(true),
5251                false,
5252            );
5253            tester.pump_by(Duration::from_millis(100));
5254            assert_eq!(tester.get_size(rail).width(), 164.0);
5255            assert_eq!(global_top_left(tester, rail), Offset::new(636.0, 0.0));
5256
5257            tester.pump_and_settle();
5258            assert_eq!(tester.get_size(rail).width(), 256.0);
5259            assert_eq!(global_top_left(tester, rail), Offset::new(544.0, 0.0));
5260
5261            // The first destination is 8 from the top because of the default vertical
5262            // padding at the to of the rail; each next one is 72 below the one before.
5263            let mut next_destination_y = 8.0;
5264            for (icon, label) in icons_in_order()
5265                .into_iter()
5266                .zip(["Abc", "Def", "Ghi", "Jkl"])
5267            {
5268                let icon = icon_render_box(tester, icon);
5269                let icon_size = tester.get_size(icon);
5270                assert_offset(
5271                    global_top_left(tester, icon),
5272                    Offset::new(
5273                        800.0 - (72.0 + icon_size.width()) / 2.0,
5274                        next_destination_y + (72.0 - icon_size.height()) / 2.0,
5275                    ),
5276                );
5277                let label = label_render_box(tester, label);
5278                let label_size = tester.get_size(label);
5279                assert_offset(
5280                    global_top_left(tester, label),
5281                    Offset::new(
5282                        800.0 - 72.0 - label_size.width(),
5283                        next_destination_y + (72.0 - label_size.height()) / 2.0,
5284                    ),
5285                );
5286                next_destination_y += 72.0;
5287            }
5288        });
5289    }
5290
5291    #[test]
5292    fn material_2_extended_rail_gets_wider_with_longer_labels_are_larger_text_scale() {
5293        test_widgets(|tester| {
5294            let pump = |tester: &mut WidgetTester, extended: bool| {
5295                let root = {
5296                    let app = tester.cell.borrow();
5297                    material_app(
5298                        theme(&app, false),
5299                        Scaffold::new()
5300                            .body(
5301                                Row::new().children([
5302                                    MediaQuery::with_clamped_text_scaling(
5303                                        None,
5304                                        3.0,
5305                                        3.0,
5306                                        NavigationRail::new(abc_and_longer_label(), Some(0))
5307                                            .extended(extended),
5308                                    ),
5309                                    Expanded::new(Text::new("body")).into_widget(),
5310                                ]),
5311                            )
5312                            .into_widget(),
5313                    )
5314                };
5315                tester.pump_widget(root);
5316            };
5317            pump(tester, false);
5318
5319            let rail = rail_box(tester);
5320            assert_eq!(tester.get_size(rail).width(), 72.0);
5321
5322            pump(tester, true);
5323            tester.pump_by(Duration::from_millis(100));
5324            assert_eq!(tester.get_size(rail).width(), 328.0);
5325
5326            tester.pump_and_settle();
5327            assert_eq!(tester.get_size(rail).width(), 584.0);
5328        });
5329    }
5330
5331    /// Regression test for https://github.com/flutter/flutter/issues/65657
5332    #[test]
5333    fn material_2_extended_rail_transition_does_not_jump_from_the_beginning() {
5334        test_widgets(|tester| {
5335            pump_rail_in_app_with(
5336                tester,
5337                NavigationRail::new(abc_and_longer_label(), Some(0)),
5338                false,
5339            );
5340
5341            // Before starting the animation, the rail has a width of 72.
5342            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);
5343
5344            pump_rail_in_app_with(
5345                tester,
5346                NavigationRail::new(abc_and_longer_label(), Some(0)).extended(true),
5347                false,
5348            );
5349            // Create very close to 0, but non-zero, animation value.
5350            tester.pump_by(Duration::from_millis(1));
5351            let width = tester.get_size(rail_box(tester)).width();
5352            // Expect that it has started to extend.
5353            assert!(width > 72.0, "{width}");
5354            // Expect that it has only extended by a small amount, or that the first
5355            // frame does not jump. This helps verify that it is a smooth animation.
5356            assert!((width - 72.0).abs() <= 1.0, "{width}");
5357        });
5358    }
5359
5360    #[test]
5361    fn material_2_extended_rail_animates_the_width_and_labels_appear_text_direction_ltr() {
5362        test_widgets(|tester| {
5363            let pump = |tester: &mut WidgetTester, extended: bool| {
5364                let root = {
5365                    let app = tester.cell.borrow();
5366                    material_app(
5367                        theme(&app, false),
5368                        Scaffold::new()
5369                            .body(
5370                                Row::new().children([
5371                                    NavigationRail::new(destinations(), Some(0))
5372                                        .extended(extended)
5373                                        .into_widget(),
5374                                    Expanded::new(Text::new("body")).into_widget(),
5375                                ]),
5376                            )
5377                            .into_widget(),
5378                    )
5379                };
5380                tester.pump_widget(root);
5381            };
5382            pump(tester, false);
5383
5384            let rail = rail_box(tester);
5385            assert_eq!(tester.get_size(rail).width(), 72.0);
5386
5387            pump(tester, true);
5388            tester.pump_by(Duration::from_millis(100));
5389            assert_eq!(tester.get_size(rail).width(), 164.0);
5390
5391            tester.pump_and_settle();
5392            assert_eq!(tester.get_size(rail).width(), 256.0);
5393
5394            // The first destination is 8 from the top because of the default vertical
5395            // padding at the to of the rail; each next one is 72 below the one before.
5396            let mut next_destination_y = 8.0;
5397            for (icon, label) in icons_in_order()
5398                .into_iter()
5399                .zip(["Abc", "Def", "Ghi", "Jkl"])
5400            {
5401                expect_icon_at(
5402                    tester,
5403                    icon_render_box(tester, icon),
5404                    72.0,
5405                    72.0,
5406                    next_destination_y,
5407                );
5408                let label = label_render_box(tester, label);
5409                assert_offset(
5410                    global_top_left(tester, label),
5411                    Offset::new(
5412                        72.0,
5413                        next_destination_y + (72.0 - tester.get_size(label).height()) / 2.0,
5414                    ),
5415                );
5416                next_destination_y += 72.0;
5417            }
5418        });
5419    }
5420
5421    #[test]
5422    fn material_2_navigation_rail_destination_adds_circular_indicator_when_no_labels_are_present() {
5423        test_widgets(|tester| {
5424            pump_navigation_rail_with(
5425                tester,
5426                NavigationRail::new(abc_def_ghi(), Some(0))
5427                    .use_indicator(true)
5428                    .label_type(NavigationRailLabelType::None),
5429                m2(),
5430            );
5431
5432            let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[0];
5433            let (width, height) = tester.widget(indicator, |indicator: &NavigationIndicator| {
5434                (indicator.width, indicator.height)
5435            });
5436            assert_eq!(width, 56.0);
5437            assert_eq!(height, 56.0);
5438        });
5439    }
5440
5441    #[test]
5442    fn material_2_navigation_rail_destination_has_center_aligned_indicator_label_type_none() {
5443        has_center_aligned_indicator(false, 24.0);
5444    }
5445
5446    #[test]
5447    fn material_2_navigation_rail_respects_the_notch_system_navigation_bar_in_landscape_mode() {
5448        respects_the_notch(false, 72.0);
5449    }
5450}