Skip to main content

waft_material/
navigation_bar.rs

1//! Flutter counterpart: material_ui's `navigation_bar.dart` (and its part
2//! `generated/navigation_bar_defaults_m3.g.dart`).
3
4use std::any::Any;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{
10    Animatable, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
11    AnimationStatusListener, AnyAnimation, Curve, CurveTween, Curves, Drive, Tween,
12    k_always_complete_animation, k_always_dismissed_animation,
13};
14use waft_embedder::{Color, Offset, Radius, SemanticsRole, Size};
15use waft_foundation::{
16    App, Handle, K_IS_WEB, Listenable, Listener, OptionRetained, Ref, ValueChanged, ValueKey,
17};
18use waft_painting::{
19    AlignmentGeometry, BorderRadius, BorderSide, EdgeInsetsGeometry, RoundedRectangleBorder,
20    ShapeBorderRef, ShapeDecoration, TextStyle,
21};
22use waft_rendering::{
23    AnyRenderBox, BoxConstraints, ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
24};
25use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
26use waft_widgets::{
27    AnimatedBuilder, BuildContext, CustomMultiChildLayout, Expanded, FadeTransition, GlobalKey,
28    IconTheme, IconThemeData, InheritedWidget, IntoWidget, KeyRef, KeyedSubtree, LayoutId, Matrix4,
29    MediaQuery, MergeSemantics, Padding, Row, SafeArea, Semantics, SingleTickerProviderStateMixin,
30    SingleTickerProviderStateMixinData, SizedBox, Stack, State, StateData, StatefulWidget,
31    StatelessWidget, StatusTransitionWidget, Text, Transform, TransitionBuilder, WidgetBuilder,
32    WidgetRef, WidgetState, WidgetStatePropertyRef, WidgetStates,
33};
34
35use crate::colors::Colors;
36use crate::elevation_overlay::ElevationOverlay;
37use crate::generated::navigation_bar_defaults_m3::NavigationBarDefaultsM3;
38use crate::ink_decoration::Ink;
39use crate::ink_well::InkResponse;
40use crate::material::{Material, RectCallback};
41use crate::material_localizations::MaterialLocalizations;
42#[allow(deprecated)]
43use crate::material_state::MaterialStatePropertyAll;
44use crate::navigation_bar_theme::{
45    NavigationBarTheme, NavigationBarThemeData, NavigationBarThemeDataGetters,
46};
47use crate::theme::Theme;
48use crate::theme_data_getters::DefaultsContext;
49use crate::tooltip::Tooltip;
50
51const K_INDICATOR_HEIGHT: f64 = 32.0;
52const K_INDICATOR_WIDTH: f64 = 64.0;
53const K_MAX_LABEL_TEXT_SCALE_FACTOR: f64 = 1.3;
54
55/// Material 3 Navigation Bar component.
56///
57/// Learn more about [`NavigationBar`] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=DVGYddFaLv0).
58///
59/// Navigation bars offer a persistent and convenient way to switch between
60/// primary destinations in an app.
61///
62/// This widget does not adjust its size with the `ThemeData::visual_density`.
63///
64/// The `MediaQueryData::text_scaler` does not adjust the size of this widget but
65/// rather the size of the [`Tooltip`]s displayed on long presses of the
66/// destinations.
67///
68/// The style for the icons and text are not affected by parent
69/// `DefaultTextStyle`s or [`IconTheme`]s but rather controlled by parameters or
70/// the [`NavigationBarThemeData`].
71///
72/// This widget holds a collection of destinations (usually
73/// [`NavigationDestination`]s).
74///
75/// See also:
76///
77///  * [`NavigationDestination`]
78///  * `BottomNavigationBar`
79///  * <https://api.flutter.dev/flutter/material/NavigationDestination-class.html>
80///  * <https://m3.material.io/components/navigation-bar>
81pub struct NavigationBar {
82    pub key: Option<KeyRef>,
83
84    /// Determines the transition time for each destination as it goes between
85    /// selected and unselected.
86    pub animation_duration: Option<Duration>,
87
88    /// Determines which one of the [`destinations`](Self::destinations) is currently selected.
89    ///
90    /// When this is updated, the destination (from [`destinations`](Self::destinations)) at
91    /// [`selected_index`](Self::selected_index) goes from unselected to selected.
92    pub selected_index: usize,
93
94    /// The list of destinations (usually [`NavigationDestination`]s) in this
95    /// [`NavigationBar`].
96    ///
97    /// When [`selected_index`](Self::selected_index) is updated, the destination from this
98    /// list at [`selected_index`](Self::selected_index) will animate from 0 (unselected) to
99    /// 1.0 (selected). When the animation is increasing or completed, the destination is
100    /// considered selected, when the animation is decreasing or dismissed, the destination
101    /// is considered unselected.
102    pub destinations: Vec<WidgetRef>,
103
104    /// Called when one of the [`destinations`](Self::destinations) is selected.
105    ///
106    /// This callback usually updates the int passed to [`selected_index`](Self::selected_index).
107    ///
108    /// Upon updating [`selected_index`](Self::selected_index), the [`NavigationBar`] will be
109    /// rebuilt.
110    pub on_destination_selected: Option<ValueChanged<usize>>,
111
112    /// The color of the [`NavigationBar`] itself.
113    ///
114    /// If null, `NavigationBarThemeData::background_color` is used. If that
115    /// is also null, then if `ThemeData::use_material3` is true, the value is
116    /// `ColorScheme::surface_container`. If that is false, the default blends
117    /// `ColorScheme::surface` and `ColorScheme::on_surface` using an [`ElevationOverlay`].
118    pub background_color: Option<Color>,
119
120    /// The elevation of the [`NavigationBar`] itself.
121    ///
122    /// If null, `NavigationBarThemeData::elevation` is used. If that
123    /// is also null, then if `ThemeData::use_material3` is true then it will
124    /// be 3.0 otherwise 0.0.
125    pub elevation: Option<f64>,
126
127    /// The color used for the drop shadow to indicate elevation.
128    ///
129    /// If null, `NavigationBarThemeData::shadow_color` is used. If that
130    /// is also null, the default value is `Colors::TRANSPARENT` which
131    /// indicates that no drop shadow will be displayed.
132    ///
133    /// See `Material::shadow_color` for more details on drop shadows.
134    pub shadow_color: Option<Color>,
135
136    /// The color used as an overlay on [`background_color`](Self::background_color) to
137    /// indicate elevation.
138    ///
139    /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
140    /// introduced a set of tone-based surfaces and surface containers in its `ColorScheme`,
141    /// which provide more flexibility. The intention is to eventually remove surface tint color from
142    /// the framework.
143    ///
144    /// If null, `NavigationBarThemeData::surface_tint_color` is used. If that
145    /// is also null, the default value is `Colors::TRANSPARENT`.
146    ///
147    /// See `Material::surface_tint_color` for more details on how this
148    /// overlay is applied.
149    pub surface_tint_color: Option<Color>,
150
151    /// The color of the [`indicator_shape`](Self::indicator_shape) when this destination is
152    /// selected.
153    ///
154    /// If null, `NavigationBarThemeData::indicator_color` is used. If that
155    /// is also null and `ThemeData::use_material3` is true, `ColorScheme::secondary_container`
156    /// is used. Otherwise, `ColorScheme::secondary` with an opacity of 0.24 is used.
157    pub indicator_color: Option<Color>,
158
159    /// The shape of the selected indicator.
160    ///
161    /// If null, `NavigationBarThemeData::indicator_shape` is used. If that
162    /// is also null and `ThemeData::use_material3` is true, `StadiumBorder` is used.
163    /// Otherwise, [`RoundedRectangleBorder`] with a circular border radius of 16 is used.
164    pub indicator_shape: Option<ShapeBorderRef>,
165
166    /// The height of the [`NavigationBar`] itself.
167    ///
168    /// If this is used in `Scaffold::bottom_navigation_bar` and the scaffold is
169    /// full-screen, the safe area padding is also added to the height
170    /// automatically.
171    ///
172    /// The height does not adjust with `ThemeData::visual_density` or
173    /// `MediaQueryData::text_scaler` as this component loses usability at
174    /// larger and smaller sizes due to the truncating of labels or smaller tap
175    /// targets.
176    ///
177    /// If null, `NavigationBarThemeData::height` is used. If that
178    /// is also null, the default is 80.
179    pub height: Option<f64>,
180
181    /// Defines how the [`destinations`](Self::destinations)' labels will be laid out and when
182    /// they'll be displayed.
183    ///
184    /// Can be used to show all labels, show only the selected label, or hide all
185    /// labels.
186    ///
187    /// If null, `NavigationBarThemeData::label_behavior` is used. If that
188    /// is also null, the default is
189    /// [`NavigationDestinationLabelBehavior::AlwaysShow`].
190    pub label_behavior: Option<NavigationDestinationLabelBehavior>,
191
192    /// The highlight color that's typically used to indicate that
193    /// the [`NavigationDestination`] is focused, hovered, or pressed.
194    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
195
196    /// The text style of the label.
197    ///
198    /// If null, `NavigationBarThemeData::label_text_style` is used. If that
199    /// is also null, the default text style is `TextTheme::label_medium` with
200    /// `ColorScheme::on_surface` when the destination is selected, and
201    /// `ColorScheme::on_surface_variant` when the destination is unselected, and
202    /// `ColorScheme::on_surface_variant` with an opacity of 0.38 when the
203    /// destination is disabled.
204    ///
205    /// If `ThemeData::use_material3` is false, then the default text style is
206    /// `TextTheme::label_small` with `ColorScheme::on_surface`.
207    pub label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
208
209    /// The padding around the `NavigationDestination::label` widget.
210    ///
211    /// When [`label_padding`](Self::label_padding) is null,
212    /// `NavigationBarThemeData::label_padding` is used. If that is also null, the default
213    /// padding is 4 pixels on the top.
214    pub label_padding: Option<EdgeInsetsGeometry>,
215
216    /// Specifies whether the underlying [`SafeArea`] should maintain the bottom
217    /// `MediaQueryData::view_padding` instead of the bottom `MediaQueryData::padding`.
218    ///
219    /// When true, this will prevent the [`NavigationBar`] from shifting when opening a
220    /// software keyboard due to the change in the padding value, especially when the
221    /// app uses `SystemUiMode::EdgeToEdge`, which renders the system bars over the
222    /// application instead of outside it.
223    ///
224    /// Defaults to false.
225    ///
226    /// See also:
227    ///
228    ///  * `SafeArea::maintain_bottom_view_padding`, which specifies whether the [`SafeArea`]
229    ///    should maintain the bottom `MediaQueryData::view_padding`.
230    ///  * `SystemUiMode::EdgeToEdge`, which sets a fullscreen display with status and
231    ///    navigation elements rendered over the application.
232    pub maintain_bottom_view_padding: bool,
233}
234
235impl NavigationBar {
236    /// Creates a Material 3 Navigation Bar component.
237    ///
238    /// The value of [`destinations`](Self::destinations) must be a list of two or more
239    /// [`NavigationDestination`] values.
240    pub fn new(destinations: impl IntoIterator<Item = WidgetRef>) -> NavigationBar {
241        NavigationBar {
242            key: None,
243            animation_duration: None,
244            selected_index: 0,
245            destinations: destinations.into_iter().collect(),
246            on_destination_selected: None,
247            background_color: None,
248            elevation: None,
249            shadow_color: None,
250            surface_tint_color: None,
251            indicator_color: None,
252            indicator_shape: None,
253            height: None,
254            label_behavior: None,
255            overlay_color: None,
256            label_text_style: None,
257            label_padding: None,
258            maintain_bottom_view_padding: false,
259        }
260    }
261
262    /// Dart `NavigationBar(key:)`.
263    pub fn key(mut self, key: KeyRef) -> NavigationBar {
264        self.key = Some(key);
265        self
266    }
267
268    /// Dart `NavigationBar(animationDuration:)`.
269    pub fn animation_duration(mut self, animation_duration: Duration) -> NavigationBar {
270        self.animation_duration = Some(animation_duration);
271        self
272    }
273
274    /// Dart `NavigationBar(selectedIndex:)`.
275    pub fn selected_index(mut self, selected_index: usize) -> NavigationBar {
276        self.selected_index = selected_index;
277        self
278    }
279
280    /// Dart `NavigationBar(onDestinationSelected:)`.
281    pub fn on_destination_selected(
282        mut self,
283        on_destination_selected: impl Fn(&mut App, usize) + 'static,
284    ) -> NavigationBar {
285        self.on_destination_selected = Some(Rc::new(on_destination_selected));
286        self
287    }
288
289    /// Dart `NavigationBar(backgroundColor:)`.
290    pub fn background_color(mut self, background_color: Color) -> NavigationBar {
291        self.background_color = Some(background_color);
292        self
293    }
294
295    /// Dart `NavigationBar(elevation:)`.
296    pub fn elevation(mut self, elevation: f64) -> NavigationBar {
297        self.elevation = Some(elevation);
298        self
299    }
300
301    /// Dart `NavigationBar(shadowColor:)`.
302    pub fn shadow_color(mut self, shadow_color: Color) -> NavigationBar {
303        self.shadow_color = Some(shadow_color);
304        self
305    }
306
307    /// Dart `NavigationBar(surfaceTintColor:)`.
308    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> NavigationBar {
309        self.surface_tint_color = Some(surface_tint_color);
310        self
311    }
312
313    /// Dart `NavigationBar(indicatorColor:)`.
314    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationBar {
315        self.indicator_color = Some(indicator_color);
316        self
317    }
318
319    /// Dart `NavigationBar(indicatorShape:)`.
320    pub fn indicator_shape(mut self, indicator_shape: impl Into<ShapeBorderRef>) -> NavigationBar {
321        self.indicator_shape = Some(indicator_shape.into());
322        self
323    }
324
325    /// Dart `NavigationBar(height:)`.
326    pub fn height(mut self, height: f64) -> NavigationBar {
327        self.height = Some(height);
328        self
329    }
330
331    /// Dart `NavigationBar(labelBehavior:)`.
332    pub fn label_behavior(
333        mut self,
334        label_behavior: NavigationDestinationLabelBehavior,
335    ) -> NavigationBar {
336        self.label_behavior = Some(label_behavior);
337        self
338    }
339
340    /// Dart `NavigationBar(overlayColor:)`.
341    pub fn overlay_color(
342        mut self,
343        overlay_color: WidgetStatePropertyRef<Option<Color>>,
344    ) -> NavigationBar {
345        self.overlay_color = Some(overlay_color);
346        self
347    }
348
349    /// Dart `NavigationBar(labelTextStyle:)`.
350    pub fn label_text_style(
351        mut self,
352        label_text_style: WidgetStatePropertyRef<Option<TextStyle>>,
353    ) -> NavigationBar {
354        self.label_text_style = Some(label_text_style);
355        self
356    }
357
358    /// Dart `NavigationBar(labelPadding:)`.
359    pub fn label_padding(mut self, label_padding: impl Into<EdgeInsetsGeometry>) -> NavigationBar {
360        self.label_padding = Some(label_padding.into());
361        self
362    }
363
364    /// Dart `NavigationBar(maintainBottomViewPadding:)`.
365    pub fn maintain_bottom_view_padding(
366        mut self,
367        maintain_bottom_view_padding: bool,
368    ) -> NavigationBar {
369        self.maintain_bottom_view_padding = maintain_bottom_view_padding;
370        self
371    }
372
373    fn handle_tap(on_destination_selected: Option<&ValueChanged<usize>>, index: usize) -> Listener {
374        match on_destination_selected.cloned() {
375            Some(on_destination_selected) => {
376                Listener::new(move |app| on_destination_selected(app, index))
377            }
378            None => Listener::new(|_app| {}),
379        }
380    }
381}
382
383impl Debug for NavigationBar {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        f.debug_struct("NavigationBar")
386            .field("animation_duration", &self.animation_duration)
387            .field("selected_index", &self.selected_index)
388            .field("destinations", &self.destinations)
389            .field("background_color", &self.background_color)
390            .field("elevation", &self.elevation)
391            .field("shadow_color", &self.shadow_color)
392            .field("surface_tint_color", &self.surface_tint_color)
393            .field("indicator_color", &self.indicator_color)
394            .field("indicator_shape", &self.indicator_shape)
395            .field("height", &self.height)
396            .field("label_behavior", &self.label_behavior)
397            .field("label_padding", &self.label_padding)
398            .field(
399                "maintain_bottom_view_padding",
400                &self.maintain_bottom_view_padding,
401            )
402            .finish_non_exhaustive()
403    }
404}
405
406impl StatelessWidget for NavigationBar {
407    fn key(&self) -> Option<&KeyRef> {
408        self.key.as_ref()
409    }
410
411    fn debug_check_constructor(&self) {
412        debug_assert!(self.destinations.len() >= 2);
413        debug_assert!(self.selected_index < self.destinations.len());
414    }
415
416    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
417        let defaults = defaults_for(app, context);
418
419        let navigation_bar_theme = NavigationBarTheme::of(app, context);
420        let effective_height = self
421            .height
422            .or(navigation_bar_theme.height)
423            .or_else(|| defaults.height(app))
424            .expect("the defaults give a height");
425        let effective_label_behavior = self
426            .label_behavior
427            .or(navigation_bar_theme.label_behavior)
428            .or_else(|| defaults.label_behavior(app))
429            .expect("the defaults give a label behavior");
430
431        let mut material = Material::new()
432            .color(
433                self.background_color
434                    .or(navigation_bar_theme.background_color)
435                    .or_else(|| defaults.background_color(app))
436                    .expect("the defaults give a background color"),
437            )
438            .elevation(
439                self.elevation
440                    .or(navigation_bar_theme.elevation)
441                    .or_else(|| defaults.elevation(app))
442                    .expect("the defaults give an elevation"),
443            );
444        material.shadow_color = self
445            .shadow_color
446            .or(navigation_bar_theme.shadow_color)
447            .or_else(|| defaults.shadow_color(app));
448        material.surface_tint_color = self
449            .surface_tint_color
450            .or(navigation_bar_theme.surface_tint_color)
451            .or_else(|| defaults.surface_tint_color(app));
452
453        let destination_count = self.destinations.len();
454        let destinations = (0..destination_count).map(|i| {
455            let selected_index = self.selected_index;
456            let indicator_color = self.indicator_color;
457            let indicator_shape = self.indicator_shape.clone();
458            let overlay_color = self.overlay_color.clone();
459            let on_destination_selected = self.on_destination_selected.clone();
460            let label_text_style = self.label_text_style.clone();
461            let label_padding = self.label_padding;
462            let destination = self.destinations[i].clone();
463            Expanded::new(
464                MergeSemantics::new().child(
465                    Semantics::new()
466                        .role(SemanticsRole::Tab)
467                        .selected(i == selected_index)
468                        .child(
469                            SelectableAnimatedBuilder::new(
470                                i == selected_index,
471                                move |_app, _context, animation| {
472                                    NavigationDestinationInfo {
473                                        index: i,
474                                        selected_index,
475                                        total_number_of_destinations: destination_count,
476                                        selected_animation: animation,
477                                        label_behavior: effective_label_behavior,
478                                        indicator_color,
479                                        indicator_shape: indicator_shape.clone(),
480                                        overlay_color: overlay_color.clone(),
481                                        on_tap: NavigationBar::handle_tap(
482                                            on_destination_selected.as_ref(),
483                                            i,
484                                        ),
485                                        label_text_style: label_text_style.clone(),
486                                        label_padding,
487                                        child: destination.clone(),
488                                    }
489                                    .into_widget()
490                                },
491                            )
492                            .duration(
493                                self.animation_duration
494                                    .unwrap_or(Duration::from_millis(500)),
495                            ),
496                        ),
497                ),
498            )
499            .into_widget()
500        });
501
502        material
503            .child(
504                SafeArea::new(
505                    Semantics::new()
506                        .role(SemanticsRole::TabBar)
507                        .explicit_child_nodes(true)
508                        .container(true)
509                        .child(
510                            SizedBox::new()
511                                .height(effective_height)
512                                .child(Row::new().children(destinations.collect::<Vec<_>>())),
513                        ),
514                )
515                .maintain_bottom_view_padding(self.maintain_bottom_view_padding),
516            )
517            .into_widget()
518    }
519}
520
521/// Specifies when each `NavigationDestination`'s label should appear.
522///
523/// This is used to determine the behavior of `NavigationBar`'s destinations.
524#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
525pub enum NavigationDestinationLabelBehavior {
526    /// Always shows all of the labels under each navigation bar destination,
527    /// selected and unselected.
528    AlwaysShow,
529
530    /// Never shows any of the labels under the navigation bar destinations,
531    /// regardless of selected vs unselected.
532    AlwaysHide,
533
534    /// Only shows the labels of the selected navigation bar destination.
535    ///
536    /// When a destination is unselected, the label will be faded out, and the
537    /// icon will be centered.
538    ///
539    /// When a destination is selected, the label will fade in and the label and
540    /// icon will slide up so that they are both centered.
541    OnlyShowSelected,
542}
543
544/// A Material 3 [`NavigationBar`] destination.
545///
546/// Displays a label below an icon. Use with [`NavigationBar::destinations`].
547///
548/// See also:
549///
550///  * [`NavigationBar`], for an interactive code sample.
551#[derive(Debug)]
552pub struct NavigationDestination {
553    pub key: Option<KeyRef>,
554
555    /// The [`WidgetRef`] (usually an `Icon`) that's displayed for this
556    /// [`NavigationDestination`].
557    ///
558    /// The icon will use `NavigationBarThemeData::icon_theme`. If this is
559    /// null, the default [`IconThemeData`] would use a size of 24.0 and
560    /// `ColorScheme::on_surface`.
561    pub icon: WidgetRef,
562
563    /// The optional [`WidgetRef`] (usually an `Icon`) that's displayed when this
564    /// [`NavigationDestination`] is selected.
565    ///
566    /// If [`selected_icon`](Self::selected_icon) is non-null, the destination will fade from
567    /// [`icon`](Self::icon) to [`selected_icon`](Self::selected_icon) when this destination
568    /// goes from unselected to selected.
569    ///
570    /// The icon will use `NavigationBarThemeData::icon_theme` with
571    /// [`WidgetState::Selected`]. If this is null, the default [`IconThemeData`]
572    /// would use a size of 24.0 and `ColorScheme::on_surface`.
573    pub selected_icon: Option<WidgetRef>,
574
575    /// The text label that appears below the icon of this
576    /// [`NavigationDestination`].
577    ///
578    /// The accompanying [`Text`] widget will use `NavigationBarThemeData::label_text_style`.
579    /// If this is null, the default text style will use `TextTheme::label_medium` with
580    /// `ColorScheme::on_surface` when the destination is selected and
581    /// `ColorScheme::on_surface_variant` when the destination is unselected. If
582    /// `ThemeData::use_material3` is false, then the default text style will use
583    /// `TextTheme::label_small` with `ColorScheme::on_surface`.
584    pub label: String,
585
586    /// The text to display in the tooltip for this [`NavigationDestination`], when
587    /// the user long presses the destination.
588    ///
589    /// If [`tooltip`](Self::tooltip) is an empty string, no tooltip will be used.
590    ///
591    /// Defaults to null, in which case the [`label`](Self::label) text will be used.
592    pub tooltip: Option<String>,
593
594    /// Indicates that this destination is selectable.
595    ///
596    /// Defaults to true.
597    pub enabled: bool,
598}
599
600impl NavigationDestination {
601    /// Creates a navigation bar destination with an icon and a label, to be used
602    /// in the [`NavigationBar::destinations`].
603    #[cfg_attr(debug_assertions, track_caller)]
604    pub fn new<K>(icon: impl IntoWidget<K>, label: impl Into<String>) -> NavigationDestination {
605        NavigationDestination {
606            key: None,
607            icon: icon.into_widget(),
608            selected_icon: None,
609            label: label.into(),
610            tooltip: None,
611            enabled: true,
612        }
613    }
614
615    /// Dart `NavigationDestination(key:)`.
616    pub fn key(mut self, key: KeyRef) -> NavigationDestination {
617        self.key = Some(key);
618        self
619    }
620
621    /// Dart `NavigationDestination(selectedIcon:)`.
622    #[cfg_attr(debug_assertions, track_caller)]
623    pub fn selected_icon<K>(mut self, selected_icon: impl IntoWidget<K>) -> NavigationDestination {
624        self.selected_icon = Some(selected_icon.into_widget());
625        self
626    }
627
628    /// Dart `NavigationDestination(tooltip:)`.
629    pub fn tooltip(mut self, tooltip: impl Into<String>) -> NavigationDestination {
630        self.tooltip = Some(tooltip.into());
631        self
632    }
633
634    /// Dart `NavigationDestination(enabled:)`.
635    pub fn enabled(mut self, enabled: bool) -> NavigationDestination {
636        self.enabled = enabled;
637        self
638    }
639}
640
641impl StatelessWidget for NavigationDestination {
642    fn key(&self) -> Option<&KeyRef> {
643        self.key.as_ref()
644    }
645
646    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
647        let info = NavigationDestinationInfo::of(app, context);
648        let selected_state: WidgetStates = [WidgetState::Selected].into_iter().collect();
649        let unselected_state = WidgetStates::new();
650        let disabled_state: WidgetStates = [WidgetState::Disabled].into_iter().collect();
651
652        let navigation_bar_theme = NavigationBarTheme::of(app, context);
653        let defaults = defaults_for(app, context);
654        let animation = info.selected_animation.clone();
655
656        let enabled = self.enabled;
657        let icon = self.icon.clone();
658        let selected_icon = self.selected_icon.clone();
659        let build_icon = {
660            let navigation_bar_theme = navigation_bar_theme.clone();
661            let defaults = Rc::clone(&defaults);
662            let info = info.clone();
663            let animation = animation.clone();
664            let (selected_state, unselected_state, disabled_state) = (
665                selected_state.clone(),
666                unselected_state.clone(),
667                disabled_state.clone(),
668            );
669            move |app: &mut App, _context: BuildContext| {
670                let resolve_icon_theme = |app: &mut App, states: &WidgetStates| {
671                    navigation_bar_theme
672                        .icon_theme
673                        .as_ref()
674                        .and_then(|icon_theme| icon_theme.resolve(states))
675                        .unwrap_or_else(|| {
676                            defaults
677                                .icon_theme(app)
678                                .expect("the defaults give an icon theme")
679                                .resolve(states)
680                                .expect("the default icon theme resolves")
681                        })
682                };
683                let selected_icon_theme = resolve_icon_theme(app, &selected_state);
684                let unselected_icon_theme = resolve_icon_theme(app, &unselected_state);
685                let disabled_icon_theme = resolve_icon_theme(app, &disabled_state);
686
687                let selected_icon_widget = IconTheme::merge(
688                    None,
689                    if enabled {
690                        selected_icon_theme
691                    } else {
692                        disabled_icon_theme.clone()
693                    },
694                    selected_icon.clone().unwrap_or_else(|| icon.clone()),
695                );
696                let unselected_icon_widget = IconTheme::merge(
697                    None,
698                    if enabled {
699                        unselected_icon_theme
700                    } else {
701                        disabled_icon_theme
702                    },
703                    icon.clone(),
704                );
705
706                Stack::new()
707                    .alignment(AlignmentGeometry::CENTER)
708                    .children([
709                        NavigationIndicator::new(animation.clone())
710                            .color(
711                                info.indicator_color
712                                    .or(navigation_bar_theme.indicator_color)
713                                    .or_else(|| defaults.indicator_color(app))
714                                    .expect("the defaults give an indicator color"),
715                            )
716                            .shape(
717                                info.indicator_shape
718                                    .clone()
719                                    .or_else(|| navigation_bar_theme.indicator_shape.clone())
720                                    .or_else(|| defaults.indicator_shape(app))
721                                    .expect("the defaults give an indicator shape"),
722                            )
723                            .into_widget(),
724                        StatusTransitionWidgetBuilder::new(animation.clone(), {
725                            let animation = animation.clone();
726                            move |app, _context, _child| {
727                                if animation.is_forward_or_completed(app) {
728                                    selected_icon_widget.clone()
729                                } else {
730                                    unselected_icon_widget.clone()
731                                }
732                            }
733                        })
734                        .into_widget(),
735                    ])
736                    .into_widget()
737            }
738        };
739        let label = self.label.clone();
740        let build_label = move |app: &mut App, _context: BuildContext| {
741            let resolve_label_text_style = |app: &mut App, states: &WidgetStates| {
742                info.label_text_style
743                    .as_ref()
744                    .and_then(|style| style.resolve(states))
745                    .or_else(|| {
746                        navigation_bar_theme
747                            .label_text_style
748                            .as_ref()
749                            .and_then(|style| style.resolve(states))
750                    })
751                    .or_else(|| {
752                        defaults
753                            .label_text_style(app)
754                            .expect("the defaults give a label text style")
755                            .resolve(states)
756                    })
757            };
758            let effective_selected_label_text_style =
759                resolve_label_text_style(app, &selected_state);
760            let effective_unselected_label_text_style =
761                resolve_label_text_style(app, &unselected_state);
762            let effective_disabled_label_text_style =
763                resolve_label_text_style(app, &disabled_state);
764            let label_padding = info
765                .label_padding
766                .or(navigation_bar_theme.label_padding)
767                .or_else(|| defaults.label_padding(app))
768                .expect("the defaults give a label padding");
769
770            let text_style = if enabled {
771                if animation.is_forward_or_completed(app) {
772                    effective_selected_label_text_style
773                } else {
774                    effective_unselected_label_text_style
775                }
776            } else {
777                effective_disabled_label_text_style
778            };
779
780            let mut text = Text::new(label.clone());
781            if let Some(text_style) = text_style {
782                text = text.style(text_style);
783            }
784            Padding::new(label_padding)
785                .child(
786                    // Set maximum text scale factor to K_MAX_LABEL_TEXT_SCALE_FACTOR for the
787                    // label to keep the visual hierarchy the same even with larger font
788                    // sizes. To opt out, wrap the `label` widget in a `MediaQuery` widget
789                    // with a different `TextScaler`.
790                    MediaQuery::with_clamped_text_scaling(
791                        None,
792                        0.0,
793                        K_MAX_LABEL_TEXT_SCALE_FACTOR,
794                        text,
795                    ),
796                )
797                .into_widget()
798        };
799
800        NavigationDestinationBuilder {
801            build_icon: Rc::new(build_icon),
802            build_label: Rc::new(build_label),
803            label: self.label.clone(),
804            tooltip: self.tooltip.clone(),
805            enabled: self.enabled,
806        }
807        .into_widget()
808    }
809}
810
811/// Widget that handles the semantics and layout of a navigation bar
812/// destination.
813///
814/// Prefer [`NavigationDestination`] over this widget, as it is a simpler
815/// (although less customizable) way to get navigation bar destinations.
816///
817/// The icon and label of this destination are built with [`build_icon`](Self::build_icon)
818/// and [`build_label`](Self::build_label). They should build the unselected and selected icon
819/// and label according to [`NavigationDestinationInfo::selected_animation`], where an
820/// animation value of 0 is unselected and 1 is selected.
821///
822/// See [`NavigationDestination`] for an example.
823struct NavigationDestinationBuilder {
824    /// Builds the icon for a destination in a [`NavigationBar`].
825    ///
826    /// To animate between unselected and selected, build the icon based on
827    /// [`NavigationDestinationInfo::selected_animation`]. When the animation is 0,
828    /// the destination is unselected, when the animation is 1, the destination is
829    /// selected.
830    ///
831    /// The destination is considered selected as soon as the animation is
832    /// increasing or completed, and it is considered unselected as soon as the
833    /// animation is decreasing or dismissed.
834    build_icon: WidgetBuilder,
835
836    /// Builds the label for a destination in a [`NavigationBar`].
837    ///
838    /// To animate between unselected and selected, build the icon based on
839    /// [`NavigationDestinationInfo::selected_animation`]. When the animation is
840    /// 0, the destination is unselected, when the animation is 1, the destination
841    /// is selected.
842    ///
843    /// The destination is considered selected as soon as the animation is
844    /// increasing or completed, and it is considered unselected as soon as the
845    /// animation is decreasing or dismissed.
846    build_label: WidgetBuilder,
847
848    /// The text value of what is in the label widget, this is required for
849    /// semantics so that screen readers and tooltips can read the proper label.
850    label: String,
851
852    /// The text to display in the tooltip for this [`NavigationDestination`], when
853    /// the user long presses the destination.
854    ///
855    /// If [`tooltip`](Self::tooltip) is an empty string, no tooltip will be used.
856    ///
857    /// Defaults to null, in which case the [`label`](Self::label) text will be used.
858    tooltip: Option<String>,
859
860    /// Indicates that this destination is selectable.
861    ///
862    /// Defaults to true.
863    enabled: bool,
864}
865
866impl Debug for NavigationDestinationBuilder {
867    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
868        f.debug_struct("_NavigationDestinationBuilder")
869            .field("label", &self.label)
870            .field("tooltip", &self.tooltip)
871            .field("enabled", &self.enabled)
872            .finish_non_exhaustive()
873    }
874}
875
876impl StatefulWidget for NavigationDestinationBuilder {
877    type State = NavigationDestinationBuilderState;
878
879    fn create_state(&self) -> NavigationDestinationBuilderState {
880        NavigationDestinationBuilderState {
881            state: StateData::new(),
882            icon_key: GlobalKey::new(),
883        }
884    }
885}
886
887/// Dart's `_NavigationDestinationBuilderState`.
888struct NavigationDestinationBuilderState {
889    state: StateData<NavigationDestinationBuilder>,
890    icon_key: GlobalKey,
891}
892
893impl State for NavigationDestinationBuilderState {
894    type Widget = NavigationDestinationBuilder;
895    waft_widgets::state_accessors!();
896
897    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
898        let info = NavigationDestinationInfo::of(app, context);
899        let navigation_bar_theme = NavigationBarTheme::of(app, context);
900        let defaults = defaults_for(app, context);
901
902        let icon_key = app.get(self).icon_key.clone();
903        let widget = self.widget(app);
904        let enabled = widget.enabled;
905        let message = widget
906            .tooltip
907            .clone()
908            .unwrap_or_else(|| widget.label.clone());
909        let build_icon = Rc::clone(&widget.build_icon);
910        let build_label = Rc::clone(&widget.build_label);
911
912        let mut ink_well = IndicatorInkWell::new(icon_key.clone(), info.label_behavior);
913        if let Some(custom_border) = info
914            .indicator_shape
915            .clone()
916            .or_else(|| navigation_bar_theme.indicator_shape.clone())
917            .or_else(|| defaults.indicator_shape(app))
918        {
919            ink_well = ink_well.custom_border(custom_border);
920        }
921        if let Some(overlay_color) = info
922            .overlay_color
923            .clone()
924            .or_else(|| navigation_bar_theme.overlay_color.clone())
925        {
926            ink_well = ink_well.overlay_color(overlay_color);
927        }
928        if enabled {
929            ink_well = ink_well.on_tap(info.on_tap.clone());
930        }
931        let icon = build_icon(app, context);
932        let label = build_label(app, context);
933
934        NavigationBarDestinationSemantics::new(
935            enabled,
936            NavigationBarDestinationTooltip::new(
937                message,
938                ink_well.child(
939                    Row::new().children([Expanded::new(NavigationBarDestinationLayout {
940                        icon,
941                        icon_key,
942                        label,
943                    })
944                    .into_widget()]),
945                ),
946            ),
947        )
948        .into_widget()
949    }
950}
951
952/// Dart's `_IndicatorInkWell extends InkResponse`: an [`InkResponse`] whose highlight and
953/// splash are clipped to the icon's rectangle.
954#[derive(Debug)]
955struct IndicatorInkWell {
956    ink_response: InkResponse,
957    #[allow(dead_code, reason = "Dart keeps the field, which nothing reads")]
958    icon_key: GlobalKey,
959    #[allow(dead_code, reason = "Dart keeps the field, which nothing reads")]
960    label_behavior: NavigationDestinationLabelBehavior,
961}
962
963impl IndicatorInkWell {
964    fn new(
965        icon_key: GlobalKey,
966        label_behavior: NavigationDestinationLabelBehavior,
967    ) -> IndicatorInkWell {
968        let rect_icon_key = icon_key.clone();
969        let ink_response = InkResponse::new()
970            .contained_ink_well(true)
971            .highlight_color(Colors::TRANSPARENT)
972            .override_get_rect_callback(move |_app, reference_box| {
973                Some(IndicatorInkWell::get_rect_callback(
974                    rect_icon_key.clone(),
975                    reference_box,
976                ))
977            });
978        IndicatorInkWell {
979            ink_response,
980            icon_key,
981            label_behavior,
982        }
983    }
984
985    /// Dart's override of `getRectCallback`.
986    fn get_rect_callback(icon_key: GlobalKey, reference_box: AnyRenderBox) -> RectCallback {
987        Rc::new(move |app| {
988            let icon_box = icon_key
989                .current_context(app)
990                .expect("the icon is mounted")
991                .find_render_object(app)
992                .and_then(|render_object| render_object.as_box())
993                .expect("the icon has a render box");
994            let icon_rect = icon_box.local_to_global(app, Offset::ZERO, None) & icon_box.size(app);
995            reference_box.global_to_local(app, icon_rect.top_left(), None) & icon_box.size(app)
996        })
997    }
998
999    /// Dart `_IndicatorInkWell(overlayColor:)`.
1000    fn overlay_color(mut self, overlay_color: WidgetStatePropertyRef<Option<Color>>) -> Self {
1001        self.ink_response = self.ink_response.overlay_color(overlay_color);
1002        self
1003    }
1004
1005    /// Dart `_IndicatorInkWell(customBorder:)`.
1006    fn custom_border(mut self, custom_border: ShapeBorderRef) -> Self {
1007        self.ink_response = self.ink_response.custom_border(custom_border);
1008        self
1009    }
1010
1011    /// Dart `_IndicatorInkWell(onTap:)`.
1012    fn on_tap(mut self, on_tap: Listener) -> Self {
1013        self.ink_response = self.ink_response.on_tap(on_tap);
1014        self
1015    }
1016
1017    /// Dart `_IndicatorInkWell(child:)`.
1018    #[cfg_attr(debug_assertions, track_caller)]
1019    fn child<K>(mut self, child: impl IntoWidget<K>) -> Self {
1020        self.ink_response = self.ink_response.child(child);
1021        self
1022    }
1023}
1024
1025impl StatelessWidget for IndicatorInkWell {
1026    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1027        self.ink_response.clone().into_widget()
1028    }
1029}
1030
1031/// Inherited widget for passing data from the [`NavigationBar`] to the
1032/// [`NavigationBar::destinations`] children widgets.
1033///
1034/// Useful for building navigation destinations using:
1035/// `NavigationDestinationInfo::of(app, context)`.
1036#[derive(Clone)]
1037struct NavigationDestinationInfo {
1038    /// Which destination index is this in the navigation bar.
1039    ///
1040    /// For example:
1041    ///
1042    /// ```text
1043    /// NavigationBar::new([
1044    ///     // This is destination index 0.
1045    ///     NavigationDestination::new(Icon::new(Some(Icons::surfing())), "Surfing").into_widget(),
1046    ///     // This is destination index 1.
1047    ///     NavigationDestination::new(Icon::new(Some(Icons::support())), "Support").into_widget(),
1048    ///     // This is destination index 2.
1049    ///     NavigationDestination::new(Icon::new(Some(Icons::local_hospital())), "Hospital")
1050    ///         .into_widget(),
1051    /// ])
1052    /// ```
1053    ///
1054    /// This is required for semantics, so that each destination can have a label
1055    /// "Tab 1 of 3", for example.
1056    index: usize,
1057
1058    /// This is the index of the currently selected destination.
1059    ///
1060    /// This is required for `IndicatorInkWell` to apply label padding to ripple animations
1061    /// when label behavior is [`NavigationDestinationLabelBehavior::OnlyShowSelected`].
1062    #[allow(dead_code, reason = "Dart keeps the field, which nothing reads")]
1063    selected_index: usize,
1064
1065    /// How many total destinations are in this navigation bar.
1066    ///
1067    /// This is required for semantics, so that each destination can have a label
1068    /// "Tab 1 of 4", for example.
1069    total_number_of_destinations: usize,
1070
1071    /// Indicates whether or not this destination is selected, from 0 (unselected)
1072    /// to 1 (selected).
1073    selected_animation: AnimationRef<f64>,
1074
1075    /// Determines the behavior for how the labels will layout.
1076    ///
1077    /// Can be used to show all labels (the default), show only the selected
1078    /// label, or hide all labels.
1079    label_behavior: NavigationDestinationLabelBehavior,
1080
1081    /// The color of the selection indicator.
1082    ///
1083    /// This is used by destinations to override the indicator color.
1084    indicator_color: Option<Color>,
1085
1086    /// The shape of the selection indicator.
1087    ///
1088    /// This is used by destinations to override the indicator shape.
1089    indicator_shape: Option<ShapeBorderRef>,
1090
1091    /// The highlight color that's typically used to indicate that
1092    /// the [`NavigationDestination`] is focused, hovered, or pressed.
1093    ///
1094    /// This is used by destinations to override the overlay color.
1095    overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1096
1097    /// The callback that should be called when this destination is tapped.
1098    ///
1099    /// This is computed by calling [`NavigationBar::on_destination_selected`]
1100    /// with [`index`](Self::index) passed in.
1101    on_tap: Listener,
1102
1103    /// The text style of the label.
1104    label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
1105
1106    /// The padding around the label.
1107    ///
1108    /// Defaults to a padding of 4 pixels on the top.
1109    label_padding: Option<EdgeInsetsGeometry>,
1110
1111    child: WidgetRef,
1112}
1113
1114impl NavigationDestinationInfo {
1115    /// Returns a non null [`NavigationDestinationInfo`].
1116    ///
1117    /// This will return an error if called with no [`NavigationDestinationInfo`]
1118    /// ancestor.
1119    ///
1120    /// Used by widgets that are implementing a navigation destination info to
1121    /// get information like the selected animation and destination number.
1122    fn of(app: &mut App, context: BuildContext) -> NavigationDestinationInfo {
1123        let result = context
1124            .depend_on_inherited_widget_of_exact_type::<NavigationDestinationInfo>(app)
1125            .cloned();
1126        debug_assert!(
1127            result.is_some(),
1128            "Navigation destinations need a _NavigationDestinationInfo parent, which is usually \
1129             provided by NavigationBar."
1130        );
1131        result.expect("a _NavigationDestinationInfo above the destination")
1132    }
1133}
1134
1135impl Debug for NavigationDestinationInfo {
1136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1137        f.debug_struct("_NavigationDestinationInfo")
1138            .field("index", &self.index)
1139            .field("selected_index", &self.selected_index)
1140            .field(
1141                "total_number_of_destinations",
1142                &self.total_number_of_destinations,
1143            )
1144            .field("selected_animation", &self.selected_animation)
1145            .field("label_behavior", &self.label_behavior)
1146            .field("indicator_color", &self.indicator_color)
1147            .field("indicator_shape", &self.indicator_shape)
1148            .field("label_padding", &self.label_padding)
1149            .field("child", &self.child)
1150            .finish_non_exhaustive()
1151    }
1152}
1153
1154impl InheritedWidget for NavigationDestinationInfo {
1155    fn child(&self) -> &WidgetRef {
1156        &self.child
1157    }
1158
1159    fn update_should_notify(&self, old_widget: &NavigationDestinationInfo) -> bool {
1160        self.index != old_widget.index
1161            || self.total_number_of_destinations != old_widget.total_number_of_destinations
1162            || self.selected_animation != old_widget.selected_animation
1163            || self.label_behavior != old_widget.label_behavior
1164            || self.on_tap != old_widget.on_tap
1165    }
1166}
1167
1168/// Selection Indicator for the Material 3 `NavigationBar` and `NavigationRail`
1169/// components.
1170///
1171/// When [`animation`](Self::animation) is 0, the indicator is not present. As
1172/// [`animation`](Self::animation) grows from 0 to 1, the indicator scales in on the x axis.
1173///
1174/// Used in a `Stack` widget behind the icons in the Material 3 Navigation Bar
1175/// to illuminate the selected destination.
1176pub struct NavigationIndicator {
1177    pub key: Option<KeyRef>,
1178
1179    /// Determines the scale of the indicator.
1180    ///
1181    /// When [`animation`](Self::animation) is 0, the indicator is not present. The indicator
1182    /// scales in as [`animation`](Self::animation) grows from 0 to 1.
1183    pub animation: AnimationRef<f64>,
1184
1185    /// The fill color of this indicator.
1186    ///
1187    /// If null, defaults to `ColorScheme::secondary`.
1188    pub color: Option<Color>,
1189
1190    /// The width of this indicator.
1191    ///
1192    /// Defaults to `64`.
1193    pub width: f64,
1194
1195    /// The height of this indicator.
1196    ///
1197    /// Defaults to `32`.
1198    pub height: f64,
1199
1200    /// The border radius of the shape of the indicator.
1201    ///
1202    /// This is used to create a `RoundedRectangleBorder` shape for the indicator.
1203    /// This is ignored if [`shape`](Self::shape) is non-null.
1204    ///
1205    /// Defaults to `BorderRadius.circular(16)`.
1206    pub border_radius: BorderRadius,
1207
1208    /// The shape of the indicator.
1209    ///
1210    /// If non-null this is used as the shape used to draw the background
1211    /// of the indicator. If null then a `RoundedRectangleBorder` with the
1212    /// [`border_radius`](Self::border_radius) is used.
1213    pub shape: Option<ShapeBorderRef>,
1214}
1215
1216impl NavigationIndicator {
1217    /// Builds an indicator, usually used in a stack behind the icon of a
1218    /// navigation bar destination.
1219    pub fn new(animation: AnimationRef<f64>) -> NavigationIndicator {
1220        NavigationIndicator {
1221            key: None,
1222            animation,
1223            color: None,
1224            width: K_INDICATOR_WIDTH,
1225            height: K_INDICATOR_HEIGHT,
1226            border_radius: BorderRadius::all(Radius::circular(16.0)),
1227            shape: None,
1228        }
1229    }
1230
1231    /// Dart `NavigationIndicator(key:)`.
1232    pub fn key(mut self, key: KeyRef) -> NavigationIndicator {
1233        self.key = Some(key);
1234        self
1235    }
1236
1237    /// Dart `NavigationIndicator(color:)`.
1238    pub fn color(mut self, color: Color) -> NavigationIndicator {
1239        self.color = Some(color);
1240        self
1241    }
1242
1243    /// Dart `NavigationIndicator(width:)`.
1244    pub fn width(mut self, width: f64) -> NavigationIndicator {
1245        self.width = width;
1246        self
1247    }
1248
1249    /// Dart `NavigationIndicator(height:)`.
1250    pub fn height(mut self, height: f64) -> NavigationIndicator {
1251        self.height = height;
1252        self
1253    }
1254
1255    /// Dart `NavigationIndicator(borderRadius:)`.
1256    pub fn border_radius(mut self, border_radius: BorderRadius) -> NavigationIndicator {
1257        self.border_radius = border_radius;
1258        self
1259    }
1260
1261    /// Dart `NavigationIndicator(shape:)`.
1262    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> NavigationIndicator {
1263        self.shape = Some(shape.into());
1264        self
1265    }
1266}
1267
1268impl Debug for NavigationIndicator {
1269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1270        f.debug_struct("NavigationIndicator")
1271            .field("animation", &self.animation)
1272            .field("color", &self.color)
1273            .field("width", &self.width)
1274            .field("height", &self.height)
1275            .field("border_radius", &self.border_radius)
1276            .field("shape", &self.shape)
1277            .finish()
1278    }
1279}
1280
1281impl StatelessWidget for NavigationIndicator {
1282    fn key(&self) -> Option<&KeyRef> {
1283        self.key.as_ref()
1284    }
1285
1286    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1287        let animation = self.animation.clone();
1288        let status_animation = animation.clone();
1289        let width = self.width;
1290        let height = self.height;
1291        let border_radius = self.border_radius;
1292        let shape = self.shape.clone();
1293        let color = self.color;
1294        AnimatedBuilder::new(Rc::new(animation.clone()), move |app, context, child| {
1295            // The scale should be 0 when the animation is unselected, as soon as
1296            // the animation starts, the scale jumps to 40%, and then animates to
1297            // 100% along a curve.
1298            let scale = if animation.is_dismissed(app) {
1299                0.0
1300            } else {
1301                let curved = transform_curve_tween(
1302                    app,
1303                    Curves::ease_in_out_cubic_emphasized(),
1304                    animation.value(app),
1305                );
1306                transform_tween(app, 0.4, 1.0, curved)
1307            };
1308
1309            // The indicator is drawn by the Ink widget below, which paints on the
1310            // nearest ancestor Material rather than locally. When the animation
1311            // ticks without an accompanying pointer interaction (for example, the
1312            // selected index was changed programmatically), that Material is not
1313            // otherwise notified and would keep showing the indicator's previous
1314            // frame. See https://github.com/flutter/flutter/issues/180359.
1315            Material::of(app, context).mark_needs_paint(app);
1316
1317            let mut transform = Transform::new(Matrix4::scale(scale as f32, 1.0))
1318                .alignment(AlignmentGeometry::CENTER);
1319            if let Some(child) = child {
1320                transform = transform.child(child.clone());
1321            }
1322            transform.into_widget()
1323        })
1324        // Fade should be a 100ms animation whenever the parent animation changes
1325        // direction.
1326        .child(StatusTransitionWidgetBuilder::new(
1327            status_animation.clone(),
1328            move |app, _context, _child| {
1329                let shape = shape.clone();
1330                SelectableAnimatedBuilder::new(
1331                    status_animation.is_forward_or_completed(app),
1332                    move |app, context, fade_animation| {
1333                        let shape = shape.clone().unwrap_or_else(|| {
1334                            ShapeBorderRef::new(RoundedRectangleBorder::new(
1335                                BorderSide::NONE,
1336                                border_radius.into(),
1337                            ))
1338                        });
1339                        let color = color
1340                            .unwrap_or_else(|| Theme::of(app, context).color_scheme.secondary());
1341                        FadeTransition::new(fade_animation)
1342                            .child(
1343                                Ink::new()
1344                                    .width(width)
1345                                    .height(height)
1346                                    .decoration(ShapeDecoration::new(shape).color(color)),
1347                            )
1348                            .into_widget()
1349                    },
1350                )
1351                .duration(Duration::from_millis(100))
1352                .always_do_full_animation(true)
1353                .into_widget()
1354            },
1355        ))
1356        .into_widget()
1357    }
1358}
1359
1360/// Widget that handles the layout of the icon + label in a navigation bar
1361/// destination, based on [`NavigationDestinationInfo::label_behavior`] and
1362/// [`NavigationDestinationInfo::selected_animation`].
1363///
1364/// Depending on the [`NavigationDestinationInfo::label_behavior`], the labels
1365/// will shift and fade accordingly.
1366#[derive(Debug)]
1367struct NavigationBarDestinationLayout {
1368    /// The icon widget that sits on top of the label.
1369    ///
1370    /// See [`NavigationDestination::icon`].
1371    icon: WidgetRef,
1372
1373    /// The global key for the icon of this destination.
1374    ///
1375    /// This is used to determine the position of the icon.
1376    icon_key: GlobalKey,
1377
1378    /// The label widget that sits below the icon.
1379    ///
1380    /// This widget will sometimes be faded out, depending on
1381    /// [`NavigationDestinationInfo::selected_animation`].
1382    ///
1383    /// See [`NavigationDestination::label`].
1384    label: WidgetRef,
1385}
1386
1387impl StatelessWidget for NavigationBarDestinationLayout {
1388    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1389        let icon = self.icon.clone();
1390        let icon_key = self.icon_key.clone();
1391        let label = self.label.clone();
1392        DestinationLayoutAnimationBuilder {
1393            builder: Rc::new(move |_app, _context, animation| {
1394                CustomMultiChildLayout::new(Rc::new(NavigationDestinationLayoutDelegate::new(
1395                    animation.clone(),
1396                )))
1397                .children([
1398                    LayoutId::new(
1399                        NavigationDestinationLayoutDelegate::icon_id(),
1400                        // The key is used by the IndicatorInkWell to query the icon position.
1401                        KeyedSubtree::new(icon.clone()).key(KeyRef::from(icon_key.clone())),
1402                    )
1403                    .into_widget(),
1404                    LayoutId::new(
1405                        NavigationDestinationLayoutDelegate::label_id(),
1406                        FadeTransition::new(animation).child(label.clone()),
1407                    )
1408                    .into_widget(),
1409                ])
1410                .into_widget()
1411            }),
1412        }
1413        .into_widget()
1414    }
1415}
1416
1417/// Determines the appropriate [`Curve`] and [`AnyAnimation`] to use for laying out the
1418/// [`NavigationDestination`], based on
1419/// [`NavigationDestinationInfo::label_behavior`].
1420///
1421/// The animation controlling the position and fade of the labels differs
1422/// from the selection animation, depending on the
1423/// [`NavigationDestinationLabelBehavior`]. This widget determines what
1424/// animation should be used for the position and fade of the labels.
1425struct DestinationLayoutAnimationBuilder {
1426    /// Builds the child of this widget.
1427    ///
1428    /// The animation will be the appropriate animation to use for the layout
1429    /// and fade of the [`NavigationDestination`], either a curve, always
1430    /// showing (1), or always hiding (0).
1431    builder: AnimationWidgetBuilder,
1432}
1433
1434impl Debug for DestinationLayoutAnimationBuilder {
1435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436        f.debug_struct("_DestinationLayoutAnimationBuilder")
1437            .finish_non_exhaustive()
1438    }
1439}
1440
1441impl StatelessWidget for DestinationLayoutAnimationBuilder {
1442    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1443        let info = NavigationDestinationInfo::of(app, context);
1444        match info.label_behavior {
1445            NavigationDestinationLabelBehavior::AlwaysShow => {
1446                let animation = k_always_complete_animation(app);
1447                (self.builder)(app, context, animation)
1448            }
1449            NavigationDestinationLabelBehavior::AlwaysHide => {
1450                let animation = k_always_dismissed_animation(app);
1451                (self.builder)(app, context, animation)
1452            }
1453            NavigationDestinationLabelBehavior::OnlyShowSelected => CurvedAnimationBuilder {
1454                animation: info.selected_animation,
1455                curve: Curves::ease_in_out_cubic_emphasized(),
1456                reverse_curve: Rc::new(Curves::ease_in_out_cubic_emphasized().flipped()),
1457                builder: Rc::clone(&self.builder),
1458            }
1459            .into_widget(),
1460        }
1461    }
1462}
1463
1464/// Semantics widget for a navigation bar destination.
1465///
1466/// Requires a [`NavigationDestinationInfo`] parent (normally provided by the
1467/// [`NavigationBar`] by default).
1468///
1469/// Provides localized semantic labels to the destination, for example, it will
1470/// read "Home, Tab 1 of 3".
1471///
1472/// Used by [`NavigationDestinationBuilder`].
1473#[derive(Debug)]
1474struct NavigationBarDestinationSemantics {
1475    /// Whether this widget is enabled.
1476    enabled: bool,
1477
1478    /// The widget that should receive the destination semantics.
1479    child: WidgetRef,
1480}
1481
1482impl NavigationBarDestinationSemantics {
1483    /// Adds the appropriate semantics for navigation bar destinations to the
1484    /// [`child`](Self::child).
1485    #[cfg_attr(debug_assertions, track_caller)]
1486    fn new<K>(enabled: bool, child: impl IntoWidget<K>) -> NavigationBarDestinationSemantics {
1487        NavigationBarDestinationSemantics {
1488            enabled,
1489            child: child.into_widget(),
1490        }
1491    }
1492}
1493
1494impl StatelessWidget for NavigationBarDestinationSemantics {
1495    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1496        let localizations = <dyn MaterialLocalizations>::of(app, context);
1497        let destination_info = NavigationDestinationInfo::of(app, context);
1498        let enabled = self.enabled;
1499        // The AnimationStatusBuilder will make sure that the semantics update to
1500        // "selected" when the animation status changes.
1501        StatusTransitionWidgetBuilder::new(
1502            destination_info.selected_animation,
1503            move |_app, _context, child| {
1504                let mut semantics = Semantics::new().enabled(enabled).button(true);
1505                if let Some(child) = child {
1506                    semantics = semantics.child(child.clone());
1507                }
1508                semantics.into_widget()
1509            },
1510        )
1511        .child(if K_IS_WEB {
1512            self.child.clone()
1513        } else {
1514            Stack::new()
1515                .alignment(AlignmentGeometry::CENTER)
1516                .children([
1517                    self.child.clone(),
1518                    Semantics::new()
1519                        .label(localizations.tab_label(
1520                            destination_info.index as i32 + 1,
1521                            destination_info.total_number_of_destinations as i32,
1522                        ))
1523                        .into_widget(),
1524                ])
1525                .into_widget()
1526        })
1527        .into_widget()
1528    }
1529}
1530
1531/// Tooltip widget for use in a [`NavigationBar`].
1532///
1533/// It appears just above the navigation bar when one of the destinations is
1534/// long pressed.
1535#[derive(Debug)]
1536struct NavigationBarDestinationTooltip {
1537    /// The text that is rendered in the tooltip when it appears.
1538    message: String,
1539
1540    /// The widget that, when pressed, will show a tooltip.
1541    child: WidgetRef,
1542}
1543
1544impl NavigationBarDestinationTooltip {
1545    /// Adds a tooltip to the [`child`](Self::child) widget.
1546    #[cfg_attr(debug_assertions, track_caller)]
1547    fn new<K>(message: String, child: impl IntoWidget<K>) -> NavigationBarDestinationTooltip {
1548        NavigationBarDestinationTooltip {
1549            message,
1550            child: child.into_widget(),
1551        }
1552    }
1553}
1554
1555impl StatelessWidget for NavigationBarDestinationTooltip {
1556    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1557        Tooltip::new()
1558            .message(self.message.clone())
1559            // TODO(johnsonmh): Make this value configurable/themable.
1560            .vertical_offset(42.0)
1561            .exclude_from_semantics(true)
1562            .prefer_below(false)
1563            .child(self.child.clone())
1564            .into_widget()
1565    }
1566}
1567
1568/// Custom layout delegate for shifting navigation bar destinations.
1569///
1570/// This will lay out the icon + label according to the [`animation`](Self::animation).
1571///
1572/// When the [`animation`](Self::animation) is 0, the icon will be centered, and the label
1573/// will be positioned directly below it.
1574///
1575/// When the [`animation`](Self::animation) is 1, the label will still be positioned
1576/// directly below the icon, but the icon + label combination will be centered.
1577///
1578/// Used in a [`CustomMultiChildLayout`] widget in the
1579/// [`NavigationDestinationBuilder`].
1580struct NavigationDestinationLayoutDelegate {
1581    /// The selection animation that indicates whether or not this destination is
1582    /// selected.
1583    ///
1584    /// See [`NavigationDestinationInfo::selected_animation`].
1585    animation: AnimationRef<f64>,
1586
1587    /// Dart's `super(relayout: animation)`.
1588    relayout: Rc<dyn Listenable>,
1589}
1590
1591impl Debug for NavigationDestinationLayoutDelegate {
1592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1593        f.debug_struct("_NavigationDestinationLayoutDelegate")
1594            .field("animation", &self.animation)
1595            .finish_non_exhaustive()
1596    }
1597}
1598
1599impl NavigationDestinationLayoutDelegate {
1600    fn new(animation: AnimationRef<f64>) -> NavigationDestinationLayoutDelegate {
1601        NavigationDestinationLayoutDelegate {
1602            relayout: Rc::new(animation.clone()),
1603            animation,
1604        }
1605    }
1606
1607    /// ID for the icon widget child.
1608    ///
1609    /// This is used by the [`LayoutId`] when this delegate is used in a
1610    /// [`CustomMultiChildLayout`].
1611    ///
1612    /// See [`NavigationDestinationBuilder`].
1613    const ICON_ID: i64 = 1;
1614
1615    /// ID for the label widget child.
1616    ///
1617    /// This is used by the [`LayoutId`] when this delegate is used in a
1618    /// [`CustomMultiChildLayout`].
1619    ///
1620    /// See [`NavigationDestinationBuilder`].
1621    const LABEL_ID: i64 = 2;
1622
1623    /// [`ICON_ID`](Self::ICON_ID) as the [`ChildLayoutId`] of its [`LayoutId`].
1624    fn icon_id() -> ChildLayoutId {
1625        Rc::new(ValueKey::new(Self::ICON_ID))
1626    }
1627
1628    /// [`LABEL_ID`](Self::LABEL_ID) as the [`ChildLayoutId`] of its [`LayoutId`].
1629    fn label_id() -> ChildLayoutId {
1630        Rc::new(ValueKey::new(Self::LABEL_ID))
1631    }
1632}
1633
1634impl MultiChildLayoutDelegate for NavigationDestinationLayoutDelegate {
1635    fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
1636        Some(&self.relayout)
1637    }
1638
1639    fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size) {
1640        let half_width = |size: Size| size.width() / 2.0;
1641        let half_height = |size: Size| size.height() / 2.0;
1642
1643        let icon_size = children.layout_child(app, &Self::icon_id(), BoxConstraints::loose(size));
1644        let label_size = children.layout_child(app, &Self::label_id(), BoxConstraints::loose(size));
1645
1646        let animation_value = self.animation.value(app);
1647        let y_position_offset = transform_tween(
1648            app,
1649            // When unselected, the icon is centered vertically.
1650            half_height(icon_size),
1651            // When selected, the icon and label are centered vertically.
1652            half_height(icon_size) + half_height(label_size),
1653            animation_value,
1654        );
1655        let icon_y_position = half_height(size) - y_position_offset;
1656
1657        // Position the icon.
1658        children.position_child(
1659            app,
1660            &Self::icon_id(),
1661            Offset::new(
1662                // Center the icon horizontally.
1663                half_width(size) - half_width(icon_size),
1664                icon_y_position,
1665            ),
1666        );
1667
1668        // Position the label.
1669        children.position_child(
1670            app,
1671            &Self::label_id(),
1672            Offset::new(
1673                // Center the label horizontally.
1674                half_width(size) - half_width(label_size),
1675                // Label always appears directly below the icon.
1676                icon_y_position + icon_size.height(),
1677            ),
1678        );
1679    }
1680
1681    fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
1682        let old_delegate = old_delegate
1683            .as_any()
1684            .downcast_ref::<NavigationDestinationLayoutDelegate>()
1685            .expect("the same delegate type");
1686        old_delegate.animation != self.animation
1687    }
1688
1689    fn as_any(&self) -> &dyn Any {
1690        self
1691    }
1692}
1693
1694/// Widget that listens to an animation, and rebuilds when the animation changes
1695/// `AnimationStatus`.
1696///
1697/// This can be more efficient than just using an `AnimatedBuilder` when you
1698/// only need to rebuild when the `Animation::status` changes, since
1699/// `AnimatedBuilder` rebuilds every time the animation ticks.
1700struct StatusTransitionWidgetBuilder {
1701    animation: AnimationRef<f64>,
1702
1703    /// Called every time the animation changes `AnimationStatus`.
1704    builder: TransitionBuilder,
1705
1706    /// The child widget to pass to the [`builder`](Self::builder).
1707    ///
1708    /// If a [`builder`](Self::builder) callback's return value contains a subtree that does
1709    /// not depend on the animation, it's more efficient to build that subtree once
1710    /// instead of rebuilding it on every animation status change.
1711    ///
1712    /// Using this pre-built child is entirely optional, but can improve
1713    /// performance in some cases and is therefore a good practice.
1714    ///
1715    /// See: `AnimatedBuilder::child`
1716    child: Option<WidgetRef>,
1717}
1718
1719impl StatusTransitionWidgetBuilder {
1720    /// Creates a widget that rebuilds when the given animation changes status.
1721    fn new(
1722        animation: AnimationRef<f64>,
1723        builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
1724    ) -> StatusTransitionWidgetBuilder {
1725        StatusTransitionWidgetBuilder {
1726            animation,
1727            builder: Rc::new(builder),
1728            child: None,
1729        }
1730    }
1731
1732    /// Dart `_StatusTransitionWidgetBuilder(child:)`.
1733    #[cfg_attr(debug_assertions, track_caller)]
1734    fn child<K>(mut self, child: impl IntoWidget<K>) -> StatusTransitionWidgetBuilder {
1735        self.child = Some(child.into_widget());
1736        self
1737    }
1738}
1739
1740impl Debug for StatusTransitionWidgetBuilder {
1741    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1742        f.debug_struct("_StatusTransitionWidgetBuilder")
1743            .field("animation", &self.animation)
1744            .field("child", &self.child)
1745            .finish_non_exhaustive()
1746    }
1747}
1748
1749impl StatusTransitionWidget for StatusTransitionWidgetBuilder {
1750    fn animation(&self) -> AnyAnimation<f64> {
1751        self.animation.handle()
1752    }
1753
1754    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1755        (self.builder)(app, context, self.child.as_ref())
1756    }
1757}
1758
1759/// Dart's `Widget Function(BuildContext, Animation<double>)` builders of this file.
1760type AnimationWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;
1761
1762// Builder widget for widgets that need to be animated from 0 (unselected) to
1763// 1.0 (selected).
1764//
1765// This widget creates and manages an `AnimationController` that it passes down
1766// to the child through the `builder` function.
1767//
1768// When `is_selected` is `true`, the animation controller will animate from
1769// 0 to 1 (for `duration` time).
1770//
1771// When `is_selected` is `false`, the animation controller will animate from
1772// 1 to 0 (for `duration` time).
1773//
1774// If `is_selected` is updated while the widget is animating, the animation will
1775// be reversed until it is either 0 or 1 again. If `always_do_full_animation` is
1776// true, the animation will reset to 0 or 1 before beginning the animation, so
1777// that the full animation is done.
1778struct SelectableAnimatedBuilder {
1779    /// When true, the widget will animate an animation controller from 0 to 1.
1780    ///
1781    /// The animation controller is passed to the child widget through
1782    /// [`builder`](Self::builder).
1783    is_selected: bool,
1784
1785    /// How long the animation controller should animate for when
1786    /// [`is_selected`](Self::is_selected) is updated.
1787    ///
1788    /// If the animation is currently running and [`is_selected`](Self::is_selected) is
1789    /// updated, only the [`duration`](Self::duration) left to finish the animation will be
1790    /// run.
1791    duration: Duration,
1792
1793    /// If true, the animation will always go all the way from 0 to 1 when
1794    /// [`is_selected`](Self::is_selected) is true, and from 1 to 0 when
1795    /// [`is_selected`](Self::is_selected) is false, even when the status changes mid
1796    /// animation.
1797    ///
1798    /// If this is false and the status changes mid animation, the animation will
1799    /// reverse direction from it's current point.
1800    ///
1801    /// Defaults to false.
1802    always_do_full_animation: bool,
1803
1804    /// Builds the child widget based on the current animation status.
1805    builder: AnimationWidgetBuilder,
1806}
1807
1808impl SelectableAnimatedBuilder {
1809    /// Builds and maintains an `AnimationController` that will animate from 0 to
1810    /// 1 and back depending on when [`is_selected`](Self::is_selected) is true.
1811    fn new(
1812        is_selected: bool,
1813        builder: impl Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef + 'static,
1814    ) -> SelectableAnimatedBuilder {
1815        SelectableAnimatedBuilder {
1816            is_selected,
1817            duration: Duration::from_millis(200),
1818            always_do_full_animation: false,
1819            builder: Rc::new(builder),
1820        }
1821    }
1822
1823    /// Dart `_SelectableAnimatedBuilder(duration:)`.
1824    fn duration(mut self, duration: Duration) -> SelectableAnimatedBuilder {
1825        self.duration = duration;
1826        self
1827    }
1828
1829    /// Dart `_SelectableAnimatedBuilder(alwaysDoFullAnimation:)`.
1830    fn always_do_full_animation(
1831        mut self,
1832        always_do_full_animation: bool,
1833    ) -> SelectableAnimatedBuilder {
1834        self.always_do_full_animation = always_do_full_animation;
1835        self
1836    }
1837}
1838
1839impl Debug for SelectableAnimatedBuilder {
1840    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1841        f.debug_struct("_SelectableAnimatedBuilder")
1842            .field("is_selected", &self.is_selected)
1843            .field("duration", &self.duration)
1844            .field("always_do_full_animation", &self.always_do_full_animation)
1845            .finish_non_exhaustive()
1846    }
1847}
1848
1849impl StatefulWidget for SelectableAnimatedBuilder {
1850    type State = SelectableAnimatedBuilderState;
1851
1852    fn create_state(&self) -> SelectableAnimatedBuilderState {
1853        SelectableAnimatedBuilderState {
1854            state: StateData::new(),
1855            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1856            controller: None,
1857        }
1858    }
1859}
1860
1861/// Dart's `_SelectableAnimatedBuilderState`.
1862struct SelectableAnimatedBuilderState {
1863    state: StateData<SelectableAnimatedBuilder>,
1864    single_ticker_provider: SingleTickerProviderStateMixinData,
1865    controller: Option<Ref<AnimationController>>,
1866}
1867
1868impl SelectableAnimatedBuilderState {
1869    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1870        app.get(self)
1871            .controller
1872            .handle()
1873            .expect("created in init_state")
1874    }
1875}
1876
1877impl SingleTickerProviderStateMixin for SelectableAnimatedBuilderState {
1878    fn single_ticker_provider_data(
1879        self: Handle<Self>,
1880        app: &App,
1881    ) -> &SingleTickerProviderStateMixinData {
1882        &app.get(self).single_ticker_provider
1883    }
1884
1885    fn single_ticker_provider_data_mut(
1886        self: Handle<Self>,
1887        app: &mut App,
1888    ) -> &mut SingleTickerProviderStateMixinData {
1889        &mut app.get_mut(self).single_ticker_provider
1890    }
1891}
1892
1893impl TickerProviderObject for SelectableAnimatedBuilderState {
1894    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1895        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1896    }
1897}
1898
1899impl State for SelectableAnimatedBuilderState {
1900    type Widget = SelectableAnimatedBuilder;
1901    waft_widgets::state_accessors!();
1902
1903    fn init_state(self: Handle<Self>, app: &mut App) {
1904        let controller = AnimationController::new(
1905            app,
1906            None,
1907            None,
1908            None,
1909            0.0,
1910            1.0,
1911            AnimationBehavior::Normal,
1912            self,
1913        );
1914        app.get_mut(self).controller = Some(controller.clone());
1915        let widget = self.widget(app);
1916        let duration = widget.duration;
1917        let value = if widget.is_selected { 1.0 } else { 0.0 };
1918        app.get_mut(&controller).duration = Some(duration);
1919        controller.set_value(app, value);
1920    }
1921
1922    fn did_update_widget(
1923        self: Handle<Self>,
1924        app: &mut App,
1925        old_widget: &SelectableAnimatedBuilder,
1926    ) {
1927        let controller = self.controller(app);
1928        let widget = self.widget(app);
1929        let duration = widget.duration;
1930        let is_selected = widget.is_selected;
1931        let always_do_full_animation = widget.always_do_full_animation;
1932        if old_widget.duration != duration {
1933            app.get_mut(controller).duration = Some(duration);
1934        }
1935        if old_widget.is_selected != is_selected {
1936            if is_selected {
1937                controller.forward(app, always_do_full_animation.then_some(0.0));
1938            } else {
1939                controller.reverse(app, always_do_full_animation.then_some(1.0));
1940            }
1941        }
1942    }
1943
1944    fn activate(self: Handle<Self>, app: &mut App) {
1945        SingleTickerProviderStateMixin::activate(self, app);
1946    }
1947
1948    fn dispose(self: Handle<Self>, app: &mut App) {
1949        let controller = self.controller(app);
1950        controller.dispose(app);
1951        SingleTickerProviderStateMixin::dispose(self, app);
1952    }
1953
1954    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1955        let builder = Rc::clone(&self.widget(app).builder);
1956        let controller = app
1957            .get(self)
1958            .controller
1959            .as_ref()
1960            .expect("created in init_state")
1961            .erase();
1962        builder(app, context, controller)
1963    }
1964}
1965
1966/// Watches [`animation`](Self::animation) and calls [`builder`](Self::builder) with the
1967/// appropriate [`Curve`] depending on the direction of the [`animation`](Self::animation)
1968/// status.
1969///
1970/// If `Animation::status` is forward or complete, [`curve`](Self::curve) is used. If
1971/// `Animation::status` is reverse or dismissed, [`reverse_curve`](Self::reverse_curve) is
1972/// used.
1973///
1974/// If the [`animation`](Self::animation) changes direction while it is already running, the curve
1975/// used will not change, this will keep the animations smooth until it
1976/// completes.
1977///
1978/// This is similar to `CurvedAnimation` except the animation status listeners
1979/// are removed when this widget is disposed.
1980struct CurvedAnimationBuilder {
1981    animation: AnimationRef<f64>,
1982    curve: Rc<dyn Curve>,
1983    reverse_curve: Rc<dyn Curve>,
1984    builder: AnimationWidgetBuilder,
1985}
1986
1987impl Debug for CurvedAnimationBuilder {
1988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1989        f.debug_struct("_CurvedAnimationBuilder")
1990            .field("animation", &self.animation)
1991            .finish_non_exhaustive()
1992    }
1993}
1994
1995impl StatefulWidget for CurvedAnimationBuilder {
1996    type State = CurvedAnimationBuilderState;
1997
1998    fn create_state(&self) -> CurvedAnimationBuilderState {
1999        CurvedAnimationBuilderState {
2000            state: StateData::new(),
2001            animation_direction: AnimationStatus::Dismissed,
2002            preserved_direction: None,
2003        }
2004    }
2005}
2006
2007/// Dart's `_CurvedAnimationBuilderState`.
2008struct CurvedAnimationBuilderState {
2009    state: StateData<CurvedAnimationBuilder>,
2010    animation_direction: AnimationStatus,
2011    preserved_direction: Option<AnimationStatus>,
2012}
2013
2014impl CurvedAnimationBuilderState {
2015    // Keeps track of the current animation status, as well as the "preserved
2016    // direction" when the animation changes direction mid animation.
2017    //
2018    // The preserved direction is reset when the animation finishes in either
2019    // direction.
2020    fn update_status(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
2021        if app.get(self).animation_direction != status {
2022            self.set_state(app, |state| {
2023                state.animation_direction = status;
2024            });
2025        }
2026        match status {
2027            AnimationStatus::Forward | AnimationStatus::Reverse
2028                if app.get(self).preserved_direction.is_some() => {}
2029            AnimationStatus::Forward | AnimationStatus::Reverse => {
2030                self.set_state(app, |state| {
2031                    state.preserved_direction = Some(status);
2032                });
2033            }
2034            AnimationStatus::Completed | AnimationStatus::Dismissed => {
2035                self.set_state(app, |state| {
2036                    state.preserved_direction = None;
2037                });
2038            }
2039        }
2040    }
2041}
2042
2043impl State for CurvedAnimationBuilderState {
2044    type Widget = CurvedAnimationBuilder;
2045    waft_widgets::state_accessors!();
2046
2047    fn init_state(self: Handle<Self>, app: &mut App) {
2048        let animation = self.widget(app).animation.clone();
2049        let status = animation.status(app);
2050        app.get_mut(self).animation_direction = status;
2051        self.update_status(app, status);
2052        animation.add_status_listener(
2053            app,
2054            AnimationStatusListener::handle_method(self, Self::update_status),
2055        );
2056    }
2057
2058    fn dispose(self: Handle<Self>, app: &mut App) {
2059        let animation = self.widget(app).animation.clone();
2060        animation.remove_status_listener(
2061            app,
2062            &AnimationStatusListener::handle_method(self, Self::update_status),
2063        );
2064    }
2065
2066    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2067        let state = app.get(self);
2068        let should_use_forward_curve = state
2069            .preserved_direction
2070            .unwrap_or(state.animation_direction)
2071            != AnimationStatus::Reverse;
2072
2073        let widget = self.widget(app);
2074        let curve = if should_use_forward_curve {
2075            Rc::clone(&widget.curve)
2076        } else {
2077            Rc::clone(&widget.reverse_curve)
2078        };
2079        let parent = widget.animation.clone();
2080        let builder = Rc::clone(&widget.builder);
2081        let curve_tween = CurveTween::new(app, curve);
2082        let curved_animation = parent.drive(app, curve_tween);
2083
2084        builder(app, context, curved_animation)
2085    }
2086}
2087
2088/// Dart's `_defaultsFor(context)`.
2089fn defaults_for(app: &mut App, context: BuildContext) -> Rc<dyn NavigationBarThemeDataGetters> {
2090    if Theme::of(app, context).use_material3 {
2091        Rc::new(NavigationBarDefaultsM3::new(context))
2092    } else {
2093        Rc::new(NavigationBarDefaultsM2::new(app, context))
2094    }
2095}
2096
2097/// Hand coded defaults based on Material Design 2: Dart's `_NavigationBarDefaultsM2`.
2098struct NavigationBarDefaultsM2 {
2099    /// Dart's `super(..)` arguments.
2100    navigation_bar_theme_data: NavigationBarThemeData,
2101    context: DefaultsContext,
2102}
2103
2104impl NavigationBarDefaultsM2 {
2105    fn new(app: &mut App, context: BuildContext) -> NavigationBarDefaultsM2 {
2106        NavigationBarDefaultsM2 {
2107            navigation_bar_theme_data: NavigationBarThemeData::new()
2108                .height(80.0)
2109                .elevation(0.0)
2110                .indicator_shape(RoundedRectangleBorder::new(
2111                    BorderSide::NONE,
2112                    BorderRadius::all(Radius::circular(16.0)).into(),
2113                ))
2114                .label_behavior(NavigationDestinationLabelBehavior::AlwaysShow),
2115            context: DefaultsContext::with_theme(app, context),
2116        }
2117    }
2118}
2119
2120#[allow(deprecated)]
2121impl NavigationBarThemeDataGetters for NavigationBarDefaultsM2 {
2122    fn navigation_bar_theme_data(&self) -> &NavigationBarThemeData {
2123        &self.navigation_bar_theme_data
2124    }
2125
2126    // With Material 2, the NavigationBar uses an overlay blend for the
2127    // default color regardless of light/dark mode.
2128    fn background_color(&self, app: &mut App) -> Option<Color> {
2129        let theme = self.context.theme(app);
2130        let colors = &theme.color_scheme;
2131        Some(ElevationOverlay::color_with_overlay(
2132            colors.surface(),
2133            colors.on_surface(),
2134            3.0,
2135        ))
2136    }
2137
2138    fn icon_theme(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<IconThemeData>>> {
2139        let theme = self.context.theme(app);
2140        let colors = &theme.color_scheme;
2141        Some(Rc::new(MaterialStatePropertyAll::new(Some(
2142            IconThemeData::new().size(24.0).color(colors.on_surface()),
2143        ))))
2144    }
2145
2146    fn indicator_color(&self, app: &mut App) -> Option<Color> {
2147        let theme = self.context.theme(app);
2148        let colors = &theme.color_scheme;
2149        Some(colors.secondary().with_opacity(0.24))
2150    }
2151
2152    fn label_text_style(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<TextStyle>>> {
2153        let theme = self.context.theme(app);
2154        let colors = &theme.color_scheme;
2155        Some(Rc::new(MaterialStatePropertyAll::new(Some(
2156            theme
2157                .text_theme
2158                .label_small
2159                .clone()
2160                .expect("the text theme gives labelSmall")
2161                .copy_with()
2162                .color(colors.on_surface()),
2163        ))))
2164    }
2165
2166    fn label_padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
2167        Some(EdgeInsetsGeometry::from(waft_painting::EdgeInsets::only(
2168            0.0, 4.0, 0.0, 0.0,
2169        )))
2170    }
2171}
2172
2173/// Dart's `CurveTween(curve: curve).transform(t)`.
2174fn transform_curve_tween(app: &mut App, curve: Rc<dyn Curve>, t: f64) -> f64 {
2175    let curve_tween = CurveTween::new(app, curve);
2176    Animatable::transform(&curve_tween, app, t)
2177}
2178
2179/// Dart's `Tween<double>(begin: begin, end: end).transform(t)`.
2180fn transform_tween(app: &mut App, begin: f64, end: f64, t: f64) -> f64 {
2181    let tween = Tween::new(app, Some(begin), Some(end));
2182    Animatable::transform(&tween, app, t)
2183}
2184
2185#[cfg(test)]
2186pub(crate) mod tests {
2187    use std::cell::Cell;
2188    use waft_painting::ShapeBorder;
2189
2190    use waft_embedder::{PointerChange, TextDirection, valo};
2191    use waft_painting::{EdgeInsets, StadiumBorder, TextScaler};
2192    use waft_rendering::RenderBox as _;
2193    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
2194    use waft_widgets::{
2195        AnyElement, Center, Directionality, FocusHighlightStrategy, Icon, IconData, MediaQueryData,
2196        RichText, StatefulBuilder, WidgetStateProperty,
2197    };
2198
2199    use waft_widgets::testing::{
2200        TestPointer, WidgetTester, expect, find, finds_n_widgets, finds_one_widget, test_widgets,
2201    };
2202
2203    use super::*;
2204    use crate::icons::Icons;
2205    use crate::material::RenderInkFeatures;
2206    use crate::scaffold::Scaffold;
2207    use crate::test_support::material_app;
2208    use crate::theme_data::ThemeData;
2209    use crate::tooltip::tests::{m2, m3, pump_app};
2210
2211    pub(crate) fn icon(icon: IconData) -> WidgetRef {
2212        Icon::new(Some(icon)).into_widget()
2213    }
2214
2215    pub(crate) fn destination(icon_data: IconData, label: &str) -> WidgetRef {
2216        NavigationDestination::new(icon(icon_data), label).into_widget()
2217    }
2218
2219    /// `[NavigationDestination(Icons.ac_unit, 'AC'), NavigationDestination(Icons.access_alarm,
2220    /// 'Alarm')]`.
2221    pub(crate) fn ac_alarm() -> Vec<WidgetRef> {
2222        vec![
2223            destination(Icons::ac_unit(), "AC"),
2224            destination(Icons::access_alarm(), "Alarm"),
2225        ]
2226    }
2227
2228    /// Dart's `_buildWidget(child, useMaterial3:)`.
2229    pub(crate) fn build_widget(
2230        tester: &mut WidgetTester,
2231        theme: impl FnOnce(&App) -> ThemeData,
2232        child: impl FnOnce() -> WidgetRef,
2233    ) {
2234        pump_app(tester, theme, |_app| {
2235            Scaffold::new()
2236                .bottom_navigation_bar(Center::new().child(child()))
2237                .into_widget()
2238        });
2239    }
2240
2241    pub(crate) fn navigation_bar(tester: &WidgetTester) -> AnyElement {
2242        find::by_type::<NavigationBar>().evaluate(tester)[0]
2243    }
2244
2245    pub(crate) fn bar_size(tester: &WidgetTester) -> Size {
2246        tester
2247            .render_box_of(navigation_bar(tester))
2248            .size(&tester.cell.borrow())
2249    }
2250
2251    /// Dart's `_getMaterial(tester)`: the first `Material` under the bar.
2252    pub(crate) fn bar_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
2253        let material = tester.descendants_of_type::<Material>(navigation_bar(tester))[0];
2254        tester.widget(material, read)
2255    }
2256
2257    /// Dart's `_getIndicatorDecoration(tester)`: the color and shape of the first `Ink` under
2258    /// a `FadeTransition`.
2259    pub(crate) fn indicator_decoration(tester: &WidgetTester) -> (Option<Color>, ShapeBorderRef) {
2260        let fade = find::by_type::<FadeTransition>().evaluate(tester);
2261        let ink = find::by_type::<Ink>()
2262            .evaluate(tester)
2263            .into_iter()
2264            .find(|ink| {
2265                let ancestors = tester.ancestors(*ink);
2266                fade.iter().any(|fade| ancestors.contains(fade))
2267            })
2268            .expect("an Ink under a FadeTransition");
2269        tester.widget(ink, |ink: &Ink| {
2270            let decoration = ink
2271                .decoration
2272                .as_ref()
2273                .and_then(|decoration| decoration.as_any().downcast_ref::<ShapeDecoration>())
2274                .expect("a ShapeDecoration");
2275            (
2276                decoration.color.as_deref().copied(),
2277                decoration.shape.clone(),
2278            )
2279        })
2280    }
2281
2282    pub(crate) fn text(tester: &WidgetTester, text: &str) -> AnyElement {
2283        let found = find::text(text).evaluate(tester);
2284        assert_eq!(found.len(), 1, "one Text showing {text}");
2285        found[0]
2286    }
2287
2288    /// Dart's `_getLabelPadding(tester, text)`.
2289    pub(crate) fn label_padding(tester: &WidgetTester, label: &str) -> EdgeInsetsGeometry {
2290        let padding =
2291            tester.element(find::ancestor(find::text(label), find::by_type::<Padding>()).first());
2292        tester.widget(padding, |padding: &Padding| padding.padding)
2293    }
2294
2295    /// Dart's `_getLabelStyle(tester, text)`.
2296    pub(crate) fn label_style(tester: &WidgetTester, label: &str) -> TextStyle {
2297        let label = text(tester, label);
2298        let rich_text = tester.descendants_of_type::<RichText>(label)[0];
2299        tester.widget(rich_text, |rich_text: &RichText| {
2300            rich_text
2301                .text
2302                .style()
2303                .cloned()
2304                .expect("the label has a style")
2305        })
2306    }
2307
2308    fn argb(color: valo::Color) -> u32 {
2309        let channel = |value: f32| (value * 255.0).round() as u32;
2310        (channel(color.a) << 24)
2311            | (channel(color.r) << 16)
2312            | (channel(color.g) << 8)
2313            | channel(color.b)
2314    }
2315
2316    /// What the ink features of the bar's own `Material` draw, in its coordinates: Dart's
2317    /// `paints` on the first `_RenderInkFeatures`, which records the features' calls with
2318    /// the arguments they are given.
2319    pub(crate) fn bar_ink_ops(tester: &WidgetTester) -> Vec<valo::Op> {
2320        let bar = tester.render_box_of(navigation_bar(tester)).as_object();
2321        let render = tester
2322            .all::<RenderInkFeatures>()
2323            .into_iter()
2324            .find(|render| {
2325                let app = tester.cell.borrow();
2326                std::iter::successors(render.as_object().parent(&app), |parent| {
2327                    parent.parent(&app)
2328                })
2329                .any(|ancestor| ancestor == bar)
2330            })
2331            .expect("the bar's Material");
2332        let mut canvas = waft_embedder::Canvas::new();
2333        render.paint_ink_features(&mut tester.cell.borrow_mut(), &mut canvas, Offset::ZERO);
2334        canvas.build().ops().to_vec()
2335    }
2336
2337    /// Dart's `circle(x:, y:, radius:, color:)` calls: centre, radius and colour.
2338    pub(crate) fn circles(ops: &[valo::Op]) -> Vec<(Offset, f64, u32)> {
2339        ops.iter()
2340            .filter_map(|op| match op {
2341                valo::Op::DrawPath { path, paint, .. } => path.as_oval().map(|oval| {
2342                    (
2343                        Offset::new(
2344                            f64::from(oval.x + oval.width / 2.0),
2345                            f64::from(oval.y + oval.height / 2.0),
2346                        ),
2347                        f64::from(oval.width) / 2.0,
2348                        argb(paint.color),
2349                    )
2350                }),
2351                _ => None,
2352            })
2353            .collect()
2354    }
2355
2356    /// Dart's `paints..clipPath(pathMatcher: isPathThat(includes:, excludes:))..circle(x:, y:,
2357    /// radius: 35.0, color: Color(0x0a000000))` for the indicator of `center`: a clip that
2358    /// holds the four edge midpoints of a 64x32 box and none of a 74x40 one, then the hover
2359    /// circle.
2360    pub(crate) fn paints_indicator_ripple(ops: &[valo::Op], center: Offset) -> bool {
2361        let midpoints = |size: Size| {
2362            [
2363                Offset::new(center.dx() - size.width() / 2.0, center.dy()),
2364                Offset::new(center.dx(), center.dy() - size.height() / 2.0),
2365                Offset::new(center.dx() + size.width() / 2.0, center.dy()),
2366                Offset::new(center.dx(), center.dy() + size.height() / 2.0),
2367            ]
2368        };
2369        // Dart's included points lie on the path's edge; the path is laid out through
2370        // valo's f32 `Matrix4`, so each is taken `POSITION_TOLERANCE` inside it.
2371        let inside = |size: Size| {
2372            midpoints(Size::new(
2373                size.width() - 2.0 * POSITION_TOLERANCE,
2374                size.height() - 2.0 * POSITION_TOLERANCE,
2375            ))
2376        };
2377        let contains = |path: &valo::Path, point: Offset| {
2378            path.contains(
2379                valo::Point::new(point.dx() as f32, point.dy() as f32),
2380                valo::FillRule::NonZero,
2381            )
2382        };
2383        let Some(clip_at) = ops.iter().position(|op| match op {
2384            valo::Op::ClipPath {
2385                path,
2386                is_axis_aligned_rect: false,
2387                ..
2388            } => {
2389                inside(Size::new(64.0, 32.0))
2390                    .iter()
2391                    .all(|point| contains(path, *point))
2392                    && midpoints(Size::new(74.0, 40.0))
2393                        .iter()
2394                        .all(|point| !contains(path, *point))
2395            }
2396            _ => false,
2397        }) else {
2398            return false;
2399        };
2400        circles(&ops[clip_at..])
2401            .iter()
2402            .any(|(circle_center, radius, color)| {
2403                (circle_center.dx() - center.dx()).abs() < 1e-3
2404                    && (circle_center.dy() - center.dy()).abs() < 1e-3
2405                    && (radius - 35.0).abs() < 1e-3
2406                    && *color == 0x0a000000
2407            })
2408    }
2409
2410    fn mouse_over(tester: &mut WidgetTester, mouse: &mut TestPointer, at: Offset) {
2411        tester.move_to(mouse, at, false);
2412        tester.pump_and_settle();
2413    }
2414
2415    #[test]
2416    fn navigation_bar_updates_destinations_when_tapped() {
2417        test_widgets(|tester| {
2418            let mutated_index = Rc::new(Cell::new(None));
2419            let seen = Rc::clone(&mutated_index);
2420            build_widget(tester, m3, move || {
2421                NavigationBar::new(ac_alarm())
2422                    .on_destination_selected(move |_app, i| seen.set(Some(i)))
2423                    .into_widget()
2424            });
2425
2426            expect(tester, &find::text("AC"), finds_one_widget());
2427            expect(tester, &find::text("Alarm"), finds_one_widget());
2428
2429            tester.tap_at(tester.get_center(text(tester, "Alarm")), 1);
2430            assert_eq!(mutated_index.get(), Some(1));
2431
2432            tester.tap_at(tester.get_center(text(tester, "AC")), 2);
2433            assert_eq!(mutated_index.get(), Some(0));
2434        });
2435    }
2436
2437    #[test]
2438    fn navigation_bar_can_update_background_color() {
2439        test_widgets(|tester| {
2440            let color = Colors::YELLOW.primary();
2441            build_widget(tester, m3, move || {
2442                NavigationBar::new(ac_alarm())
2443                    .background_color(color)
2444                    .on_destination_selected(|_app, _i| {})
2445                    .into_widget()
2446            });
2447
2448            assert_eq!(bar_material(tester, |material| material.color), Some(color));
2449        });
2450    }
2451
2452    #[test]
2453    fn navigation_bar_can_update_elevation() {
2454        test_widgets(|tester| {
2455            build_widget(tester, m3, || {
2456                NavigationBar::new(ac_alarm())
2457                    .elevation(42.0)
2458                    .on_destination_selected(|_app, _i| {})
2459                    .into_widget()
2460            });
2461
2462            assert_eq!(bar_material(tester, |material| material.elevation), 42.0);
2463        });
2464    }
2465
2466    #[test]
2467    fn navigation_bar_adds_bottom_padding_to_height() {
2468        test_widgets(|tester| {
2469            let bottom_padding = 40.0;
2470            build_widget(tester, m3, || {
2471                NavigationBar::new(ac_alarm())
2472                    .on_destination_selected(|_app, _i| {})
2473                    .into_widget()
2474            });
2475
2476            let default_size = bar_size(tester).height();
2477            assert_eq!(default_size, 80.0);
2478
2479            build_widget(tester, m3, || {
2480                MediaQuery::new(
2481                    MediaQueryData::new().padding(EdgeInsets::only(0.0, 0.0, 0.0, bottom_padding)),
2482                    NavigationBar::new(ac_alarm()).on_destination_selected(|_app, _i| {}),
2483                )
2484                .into_widget()
2485            });
2486
2487            let expected_height = default_size + bottom_padding;
2488            assert_eq!(bar_size(tester).height(), expected_height);
2489        });
2490    }
2491
2492    /// The tolerance of a position read through `local_to_global`: `Matrix4` is valo's f32
2493    /// matrix (waft-gestures' PORTING.md), so a position is exact only to f32 where Dart's f64
2494    /// one is exact.
2495    const POSITION_TOLERANCE: f64 = 1e-4;
2496
2497    /// Dart's `expect(x, y)` and `closeTo(y, precisionErrorTolerance)` on a coordinate read
2498    /// through `local_to_global`.
2499    fn assert_coordinate_eq(actual: f64, expected: f64) {
2500        assert!(
2501            (actual - expected).abs() < POSITION_TOLERANCE,
2502            "{actual} is not {expected}"
2503        );
2504    }
2505
2506    #[test]
2507    fn navigation_bar_respects_the_notch_or_system_navigation_bar_in_landscape_mode() {
2508        test_widgets(|tester| {
2509            let safe_area_padding = 40.0;
2510            let center_key = || KeyRef::from(<dyn waft_foundation::Key>::new("Center"));
2511            let navigation_bar = move || {
2512                NavigationBar::new([
2513                    destination(Icons::ac_unit(), "AC"),
2514                    NavigationDestination::new(icon(Icons::center_focus_strong()), "Center")
2515                        .key(center_key())
2516                        .into_widget(),
2517                    destination(Icons::access_alarm(), "Alarm"),
2518                ])
2519                .on_destination_selected(|_app, _i| {})
2520            };
2521            let center_item = |tester: &WidgetTester| {
2522                let found = find::by_key(center_key()).evaluate(tester);
2523                tester.get_center(found[0])
2524            };
2525            let with_padding = |padding: EdgeInsets| {
2526                move || {
2527                    MediaQuery::new(MediaQueryData::new().padding(padding), navigation_bar())
2528                        .into_widget()
2529                }
2530            };
2531
2532            build_widget(tester, m3, || navigation_bar().into_widget());
2533            let default_width = bar_size(tester).width();
2534            assert_coordinate_eq(center_item(tester).dx(), default_width / 2.0);
2535
2536            // The position of center item of navigation bar should indicate whether
2537            // the safe area is sufficiently respected, when safe area is on the left side.
2538            // e.g. Android device with system navigation bar in landscape mode.
2539            build_widget(
2540                tester,
2541                m3,
2542                with_padding(EdgeInsets::only(safe_area_padding, 0.0, 0.0, 0.0)),
2543            );
2544            assert_coordinate_eq(
2545                center_item(tester).dx(),
2546                (default_width + safe_area_padding) / 2.0,
2547            );
2548
2549            // The position of center item of navigation bar should indicate whether
2550            // the safe area is sufficiently respected, when safe area is on the right side.
2551            // e.g. Android device with system navigation bar in landscape mode.
2552            build_widget(
2553                tester,
2554                m3,
2555                with_padding(EdgeInsets::only(0.0, 0.0, safe_area_padding, 0.0)),
2556            );
2557            assert_coordinate_eq(
2558                center_item(tester).dx(),
2559                (default_width - safe_area_padding) / 2.0,
2560            );
2561
2562            // The position of center item of navigation bar should indicate whether
2563            // the safe area is sufficiently respected, when safe areas are on both sides.
2564            // e.g. iOS device with both sides of round corner.
2565            build_widget(
2566                tester,
2567                m3,
2568                with_padding(EdgeInsets::from_ltrb(
2569                    safe_area_padding,
2570                    0.0,
2571                    safe_area_padding,
2572                    safe_area_padding,
2573                )),
2574            );
2575            assert_coordinate_eq(center_item(tester).dx(), default_width / 2.0);
2576        });
2577    }
2578
2579    #[test]
2580    fn material2_navigation_bar_uses_proper_defaults_when_no_parameters_are_given() {
2581        test_widgets(|tester| {
2582            // M2 settings that were hand coded.
2583            build_widget(tester, m2, || {
2584                NavigationBar::new(ac_alarm())
2585                    .on_destination_selected(|_app, _i| {})
2586                    .into_widget()
2587            });
2588
2589            assert_eq!(
2590                bar_material(tester, |material| material.color),
2591                Some(Color::new(0xffeaeaea))
2592            );
2593            assert_eq!(
2594                bar_material(tester, |material| material.surface_tint_color),
2595                None
2596            );
2597            assert_eq!(bar_material(tester, |material| material.elevation), 0.0);
2598            assert_eq!(bar_size(tester).height(), 80.0);
2599            let (color, shape) = indicator_decoration(tester);
2600            assert_eq!(color, Some(Color::new(0x3d2196f3)));
2601            assert_eq!(
2602                &*shape,
2603                &RoundedRectangleBorder::new(
2604                    BorderSide::NONE,
2605                    BorderRadius::all(Radius::circular(16.0)).into()
2606                ) as &dyn ShapeBorder
2607            );
2608        });
2609    }
2610
2611    #[test]
2612    fn material3_navigation_bar_uses_proper_defaults_when_no_parameters_are_given() {
2613        test_widgets(|tester| {
2614            // M3 settings from the token database.
2615            let theme = m3(&tester.cell.borrow());
2616            build_widget(tester, m3, || {
2617                NavigationBar::new(ac_alarm())
2618                    .on_destination_selected(|_app, _i| {})
2619                    .into_widget()
2620            });
2621
2622            assert_eq!(
2623                bar_material(tester, |material| material.color),
2624                Some(theme.color_scheme.surface_container())
2625            );
2626            assert_eq!(
2627                bar_material(tester, |material| material.surface_tint_color),
2628                Some(Colors::TRANSPARENT)
2629            );
2630            assert_eq!(bar_material(tester, |material| material.elevation), 3.0);
2631            assert_eq!(bar_size(tester).height(), 80.0);
2632            let (color, shape) = indicator_decoration(tester);
2633            assert_eq!(color, Some(theme.color_scheme.secondary_container()));
2634            assert_eq!(
2635                &*shape,
2636                &StadiumBorder::new(BorderSide::NONE) as &dyn ShapeBorder
2637            );
2638        });
2639    }
2640
2641    /// The app of the tooltip text-scaling cases: `MediaQuery(data: MediaQueryData(textScaler:
2642    /// text_scaler), child: MaterialApp(home: Scaffold(bottomNavigationBar: NavigationBar(..))))`.
2643    fn pump_scaled_bar(
2644        tester: &mut WidgetTester,
2645        theme: impl FnOnce(&App) -> ThemeData,
2646        text_scaler: TextScaler,
2647        first: NavigationDestination,
2648    ) {
2649        let root = {
2650            let app = tester.cell.borrow();
2651            let theme = theme(&app);
2652            MediaQuery::new(
2653                MediaQueryData::new().text_scaler(text_scaler),
2654                material_app(
2655                    theme,
2656                    Scaffold::new()
2657                        .bottom_navigation_bar(NavigationBar::new([
2658                            first.into_widget(),
2659                            destination(Icons::battery_alert(), "B"),
2660                        ]))
2661                        .into_widget(),
2662                ),
2663            )
2664            .into_widget()
2665        };
2666        tester.pump_widget(root);
2667    }
2668
2669    fn text_size(tester: &WidgetTester, element: AnyElement) -> Size {
2670        tester.render_box_of(element).size(&tester.cell.borrow())
2671    }
2672
2673    #[test]
2674    fn material2_navigation_bar_shows_tooltips_with_text_scaling() {
2675        test_widgets(|tester| {
2676            let label = "A";
2677            let first = || NavigationDestination::new(icon(Icons::ac_unit()), label).tooltip(label);
2678
2679            pump_scaled_bar(tester, m2, TextScaler::NO_SCALING, first());
2680            expect(tester, &find::text(label), finds_one_widget());
2681            tester.long_press_at(tester.get_center(find::text(label).evaluate(tester)[0]), 1);
2682            expect(tester, &find::text(label), finds_n_widgets(2));
2683
2684            // The default size of a tooltip with the text A.
2685            let default_tooltip_size = Size::new(14.0, 14.0);
2686            let found = find::text(label).evaluate(tester);
2687            assert_eq!(
2688                text_size(tester, found[found.len() - 1]),
2689                default_tooltip_size
2690            );
2691            // The duration is needed to ensure the tooltip disappears.
2692            tester.pump_and_settle_by(Duration::from_secs(2));
2693
2694            pump_scaled_bar(tester, m2, TextScaler::linear(4.0), first());
2695            expect(tester, &find::text(label), finds_one_widget());
2696            tester.long_press_at(tester.get_center(find::text(label).evaluate(tester)[0]), 2);
2697            let found = find::text(label).evaluate(tester);
2698            assert_eq!(
2699                text_size(tester, found[found.len() - 1]),
2700                Size::new(
2701                    default_tooltip_size.width() * 4.0,
2702                    default_tooltip_size.height() * 4.0
2703                )
2704            );
2705        });
2706    }
2707
2708    #[test]
2709    fn material3_navigation_bar_shows_tooltips_with_text_scaling() {
2710        test_widgets(|tester| {
2711            let label = "A";
2712            let first = || NavigationDestination::new(icon(Icons::ac_unit()), label).tooltip(label);
2713
2714            pump_scaled_bar(tester, m3, TextScaler::NO_SCALING, first());
2715            expect(tester, &find::text(label), finds_one_widget());
2716            tester.long_press_at(tester.get_center(find::text(label).evaluate(tester)[0]), 1);
2717            expect(tester, &find::text(label), finds_n_widgets(2));
2718
2719            let found = find::text(label).evaluate(tester);
2720            assert_eq!(
2721                text_size(tester, found[found.len() - 1]),
2722                Size::new(14.25, 20.0)
2723            );
2724            // The duration is needed to ensure the tooltip disappears.
2725            tester.pump_and_settle_by(Duration::from_secs(2));
2726
2727            pump_scaled_bar(tester, m3, TextScaler::linear(4.0), first());
2728            expect(tester, &find::text(label), finds_one_widget());
2729            tester.long_press_at(tester.get_center(find::text(label).evaluate(tester)[0]), 2);
2730
2731            let found = find::text(label).evaluate(tester);
2732            assert_eq!(
2733                text_size(tester, found[found.len() - 1]),
2734                Size::new(56.25, 80.0)
2735            );
2736        });
2737    }
2738
2739    /// Dart's `_sizeAlmostEqual(a, b)`, with its default `maxDiff` of 0.05.
2740    fn size_almost_equal(a: Size, b: Size) -> bool {
2741        (a.width() - b.width()).abs() <= 0.05 && (a.height() - b.height()).abs() <= 0.05
2742    }
2743
2744    #[test]
2745    fn material3_navigation_bar_label_can_scale_and_has_max_scale_factor() {
2746        test_widgets(|tester| {
2747            let label = "A";
2748            let first = || NavigationDestination::new(icon(Icons::ac_unit()), label);
2749
2750            pump_scaled_bar(tester, m3, TextScaler::NO_SCALING, first());
2751            expect(tester, &find::text(label), finds_one_widget());
2752            let size = text_size(tester, text(tester, label));
2753            assert!(size_almost_equal(size, Size::new(12.5, 16.0)), "{size:?}");
2754
2755            pump_scaled_bar(tester, m3, TextScaler::linear(1.1), first());
2756            tester.pump_and_settle();
2757            let size = text_size(tester, text(tester, label));
2758            assert!(size_almost_equal(size, Size::new(13.7, 18.0)), "{size:?}");
2759
2760            pump_scaled_bar(tester, m3, TextScaler::linear(1.3), first());
2761            let size = text_size(tester, text(tester, label));
2762            assert!(size_almost_equal(size, Size::new(16.1, 21.0)), "{size:?}");
2763
2764            pump_scaled_bar(tester, m3, TextScaler::linear(4.0), first());
2765            let size = text_size(tester, text(tester, label));
2766            assert!(size_almost_equal(size, Size::new(16.1, 21.0)), "{size:?}");
2767        });
2768    }
2769
2770    /// Dart's `findByTooltip(message)`: the `Tooltip`s whose message is `message`.
2771    fn tooltips_with_message(tester: &WidgetTester, message: &str) -> usize {
2772        find::by_type::<Tooltip>()
2773            .evaluate(tester)
2774            .into_iter()
2775            .filter(|tooltip| {
2776                tester.widget(*tooltip, |tooltip: &Tooltip| {
2777                    tooltip.message.as_deref() == Some(message)
2778                })
2779            })
2780            .count()
2781    }
2782
2783    #[test]
2784    fn custom_tooltips_in_navigation_bar_destination() {
2785        test_widgets(|tester| {
2786            pump_app(tester, m3, |_app| {
2787                Scaffold::new()
2788                    .bottom_navigation_bar(NavigationBar::new([
2789                        NavigationDestination::new(icon(Icons::ac_unit()), "A")
2790                            .tooltip("A tooltip")
2791                            .into_widget(),
2792                        destination(Icons::battery_alert(), "B"),
2793                        NavigationDestination::new(icon(Icons::cake()), "C")
2794                            .tooltip("")
2795                            .into_widget(),
2796                    ]))
2797                    .into_widget()
2798            });
2799
2800            expect(tester, &find::text("A"), finds_one_widget());
2801            tester.long_press_at(tester.get_center(text(tester, "A")), 1);
2802            assert_eq!(tooltips_with_message(tester, "A tooltip"), 1);
2803
2804            expect(tester, &find::text("B"), finds_one_widget());
2805            tester.long_press_at(tester.get_center(text(tester, "B")), 2);
2806            assert_eq!(tooltips_with_message(tester, "B"), 1);
2807
2808            expect(tester, &find::text("C"), finds_one_widget());
2809            tester.long_press_at(tester.get_center(text(tester, "C")), 3);
2810            assert_eq!(tooltips_with_message(tester, "C"), 0);
2811        });
2812    }
2813
2814    #[test]
2815    fn navigation_bar_does_not_grow_with_text_scale_factor() {
2816        test_widgets(|tester| {
2817            let widget = |text_scaler: TextScaler| {
2818                move || {
2819                    MediaQuery::new(
2820                        MediaQueryData::new().text_scaler(text_scaler),
2821                        NavigationBar::new(ac_alarm())
2822                            .animation_duration(Duration::from_millis(800)),
2823                    )
2824                    .into_widget()
2825                }
2826            };
2827
2828            build_widget(tester, m3, widget(TextScaler::NO_SCALING));
2829            let initial_height = bar_size(tester).height();
2830
2831            build_widget(tester, m3, widget(TextScaler::linear(2.0)));
2832            let new_height = bar_size(tester).height();
2833
2834            assert_eq!(new_height, initial_height);
2835        });
2836    }
2837
2838    /// The bar of the ripple cases, centred in the scaffold's bottom slot.
2839    fn pump_ripple_bar(
2840        tester: &mut WidgetTester,
2841        theme: fn(&App) -> ThemeData,
2842        selected_index: usize,
2843        label_behavior: Option<NavigationDestinationLabelBehavior>,
2844    ) {
2845        build_widget(tester, theme, move || {
2846            let mut bar = NavigationBar::new(ac_alarm())
2847                .selected_index(selected_index)
2848                .on_destination_selected(|_app, _i| {});
2849            if let Some(label_behavior) = label_behavior {
2850                bar = bar.label_behavior(label_behavior);
2851            }
2852            bar.into_widget()
2853        });
2854    }
2855
2856    fn icon_center(tester: &WidgetTester, icon: &IconData) -> Offset {
2857        tester.get_center(tester.element(find::by_icon(icon).first()))
2858    }
2859
2860    /// Dart's `Material3/Material2 - Navigation indicator renders ripple`, with the indicator
2861    /// centres the label behaviours give.
2862    fn indicator_renders_ripple(
2863        tester: &mut WidgetTester,
2864        theme: fn(&App) -> ThemeData,
2865        always_show_center: Offset,
2866        always_hide_center: Offset,
2867    ) {
2868        // This is a regression test for https://github.com/flutter/flutter/issues/116751.
2869        pump_ripple_bar(tester, theme, 0, None);
2870
2871        let mut mouse = TestPointer::mouse(1, 0);
2872        tester.add_pointer(&mut mouse, Offset::ZERO);
2873        let alarm = icon_center(tester, &Icons::access_alarm());
2874        mouse_over(tester, &mut mouse, alarm);
2875
2876        // Test ripple when NavigationBar is using `NavigationDestinationLabelBehavior.alwaysShow` (default).
2877        assert!(paints_indicator_ripple(
2878            &bar_ink_ops(tester),
2879            always_show_center
2880        ));
2881
2882        // Test ripple when NavigationBar is using `NavigationDestinationLabelBehavior.alwaysHide`.
2883        pump_ripple_bar(
2884            tester,
2885            theme,
2886            0,
2887            Some(NavigationDestinationLabelBehavior::AlwaysHide),
2888        );
2889        let alarm = icon_center(tester, &Icons::access_alarm());
2890        mouse_over(tester, &mut mouse, alarm);
2891        assert!(paints_indicator_ripple(
2892            &bar_ink_ops(tester),
2893            always_hide_center
2894        ));
2895
2896        // Test ripple when NavigationBar is using `NavigationDestinationLabelBehavior.onlyShowSelected`.
2897        pump_ripple_bar(
2898            tester,
2899            theme,
2900            0,
2901            Some(NavigationDestinationLabelBehavior::OnlyShowSelected),
2902        );
2903        let alarm = icon_center(tester, &Icons::access_alarm());
2904        mouse_over(tester, &mut mouse, alarm);
2905        assert!(paints_indicator_ripple(
2906            &bar_ink_ops(tester),
2907            always_hide_center
2908        ));
2909
2910        // Make sure ripple is shifted when selectedIndex changes.
2911        pump_ripple_bar(
2912            tester,
2913            theme,
2914            1,
2915            Some(NavigationDestinationLabelBehavior::OnlyShowSelected),
2916        );
2917        tester.pump_and_settle();
2918        assert!(paints_indicator_ripple(
2919            &bar_ink_ops(tester),
2920            always_show_center
2921        ));
2922    }
2923
2924    #[test]
2925    fn material3_navigation_indicator_renders_ripple() {
2926        test_widgets(|tester| {
2927            indicator_renders_ripple(
2928                tester,
2929                m3,
2930                Offset::new(600.0, 30.0),
2931                Offset::new(600.0, 40.0),
2932            );
2933        });
2934    }
2935
2936    #[test]
2937    fn material2_navigation_indicator_renders_ripple() {
2938        test_widgets(|tester| {
2939            indicator_renders_ripple(
2940                tester,
2941                m2,
2942                Offset::new(600.0, 33.0),
2943                Offset::new(600.0, 40.0),
2944            );
2945        });
2946    }
2947
2948    /// The x scale of the last `Transform` under a `NavigationIndicator`.
2949    fn indicator_x_scale(tester: &WidgetTester) -> f32 {
2950        let transforms: Vec<AnyElement> = find::by_type::<NavigationIndicator>()
2951            .evaluate(tester)
2952            .into_iter()
2953            .flat_map(|indicator| tester.descendants_of_type::<Transform>(indicator))
2954            .collect();
2955        let transform = *transforms.last().expect("a Transform under an indicator");
2956        tester.widget(transform, |transform: &Transform| {
2957            transform.transform.to_flutter_array()[0]
2958        })
2959    }
2960
2961    #[test]
2962    fn navigation_indicator_scale_transform() {
2963        test_widgets(|tester| {
2964            pump_ripple_bar(tester, m3, 0, None);
2965            tester.pump_and_settle();
2966            assert_eq!(indicator_x_scale(tester), 0.0);
2967
2968            pump_ripple_bar(tester, m3, 1, None);
2969            tester.pump_by(Duration::from_millis(100));
2970            // The matrix is valo's f32 one: Dart's double, rounded to f32.
2971            assert_eq!(indicator_x_scale(tester), 0.7805849514007568_f64 as f32);
2972
2973            tester.pump_by(Duration::from_millis(100));
2974            assert_eq!(indicator_x_scale(tester), 0.9473570239543915_f64 as f32);
2975
2976            tester.pump_and_settle();
2977            assert_eq!(indicator_x_scale(tester), 1.0);
2978        });
2979    }
2980
2981    #[test]
2982    fn material3_navigation_destination_updates_indicator_color_and_shape() {
2983        test_widgets(|tester| {
2984            let color = Color::new(0xff0000ff);
2985            let shape = || RoundedRectangleBorder::new(BorderSide::NONE, BorderRadius::ZERO.into());
2986            let theme = m3(&tester.cell.borrow());
2987            let pump = |tester: &mut WidgetTester, custom: bool| {
2988                pump_app(tester, m3, |_app| {
2989                    let mut bar =
2990                        NavigationBar::new(ac_alarm()).on_destination_selected(|_app, _i| {});
2991                    if custom {
2992                        bar = bar.indicator_color(color).indicator_shape(shape());
2993                    }
2994                    Scaffold::new()
2995                        .bottom_navigation_bar(waft_widgets::RepaintBoundary::new().child(bar))
2996                        .into_widget()
2997                });
2998            };
2999
3000            pump(tester, false);
3001
3002            // Test default indicator color and shape.
3003            let (default_color, default_shape) = indicator_decoration(tester);
3004            assert_eq!(
3005                default_color,
3006                Some(theme.color_scheme.secondary_container())
3007            );
3008            assert_eq!(
3009                &*default_shape,
3010                &StadiumBorder::new(BorderSide::NONE) as &dyn ShapeBorder
3011            );
3012
3013            pump(tester, true);
3014
3015            // Test custom indicator color and shape.
3016            let (custom_color, custom_shape) = indicator_decoration(tester);
3017            assert_eq!(custom_color, Some(color));
3018            assert_eq!(&*custom_shape, &shape() as &dyn ShapeBorder);
3019        });
3020    }
3021
3022    #[test]
3023    fn destinations_respect_their_disabled_state() {
3024        test_widgets(|tester| {
3025            let selected_index = Rc::new(Cell::new(0));
3026            let seen = Rc::clone(&selected_index);
3027            build_widget(tester, m3, move || {
3028                let current = seen.get();
3029                NavigationBar::new([
3030                    destination(Icons::ac_unit(), "AC"),
3031                    destination(Icons::access_alarm(), "Alarm"),
3032                    NavigationDestination::new(icon(Icons::bookmark()), "Bookmark")
3033                        .enabled(false)
3034                        .into_widget(),
3035                ])
3036                .on_destination_selected(move |_app, i| seen.set(i))
3037                .selected_index(current)
3038                .into_widget()
3039            });
3040
3041            tester.tap_at(tester.get_center(text(tester, "AC")), 1);
3042            assert_eq!(selected_index.get(), 0);
3043
3044            tester.tap_at(tester.get_center(text(tester, "Alarm")), 2);
3045            assert_eq!(selected_index.get(), 1);
3046
3047            tester.tap_at(tester.get_center(text(tester, "Bookmark")), 3);
3048            assert_eq!(selected_index.get(), 1);
3049        });
3050    }
3051
3052    /// Dart's `overlayColor` of the overlay-colour cases: hovered, focused, pressed, else
3053    /// transparent.
3054    pub(crate) fn state_overlay_color() -> WidgetStatePropertyRef<Option<Color>> {
3055        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
3056            Some(if states.contains(&WidgetState::Hovered) {
3057                Color::new(0xff0000ff)
3058            } else if states.contains(&WidgetState::Focused) {
3059                Color::new(0xff00ffff)
3060            } else if states.contains(&WidgetState::Pressed) {
3061                Color::new(0xffff00ff)
3062            } else {
3063                Colors::TRANSPARENT
3064            })
3065        })
3066    }
3067
3068    /// Dart's hover, press and focus steps of the overlay-colour cases, on a bar already
3069    /// pumped.
3070    pub(crate) fn respects_overlay_color(tester: &mut WidgetTester) {
3071        let hover_color = 0xff0000ff;
3072        let focus_color = 0xff00ffff;
3073        let pressed_color = 0xffff00ff;
3074
3075        let indicators = find::by_type::<NavigationIndicator>().evaluate(tester);
3076        let indicator = tester.get_center(indicators[indicators.len() - 1]);
3077        let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3078        tester.add_pointer(&mut mouse, Offset::ZERO);
3079        mouse_over(tester, &mut mouse, indicator);
3080
3081        // Test hovered state.
3082        let colors = |tester: &WidgetTester| -> Vec<u32> {
3083            circles(&bar_ink_ops(tester))
3084                .into_iter()
3085                .map(|(_, _, color)| color)
3086                .collect()
3087        };
3088        assert!(colors(tester).contains(&hover_color));
3089
3090        tester.send(&mouse, PointerChange::Down);
3091        tester.pump_and_settle();
3092
3093        // Test pressed state.
3094        let pressed = colors(tester);
3095        let at = pressed
3096            .iter()
3097            .position(|color| *color == pressed_color)
3098            .expect("a circle in the pressed colour");
3099        assert!(at >= 1, "a circle before the pressed one: {pressed:x?}");
3100
3101        tester.send(&mouse, PointerChange::Up);
3102        tester.pump_and_settle();
3103
3104        // Press tab to focus the navigation bar.
3105        tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
3106        tester.pump_and_settle();
3107
3108        // Test focused state.
3109        let focused = colors(tester);
3110        let at = focused
3111            .iter()
3112            .position(|color| *color == focus_color)
3113            .expect("a circle in the focus colour");
3114        assert!(at >= 1, "a circle before the focused one: {focused:x?}");
3115    }
3116
3117    #[test]
3118    fn navigation_bar_respects_overlay_color_in_active_pressed_hovered_states() {
3119        test_widgets(|tester| {
3120            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
3121            pump_app(tester, m3, |_app| {
3122                Scaffold::new()
3123                    .bottom_navigation_bar(
3124                        waft_widgets::RepaintBoundary::new().child(
3125                            NavigationBar::new(ac_alarm())
3126                                .overlay_color(state_overlay_color())
3127                                .on_destination_selected(|_app, _i| {}),
3128                        ),
3129                    )
3130                    .into_widget()
3131            });
3132
3133            respects_overlay_color(tester);
3134        });
3135    }
3136
3137    #[test]
3138    fn navigation_bar_label_padding_overrides_navigation_destination_label_padding() {
3139        test_widgets(|tester| {
3140            let label_padding = EdgeInsetsGeometry::all(8.0);
3141            let pump = |tester: &mut WidgetTester, padding: Option<EdgeInsetsGeometry>| {
3142                pump_app(tester, m3, |_app| {
3143                    let mut bar = NavigationBar::new([
3144                        destination(Icons::home(), "Home"),
3145                        destination(Icons::settings(), "Settings"),
3146                    ])
3147                    .on_destination_selected(|_app, _i| {});
3148                    if let Some(padding) = padding {
3149                        bar = bar.label_padding(padding);
3150                    }
3151                    Scaffold::new().bottom_navigation_bar(bar).into_widget()
3152                });
3153            };
3154
3155            pump(tester, None);
3156            let default_padding: EdgeInsetsGeometry = EdgeInsets::only(0.0, 4.0, 0.0, 0.0).into();
3157            assert_eq!(label_padding_of(tester, "Home"), default_padding);
3158            assert_eq!(label_padding_of(tester, "Settings"), default_padding);
3159
3160            pump(tester, Some(label_padding));
3161            assert_eq!(label_padding_of(tester, "Home"), label_padding);
3162            assert_eq!(label_padding_of(tester, "Settings"), label_padding);
3163        });
3164    }
3165
3166    fn label_padding_of(tester: &WidgetTester, label: &str) -> EdgeInsetsGeometry {
3167        label_padding(tester, label)
3168    }
3169
3170    #[test]
3171    fn material2_navigation_destination_updates_indicator_color_and_shape() {
3172        test_widgets(|tester| {
3173            let color = Color::new(0xff0000ff);
3174            let shape = || RoundedRectangleBorder::new(BorderSide::NONE, BorderRadius::ZERO.into());
3175            let theme = m2(&tester.cell.borrow());
3176            let pump = |tester: &mut WidgetTester, custom: bool| {
3177                pump_app(tester, m2, |_app| {
3178                    let mut bar =
3179                        NavigationBar::new(ac_alarm()).on_destination_selected(|_app, _i| {});
3180                    if custom {
3181                        bar = bar.indicator_color(color).indicator_shape(shape());
3182                    }
3183                    Scaffold::new().bottom_navigation_bar(bar).into_widget()
3184                });
3185            };
3186
3187            pump(tester, false);
3188
3189            // Test default indicator color and shape.
3190            let (default_color, default_shape) = indicator_decoration(tester);
3191            #[allow(deprecated)]
3192            let expected_color = theme.color_scheme.secondary().with_opacity(0.24);
3193            assert_eq!(default_color, Some(expected_color));
3194            assert_eq!(
3195                &*default_shape,
3196                &RoundedRectangleBorder::new(
3197                    BorderSide::NONE,
3198                    BorderRadius::all(Radius::circular(16.0)).into()
3199                ) as &dyn ShapeBorder
3200            );
3201
3202            pump(tester, true);
3203
3204            // Test custom indicator color and shape.
3205            let (custom_color, custom_shape) = indicator_decoration(tester);
3206            assert_eq!(custom_color, Some(color));
3207            assert_eq!(&*custom_shape, &shape() as &dyn ShapeBorder);
3208        });
3209    }
3210
3211    /// Dart's `IconWithRandomColor`: an `Icon` whose colour differs on every build.
3212    #[derive(Debug)]
3213    struct IconWithChangingColor {
3214        icon: IconData,
3215        builds: Rc<Cell<u32>>,
3216    }
3217
3218    impl StatelessWidget for IconWithChangingColor {
3219        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
3220            self.builds.set(self.builds.get() + 1);
3221            let color = Color::new(0xff000000 | self.builds.get());
3222            Icon::new(Some(self.icon.clone()))
3223                .color(color)
3224                .into_widget()
3225        }
3226    }
3227
3228    #[test]
3229    fn material2_destination_icon_does_not_rebuild_when_tapped() {
3230        test_widgets(|tester| {
3231            // This is a regression test for https://github.com/flutter/flutter/issues/122811.
3232            let builds = Rc::new(Cell::new(0));
3233            // Dart's `const` destinations: one instance across the builder's builds.
3234            let destinations = vec![
3235                NavigationDestination::new(
3236                    IconWithChangingColor {
3237                        icon: Icons::ac_unit(),
3238                        builds: Rc::clone(&builds),
3239                    },
3240                    "AC",
3241                )
3242                .into_widget(),
3243                NavigationDestination::new(
3244                    IconWithChangingColor {
3245                        icon: Icons::access_alarm(),
3246                        builds: Rc::clone(&builds),
3247                    },
3248                    "Alarm",
3249                )
3250                .into_widget(),
3251            ];
3252            pump_app(tester, m3, move |_app| {
3253                Scaffold::new()
3254                    .bottom_navigation_bar(StatefulBuilder::new(
3255                        move |_app, _context, set_state| {
3256                            let selected_index = 0;
3257                            NavigationBar::new(destinations.clone())
3258                                .selected_index(selected_index)
3259                                .on_destination_selected(move |app, _i| {
3260                                    set_state(app, &mut |_app| {});
3261                                })
3262                                .into_widget()
3263                        },
3264                    ))
3265                    .into_widget()
3266            });
3267            let last_icon_color = |tester: &WidgetTester| {
3268                let icons = find::by_type::<Icon>().evaluate(tester);
3269                tester.widget(icons[icons.len() - 1], |icon: &Icon| icon.color.clone())
3270            };
3271            let initial_color = last_icon_color(tester).expect("the icon has a color");
3272
3273            // Trigger a rebuild.
3274            tester.tap_at(tester.get_center(text(tester, "Alarm")), 1);
3275            tester.pump_and_settle();
3276
3277            // Icon color should be the same as before the rebuild.
3278            assert_eq!(last_icon_color(tester), Some(initial_color));
3279        });
3280    }
3281
3282    #[test]
3283    fn navigation_bar_label_text_style_overrides_navigation_destination_label_text_style() {
3284        test_widgets(|tester| {
3285            let selected_text = "Home";
3286            let unselected_text = "Settings";
3287            let disabled_text = "Bookmark";
3288            let pump = |tester: &mut WidgetTester,
3289                        label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>| {
3290                pump_app(tester, m3, |_app| {
3291                    let mut bar = NavigationBar::new([
3292                        destination(Icons::home(), selected_text),
3293                        destination(Icons::settings(), unselected_text),
3294                        NavigationDestination::new(icon(Icons::bookmark()), disabled_text)
3295                            .enabled(false)
3296                            .into_widget(),
3297                    ]);
3298                    if let Some(label_text_style) = label_text_style {
3299                        bar = bar.label_text_style(label_text_style);
3300                    }
3301                    Scaffold::new().bottom_navigation_bar(bar).into_widget()
3302                });
3303            };
3304            let theme = m3(&tester.cell.borrow());
3305
3306            pump(tester, None);
3307
3308            // Test selected label text style.
3309            assert_eq!(label_style(tester, selected_text).font_size, Some(12.0));
3310            assert_eq!(
3311                label_style(tester, selected_text).color.as_deref().copied(),
3312                Some(theme.color_scheme.on_surface())
3313            );
3314
3315            // Test unselected label text style.
3316            assert_eq!(label_style(tester, unselected_text).font_size, Some(12.0));
3317            assert_eq!(
3318                label_style(tester, unselected_text)
3319                    .color
3320                    .as_deref()
3321                    .copied(),
3322                Some(theme.color_scheme.on_surface_variant())
3323            );
3324
3325            // Test disabled label text style.
3326            assert_eq!(label_style(tester, disabled_text).font_size, Some(12.0));
3327            #[allow(deprecated)]
3328            let disabled_color = theme.color_scheme.on_surface_variant().with_opacity(0.38);
3329            assert_eq!(
3330                label_style(tester, disabled_text).color.as_deref().copied(),
3331                Some(disabled_color)
3332            );
3333
3334            let selected_text_style = TextStyle::new()
3335                .font_size(15.0)
3336                .color(Color::new(0xFF00FF00));
3337            let unselected_text_style = TextStyle::new()
3338                .font_size(15.0)
3339                .color(Color::new(0xFF0000FF));
3340            let disabled_text_style = TextStyle::new()
3341                .font_size(16.0)
3342                .color(Color::new(0xFFFF0000));
3343            pump(
3344                tester,
3345                Some(<dyn WidgetStateProperty<Option<TextStyle>>>::from_map(
3346                    vec![
3347                        (
3348                            WidgetState::Disabled.into(),
3349                            Some(disabled_text_style.clone()),
3350                        ),
3351                        (
3352                            WidgetState::Selected.into(),
3353                            Some(selected_text_style.clone()),
3354                        ),
3355                        (WidgetState::any(), Some(unselected_text_style.clone())),
3356                    ],
3357                )),
3358            );
3359
3360            // Test selected label text style.
3361            assert_eq!(
3362                label_style(tester, selected_text).font_size,
3363                selected_text_style.font_size
3364            );
3365            assert_eq!(
3366                label_style(tester, selected_text).color,
3367                selected_text_style.color
3368            );
3369
3370            // Test unselected label text style.
3371            assert_eq!(
3372                label_style(tester, unselected_text).font_size,
3373                unselected_text_style.font_size
3374            );
3375            assert_eq!(
3376                label_style(tester, unselected_text).color,
3377                unselected_text_style.color
3378            );
3379
3380            // Test disabled label text style.
3381            assert_eq!(
3382                label_style(tester, disabled_text).font_size,
3383                disabled_text_style.font_size
3384            );
3385            assert_eq!(
3386                label_style(tester, disabled_text).color,
3387                disabled_text_style.color
3388            );
3389        });
3390    }
3391
3392    #[test]
3393    fn navigation_bar_maintain_bottom_view_padding_can_consume_bottom_media_query_padding() {
3394        test_widgets(|tester| {
3395            let bottom_padding = 40.0;
3396            let text_direction = TextDirection::Ltr;
3397            pump_app(tester, m3, move |_app| {
3398                Directionality::new(
3399                    text_direction,
3400                    MediaQuery::new(
3401                        MediaQueryData::new().padding(EdgeInsets::only(
3402                            0.0,
3403                            0.0,
3404                            0.0,
3405                            bottom_padding,
3406                        )),
3407                        Scaffold::new()
3408                            .bottom_navigation_bar(
3409                                NavigationBar::new(ac_alarm()).maintain_bottom_view_padding(true),
3410                            )
3411                            .into_widget(),
3412                    )
3413                    .into_widget(),
3414                )
3415                .into_widget()
3416            });
3417
3418            let padding = find::by_type::<Padding>().evaluate(tester)[0];
3419            let safe_area_bottom_padding = tester.widget(padding, |padding: &Padding| {
3420                padding.padding.resolve(Some(text_direction)).bottom
3421            });
3422            assert_eq!(safe_area_bottom_padding, 0.0);
3423        });
3424    }
3425
3426    #[test]
3427    fn navigation_bar_does_not_crash_at_zero_area() {
3428        test_widgets(|tester| {
3429            pump_app(tester, m3, |_app| {
3430                Center::new()
3431                    .child(SizedBox::shrink().child(NavigationBar::new([
3432                        destination(Icons::add(), "X"),
3433                        destination(Icons::abc(), "Y"),
3434                    ])))
3435                    .into_widget()
3436            });
3437            assert_eq!(bar_size(tester), Size::ZERO);
3438        });
3439    }
3440}