1use 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
55pub struct NavigationBar {
82 pub key: Option<KeyRef>,
83
84 pub animation_duration: Option<Duration>,
87
88 pub selected_index: usize,
93
94 pub destinations: Vec<WidgetRef>,
103
104 pub on_destination_selected: Option<ValueChanged<usize>>,
111
112 pub background_color: Option<Color>,
119
120 pub elevation: Option<f64>,
126
127 pub shadow_color: Option<Color>,
135
136 pub surface_tint_color: Option<Color>,
150
151 pub indicator_color: Option<Color>,
158
159 pub indicator_shape: Option<ShapeBorderRef>,
165
166 pub height: Option<f64>,
180
181 pub label_behavior: Option<NavigationDestinationLabelBehavior>,
191
192 pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
195
196 pub label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
208
209 pub label_padding: Option<EdgeInsetsGeometry>,
215
216 pub maintain_bottom_view_padding: bool,
233}
234
235impl NavigationBar {
236 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 pub fn key(mut self, key: KeyRef) -> NavigationBar {
264 self.key = Some(key);
265 self
266 }
267
268 pub fn animation_duration(mut self, animation_duration: Duration) -> NavigationBar {
270 self.animation_duration = Some(animation_duration);
271 self
272 }
273
274 pub fn selected_index(mut self, selected_index: usize) -> NavigationBar {
276 self.selected_index = selected_index;
277 self
278 }
279
280 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 pub fn background_color(mut self, background_color: Color) -> NavigationBar {
291 self.background_color = Some(background_color);
292 self
293 }
294
295 pub fn elevation(mut self, elevation: f64) -> NavigationBar {
297 self.elevation = Some(elevation);
298 self
299 }
300
301 pub fn shadow_color(mut self, shadow_color: Color) -> NavigationBar {
303 self.shadow_color = Some(shadow_color);
304 self
305 }
306
307 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 pub fn indicator_color(mut self, indicator_color: Color) -> NavigationBar {
315 self.indicator_color = Some(indicator_color);
316 self
317 }
318
319 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 pub fn height(mut self, height: f64) -> NavigationBar {
327 self.height = Some(height);
328 self
329 }
330
331 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 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
525pub enum NavigationDestinationLabelBehavior {
526 AlwaysShow,
529
530 AlwaysHide,
533
534 OnlyShowSelected,
542}
543
544#[derive(Debug)]
552pub struct NavigationDestination {
553 pub key: Option<KeyRef>,
554
555 pub icon: WidgetRef,
562
563 pub selected_icon: Option<WidgetRef>,
574
575 pub label: String,
585
586 pub tooltip: Option<String>,
593
594 pub enabled: bool,
598}
599
600impl NavigationDestination {
601 #[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 pub fn key(mut self, key: KeyRef) -> NavigationDestination {
617 self.key = Some(key);
618 self
619 }
620
621 #[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 pub fn tooltip(mut self, tooltip: impl Into<String>) -> NavigationDestination {
630 self.tooltip = Some(tooltip.into());
631 self
632 }
633
634 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 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
811struct NavigationDestinationBuilder {
824 build_icon: WidgetBuilder,
835
836 build_label: WidgetBuilder,
847
848 label: String,
851
852 tooltip: Option<String>,
859
860 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
887struct 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#[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 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 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 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 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 #[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#[derive(Clone)]
1037struct NavigationDestinationInfo {
1038 index: usize,
1057
1058 #[allow(dead_code, reason = "Dart keeps the field, which nothing reads")]
1063 selected_index: usize,
1064
1065 total_number_of_destinations: usize,
1070
1071 selected_animation: AnimationRef<f64>,
1074
1075 label_behavior: NavigationDestinationLabelBehavior,
1080
1081 indicator_color: Option<Color>,
1085
1086 indicator_shape: Option<ShapeBorderRef>,
1090
1091 overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1096
1097 on_tap: Listener,
1102
1103 label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
1105
1106 label_padding: Option<EdgeInsetsGeometry>,
1110
1111 child: WidgetRef,
1112}
1113
1114impl NavigationDestinationInfo {
1115 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
1168pub struct NavigationIndicator {
1177 pub key: Option<KeyRef>,
1178
1179 pub animation: AnimationRef<f64>,
1184
1185 pub color: Option<Color>,
1189
1190 pub width: f64,
1194
1195 pub height: f64,
1199
1200 pub border_radius: BorderRadius,
1207
1208 pub shape: Option<ShapeBorderRef>,
1214}
1215
1216impl NavigationIndicator {
1217 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 pub fn key(mut self, key: KeyRef) -> NavigationIndicator {
1233 self.key = Some(key);
1234 self
1235 }
1236
1237 pub fn color(mut self, color: Color) -> NavigationIndicator {
1239 self.color = Some(color);
1240 self
1241 }
1242
1243 pub fn width(mut self, width: f64) -> NavigationIndicator {
1245 self.width = width;
1246 self
1247 }
1248
1249 pub fn height(mut self, height: f64) -> NavigationIndicator {
1251 self.height = height;
1252 self
1253 }
1254
1255 pub fn border_radius(mut self, border_radius: BorderRadius) -> NavigationIndicator {
1257 self.border_radius = border_radius;
1258 self
1259 }
1260
1261 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 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 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 .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#[derive(Debug)]
1367struct NavigationBarDestinationLayout {
1368 icon: WidgetRef,
1372
1373 icon_key: GlobalKey,
1377
1378 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 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
1417struct DestinationLayoutAnimationBuilder {
1426 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#[derive(Debug)]
1474struct NavigationBarDestinationSemantics {
1475 enabled: bool,
1477
1478 child: WidgetRef,
1480}
1481
1482impl NavigationBarDestinationSemantics {
1483 #[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 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#[derive(Debug)]
1536struct NavigationBarDestinationTooltip {
1537 message: String,
1539
1540 child: WidgetRef,
1542}
1543
1544impl NavigationBarDestinationTooltip {
1545 #[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 .vertical_offset(42.0)
1561 .exclude_from_semantics(true)
1562 .prefer_below(false)
1563 .child(self.child.clone())
1564 .into_widget()
1565 }
1566}
1567
1568struct NavigationDestinationLayoutDelegate {
1581 animation: AnimationRef<f64>,
1586
1587 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 const ICON_ID: i64 = 1;
1614
1615 const LABEL_ID: i64 = 2;
1622
1623 fn icon_id() -> ChildLayoutId {
1625 Rc::new(ValueKey::new(Self::ICON_ID))
1626 }
1627
1628 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 half_height(icon_size),
1651 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 children.position_child(
1659 app,
1660 &Self::icon_id(),
1661 Offset::new(
1662 half_width(size) - half_width(icon_size),
1664 icon_y_position,
1665 ),
1666 );
1667
1668 children.position_child(
1670 app,
1671 &Self::label_id(),
1672 Offset::new(
1673 half_width(size) - half_width(label_size),
1675 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
1694struct StatusTransitionWidgetBuilder {
1701 animation: AnimationRef<f64>,
1702
1703 builder: TransitionBuilder,
1705
1706 child: Option<WidgetRef>,
1717}
1718
1719impl StatusTransitionWidgetBuilder {
1720 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 #[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
1759type AnimationWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;
1761
1762struct SelectableAnimatedBuilder {
1779 is_selected: bool,
1784
1785 duration: Duration,
1792
1793 always_do_full_animation: bool,
1803
1804 builder: AnimationWidgetBuilder,
1806}
1807
1808impl SelectableAnimatedBuilder {
1809 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 fn duration(mut self, duration: Duration) -> SelectableAnimatedBuilder {
1825 self.duration = duration;
1826 self
1827 }
1828
1829 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
1861struct 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
1966struct 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
2007struct CurvedAnimationBuilderState {
2009 state: StateData<CurvedAnimationBuilder>,
2010 animation_direction: AnimationStatus,
2011 preserved_direction: Option<AnimationStatus>,
2012}
2013
2014impl CurvedAnimationBuilderState {
2015 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
2088fn 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
2097struct NavigationBarDefaultsM2 {
2099 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 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
2173fn 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
2179fn 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 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 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 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 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 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 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 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 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 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 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 const POSITION_TOLERANCE: f64 = 1e-4;
2496
2497 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert!(paints_indicator_ripple(
2878 &bar_ink_ops(tester),
2879 always_show_center
2880 ));
2881
2882 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 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 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 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 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 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 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 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 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 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 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 tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
3106 tester.pump_and_settle();
3107
3108 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 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 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 #[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 let builds = Rc::new(Cell::new(0));
3233 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 tester.tap_at(tester.get_center(text(tester, "Alarm")), 1);
3275 tester.pump_and_settle();
3276
3277 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 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 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 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 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 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 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}