1use std::any::Any;
4use std::collections::VecDeque;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_animation::{
9 Animatable, Animation as _, AnimationBehavior, AnimationController, AnimationRef,
10 AnimationStatusListener, AnyAnimation, ColorTween, CurvedAnimation, Curves, Tween,
11};
12use waft_embedder::{Brightness, Canvas, Color, Offset, Paint, Rect, Size};
13use waft_foundation::{App, Handle, Listener, Ref, ValueChanged};
14use waft_painting::{
15 AlignmentGeometry, EdgeInsetsGeometry, TextDirection, TextOverflow, TextStyle,
16};
17use waft_rendering::{BoxConstraints, CustomPainter, MainAxisAlignment, MainAxisSize};
18use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
19use waft_services::MouseCursorRef;
20use waft_widgets::{
21 Align, BottomNavigationBarItem, BuildContext, Column, ConstrainedBox, CustomPaint,
22 DefaultTextStyle, Directionality, Expanded, FadeTransition, Flexible, IconTheme, IconThemeData,
23 IntoWidget, IntrinsicWidth, KeyRef, Matrix4, MediaQuery, Orientation, Padding, Row, Semantics,
24 SizedBox, Stack, State, StateData, StatefulWidget, StatelessWidget, Text,
25 TickerProviderStateMixin, TickerProviderStateMixinData, Transform, Visibility, WidgetRef,
26 WidgetState, WidgetStateMouseCursor, WidgetStateProperty, WidgetStates,
27 debug_check_has_directionality, debug_check_has_media_query, debug_check_has_overlay,
28};
29
30use crate::bottom_navigation_bar_theme::BottomNavigationBarTheme;
31use crate::constants::K_BOTTOM_NAVIGATION_BAR_HEIGHT;
32use crate::debug::debug_check_has_material_localizations;
33use crate::ink_well::InkResponse;
34use crate::material::{Material, MaterialType};
35use crate::material_localizations::MaterialLocalizations;
36use crate::theme::{K_THEME_ANIMATION_DURATION, Theme};
37use crate::tooltip::Tooltip;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum BottomNavigationBarType {
49 Fixed,
51
52 Shifting,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub enum BottomNavigationBarLandscapeLayout {
61 Spread,
66
67 Centered,
74
75 Linear,
80}
81
82pub struct BottomNavigationBar {
158 pub key: Option<KeyRef>,
159
160 pub items: Vec<BottomNavigationBarItem>,
163
164 pub on_tap: Option<ValueChanged<usize>>,
171
172 pub current_index: usize,
175
176 pub elevation: Option<f64>,
182
183 pub r#type: Option<BottomNavigationBarType>,
188
189 pub fixed_color: Option<Color>,
192
193 pub background_color: Option<Color>,
199
200 pub icon_size: f64,
204
205 pub selected_item_color: Option<Color>,
217
218 pub unselected_item_color: Option<Color>,
224
225 pub selected_icon_theme: Option<IconThemeData>,
235
236 pub unselected_icon_theme: Option<IconThemeData>,
246
247 pub selected_label_style: Option<TextStyle>,
250
251 pub unselected_label_style: Option<TextStyle>,
254
255 pub selected_font_size: f64,
262
263 pub unselected_font_size: f64,
272
273 pub show_unselected_labels: Option<bool>,
275
276 pub show_selected_labels: Option<bool>,
278
279 pub mouse_cursor: Option<MouseCursorRef>,
289
290 pub enable_feedback: Option<bool>,
299
300 pub landscape_layout: Option<BottomNavigationBarLandscapeLayout>,
333
334 pub use_legacy_color_scheme: bool,
342}
343
344impl BottomNavigationBar {
345 pub fn new(items: Vec<BottomNavigationBarItem>) -> BottomNavigationBar {
399 BottomNavigationBar {
400 key: None,
401 items,
402 on_tap: None,
403 current_index: 0,
404 elevation: None,
405 r#type: None,
406 fixed_color: None,
407 background_color: None,
408 icon_size: 24.0,
409 selected_item_color: None,
410 unselected_item_color: None,
411 selected_icon_theme: None,
412 unselected_icon_theme: None,
413 selected_font_size: 14.0,
414 unselected_font_size: 12.0,
415 selected_label_style: None,
416 unselected_label_style: None,
417 show_selected_labels: None,
418 show_unselected_labels: None,
419 mouse_cursor: None,
420 enable_feedback: None,
421 landscape_layout: None,
422 use_legacy_color_scheme: true,
423 }
424 }
425
426 pub fn key(mut self, key: KeyRef) -> BottomNavigationBar {
428 self.key = Some(key);
429 self
430 }
431
432 pub fn on_tap(mut self, on_tap: impl Fn(&mut App, usize) + 'static) -> BottomNavigationBar {
434 self.on_tap = Some(Rc::new(on_tap));
435 self
436 }
437
438 pub fn current_index(mut self, current_index: usize) -> BottomNavigationBar {
440 self.current_index = current_index;
441 self
442 }
443
444 pub fn elevation(mut self, elevation: f64) -> BottomNavigationBar {
446 debug_assert!(elevation >= 0.0);
447 self.elevation = Some(elevation);
448 self
449 }
450
451 pub fn r#type(mut self, r#type: BottomNavigationBarType) -> BottomNavigationBar {
453 self.r#type = Some(r#type);
454 self
455 }
456
457 pub fn fixed_color(mut self, fixed_color: Color) -> BottomNavigationBar {
459 self.fixed_color = Some(fixed_color);
460 self
461 }
462
463 pub fn background_color(mut self, background_color: Color) -> BottomNavigationBar {
465 self.background_color = Some(background_color);
466 self
467 }
468
469 pub fn icon_size(mut self, icon_size: f64) -> BottomNavigationBar {
471 debug_assert!(icon_size >= 0.0);
472 self.icon_size = icon_size;
473 self
474 }
475
476 pub fn selected_item_color(mut self, selected_item_color: Color) -> BottomNavigationBar {
478 self.selected_item_color = Some(selected_item_color);
479 self
480 }
481
482 pub fn unselected_item_color(mut self, unselected_item_color: Color) -> BottomNavigationBar {
484 self.unselected_item_color = Some(unselected_item_color);
485 self
486 }
487
488 pub fn selected_icon_theme(
490 mut self,
491 selected_icon_theme: IconThemeData,
492 ) -> BottomNavigationBar {
493 self.selected_icon_theme = Some(selected_icon_theme);
494 self
495 }
496
497 pub fn unselected_icon_theme(
499 mut self,
500 unselected_icon_theme: IconThemeData,
501 ) -> BottomNavigationBar {
502 self.unselected_icon_theme = Some(unselected_icon_theme);
503 self
504 }
505
506 pub fn selected_font_size(mut self, selected_font_size: f64) -> BottomNavigationBar {
508 debug_assert!(selected_font_size >= 0.0);
509 self.selected_font_size = selected_font_size;
510 self
511 }
512
513 pub fn unselected_font_size(mut self, unselected_font_size: f64) -> BottomNavigationBar {
515 debug_assert!(unselected_font_size >= 0.0);
516 self.unselected_font_size = unselected_font_size;
517 self
518 }
519
520 pub fn selected_label_style(mut self, selected_label_style: TextStyle) -> BottomNavigationBar {
522 self.selected_label_style = Some(selected_label_style);
523 self
524 }
525
526 pub fn unselected_label_style(
528 mut self,
529 unselected_label_style: TextStyle,
530 ) -> BottomNavigationBar {
531 self.unselected_label_style = Some(unselected_label_style);
532 self
533 }
534
535 pub fn show_selected_labels(mut self, show_selected_labels: bool) -> BottomNavigationBar {
537 self.show_selected_labels = Some(show_selected_labels);
538 self
539 }
540
541 pub fn show_unselected_labels(mut self, show_unselected_labels: bool) -> BottomNavigationBar {
543 self.show_unselected_labels = Some(show_unselected_labels);
544 self
545 }
546
547 pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> BottomNavigationBar {
549 self.mouse_cursor = Some(mouse_cursor.into());
550 self
551 }
552
553 pub fn enable_feedback(mut self, enable_feedback: bool) -> BottomNavigationBar {
555 self.enable_feedback = Some(enable_feedback);
556 self
557 }
558
559 pub fn landscape_layout(
561 mut self,
562 landscape_layout: BottomNavigationBarLandscapeLayout,
563 ) -> BottomNavigationBar {
564 self.landscape_layout = Some(landscape_layout);
565 self
566 }
567
568 pub fn use_legacy_color_scheme(mut self, use_legacy_color_scheme: bool) -> BottomNavigationBar {
570 self.use_legacy_color_scheme = use_legacy_color_scheme;
571 self
572 }
573
574 pub fn effective_selected_item_color(&self) -> Option<Color> {
577 self.selected_item_color.or(self.fixed_color)
578 }
579
580 pub fn effective_fixed_color(&self) -> Option<Color> {
585 self.effective_selected_item_color()
586 }
587}
588
589impl Debug for BottomNavigationBar {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 f.debug_struct("BottomNavigationBar")
592 .field("items", &self.items)
593 .field("current_index", &self.current_index)
594 .field("type", &self.r#type)
595 .finish_non_exhaustive()
596 }
597}
598
599impl StatefulWidget for BottomNavigationBar {
600 type State = BottomNavigationBarState;
601
602 fn key(&self) -> Option<&KeyRef> {
603 self.key.as_ref()
604 }
605
606 fn debug_check_constructor(&self) {
607 debug_assert!(self.items.len() >= 2);
608 debug_assert!(
609 self.items.iter().all(|item| item.label.is_some()),
610 "Every item must have a non-null label"
611 );
612 debug_assert!(self.current_index < self.items.len());
613 debug_assert!(
614 self.selected_item_color.is_none() || self.fixed_color.is_none(),
615 "Either selectedItemColor or fixedColor can be specified, but not both"
616 );
617 }
618
619 fn create_state(&self) -> BottomNavigationBarState {
620 BottomNavigationBarState {
621 state: StateData::new(),
622 ticker_provider: TickerProviderStateMixinData::new(),
623 controllers: Vec::new(),
624 animations: Vec::new(),
625 circles: VecDeque::new(),
626 background_color: None,
627 flex_tween: None,
628 }
629 }
630}
631
632fn evaluate_tween(app: &mut App, begin: f64, end: f64, animation: AnyAnimation<f64>) -> f64 {
634 let tween = Tween::new(app, Some(begin), Some(end));
635 tween.evaluate(app, animation)
636}
637
638fn transform_tween(app: &mut App, begin: f64, end: f64, t: f64) -> f64 {
640 let tween = Tween::new(app, Some(begin), Some(end));
641 tween.transform(app, t)
642}
643
644struct BottomNavigationTile {
647 r#type: BottomNavigationBarType,
648 item: BottomNavigationBarItem,
649 animation: AnimationRef<f64>,
650 icon_size: f64,
651 key: Option<KeyRef>,
652 on_tap: Option<Listener>,
653 label_color_tween: Option<Ref<ColorTween>>,
654 icon_color_tween: Option<Ref<ColorTween>>,
655 flex: Option<f64>,
656 selected: bool,
657 selected_icon_theme: Option<IconThemeData>,
658 unselected_icon_theme: Option<IconThemeData>,
659 selected_label_style: TextStyle,
660 unselected_label_style: TextStyle,
661 index_label: Option<String>,
662 show_selected_labels: bool,
663 show_unselected_labels: bool,
664 mouse_cursor: MouseCursorRef,
665 enable_feedback: bool,
666 layout: BottomNavigationBarLandscapeLayout,
667}
668
669impl Debug for BottomNavigationTile {
670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671 f.debug_struct("_BottomNavigationTile")
672 .field("type", &self.r#type)
673 .field("item", &self.item)
674 .field("selected", &self.selected)
675 .finish_non_exhaustive()
676 }
677}
678
679impl StatelessWidget for BottomNavigationTile {
680 fn key(&self) -> Option<&KeyRef> {
681 self.key.as_ref()
682 }
683
684 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
685 let selected_font_size = self
686 .selected_label_style
687 .font_size
688 .expect("the bar gives its label styles a font size");
689
690 let selected_icon_size = self
691 .selected_icon_theme
692 .as_ref()
693 .and_then(|theme| theme.size)
694 .unwrap_or(self.icon_size);
695 let unselected_icon_size = self
696 .unselected_icon_theme
697 .as_ref()
698 .and_then(|theme| theme.size)
699 .unwrap_or(self.icon_size);
700
701 let selected_icon_diff = (selected_icon_size - unselected_icon_size).max(0.0);
704 let unselected_icon_diff = (unselected_icon_size - selected_icon_size).max(0.0);
707
708 let effective_tooltip = self
710 .item
711 .tooltip
712 .clone()
713 .filter(|tooltip| !tooltip.is_empty());
714
715 let (bottom_padding, top_padding) =
733 if self.show_selected_labels && !self.show_unselected_labels {
734 (
735 evaluate_tween(
736 app,
737 selected_icon_diff / 2.0,
738 selected_font_size / 2.0 - unselected_icon_diff / 2.0,
739 self.animation.handle(),
740 ),
741 evaluate_tween(
742 app,
743 selected_font_size + selected_icon_diff / 2.0,
744 selected_font_size / 2.0 - unselected_icon_diff / 2.0,
745 self.animation.handle(),
746 ),
747 )
748 } else if !self.show_selected_labels && !self.show_unselected_labels {
749 (
750 evaluate_tween(
751 app,
752 selected_icon_diff / 2.0,
753 unselected_icon_diff / 2.0,
754 self.animation.handle(),
755 ),
756 evaluate_tween(
757 app,
758 selected_font_size + selected_icon_diff / 2.0,
759 selected_font_size + unselected_icon_diff / 2.0,
760 self.animation.handle(),
761 ),
762 )
763 } else {
764 (
765 evaluate_tween(
766 app,
767 selected_font_size / 2.0 + selected_icon_diff / 2.0,
768 selected_font_size / 2.0 + unselected_icon_diff / 2.0,
769 self.animation.handle(),
770 ),
771 evaluate_tween(
772 app,
773 selected_font_size / 2.0 + selected_icon_diff / 2.0,
774 selected_font_size / 2.0 + unselected_icon_diff / 2.0,
775 self.animation.handle(),
776 ),
777 )
778 };
779
780 let size: i32 = match self.r#type {
785 BottomNavigationBarType::Fixed => 1,
786 BottomNavigationBarType::Shifting => {
787 (self.flex.expect("a shifting tile has a flex") * 1000.0).round() as i32
788 }
789 };
790
791 let mut ink_response = InkResponse::new()
792 .mouse_cursor(self.mouse_cursor.clone())
793 .enable_feedback(self.enable_feedback)
794 .child(
795 Padding::new(EdgeInsetsGeometry::only(
796 0.0,
797 top_padding,
798 0.0,
799 bottom_padding,
800 ))
801 .child(Tile {
802 layout: self.layout,
803 icon: TileIcon {
804 color_tween: self
805 .icon_color_tween
806 .clone()
807 .expect("the bar gives each tile an icon color tween"),
808 animation: self.animation.clone(),
809 icon_size: self.icon_size,
810 selected: self.selected,
811 item: self.item.clone(),
812 selected_icon_theme: self.selected_icon_theme.clone(),
813 unselected_icon_theme: self.unselected_icon_theme.clone(),
814 }
815 .into_widget(),
816 label: Label {
817 color_tween: self
818 .label_color_tween
819 .clone()
820 .expect("the bar gives each tile a label color tween"),
821 animation: self.animation.clone(),
822 item: self.item.clone(),
823 selected_label_style: self.selected_label_style.clone(),
824 unselected_label_style: self.unselected_label_style.clone(),
825 show_selected_labels: self.show_selected_labels,
826 show_unselected_labels: self.show_unselected_labels,
827 }
828 .into_widget(),
829 }),
830 );
831 if let Some(on_tap) = &self.on_tap {
832 ink_response = ink_response.on_tap(on_tap.clone());
833 }
834 let mut result = ink_response.into_widget();
835
836 if let Some(effective_tooltip) = effective_tooltip {
837 result = Tooltip::new()
838 .message(effective_tooltip)
839 .prefer_below(false)
840 .vertical_offset(selected_icon_size + selected_font_size)
841 .exclude_from_semantics(true)
842 .child(result)
843 .into_widget();
844 }
845
846 let mut index_semantics = Semantics::new();
847 if let Some(index_label) = &self.index_label {
848 index_semantics = index_semantics.label(index_label.clone());
849 }
850 result = Semantics::new()
851 .selected(self.selected)
852 .button(true)
853 .container(true)
854 .child(Stack::new().children([result, index_semantics.into_widget()]))
855 .into_widget();
856
857 Expanded::new(result).flex(size).into_widget()
858 }
859}
860
861#[derive(Debug)]
866struct Tile {
867 layout: BottomNavigationBarLandscapeLayout,
868 icon: WidgetRef,
869 label: WidgetRef,
870}
871
872impl StatelessWidget for Tile {
873 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
874 if MediaQuery::orientation_of(app, context) == Orientation::Landscape
875 && self.layout == BottomNavigationBarLandscapeLayout::Linear
876 {
877 return Align::new()
878 .height_factor(1.0)
879 .child(
880 Row::new()
881 .main_axis_size(MainAxisSize::Min)
882 .spacing(8.0)
883 .children([
884 self.icon.clone(),
885 Flexible::new(IntrinsicWidth::new().child(self.label.clone()))
889 .into_widget(),
890 ]),
891 )
892 .into_widget();
893 }
894 Column::new()
895 .main_axis_alignment(MainAxisAlignment::SpaceBetween)
896 .main_axis_size(MainAxisSize::Min)
897 .children([self.icon.clone(), self.label.clone()])
898 .into_widget()
899 }
900}
901
902struct TileIcon {
903 color_tween: Ref<ColorTween>,
904 animation: AnimationRef<f64>,
905 icon_size: f64,
906 selected: bool,
907 item: BottomNavigationBarItem,
908 selected_icon_theme: Option<IconThemeData>,
909 unselected_icon_theme: Option<IconThemeData>,
910}
911
912impl Debug for TileIcon {
913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914 f.debug_struct("_TileIcon")
915 .field("icon_size", &self.icon_size)
916 .field("selected", &self.selected)
917 .field("item", &self.item)
918 .finish_non_exhaustive()
919 }
920}
921
922impl StatelessWidget for TileIcon {
923 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
924 let icon_color = self.color_tween.evaluate(app, self.animation.handle());
925 let mut default_icon_theme = IconThemeData::new().size(self.icon_size);
926 default_icon_theme.color = icon_color.map(Into::into);
927 let icon_theme_data = IconThemeData::lerp(
928 Some(&default_icon_theme.merge(self.unselected_icon_theme.as_ref())),
929 Some(&default_icon_theme.merge(self.selected_icon_theme.as_ref())),
930 self.animation.value(app),
931 );
932
933 Align::new()
934 .alignment(AlignmentGeometry::TOP_CENTER)
935 .height_factor(1.0)
936 .child(IconTheme::new(
937 icon_theme_data,
938 if self.selected {
939 self.item.active_icon.clone()
940 } else {
941 self.item.icon.clone()
942 },
943 ))
944 .into_widget()
945 }
946}
947
948struct Label {
949 color_tween: Ref<ColorTween>,
950 animation: AnimationRef<f64>,
951 item: BottomNavigationBarItem,
952 selected_label_style: TextStyle,
953 unselected_label_style: TextStyle,
954 show_selected_labels: bool,
955 show_unselected_labels: bool,
956}
957
958impl Debug for Label {
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 f.debug_struct("_Label")
961 .field("item", &self.item)
962 .field("show_selected_labels", &self.show_selected_labels)
963 .field("show_unselected_labels", &self.show_unselected_labels)
964 .finish_non_exhaustive()
965 }
966}
967
968impl StatelessWidget for Label {
969 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
970 let selected_font_size = self.selected_label_style.font_size;
971 let unselected_font_size = self.unselected_label_style.font_size;
972
973 let custom_style = TextStyle::lerp(
974 Some(&self.unselected_label_style),
975 Some(&self.selected_label_style),
976 self.animation.value(app),
977 )
978 .expect("both styles are given");
979 let mut style = custom_style.copy_with();
980 if let Some(selected_font_size) = selected_font_size {
981 style = style.font_size(selected_font_size);
982 }
983 if let Some(color) = self.color_tween.evaluate(app, self.animation.handle()) {
984 style = style.color(color);
985 }
986 let scale = evaluate_tween(
987 app,
988 unselected_font_size.expect("the bar gives its label styles a font size")
989 / selected_font_size.expect("the bar gives its label styles a font size"),
990 1.0,
991 self.animation.handle(),
992 );
993 let mut label = Text::new(self.item.label.clone().expect("every item has a label"));
994 if let Some(semantics_label) = &self.item.semantics_label {
995 label = label.semantics_label(semantics_label.clone());
996 }
997 let mut text = DefaultTextStyle::merge(
998 Transform::new(diagonal3_all(scale))
1002 .alignment(AlignmentGeometry::BOTTOM_CENTER)
1003 .child(label),
1004 )
1005 .style(style)
1006 .into_widget();
1007
1008 if !self.show_unselected_labels && !self.show_selected_labels {
1009 text = Visibility::maintain(text).visible(false).into_widget();
1011 } else if !self.show_unselected_labels {
1012 text = FadeTransition::new(self.animation.clone())
1014 .child(text)
1015 .into_widget();
1016 } else if !self.show_selected_labels {
1017 let tween = Tween::new(app, Some(1.0), Some(0.0));
1019 text = FadeTransition::new(tween.animate(app, self.animation.clone()))
1020 .child(text)
1021 .into_widget();
1022 }
1023
1024 text = Align::new()
1025 .alignment(AlignmentGeometry::BOTTOM_CENTER)
1026 .height_factor(1.0)
1027 .child(text)
1028 .into_widget();
1029
1030 if self.item.label.is_some() {
1031 text = MediaQuery::with_clamped_text_scaling(None, 0.0, 1.0, text);
1034 }
1035
1036 text
1037 }
1038}
1039
1040fn diagonal3_all(scale: f64) -> Matrix4 {
1042 let scale = scale as f32;
1043 Matrix4::from_flutter_array(&[
1044 scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, 1.0,
1048 ])
1049}
1050
1051pub struct BottomNavigationBarState {
1053 state: StateData<BottomNavigationBar>,
1054 ticker_provider: TickerProviderStateMixinData,
1055 controllers: Vec<Ref<AnimationController>>,
1056 animations: Vec<Ref<CurvedAnimation>>,
1057
1058 circles: VecDeque<Rc<Circle>>,
1060
1061 background_color: Option<Color>,
1064
1065 flex_tween: Option<Ref<Tween<f64>>>,
1067}
1068
1069impl BottomNavigationBarState {
1070 fn dispose_animations(self: Handle<Self>, app: &mut App) {
1071 let state = app.get_mut(self);
1072 let controllers = std::mem::take(&mut state.controllers);
1073 let circles = std::mem::take(&mut state.circles);
1074 let animations = std::mem::take(&mut state.animations);
1075 for controller in controllers {
1076 controller.dispose(app);
1077 }
1078 for circle in circles {
1079 circle.dispose(app);
1080 }
1081 for animation in animations {
1082 animation.dispose(app);
1083 }
1084 }
1085
1086 fn reset_state(self: Handle<Self>, app: &mut App) {
1087 self.dispose_animations(app);
1088
1089 let items_length = self.widget(app).items.len();
1090 let controllers: Vec<Ref<AnimationController>> = (0..items_length)
1091 .map(|_| {
1092 let controller = AnimationController::new(
1093 app,
1094 None,
1095 Some(K_THEME_ANIMATION_DURATION),
1096 None,
1097 0.0,
1098 1.0,
1099 AnimationBehavior::Normal,
1100 self,
1101 );
1102 controller.add_listener(app, Listener::handle_method(self, Self::rebuild));
1103 controller
1104 })
1105 .collect();
1106 let animations: Vec<Ref<CurvedAnimation>> = controllers
1107 .iter()
1108 .map(|controller| {
1109 CurvedAnimation::new(
1110 app,
1111 controller.erase(),
1112 Curves::fast_out_slow_in(),
1113 Some(Rc::new(Curves::fast_out_slow_in().flipped())),
1114 )
1115 })
1116 .collect();
1117 let current_index = self.widget(app).current_index;
1118 controllers[current_index].set_value(app, 1.0);
1119 let background_color = self.widget(app).items[current_index]
1120 .background_color
1121 .as_ref()
1122 .map(|color| color.color());
1123 let state = app.get_mut(self);
1124 state.controllers = controllers;
1125 state.animations = animations;
1126 state.background_color = background_color;
1127 }
1128
1129 fn effective_type(self: Handle<Self>, app: &mut App) -> BottomNavigationBarType {
1136 if let Some(r#type) = self.widget(app).r#type {
1137 return r#type;
1138 }
1139 let context = self.context(app);
1140 BottomNavigationBarTheme::of(app, context).r#type.unwrap_or(
1141 if self.widget(app).items.len() <= 3 {
1142 BottomNavigationBarType::Fixed
1143 } else {
1144 BottomNavigationBarType::Shifting
1145 },
1146 )
1147 }
1148
1149 fn default_show_unselected(self: Handle<Self>, app: &mut App) -> bool {
1154 match self.effective_type(app) {
1155 BottomNavigationBarType::Shifting => false,
1156 BottomNavigationBarType::Fixed => true,
1157 }
1158 }
1159
1160 fn rebuild(self: Handle<Self>, app: &mut App) {
1161 self.set_state(app, |_| {
1162 });
1165 }
1166
1167 fn evaluate_flex(self: Handle<Self>, app: &App, animation: AnyAnimation<f64>) -> f64 {
1168 app.get(self)
1169 .flex_tween
1170 .as_ref()
1171 .expect("made in init_state")
1172 .evaluate(app, animation)
1173 }
1174
1175 fn push_circle(self: Handle<Self>, app: &mut App, index: usize) {
1176 let Some(color) = self.widget(app).items[index]
1177 .background_color
1178 .as_ref()
1179 .map(|color| color.color())
1180 else {
1181 return;
1182 };
1183 let circle = Rc::new(Circle::new(app, self, index, color, self));
1184 circle.controller.add_status_listener(
1185 app,
1186 AnimationStatusListener::new(move |status, app| {
1187 if status.is_completed() {
1188 let mut removed = None;
1189 self.set_state(app, |state| {
1190 let circle = state
1191 .circles
1192 .pop_front()
1193 .expect("a completed circle is queued");
1194 state.background_color = Some(circle.color);
1195 removed = Some(circle);
1196 });
1197 let circle = removed.expect("set_state runs its callback");
1198 circle.dispose(app);
1199 }
1200 }),
1201 );
1202 app.get_mut(self).circles.push_back(circle);
1203 }
1204
1205 fn effective_text_style(text_style: Option<TextStyle>, font_size: f64) -> TextStyle {
1208 let text_style = text_style.unwrap_or_default();
1209 if text_style.font_size.is_none() {
1211 text_style.copy_with().font_size(font_size)
1212 } else {
1213 text_style
1214 }
1215 }
1216
1217 fn effective_icon_theme(
1221 icon_theme: Option<IconThemeData>,
1222 item_color: Option<Color>,
1223 ) -> IconThemeData {
1224 icon_theme.unwrap_or_else(|| {
1226 let mut icon_theme = IconThemeData::new();
1227 icon_theme.color = item_color.map(Into::into);
1228 icon_theme
1229 })
1230 }
1231
1232 fn create_tiles(
1233 self: Handle<Self>,
1234 app: &mut App,
1235 context: BuildContext,
1236 layout: BottomNavigationBarLandscapeLayout,
1237 ) -> Vec<WidgetRef> {
1238 let localizations = <dyn MaterialLocalizations>::of(app, context);
1239
1240 let theme_data = Theme::of(app, context);
1241 let bottom_theme = BottomNavigationBarTheme::of(app, context);
1242
1243 let theme_color = match theme_data.brightness() {
1244 Brightness::Light => theme_data.color_scheme.primary(),
1245 Brightness::Dark => theme_data.color_scheme.secondary(),
1246 };
1247
1248 let widget = self.widget(app);
1249 let effective_selected_label_style = Self::effective_text_style(
1250 widget
1251 .selected_label_style
1252 .clone()
1253 .or(bottom_theme.selected_label_style.clone()),
1254 widget.selected_font_size,
1255 );
1256
1257 let effective_unselected_label_style = Self::effective_text_style(
1258 widget
1259 .unselected_label_style
1260 .clone()
1261 .or(bottom_theme.unselected_label_style.clone()),
1262 widget.unselected_font_size,
1263 );
1264
1265 let effective_selected_icon_theme = Self::effective_icon_theme(
1266 widget
1267 .selected_icon_theme
1268 .clone()
1269 .or(bottom_theme.selected_icon_theme.clone()),
1270 Some(
1271 widget
1272 .effective_selected_item_color()
1273 .or(bottom_theme.selected_item_color)
1274 .unwrap_or(theme_color),
1275 ),
1276 );
1277
1278 let effective_unselected_icon_theme = Self::effective_icon_theme(
1279 widget
1280 .unselected_icon_theme
1281 .clone()
1282 .or(bottom_theme.unselected_icon_theme.clone()),
1283 Some(
1284 widget
1285 .unselected_item_color
1286 .or(bottom_theme.unselected_item_color)
1287 .unwrap_or(theme_data.unselected_widget_color),
1288 ),
1289 );
1290
1291 let icon_theme_color =
1292 |icon_theme: &IconThemeData| icon_theme.color.as_ref().map(|color| color.color());
1293 let label_style_color = |style: &TextStyle| style.color.as_ref().map(|color| color.color());
1294 let effective_type = self.effective_type(app);
1295 let widget = self.widget(app);
1296
1297 let color_tween_ends = match effective_type {
1298 BottomNavigationBarType::Fixed => (
1299 widget
1300 .unselected_item_color
1301 .or(bottom_theme.unselected_item_color)
1302 .unwrap_or(theme_data.unselected_widget_color),
1303 widget
1304 .effective_selected_item_color()
1305 .or(bottom_theme.selected_item_color)
1306 .or(widget.effective_fixed_color())
1307 .unwrap_or(theme_color),
1308 ),
1309 BottomNavigationBarType::Shifting => (
1310 widget
1311 .unselected_item_color
1312 .or(bottom_theme.unselected_item_color)
1313 .unwrap_or(theme_data.color_scheme.surface()),
1314 widget
1315 .effective_selected_item_color()
1316 .or(bottom_theme.selected_item_color)
1317 .unwrap_or(theme_data.color_scheme.surface()),
1318 ),
1319 };
1320
1321 let label_color_tween_ends = match effective_type {
1322 BottomNavigationBarType::Fixed => (
1323 label_style_color(&effective_unselected_label_style)
1324 .or(widget.unselected_item_color)
1325 .or(bottom_theme.unselected_item_color)
1326 .unwrap_or(theme_data.unselected_widget_color),
1327 label_style_color(&effective_selected_label_style)
1328 .or(widget.effective_selected_item_color())
1329 .or(bottom_theme.selected_item_color)
1330 .or(widget.effective_fixed_color())
1331 .unwrap_or(theme_color),
1332 ),
1333 BottomNavigationBarType::Shifting => (
1334 label_style_color(&effective_unselected_label_style)
1335 .or(widget.unselected_item_color)
1336 .or(bottom_theme.unselected_item_color)
1337 .unwrap_or(theme_data.color_scheme.surface()),
1338 label_style_color(&effective_selected_label_style)
1339 .or(widget.effective_selected_item_color())
1340 .or(bottom_theme.selected_item_color)
1341 .unwrap_or(theme_color),
1342 ),
1343 };
1344
1345 let icon_color_tween_ends = match effective_type {
1346 BottomNavigationBarType::Fixed => (
1347 icon_theme_color(&effective_selected_icon_theme)
1348 .or(widget.unselected_item_color)
1349 .or(bottom_theme.unselected_item_color)
1350 .unwrap_or(theme_data.unselected_widget_color),
1351 icon_theme_color(&effective_unselected_icon_theme)
1352 .or(widget.effective_selected_item_color())
1353 .or(bottom_theme.selected_item_color)
1354 .or(widget.effective_fixed_color())
1355 .unwrap_or(theme_color),
1356 ),
1357 BottomNavigationBarType::Shifting => (
1358 icon_theme_color(&effective_unselected_icon_theme)
1359 .or(widget.unselected_item_color)
1360 .or(bottom_theme.unselected_item_color)
1361 .unwrap_or(theme_data.color_scheme.surface()),
1362 icon_theme_color(&effective_selected_icon_theme)
1363 .or(widget.effective_selected_item_color())
1364 .or(bottom_theme.selected_item_color)
1365 .unwrap_or(theme_color),
1366 ),
1367 };
1368
1369 let color_tween = ColorTween::new(app, Some(color_tween_ends.0), Some(color_tween_ends.1));
1370 let label_color_tween = ColorTween::new(
1371 app,
1372 Some(label_color_tween_ends.0),
1373 Some(label_color_tween_ends.1),
1374 );
1375 let icon_color_tween = ColorTween::new(
1376 app,
1377 Some(icon_color_tween_ends.0),
1378 Some(icon_color_tween_ends.1),
1379 );
1380
1381 let show_unselected_labels_default = self.default_show_unselected(app);
1382 let mut tiles = Vec::new();
1383 let items_length = self.widget(app).items.len();
1384 for i in 0..items_length {
1385 let widget = self.widget(app);
1386 let mut states = WidgetStates::new();
1387 if i == widget.current_index {
1388 states.insert(WidgetState::Selected);
1389 }
1390
1391 let effective_mouse_cursor: MouseCursorRef =
1392 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
1393 &widget.mouse_cursor,
1394 &states,
1395 )
1396 .or_else(|| {
1397 bottom_theme
1398 .mouse_cursor
1399 .as_ref()
1400 .and_then(|mouse_cursor| mouse_cursor.resolve(&states))
1401 })
1402 .unwrap_or_else(|| WidgetStateMouseCursor::clickable().resolve(&states));
1403
1404 let state = app.get(self);
1405 let animation: AnimationRef<f64> = state.animations[i].erase();
1406 let flex = self.evaluate_flex(app, animation.handle());
1407 let widget = self.widget(app);
1408 tiles.push(
1409 BottomNavigationTile {
1410 r#type: effective_type,
1411 item: widget.items[i].clone(),
1412 animation,
1413 icon_size: widget.icon_size,
1414 key: widget.items[i].key.clone(),
1415 selected_icon_theme: if widget.use_legacy_color_scheme {
1416 widget
1417 .selected_icon_theme
1418 .clone()
1419 .or(bottom_theme.selected_icon_theme.clone())
1420 } else {
1421 Some(effective_selected_icon_theme.clone())
1422 },
1423 unselected_icon_theme: if widget.use_legacy_color_scheme {
1424 widget
1425 .unselected_icon_theme
1426 .clone()
1427 .or(bottom_theme.unselected_icon_theme.clone())
1428 } else {
1429 Some(effective_unselected_icon_theme.clone())
1430 },
1431 selected_label_style: effective_selected_label_style.clone(),
1432 unselected_label_style: effective_unselected_label_style.clone(),
1433 enable_feedback: widget
1434 .enable_feedback
1435 .or(bottom_theme.enable_feedback)
1436 .unwrap_or(true),
1437 on_tap: Some(Listener::new(move |app| {
1438 if let Some(on_tap) = self.widget(app).on_tap.clone() {
1439 on_tap(app, i);
1440 }
1441 })),
1442 label_color_tween: Some(if widget.use_legacy_color_scheme {
1443 color_tween.clone()
1444 } else {
1445 label_color_tween.clone()
1446 }),
1447 icon_color_tween: Some(if widget.use_legacy_color_scheme {
1448 color_tween.clone()
1449 } else {
1450 icon_color_tween.clone()
1451 }),
1452 flex: Some(flex),
1453 selected: i == widget.current_index,
1454 show_selected_labels: widget
1455 .show_selected_labels
1456 .or(bottom_theme.show_selected_labels)
1457 .unwrap_or(true),
1458 show_unselected_labels: widget
1459 .show_unselected_labels
1460 .or(bottom_theme.show_unselected_labels)
1461 .unwrap_or(show_unselected_labels_default),
1462 index_label: Some(
1463 localizations.tab_label(i as i32 + 1, widget.items.len() as i32),
1464 ),
1465 mouse_cursor: effective_mouse_cursor,
1466 layout,
1467 }
1468 .into_widget(),
1469 );
1470 }
1471 tiles
1472 }
1473}
1474
1475impl TickerProviderStateMixin for BottomNavigationBarState {
1476 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
1477 &app.get(self).ticker_provider
1478 }
1479
1480 fn ticker_provider_data_mut(
1481 self: Handle<Self>,
1482 app: &mut App,
1483 ) -> &mut TickerProviderStateMixinData {
1484 &mut app.get_mut(self).ticker_provider
1485 }
1486}
1487
1488impl TickerProviderObject for BottomNavigationBarState {
1490 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1491 TickerProviderStateMixin::create_ticker(self, app, on_tick)
1492 }
1493}
1494
1495impl State for BottomNavigationBarState {
1496 type Widget = BottomNavigationBar;
1497 waft_widgets::state_accessors!();
1498
1499 fn init_state(self: Handle<Self>, app: &mut App) {
1500 let flex_tween = Tween::new(app, Some(1.0), Some(1.5));
1501 app.get_mut(self).flex_tween = Some(flex_tween);
1502 self.reset_state(app);
1503 }
1504
1505 fn dispose(self: Handle<Self>, app: &mut App) {
1506 self.dispose_animations(app);
1507 TickerProviderStateMixin::dispose(self, app);
1508 }
1509
1510 fn activate(self: Handle<Self>, app: &mut App) {
1511 TickerProviderStateMixin::activate(self, app);
1512 }
1513
1514 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &BottomNavigationBar) {
1515 if self.widget(app).items.len() != old_widget.items.len() {
1517 self.reset_state(app);
1518 return;
1519 }
1520
1521 let current_index = self.widget(app).current_index;
1522 if current_index != old_widget.current_index {
1523 match self.effective_type(app) {
1524 BottomNavigationBarType::Fixed => {}
1525 BottomNavigationBarType::Shifting => self.push_circle(app, current_index),
1526 }
1527 let state = app.get(self);
1528 let old_controller = state.controllers[old_widget.current_index].handle();
1529 let controller = state.controllers[current_index].handle();
1530 old_controller.reverse(app, None);
1531 controller.forward(app, None);
1532 } else {
1533 let item_background_color = self.widget(app).items[current_index]
1534 .background_color
1535 .as_ref()
1536 .map(|color| color.color());
1537 if app.get(self).background_color != item_background_color {
1538 app.get_mut(self).background_color = item_background_color;
1539 }
1540 }
1541 }
1542
1543 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1544 debug_assert!(debug_check_has_directionality(
1545 app, context, None, None, None
1546 ));
1547 debug_assert!(debug_check_has_material_localizations(app, context));
1548 debug_assert!(debug_check_has_media_query(app, context));
1549 debug_assert!(debug_check_has_overlay(app, context));
1550
1551 let bottom_theme = BottomNavigationBarTheme::of(app, context);
1552 let layout = self
1553 .widget(app)
1554 .landscape_layout
1555 .or(bottom_theme.landscape_layout)
1556 .unwrap_or(BottomNavigationBarLandscapeLayout::Spread);
1557 let additional_bottom_padding = MediaQuery::view_padding_of(app, context).bottom;
1558
1559 let background_color = match self.effective_type(app) {
1560 BottomNavigationBarType::Fixed => self
1561 .widget(app)
1562 .background_color
1563 .or(bottom_theme.background_color),
1564 BottomNavigationBarType::Shifting => app.get(self).background_color,
1565 };
1566
1567 let elevation = self
1568 .widget(app)
1569 .elevation
1570 .or(bottom_theme.elevation)
1571 .unwrap_or(8.0);
1572 let circles: Rc<[Rc<Circle>]> = app.get(self).circles.iter().cloned().collect();
1573 let text_direction = Directionality::of(app, context);
1574 let tiles = self.create_tiles(app, context, layout);
1575 let row = DefaultTextStyle::merge(
1576 Row::new()
1577 .main_axis_alignment(MainAxisAlignment::SpaceBetween)
1578 .children(tiles),
1579 )
1580 .overflow(TextOverflow::Ellipsis);
1581 let without_bottom_padding =
1582 MediaQuery::remove_padding(app, context, false, false, false, true, row).into_widget();
1583 Semantics::new()
1584 .explicit_child_nodes(true)
1585 .child(Bar {
1586 layout,
1587 elevation,
1588 color: background_color,
1589 child: ConstrainedBox::new(
1590 BoxConstraints::new()
1591 .min_height(K_BOTTOM_NAVIGATION_BAR_HEIGHT + additional_bottom_padding),
1592 )
1593 .child(
1594 CustomPaint::new()
1595 .painter(RadialPainter {
1596 circles,
1597 text_direction,
1598 })
1599 .child(
1600 Material::new()
1601 .r#type(MaterialType::Transparency)
1603 .child(
1604 Padding::new(EdgeInsetsGeometry::only(
1605 0.0,
1606 0.0,
1607 0.0,
1608 additional_bottom_padding,
1609 ))
1610 .child(without_bottom_padding),
1611 ),
1612 ),
1613 )
1614 .into_widget(),
1615 })
1616 .into_widget()
1617 }
1618}
1619
1620#[derive(Debug)]
1623struct Bar {
1624 child: WidgetRef,
1625 layout: BottomNavigationBarLandscapeLayout,
1626 elevation: f64,
1627 color: Option<Color>,
1628}
1629
1630impl StatelessWidget for Bar {
1631 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1632 let mut aligned_child = self.child.clone();
1633 if MediaQuery::orientation_of(app, context) == Orientation::Landscape
1634 && self.layout == BottomNavigationBarLandscapeLayout::Centered
1635 {
1636 aligned_child = Align::new()
1637 .alignment(AlignmentGeometry::BOTTOM_CENTER)
1638 .height_factor(1.0)
1639 .child(
1640 SizedBox::new()
1641 .width(MediaQuery::height_of(app, context))
1642 .child(self.child.clone()),
1643 )
1644 .into_widget();
1645 }
1646 let mut material = Material::new().elevation(self.elevation);
1647 if let Some(color) = self.color {
1648 material = material.color(color);
1649 }
1650 material.child(aligned_child).into_widget()
1651 }
1652}
1653
1654struct Circle {
1656 state: Handle<BottomNavigationBarState>,
1657 index: usize,
1658 color: Color,
1659 controller: Ref<AnimationController>,
1660 animation: Ref<CurvedAnimation>,
1661}
1662
1663impl Circle {
1664 fn new(
1665 app: &mut App,
1666 state: Handle<BottomNavigationBarState>,
1667 index: usize,
1668 color: Color,
1669 vsync: impl waft_scheduler::TickerProvider,
1670 ) -> Circle {
1671 let controller = AnimationController::new(
1672 app,
1673 None,
1674 Some(K_THEME_ANIMATION_DURATION),
1675 None,
1676 0.0,
1677 1.0,
1678 AnimationBehavior::Normal,
1679 vsync,
1680 );
1681 let animation =
1682 CurvedAnimation::new(app, controller.erase(), Curves::fast_out_slow_in(), None);
1683 controller.forward(app, None);
1684 Circle {
1685 state,
1686 index,
1687 color,
1688 controller,
1689 animation,
1690 }
1691 }
1692
1693 fn horizontal_leading_offset(&self, app: &App) -> f64 {
1694 let weight_sum = |animations: &[Ref<CurvedAnimation>]| -> f64 {
1695 animations
1698 .iter()
1699 .map(|animation| self.state.evaluate_flex(app, animation.as_animation()))
1700 .fold(0.0, |sum, value| sum + value)
1701 };
1702
1703 let animations = &app.get(self.state).animations;
1704 let all_weights = weight_sum(animations);
1705 let leading_weights = weight_sum(&animations[0..self.index]);
1707
1708 (leading_weights
1710 + self
1711 .state
1712 .evaluate_flex(app, animations[self.index].as_animation())
1713 / 2.0)
1714 / all_weights
1715 }
1716
1717 fn dispose(&self, app: &mut App) {
1718 self.controller.dispose(app);
1719 self.animation.dispose(app);
1720 }
1721}
1722
1723struct RadialPainter {
1725 circles: Rc<[Rc<Circle>]>,
1726 text_direction: TextDirection,
1727}
1728
1729impl RadialPainter {
1730 fn max_radius(center: Offset, size: Size) -> f64 {
1735 let max_x = center.dx().max(size.width() - center.dx());
1736 let max_y = center.dy().max(size.height() - center.dy());
1737 (max_x * max_x + max_y * max_y).sqrt()
1738 }
1739}
1740
1741impl CustomPainter for RadialPainter {
1742 fn should_repaint(&self, _app: &App, old_painter: &dyn CustomPainter) -> bool {
1743 let old_painter = old_painter
1744 .as_any()
1745 .downcast_ref::<RadialPainter>()
1746 .expect("compared with a painter of its own type");
1747 if self.text_direction != old_painter.text_direction {
1748 return true;
1749 }
1750 if Rc::ptr_eq(&self.circles, &old_painter.circles) {
1751 return false;
1752 }
1753 if self.circles.len() != old_painter.circles.len() {
1754 return true;
1755 }
1756 for i in 0..self.circles.len() {
1757 if !Rc::ptr_eq(&self.circles[i], &old_painter.circles[i]) {
1758 return true;
1759 }
1760 }
1761 false
1762 }
1763
1764 fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1765 for circle in self.circles.iter() {
1766 let paint = Paint::from_color(circle.color.into());
1767 let rect = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
1768 canvas.clip_rect(rect, waft_embedder::ClipOp::Intersect, true);
1769 let left_fraction = match self.text_direction {
1770 TextDirection::Rtl => 1.0 - circle.horizontal_leading_offset(app),
1771 TextDirection::Ltr => circle.horizontal_leading_offset(app),
1772 };
1773 let center = Offset::new(left_fraction * size.width(), size.height() / 2.0);
1774 let radius = transform_tween(
1775 app,
1776 0.0,
1777 RadialPainter::max_radius(center, size),
1778 circle.animation.as_animation().value(app),
1779 );
1780 canvas.draw_circle(center, radius as f32, &paint);
1781 }
1782 }
1783
1784 fn as_any(&self) -> &dyn Any {
1785 self
1786 }
1787}
1788
1789#[cfg(test)]
1790pub(crate) mod tests {
1791 use std::cell::Cell;
1794 use std::time::Duration;
1795
1796 use waft_embedder::FontWeight;
1797 use waft_painting::EdgeInsets;
1798 use waft_widgets::{AnyElement, Icon, IconData, MediaQueryData, Opacity};
1799
1800 use waft_widgets::testing::{
1801 TestPointer, WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget,
1802 test_widgets,
1803 };
1804
1805 use super::*;
1806 use crate::color_scheme::ColorScheme;
1807 use crate::colors::Colors;
1808 use crate::icons::Icons;
1809 use crate::scaffold::Scaffold;
1810 use crate::theme_data::ThemeData;
1811 use crate::tooltip::tests::{m2, m3, pump_app};
1812
1813 pub(crate) fn diagonal3(scale: f64) -> Matrix4 {
1815 diagonal3_all(scale)
1816 }
1817
1818 pub(crate) fn item(icon: IconData, label: &str) -> BottomNavigationBarItem {
1819 BottomNavigationBarItem::new(Icon::new(Some(icon))).label(label)
1820 }
1821
1822 pub(crate) fn ac_alarm() -> Vec<BottomNavigationBarItem> {
1823 vec![
1824 item(Icons::ac_unit(), "AC"),
1825 item(Icons::access_alarm(), "Alarm"),
1826 ]
1827 }
1828
1829 pub(crate) fn pump_bar(
1831 tester: &mut WidgetTester,
1832 theme: impl FnOnce(&App) -> ThemeData,
1833 bar: impl FnOnce() -> BottomNavigationBar,
1834 ) {
1835 pump_app(tester, theme, |_app| {
1836 Scaffold::new().bottom_navigation_bar(bar()).into_widget()
1837 });
1838 }
1839
1840 pub(crate) fn first_text(tester: &WidgetTester, text: &str) -> AnyElement {
1841 *find::text(text)
1842 .evaluate(tester)
1843 .first()
1844 .expect("a Text showing the text")
1845 }
1846
1847 pub(crate) fn paragraph_style(tester: &WidgetTester, text: &str) -> TextStyle {
1849 let render = tester.render_box_of(first_text(tester, text));
1850 let app = tester.cell.borrow();
1851 let paragraph = render
1852 .as_object()
1853 .downcast::<waft_rendering::RenderParagraph>(&app)
1854 .expect("a Text renders a paragraph");
1855 paragraph
1856 .text(&app)
1857 .style()
1858 .cloned()
1859 .expect("the paragraph's text has a style")
1860 }
1861
1862 pub(crate) fn color_of(style: &TextStyle) -> Option<Color> {
1863 style.color.as_ref().map(|color| color.color())
1864 }
1865
1866 pub(crate) fn icon_style(tester: &WidgetTester, icon: IconData) -> TextStyle {
1868 tester.glyph_style(tester.element(find::by_icon(&icon).first()))
1869 }
1870
1871 fn item_padding(tester: &WidgetTester, icon: IconData) -> EdgeInsets {
1873 let ink_response = tester
1874 .element(find::ancestor(find::by_icon(&icon), find::by_type::<InkResponse>()).first());
1875 let padding = tester.descendants_of_type::<Padding>(ink_response)[0];
1876 tester.widget(padding, |padding: &Padding| {
1877 padding.padding.resolve(Some(TextDirection::Ltr))
1878 })
1879 }
1880
1881 fn opacity_of(tester: &WidgetTester, text: &str) -> f64 {
1883 let fade = tester.ancestor_of_type::<FadeTransition>(first_text(tester, text));
1884 let opacity = tester.widget(fade, |fade: &FadeTransition| fade.opacity.clone());
1885 opacity.value(&tester.cell.borrow())
1886 }
1887
1888 pub(crate) fn material_of<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
1890 let bar = find::by_type::<BottomNavigationBar>().evaluate(tester)[0];
1891 let material = tester.descendants_of_type::<Material>(bar)[0];
1892 tester.widget(material, read)
1893 }
1894
1895 pub(crate) fn label_transform(tester: &WidgetTester, text: &str) -> Matrix4 {
1897 let transform = tester.ancestor_of_type::<Transform>(first_text(tester, text));
1898 tester.widget(transform, |transform: &Transform| transform.transform)
1899 }
1900
1901 pub(crate) fn descendants_of_bar<W: 'static>(tester: &WidgetTester) -> usize {
1902 let bar = find::by_type::<BottomNavigationBar>().evaluate(tester)[0];
1903 tester.descendants_of_type::<W>(bar).len()
1904 }
1905
1906 fn bar_box(tester: &WidgetTester) -> waft_rendering::AnyRenderBox {
1907 tester.render_box_of(find::by_type::<BottomNavigationBar>().evaluate(tester)[0])
1908 }
1909
1910 #[test]
1911 fn bottom_navigation_bar_callback_test() {
1912 test_widgets(|tester| {
1913 let mutated_index = Rc::new(Cell::new(None));
1914 let seen = Rc::clone(&mutated_index);
1915 pump_bar(tester, m3, move || {
1916 BottomNavigationBar::new(ac_alarm())
1917 .on_tap(move |_app, index| seen.set(Some(index)))
1918 });
1919
1920 let at = tester.get_rect(first_text(tester, "Alarm"));
1921 tester.tap_at(at.center(), 1);
1922
1923 assert_eq!(mutated_index.get(), Some(1));
1924 });
1925 }
1926
1927 #[test]
1928 fn material2_bottom_navigation_bar_content_test() {
1929 test_widgets(|tester| {
1930 pump_bar(tester, m2, || BottomNavigationBar::new(ac_alarm()));
1931
1932 let size = bar_box(tester).size(&tester.cell.borrow());
1933 assert_eq!(size.height(), K_BOTTOM_NAVIGATION_BAR_HEIGHT);
1934 expect(tester, &find::text("AC"), finds_one_widget());
1935 expect(tester, &find::text("Alarm"), finds_one_widget());
1936 });
1937 }
1938
1939 #[test]
1940 fn material3_bottom_navigation_bar_content_test() {
1941 test_widgets(|tester| {
1942 pump_bar(tester, m3, || BottomNavigationBar::new(ac_alarm()));
1943
1944 let size = bar_box(tester).size(&tester.cell.borrow());
1945 assert!(size.height() >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
1947 expect(tester, &find::text("AC"), finds_one_widget());
1948 expect(tester, &find::text("Alarm"), finds_one_widget());
1949 });
1950 }
1951
1952 fn fixed_bottom_navigation_bar_defaults(
1953 tester: &mut WidgetTester,
1954 theme: impl FnOnce(&App, ColorScheme, Color) -> ThemeData,
1955 expected_height: Option<f64>,
1956 ) {
1957 let primary_color = Color::new(0xFF000001);
1958 let unselected_widget_color = Color::new(0xFF000002);
1959 pump_bar(
1960 tester,
1961 |app| {
1962 theme(
1963 app,
1964 ColorScheme::light().copy_with().with_primary(primary_color),
1965 unselected_widget_color,
1966 )
1967 },
1968 || BottomNavigationBar::new(ac_alarm()).r#type(BottomNavigationBarType::Fixed),
1969 );
1970
1971 let selected_font_size = 14.0;
1972 let unselected_font_size = 12.0;
1973 let selected_font_style = paragraph_style(tester, "AC");
1974 let unselected_font_style = paragraph_style(tester, "Alarm");
1975 let selected_icon = icon_style(tester, Icons::ac_unit());
1976 let unselected_icon = icon_style(tester, Icons::access_alarm());
1977 assert_eq!(color_of(&selected_font_style), Some(primary_color));
1978 assert_eq!(selected_font_style.font_size, Some(selected_font_size));
1979 assert_eq!(selected_font_style.font_weight, Some(FontWeight::W400));
1980 assert_eq!(selected_font_style.height, expected_height);
1981 assert_eq!(
1982 color_of(&unselected_font_style),
1983 Some(unselected_widget_color)
1984 );
1985 assert_eq!(unselected_font_style.font_weight, Some(FontWeight::W400));
1986 assert_eq!(unselected_font_style.height, expected_height);
1987 assert_eq!(
1989 label_transform(tester, "Alarm"),
1990 diagonal3_all(unselected_font_size / selected_font_size)
1991 );
1992 assert_eq!(color_of(&selected_icon), Some(primary_color));
1993 assert_eq!(selected_icon.font_size, Some(24.0));
1994 assert_eq!(color_of(&unselected_icon), Some(unselected_widget_color));
1995 assert_eq!(unselected_icon.font_size, Some(24.0));
1996 assert_eq!(descendants_of_bar::<Opacity>(tester), 0);
1999 assert_eq!(descendants_of_bar::<FadeTransition>(tester), 0);
2000 assert_eq!(material_of(tester, |material| material.elevation), 8.0);
2001 }
2002
2003 #[test]
2004 fn material2_fixed_bottom_navigation_bar_defaults() {
2005 test_widgets(|tester| {
2006 fixed_bottom_navigation_bar_defaults(
2007 tester,
2008 |app, color_scheme, unselected_widget_color| {
2009 ThemeData::light(app, Some(false))
2010 .copy_with()
2011 .color_scheme(color_scheme)
2012 .unselected_widget_color(unselected_widget_color)
2013 .build()
2014 },
2015 None,
2016 );
2017 });
2018 }
2019
2020 #[test]
2021 fn material3_fixed_bottom_navigation_bar_defaults() {
2022 test_widgets(|tester| {
2023 fixed_bottom_navigation_bar_defaults(
2024 tester,
2025 |app, color_scheme, unselected_widget_color| {
2026 ThemeData::builder()
2027 .color_scheme(color_scheme)
2028 .unselected_widget_color(unselected_widget_color)
2029 .build(app)
2030 },
2031 Some(1.43),
2032 );
2033 });
2034 }
2035
2036 #[test]
2037 fn custom_selected_and_unselected_font_styles() {
2038 test_widgets(|tester| {
2039 let selected_text_style = TextStyle::new()
2040 .font_weight(FontWeight::W200)
2041 .font_size(18.0);
2042 let unselected_text_style = TextStyle::new()
2043 .font_weight(FontWeight::W600)
2044 .font_size(12.0);
2045 let (selected, unselected) =
2046 (selected_text_style.clone(), unselected_text_style.clone());
2047 pump_bar(tester, m3, move || {
2048 BottomNavigationBar::new(ac_alarm())
2049 .r#type(BottomNavigationBarType::Fixed)
2050 .selected_label_style(selected)
2051 .unselected_label_style(unselected)
2052 });
2053
2054 let selected_font_style = paragraph_style(tester, "AC");
2055 let unselected_font_style = paragraph_style(tester, "Alarm");
2056 assert_eq!(selected_font_style.font_size, selected_text_style.font_size);
2057 assert_eq!(
2058 selected_font_style.font_weight,
2059 selected_text_style.font_weight
2060 );
2061 assert_eq!(
2062 label_transform(tester, "Alarm"),
2063 diagonal3_all(
2064 unselected_text_style.font_size.unwrap()
2065 / selected_text_style.font_size.unwrap()
2066 )
2067 );
2068 assert_eq!(
2069 unselected_font_style.font_weight,
2070 unselected_text_style.font_weight
2071 );
2072 });
2073 }
2074
2075 #[test]
2076 fn font_size_on_text_styles_overrides_font_size_params() {
2077 test_widgets(|tester| {
2078 let selected_text_style = TextStyle::new().font_size(18.0);
2079 let unselected_text_style = TextStyle::new().font_size(12.0);
2080 let (selected, unselected) =
2081 (selected_text_style.clone(), unselected_text_style.clone());
2082 pump_bar(tester, m3, move || {
2083 BottomNavigationBar::new(ac_alarm())
2084 .r#type(BottomNavigationBarType::Fixed)
2085 .selected_label_style(selected)
2086 .unselected_label_style(unselected)
2087 .selected_font_size(17.0)
2088 .unselected_font_size(11.0)
2089 });
2090
2091 let selected_font_style = paragraph_style(tester, "AC");
2092 assert_eq!(selected_font_style.font_size, selected_text_style.font_size);
2093 assert_eq!(
2094 label_transform(tester, "Alarm"),
2095 diagonal3_all(
2096 unselected_text_style.font_size.unwrap()
2097 / selected_text_style.font_size.unwrap()
2098 )
2099 );
2100 });
2101 }
2102
2103 #[test]
2104 fn custom_selected_and_unselected_icon_themes() {
2105 test_widgets(|tester| {
2106 let selected_icon_theme = IconThemeData::new()
2107 .size(36.0)
2108 .color(Color::new(0x00000001));
2109 let unselected_icon_theme = IconThemeData::new()
2110 .size(18.0)
2111 .color(Color::new(0x00000002));
2112 let (selected, unselected) =
2113 (selected_icon_theme.clone(), unselected_icon_theme.clone());
2114 pump_bar(tester, m3, move || {
2115 BottomNavigationBar::new(ac_alarm())
2116 .r#type(BottomNavigationBarType::Fixed)
2117 .selected_icon_theme(selected)
2118 .unselected_icon_theme(unselected)
2119 });
2120
2121 let selected_icon = icon_style(tester, Icons::ac_unit());
2122 let unselected_icon = icon_style(tester, Icons::access_alarm());
2123 assert_eq!(selected_icon.color, selected_icon_theme.color);
2124 assert_eq!(selected_icon.font_size, selected_icon_theme.size);
2125 assert_eq!(unselected_icon.color, unselected_icon_theme.color);
2126 assert_eq!(unselected_icon.font_size, unselected_icon_theme.size);
2127 });
2128 }
2129
2130 #[test]
2131 fn color_on_icon_theme_overrides_selected_and_unselected_item_colors() {
2132 test_widgets(|tester| {
2133 let selected_icon_theme = IconThemeData::new()
2134 .size(36.0)
2135 .color(Color::new(0x00000001));
2136 let unselected_icon_theme = IconThemeData::new()
2137 .size(18.0)
2138 .color(Color::new(0x00000002));
2139 let selected_item_color = Color::new(0x00000003);
2140 let unselected_item_color = Color::new(0x00000004);
2141 let (selected, unselected) =
2142 (selected_icon_theme.clone(), unselected_icon_theme.clone());
2143 pump_bar(tester, m3, move || {
2144 BottomNavigationBar::new(ac_alarm())
2145 .r#type(BottomNavigationBarType::Fixed)
2146 .selected_icon_theme(selected)
2147 .unselected_icon_theme(unselected)
2148 .selected_item_color(selected_item_color)
2149 .unselected_item_color(unselected_item_color)
2150 });
2151
2152 let selected_font_style = paragraph_style(tester, "AC");
2153 let unselected_font_style = paragraph_style(tester, "Alarm");
2154 let selected_icon = icon_style(tester, Icons::ac_unit());
2155 let unselected_icon = icon_style(tester, Icons::access_alarm());
2156 assert_eq!(selected_icon.color, selected_icon_theme.color);
2157 assert_eq!(unselected_icon.color, unselected_icon_theme.color);
2158 assert_eq!(color_of(&selected_font_style), Some(selected_item_color));
2159 assert_eq!(
2160 color_of(&unselected_font_style),
2161 Some(unselected_item_color)
2162 );
2163 });
2164 }
2165
2166 fn padded_bar(
2167 tester: &mut WidgetTester,
2168 show_selected_labels: bool,
2169 show_unselected_labels: bool,
2170 ) {
2171 pump_bar(tester, m3, move || {
2172 BottomNavigationBar::new(ac_alarm())
2173 .r#type(BottomNavigationBarType::Fixed)
2174 .show_selected_labels(show_selected_labels)
2175 .show_unselected_labels(show_unselected_labels)
2176 .selected_font_size(16.0)
2177 .selected_icon_theme(IconThemeData::new().size(36.0))
2178 .unselected_icon_theme(IconThemeData::new().size(20.0))
2179 });
2180 }
2181
2182 #[test]
2183 fn padding_is_calculated_properly_on_items_all_labels() {
2184 test_widgets(|tester| {
2185 let (selected_font_size, selected_icon_size, unselected_icon_size) = (16.0, 36.0, 20.0);
2186 padded_bar(tester, true, true);
2187
2188 let selected_item_padding = item_padding(tester, Icons::ac_unit());
2189 assert_eq!(selected_item_padding.top, selected_font_size / 2.0);
2190 assert_eq!(selected_item_padding.bottom, selected_font_size / 2.0);
2191 let unselected_item_padding = item_padding(tester, Icons::access_alarm());
2192 let expected_unselected_padding =
2193 (selected_icon_size - unselected_icon_size) / 2.0 + selected_font_size / 2.0;
2194 assert_eq!(unselected_item_padding.top, expected_unselected_padding);
2195 assert_eq!(unselected_item_padding.bottom, expected_unselected_padding);
2196 });
2197 }
2198
2199 #[test]
2200 fn padding_is_calculated_properly_on_items_selected_labels_only() {
2201 test_widgets(|tester| {
2202 let (selected_font_size, selected_icon_size, unselected_icon_size) = (16.0, 36.0, 20.0);
2203 padded_bar(tester, true, false);
2204
2205 let selected_item_padding = item_padding(tester, Icons::ac_unit());
2206 assert_eq!(selected_item_padding.top, selected_font_size / 2.0);
2207 assert_eq!(selected_item_padding.bottom, selected_font_size / 2.0);
2208 let unselected_item_padding = item_padding(tester, Icons::access_alarm());
2209 assert_eq!(
2210 unselected_item_padding.top,
2211 (selected_icon_size - unselected_icon_size) / 2.0 + selected_font_size
2212 );
2213 assert_eq!(
2214 unselected_item_padding.bottom,
2215 (selected_icon_size - unselected_icon_size) / 2.0
2216 );
2217 });
2218 }
2219
2220 #[test]
2221 fn padding_is_calculated_properly_on_items_no_labels() {
2222 test_widgets(|tester| {
2223 let (selected_font_size, selected_icon_size, unselected_icon_size) = (16.0, 36.0, 20.0);
2224 padded_bar(tester, false, false);
2225
2226 let selected_item_padding = item_padding(tester, Icons::ac_unit());
2227 assert_eq!(selected_item_padding.top, selected_font_size);
2228 assert_eq!(selected_item_padding.bottom, 0.0);
2229 let unselected_item_padding = item_padding(tester, Icons::access_alarm());
2230 assert_eq!(
2231 unselected_item_padding.top,
2232 (selected_icon_size - unselected_icon_size) / 2.0 + selected_font_size
2233 );
2234 assert_eq!(
2235 unselected_item_padding.bottom,
2236 (selected_icon_size - unselected_icon_size) / 2.0
2237 );
2238 });
2239 }
2240
2241 #[test]
2242 fn material2_shifting_bottom_navigation_bar_defaults() {
2243 test_widgets(|tester| {
2244 pump_bar(tester, m2, || {
2245 BottomNavigationBar::new(ac_alarm()).r#type(BottomNavigationBarType::Shifting)
2246 });
2247
2248 let selected_font_size = 14.0;
2249 assert_eq!(
2250 paragraph_style(tester, "AC").font_size,
2251 Some(selected_font_size)
2252 );
2253 assert_eq!(
2254 color_of(¶graph_style(tester, "AC")),
2255 Some(Colors::WHITE)
2256 );
2257 assert_eq!(opacity_of(tester, "Alarm"), 0.0);
2258 assert_eq!(material_of(tester, |material| material.elevation), 8.0);
2259 });
2260 }
2261
2262 #[test]
2263 fn material3_shifting_bottom_navigation_bar_defaults() {
2264 test_widgets(|tester| {
2265 pump_bar(tester, m3, || {
2266 BottomNavigationBar::new(ac_alarm()).r#type(BottomNavigationBarType::Shifting)
2267 });
2268
2269 let selected_font_size = 14.0;
2270 assert_eq!(
2271 paragraph_style(tester, "AC").font_size,
2272 Some(selected_font_size)
2273 );
2274 let surface = {
2275 let element = first_text(tester, "AC");
2276 let mut app = tester.cell.borrow_mut();
2277 Theme::of(&mut app, element).color_scheme.surface()
2278 };
2279 assert_eq!(color_of(¶graph_style(tester, "AC")), Some(surface));
2280 assert_eq!(opacity_of(tester, "Alarm"), 0.0);
2281 assert_eq!(material_of(tester, |material| material.elevation), 8.0);
2282 });
2283 }
2284
2285 fn primary_and_unselected_theme(app: &App) -> ThemeData {
2287 ThemeData::builder()
2288 .primary_color(Color::new(0xFF000000))
2289 .unselected_widget_color(Color::new(0xFFD501FF))
2290 .build(app)
2291 }
2292
2293 const SELECTED_COLOR: Color = Color::new(0xFF0004FF);
2294 const UNSELECTED_COLOR: Color = Color::new(0xFFE5FF00);
2295 const SELECTED_LABEL_COLOR: Color = Color::new(0xFFFF9900);
2296 const UNSELECTED_LABEL_COLOR: Color = Color::new(0xFF92F74E);
2297 const SELECTED_ICON_THEME_COLOR: Color = Color::new(0xFF1E7723);
2298 const UNSELECTED_ICON_THEME_COLOR: Color = Color::new(0xFF009688);
2299
2300 #[test]
2301 fn fixed_bottom_navigation_bar_custom_font_size_color() {
2302 test_widgets(|tester| {
2303 let (selected_font_size, unselected_font_size) = (18.0, 14.0);
2304 pump_bar(tester, primary_and_unselected_theme, move || {
2305 BottomNavigationBar::new(ac_alarm())
2306 .r#type(BottomNavigationBarType::Fixed)
2307 .selected_font_size(selected_font_size)
2308 .unselected_font_size(unselected_font_size)
2309 .selected_item_color(SELECTED_COLOR)
2310 .unselected_item_color(UNSELECTED_COLOR)
2311 });
2312
2313 let selected_icon = icon_style(tester, Icons::ac_unit());
2314 let unselected_icon = icon_style(tester, Icons::access_alarm());
2315
2316 assert_eq!(
2317 paragraph_style(tester, "AC").font_size,
2318 Some(selected_font_size)
2319 );
2320 assert_eq!(
2322 paragraph_style(tester, "Alarm").font_size,
2323 Some(selected_font_size)
2324 );
2325 assert_eq!(
2326 label_transform(tester, "Alarm"),
2327 diagonal3_all(unselected_font_size / selected_font_size)
2328 );
2329 assert_eq!(
2330 color_of(¶graph_style(tester, "AC")),
2331 Some(SELECTED_COLOR)
2332 );
2333 assert_eq!(
2334 color_of(¶graph_style(tester, "Alarm")),
2335 Some(UNSELECTED_COLOR)
2336 );
2337 assert_eq!(color_of(&selected_icon), Some(SELECTED_COLOR));
2338 assert_eq!(color_of(&unselected_icon), Some(UNSELECTED_COLOR));
2339 assert_eq!(descendants_of_bar::<Opacity>(tester), 0);
2342 assert_eq!(descendants_of_bar::<FadeTransition>(tester), 0);
2343 });
2344 }
2345
2346 #[test]
2347 fn shifting_bottom_navigation_bar_custom_font_size_color() {
2348 test_widgets(|tester| {
2349 let (selected_font_size, unselected_font_size) = (18.0, 14.0);
2350 pump_bar(tester, primary_and_unselected_theme, move || {
2351 BottomNavigationBar::new(ac_alarm())
2352 .r#type(BottomNavigationBarType::Shifting)
2353 .selected_font_size(selected_font_size)
2354 .unselected_font_size(unselected_font_size)
2355 .selected_item_color(SELECTED_COLOR)
2356 .unselected_item_color(UNSELECTED_COLOR)
2357 });
2358
2359 let selected_icon = icon_style(tester, Icons::ac_unit());
2360 let unselected_icon = icon_style(tester, Icons::access_alarm());
2361
2362 assert_eq!(
2363 paragraph_style(tester, "AC").font_size,
2364 Some(selected_font_size)
2365 );
2366 assert_eq!(
2367 color_of(¶graph_style(tester, "AC")),
2368 Some(SELECTED_COLOR)
2369 );
2370 assert_eq!(opacity_of(tester, "Alarm"), 0.0);
2371
2372 assert_eq!(color_of(&selected_icon), Some(SELECTED_COLOR));
2373 assert_eq!(color_of(&unselected_icon), Some(UNSELECTED_COLOR));
2374 });
2375 }
2376
2377 fn label_style_color_overrides_item_color_only_for_the_label(
2378 tester: &mut WidgetTester,
2379 r#type: BottomNavigationBarType,
2380 ) {
2381 pump_bar(tester, primary_and_unselected_theme, move || {
2382 BottomNavigationBar::new(ac_alarm())
2383 .r#type(r#type)
2384 .selected_label_style(TextStyle::new().color(SELECTED_LABEL_COLOR))
2385 .unselected_label_style(TextStyle::new().color(UNSELECTED_LABEL_COLOR))
2386 .selected_item_color(SELECTED_COLOR)
2387 .unselected_item_color(UNSELECTED_COLOR)
2388 .use_legacy_color_scheme(false)
2389 });
2390
2391 let selected_icon = icon_style(tester, Icons::ac_unit());
2392 let unselected_icon = icon_style(tester, Icons::access_alarm());
2393
2394 assert_eq!(color_of(&selected_icon), Some(SELECTED_COLOR));
2395 assert_eq!(color_of(&unselected_icon), Some(UNSELECTED_COLOR));
2396 assert_eq!(
2397 color_of(¶graph_style(tester, "AC")),
2398 Some(SELECTED_LABEL_COLOR)
2399 );
2400 assert_eq!(
2401 color_of(¶graph_style(tester, "Alarm")),
2402 Some(UNSELECTED_LABEL_COLOR)
2403 );
2404 }
2405
2406 #[test]
2407 fn label_style_color_should_override_item_color_only_for_the_label_for_fixed() {
2408 test_widgets(|tester| {
2409 label_style_color_overrides_item_color_only_for_the_label(
2410 tester,
2411 BottomNavigationBarType::Fixed,
2412 );
2413 });
2414 }
2415
2416 #[test]
2417 fn label_style_color_should_override_item_color_only_for_the_label_for_shifting() {
2418 test_widgets(|tester| {
2419 label_style_color_overrides_item_color_only_for_the_label(
2420 tester,
2421 BottomNavigationBarType::Shifting,
2422 );
2423 });
2424 }
2425
2426 fn icon_theme_color_overrides_item_color(
2427 tester: &mut WidgetTester,
2428 r#type: BottomNavigationBarType,
2429 label_styles: bool,
2430 item_colors: bool,
2431 ) {
2432 pump_bar(tester, primary_and_unselected_theme, move || {
2433 let mut bar = BottomNavigationBar::new(ac_alarm())
2434 .r#type(r#type)
2435 .selected_icon_theme(
2436 IconThemeData::new()
2437 .size(20.0)
2438 .color(SELECTED_ICON_THEME_COLOR),
2439 )
2440 .unselected_icon_theme(
2441 IconThemeData::new()
2442 .size(18.0)
2443 .color(UNSELECTED_ICON_THEME_COLOR),
2444 )
2445 .use_legacy_color_scheme(false);
2446 if label_styles {
2447 bar = bar
2448 .selected_label_style(
2449 TextStyle::new().font_size(18.0).color(SELECTED_LABEL_COLOR),
2450 )
2451 .unselected_label_style(
2452 TextStyle::new()
2453 .font_size(18.0)
2454 .color(UNSELECTED_LABEL_COLOR),
2455 );
2456 }
2457 if item_colors {
2458 bar = bar
2459 .selected_item_color(SELECTED_COLOR)
2460 .unselected_item_color(UNSELECTED_COLOR);
2461 }
2462 bar
2463 });
2464
2465 let selected_icon = icon_style(tester, Icons::ac_unit());
2466 let unselected_icon = icon_style(tester, Icons::access_alarm());
2467
2468 assert_eq!(color_of(&selected_icon), Some(SELECTED_ICON_THEME_COLOR));
2469 assert_eq!(
2470 color_of(&unselected_icon),
2471 Some(UNSELECTED_ICON_THEME_COLOR)
2472 );
2473 }
2474
2475 #[test]
2476 fn icon_theme_color_should_override_item_color_for_fixed() {
2477 test_widgets(|tester| {
2478 icon_theme_color_overrides_item_color(
2479 tester,
2480 BottomNavigationBarType::Fixed,
2481 true,
2482 true,
2483 );
2484 });
2485 }
2486
2487 #[test]
2488 fn icon_theme_color_should_override_item_color_for_shifted() {
2489 test_widgets(|tester| {
2490 icon_theme_color_overrides_item_color(
2491 tester,
2492 BottomNavigationBarType::Shifting,
2493 true,
2494 false,
2495 );
2496 });
2497 }
2498
2499 #[test]
2500 fn icon_theme_color_should_override_item_color_color_for_fixed() {
2501 test_widgets(|tester| {
2502 icon_theme_color_overrides_item_color(
2503 tester,
2504 BottomNavigationBarType::Fixed,
2505 false,
2506 false,
2507 );
2508 });
2509 }
2510
2511 #[test]
2512 fn icon_theme_color_should_override_item_color_for_shifted_with_item_colors() {
2513 test_widgets(|tester| {
2514 icon_theme_color_overrides_item_color(
2515 tester,
2516 BottomNavigationBarType::Shifting,
2517 false,
2518 true,
2519 );
2520 });
2521 }
2522
2523 #[test]
2524 fn fixed_bottom_navigation_bar_can_hide_unselected_labels() {
2525 test_widgets(|tester| {
2526 pump_bar(tester, m3, || {
2527 BottomNavigationBar::new(ac_alarm())
2528 .r#type(BottomNavigationBarType::Fixed)
2529 .show_unselected_labels(false)
2530 });
2531
2532 assert_eq!(opacity_of(tester, "AC"), 1.0);
2533 assert_eq!(opacity_of(tester, "Alarm"), 0.0);
2534 });
2535 }
2536
2537 #[test]
2538 fn fixed_bottom_navigation_bar_can_update_background_color() {
2539 test_widgets(|tester| {
2540 let color = Colors::YELLOW.primary();
2541 pump_bar(tester, m3, move || {
2542 BottomNavigationBar::new(ac_alarm())
2543 .r#type(BottomNavigationBarType::Fixed)
2544 .background_color(color)
2545 });
2546
2547 assert_eq!(material_of(tester, |material| material.color), Some(color));
2548 });
2549 }
2550
2551 #[test]
2552 fn shifting_bottom_navigation_bar_background_color_is_overridden_by_item_color() {
2553 test_widgets(|tester| {
2554 let item_color = Colors::YELLOW.primary();
2555 let background_color = Colors::BLUE.primary();
2556 pump_bar(tester, m3, move || {
2557 BottomNavigationBar::new(vec![
2558 item(Icons::ac_unit(), "AC").background_color(item_color),
2559 item(Icons::access_alarm(), "Alarm"),
2560 ])
2561 .r#type(BottomNavigationBarType::Shifting)
2562 .background_color(background_color)
2563 });
2564
2565 assert_eq!(
2566 material_of(tester, |material| material.color),
2567 Some(item_color)
2568 );
2569 });
2570 }
2571
2572 #[test]
2573 #[should_panic(expected = "Either selectedItemColor or fixedColor can be specified")]
2574 fn specifying_both_selected_item_color_and_fixed_color_asserts() {
2575 BottomNavigationBar::new(ac_alarm())
2576 .selected_item_color(Colors::BLACK)
2577 .fixed_color(Colors::BLACK)
2578 .into_widget();
2579 }
2580
2581 #[test]
2582 fn fixed_bottom_navigation_bar_uses_fixed_color_when_selected_item_color_not_provided() {
2583 test_widgets(|tester| {
2584 let fixed_color = Colors::BLACK;
2585 pump_bar(tester, m3, move || {
2586 BottomNavigationBar::new(ac_alarm())
2587 .r#type(BottomNavigationBarType::Fixed)
2588 .fixed_color(fixed_color)
2589 });
2590
2591 assert_eq!(color_of(¶graph_style(tester, "AC")), Some(fixed_color));
2592 });
2593 }
2594
2595 #[test]
2596 fn setting_selected_font_size_to_zero_hides_all_labels() {
2597 test_widgets(|tester| {
2598 let custom_elevation = 3.0;
2599 pump_bar(tester, m3, move || {
2600 BottomNavigationBar::new(ac_alarm())
2601 .r#type(BottomNavigationBarType::Fixed)
2602 .elevation(custom_elevation)
2603 });
2604
2605 assert_eq!(
2606 material_of(tester, |material| material.elevation),
2607 custom_elevation
2608 );
2609 });
2610 }
2611
2612 fn pump_bar_under_media_query(
2614 tester: &mut WidgetTester,
2615 theme: impl FnOnce(&App) -> ThemeData,
2616 data: MediaQueryData,
2617 bar: BottomNavigationBar,
2618 ) {
2619 pump_app(tester, theme, move |_app| {
2620 MediaQuery::new(data, Scaffold::new().bottom_navigation_bar(bar)).into_widget()
2621 });
2622 }
2623
2624 fn bar_size(tester: &WidgetTester) -> Size {
2625 bar_box(tester).size(&tester.cell.borrow())
2626 }
2627
2628 #[test]
2629 fn material2_bottom_navigation_bar_adds_bottom_padding_to_height() {
2630 test_widgets(|tester| {
2631 pump_bar_under_media_query(
2632 tester,
2633 m2,
2634 MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0)),
2635 BottomNavigationBar::new(ac_alarm()),
2636 );
2637
2638 let expected_height = K_BOTTOM_NAVIGATION_BAR_HEIGHT + 40.0;
2639 assert_eq!(bar_size(tester).height(), expected_height);
2640 });
2641 }
2642
2643 #[test]
2644 fn material3_bottom_navigation_bar_adds_bottom_padding_to_height() {
2645 test_widgets(|tester| {
2646 pump_bar_under_media_query(
2647 tester,
2648 m3,
2649 MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0)),
2650 BottomNavigationBar::new(ac_alarm()),
2651 );
2652
2653 let expected_min_height = K_BOTTOM_NAVIGATION_BAR_HEIGHT + 40.0;
2654 assert!(bar_size(tester).height() >= expected_min_height);
2655 });
2656 }
2657
2658 #[test]
2659 fn bottom_navigation_bar_adds_bottom_padding_to_height_with_a_custom_font_size() {
2660 test_widgets(|tester| {
2661 pump_bar_under_media_query(
2662 tester,
2663 m3,
2664 MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0)),
2665 BottomNavigationBar::new(ac_alarm()).selected_font_size(8.0),
2666 );
2667
2668 let expected_height = K_BOTTOM_NAVIGATION_BAR_HEIGHT + 40.0;
2669 assert_eq!(bar_size(tester).height(), expected_height);
2670 });
2671 }
2672
2673 #[test]
2674 fn bottom_navigation_bar_height_will_not_change_when_toggle_keyboard() {
2675 test_widgets(|tester| {
2676 pump_bar_under_media_query(
2678 tester,
2679 m3,
2680 MediaQueryData::new()
2681 .view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0))
2682 .padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0)),
2683 BottomNavigationBar::new(ac_alarm()).selected_font_size(8.0),
2684 );
2685
2686 let expected_height = K_BOTTOM_NAVIGATION_BAR_HEIGHT + 40.0;
2688 assert_eq!(bar_size(tester).height(), expected_height);
2689
2690 pump_bar_under_media_query(
2692 tester,
2693 m3,
2694 MediaQueryData::new()
2695 .view_padding(EdgeInsets::only(0.0, 0.0, 0.0, 40.0))
2696 .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 336.0)),
2697 BottomNavigationBar::new(ac_alarm()).selected_font_size(8.0),
2698 );
2699
2700 assert_eq!(bar_size(tester).height(), expected_height);
2702 });
2703 }
2704
2705 fn actions(tester: &WidgetTester) -> Vec<waft_rendering::AnyRenderBox> {
2707 find::by_type::<InkResponse>()
2708 .evaluate(tester)
2709 .into_iter()
2710 .map(|element| tester.render_box_of(element))
2711 .collect()
2712 }
2713
2714 fn origin_of(tester: &WidgetTester, render: waft_rendering::AnyRenderBox) -> Offset {
2715 render.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
2716 }
2717
2718 pub(crate) fn text_center(tester: &WidgetTester, text: &str) -> Offset {
2719 tester.get_rect(first_text(tester, text)).center()
2720 }
2721
2722 #[test]
2723 fn bottom_navigation_bar_action_size_test() {
2724 test_widgets(|tester| {
2725 pump_bar(tester, m3, || {
2726 BottomNavigationBar::new(ac_alarm()).r#type(BottomNavigationBarType::Shifting)
2727 });
2728
2729 let found = actions(tester);
2730 assert_eq!(found.len(), 2);
2731 assert_eq!(found[0].size(&tester.cell.borrow()).width(), 480.0);
2732 assert_eq!(found[1].size(&tester.cell.borrow()).width(), 320.0);
2733
2734 pump_bar(tester, m3, || {
2735 BottomNavigationBar::new(ac_alarm())
2736 .current_index(1)
2737 .r#type(BottomNavigationBarType::Shifting)
2738 });
2739
2740 tester.pump_by(Duration::from_millis(200));
2741
2742 let found = actions(tester);
2743 assert_eq!(found.len(), 2);
2744 assert_eq!(found[0].size(&tester.cell.borrow()).width(), 320.0);
2745 assert_eq!(found[1].size(&tester.cell.borrow()).width(), 480.0);
2746 });
2747 }
2748
2749 fn four_items() -> Vec<BottomNavigationBarItem> {
2750 vec![
2751 item(Icons::ac_unit(), "AC"),
2752 item(Icons::access_alarm(), "Alarm"),
2753 item(Icons::access_time(), "Time"),
2754 item(Icons::add(), "Add"),
2755 ]
2756 }
2757
2758 #[test]
2759 fn bottom_navigation_bar_multiple_taps_test() {
2760 test_widgets(|tester| {
2761 pump_bar(tester, m3, || {
2762 BottomNavigationBar::new(four_items()).r#type(BottomNavigationBarType::Shifting)
2763 });
2764
2765 let original_origin = origin_of(tester, actions(tester)[3]);
2770
2771 for (pointer, label) in [(1, "AC"), (2, "Alarm"), (3, "Time")] {
2772 let at = text_center(tester, label);
2773 tester.tap_at(at, pointer);
2774 tester.pump();
2775 tester.pump_by(Duration::from_millis(100));
2776
2777 assert_eq!(origin_of(tester, actions(tester)[3]), original_origin);
2778 }
2779 });
2780 }
2781
2782 fn inherits_shadowed_app_theme(tester: &mut WidgetTester, r#type: BottomNavigationBarType) {
2783 pump_app(
2784 tester,
2785 |app| {
2786 ThemeData::builder()
2787 .brightness(Brightness::Light)
2788 .build(app)
2789 },
2790 move |app| {
2791 Theme::new(
2792 ThemeData::builder().brightness(Brightness::Dark).build(app),
2793 Scaffold::new().bottom_navigation_bar(
2794 BottomNavigationBar::new(four_items()).r#type(r#type),
2795 ),
2796 )
2797 .into_widget()
2798 },
2799 );
2800
2801 let at = text_center(tester, "Alarm");
2802 tester.tap_at(at, 1);
2803 tester.pump_by(Duration::from_secs(1));
2804 let element = first_text(tester, "Alarm");
2805 let brightness = Theme::of(&mut tester.cell.borrow_mut(), element).brightness();
2806 assert_eq!(brightness, Brightness::Dark);
2807 }
2808
2809 #[test]
2810 fn bottom_navigation_bar_inherits_shadowed_app_theme_for_shifting_navbar() {
2811 test_widgets(|tester| {
2812 inherits_shadowed_app_theme(tester, BottomNavigationBarType::Shifting)
2813 });
2814 }
2815
2816 #[test]
2817 fn bottom_navigation_bar_inherits_shadowed_app_theme_for_fixed_navbar() {
2818 test_widgets(|tester| inherits_shadowed_app_theme(tester, BottomNavigationBarType::Fixed));
2819 }
2820
2821 #[test]
2822 fn bottom_navigation_bar_icon_size_test() {
2823 test_widgets(|tester| {
2824 let builder_icon_size = Rc::new(Cell::new(None));
2825 let seen = Rc::clone(&builder_icon_size);
2826 pump_bar(tester, m3, move || {
2827 BottomNavigationBar::new(vec![
2828 item(Icons::ac_unit(), "A"),
2829 BottomNavigationBarItem::new(waft_widgets::Builder::new(
2830 move |app, context| {
2831 let size = IconTheme::of(app, context).size.expect("an icon size");
2832 seen.set(Some(size));
2833 SizedBox::new().width(size).height(size).into_widget()
2834 },
2835 ))
2836 .label("B"),
2837 ])
2838 .icon_size(12.0)
2839 });
2840
2841 let icon = find::by_type::<Icon>().evaluate(tester)[0];
2842 let size = tester.render_box_of(icon).size(&tester.cell.borrow());
2843 assert_eq!(size.width(), 12.0);
2844 assert_eq!(size.height(), 12.0);
2845 assert_eq!(builder_icon_size.get(), Some(12.0));
2846 });
2847 }
2848
2849 fn ab_items() -> Vec<BottomNavigationBarItem> {
2850 vec![
2851 item(Icons::ac_unit(), "A"),
2852 item(Icons::battery_alert(), "B"),
2853 ]
2854 }
2855
2856 #[test]
2857 fn material2_bottom_navigation_bar_responds_to_text_scale_factor() {
2858 test_widgets(|tester| {
2859 pump_bar(tester, m2, || {
2860 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Fixed)
2861 });
2862 assert_eq!(bar_size(tester).height(), K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2863
2864 pump_bar(tester, m3, || {
2865 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Shifting)
2866 });
2867 assert_eq!(bar_size(tester).height(), K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2868
2869 pump_app(tester, m3, |_app| {
2870 MediaQuery::with_clamped_text_scaling(
2871 None,
2872 2.0,
2873 2.0,
2874 Scaffold::new().bottom_navigation_bar(BottomNavigationBar::new(ab_items())),
2875 )
2876 });
2877 assert_eq!(bar_size(tester).height(), 56.0);
2878 });
2879 }
2880
2881 #[test]
2882 fn material3_bottom_navigation_bar_responds_to_text_scale_factor() {
2883 test_widgets(|tester| {
2884 pump_bar(tester, m3, || {
2885 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Fixed)
2886 });
2887 assert!(bar_size(tester).height() >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2889
2890 pump_bar(tester, m3, || {
2891 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Shifting)
2892 });
2893 assert!(bar_size(tester).height() >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2895
2896 pump_app(tester, m3, |_app| {
2897 MediaQuery::with_clamped_text_scaling(
2898 None,
2899 2.0,
2900 2.0,
2901 Scaffold::new().bottom_navigation_bar(BottomNavigationBar::new(ab_items())),
2902 )
2903 });
2904 assert!(bar_size(tester).height() >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2906 });
2907 }
2908
2909 fn does_not_grow_with_text_scale_factor(
2910 tester: &mut WidgetTester,
2911 theme: fn(&App) -> ThemeData,
2912 material3: bool,
2913 ) {
2914 pump_bar(tester, theme, || {
2915 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Fixed)
2916 });
2917 let default_height = bar_size(tester).height();
2918 if material3 {
2919 assert!(default_height >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2921 } else {
2922 assert_eq!(default_height, K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2923 }
2924
2925 pump_bar(tester, m3, || {
2926 BottomNavigationBar::new(ab_items()).r#type(BottomNavigationBarType::Shifting)
2927 });
2928 let shifting_height = bar_size(tester).height();
2929 if material3 {
2930 assert!(shifting_height >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2932 } else {
2933 assert_eq!(shifting_height, K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2934 }
2935
2936 pump_bar_under_media_query(
2937 tester,
2938 m3,
2939 MediaQueryData::new().text_scaler(waft_painting::TextScaler::linear(2.0)),
2940 BottomNavigationBar::new(ab_items()),
2941 );
2942 let height = bar_size(tester).height();
2943 if material3 {
2944 assert_eq!(height, default_height);
2945 assert_eq!(height, shifting_height);
2946 } else {
2947 assert_eq!(height, K_BOTTOM_NAVIGATION_BAR_HEIGHT);
2948 }
2949 }
2950
2951 #[test]
2952 fn material2_bottom_navigation_bar_does_not_grow_with_text_scale_factor_when_labels_are_provided()
2953 {
2954 test_widgets(|tester| does_not_grow_with_text_scale_factor(tester, m2, false));
2955 }
2956
2957 #[test]
2958 fn material3_bottom_navigation_bar_does_not_grow_with_text_scale_factor_when_labels_are_provided()
2959 {
2960 test_widgets(|tester| does_not_grow_with_text_scale_factor(tester, m3, true));
2961 }
2962
2963 fn pump_tooltip_app(
2966 tester: &mut WidgetTester,
2967 theme: fn(&App) -> ThemeData,
2968 text_scaler: waft_painting::TextScaler,
2969 ) {
2970 let root = {
2971 let app = tester.cell.borrow();
2972 MediaQuery::new(
2973 MediaQueryData::new().text_scaler(text_scaler),
2974 crate::test_support::material_app(
2975 theme(&app),
2976 Scaffold::new()
2977 .bottom_navigation_bar(BottomNavigationBar::new(vec![
2978 item(Icons::ac_unit(), "Foo").tooltip("Foo"),
2979 item(Icons::battery_alert(), "B"),
2980 ]))
2981 .into_widget(),
2982 ),
2983 )
2984 .into_widget()
2985 };
2986 tester.pump_widget(root);
2987 }
2988
2989 fn last_text_size(tester: &WidgetTester, text: &str) -> Size {
2990 let found = find::text(text).evaluate(tester);
2991 let last = *found.last().expect("a Text showing the text");
2992 tester.render_box_of(last).size(&tester.cell.borrow())
2993 }
2994
2995 #[test]
2996 fn material2_bottom_navigation_bar_shows_tool_tips_with_text_scaling_on_long_press_when_labels_are_provided()
2997 {
2998 test_widgets(|tester| {
2999 let label = "Foo";
3000 pump_tooltip_app(tester, m2, waft_painting::TextScaler::linear(1.0));
3001 expect(tester, &find::text(label), finds_one_widget());
3002 let at = text_center(tester, label);
3003 tester.long_press_at(at, 1);
3004 expect(tester, &find::text(label), finds_n_widgets(2));
3005 assert_eq!(last_text_size(tester, label), Size::new(42.0, 14.0));
3006 tester.pump_and_settle_by(Duration::from_secs(2));
3007
3008 pump_tooltip_app(tester, m2, waft_painting::TextScaler::linear(4.0));
3009 expect(tester, &find::text(label), finds_one_widget());
3010 let at = text_center(tester, label);
3011 tester.long_press_at(at, 2);
3012 assert_eq!(last_text_size(tester, label), Size::new(168.0, 56.0));
3013 });
3014 }
3015
3016 #[test]
3017 fn material3_bottom_navigation_bar_shows_tool_tips_with_text_scaling_on_long_press_when_labels_are_provided()
3018 {
3019 test_widgets(|tester| {
3020 let label = "Foo";
3021 pump_tooltip_app(tester, m3, waft_painting::TextScaler::NO_SCALING);
3022 expect(tester, &find::text(label), finds_one_widget());
3023 let at = text_center(tester, label);
3024 tester.long_press_at(at, 1);
3025 expect(tester, &find::text(label), finds_n_widgets(2));
3026 assert_eq!(last_text_size(tester, label).height(), 20.0);
3027 tester.pump_and_settle_by(Duration::from_secs(2));
3028
3029 pump_tooltip_app(tester, m3, waft_painting::TextScaler::linear(4.0));
3030 expect(tester, &find::text(label), finds_one_widget());
3031 let at = text_center(tester, label);
3032 tester.long_press_at(at, 2);
3033 assert_eq!(last_text_size(tester, label).height(), 80.0);
3034 });
3035 }
3036
3037 fn tooltips_with(tester: &WidgetTester, message: &str) -> usize {
3039 find::by_type::<Tooltip>()
3040 .evaluate(tester)
3041 .into_iter()
3042 .filter(|tooltip| {
3043 tester.widget(*tooltip, |tooltip: &Tooltip| {
3044 tooltip.message.as_deref() == Some(message)
3045 })
3046 })
3047 .count()
3048 }
3049
3050 #[test]
3051 fn different_behaviour_of_tool_tip_in_bottom_navigation_bar_item() {
3052 test_widgets(|tester| {
3053 pump_bar(tester, m3, || {
3054 BottomNavigationBar::new(vec![
3055 item(Icons::ac_unit(), "A").tooltip("A tooltip"),
3056 item(Icons::battery_alert(), "B"),
3057 item(Icons::cake(), "C").tooltip(""),
3058 ])
3059 });
3060
3061 expect(tester, &find::text("A"), finds_one_widget());
3062 let at = text_center(tester, "A");
3063 tester.long_press_at(at, 1);
3064 assert_eq!(tooltips_with(tester, "A tooltip"), 1);
3065
3066 expect(tester, &find::text("B"), finds_one_widget());
3067 let at = text_center(tester, "B");
3068 tester.long_press_at(at, 2);
3069 assert_eq!(tooltips_with(tester, "B"), 0);
3070
3071 expect(tester, &find::text("C"), finds_one_widget());
3072 let at = text_center(tester, "C");
3073 tester.long_press_at(at, 3);
3074 assert_eq!(tooltips_with(tester, "C"), 0);
3075 });
3076 }
3077
3078 #[test]
3079 fn bottom_navigation_bar_limits_width_of_tiles_with_long_labels() {
3080 test_widgets(|tester| {
3081 let long_text = |letter: &str| format!("[{}]", vec![letter; 100].join(", "));
3082 let (long_text_a, long_text_b) = (long_text("A"), long_text("B"));
3083 let (a, b) = (long_text_a.clone(), long_text_b.clone());
3084 pump_bar(tester, m3, move || {
3085 BottomNavigationBar::new(vec![
3086 item(Icons::ac_unit(), &a),
3087 item(Icons::battery_alert(), &b),
3088 ])
3089 });
3090
3091 assert!(bar_size(tester).height() >= K_BOTTOM_NAVIGATION_BAR_HEIGHT);
3092
3093 let item_box_a = tester.render_box_of(first_text(tester, &long_text_a));
3094 assert_eq!(item_box_a.size(&tester.cell.borrow()).width(), 400.0);
3095 let item_box_b = tester.render_box_of(first_text(tester, &long_text_b));
3096 assert_eq!(item_box_b.size(&tester.cell.borrow()).width(), 400.0);
3097 });
3098 }
3099
3100 fn favorite_bar(
3101 selected_item: usize,
3102 filled: &KeyRef,
3103 stroked: &KeyRef,
3104 ) -> BottomNavigationBar {
3105 BottomNavigationBar::new(vec![
3106 BottomNavigationBarItem::new(
3107 Icon::new(Some(Icons::favorite_border())).key(stroked.clone()),
3108 )
3109 .active_icon(Icon::new(Some(Icons::favorite())).key(filled.clone()))
3110 .label("Favorite"),
3111 item(Icons::access_alarm(), "Alarm"),
3112 ])
3113 .current_index(selected_item)
3114 }
3115
3116 #[test]
3117 fn bottom_navigation_bar_inactive_icon_shown() {
3118 test_widgets(|tester| {
3119 let filled: KeyRef = waft_foundation::ValueKey::new("filled".to_owned()).into();
3120 let stroked: KeyRef = waft_foundation::ValueKey::new("stroked".to_owned()).into();
3121 let (f, s) = (filled.clone(), stroked.clone());
3122 pump_bar(tester, m3, move || favorite_bar(0, &f, &s));
3123
3124 expect(tester, &find::by_key(filled.clone()), finds_one_widget());
3125 expect(tester, &find::by_key(stroked.clone()), finds_nothing());
3126
3127 let (f, s) = (filled.clone(), stroked.clone());
3128 pump_bar(tester, m3, move || favorite_bar(1, &f, &s));
3129
3130 expect(tester, &find::by_key(filled.clone()), finds_nothing());
3131 expect(tester, &find::by_key(stroked.clone()), finds_one_widget());
3132 });
3133 }
3134
3135 #[test]
3136 fn bottom_navigation_bar_handles_items_length_changes() {
3137 test_widgets(|tester| {
3138 let build_frame = |tester: &mut WidgetTester, item_count: usize| {
3140 pump_bar(tester, m3, move || {
3141 BottomNavigationBar::new(
3142 (0..item_count)
3143 .map(|item_index| item(Icons::android(), &format!("item {item_index}")))
3144 .collect(),
3145 )
3146 .r#type(BottomNavigationBarType::Fixed)
3147 });
3148 };
3149 let found = |tester: &WidgetTester, text: &str| find::text(text).evaluate(tester).len();
3150
3151 build_frame(tester, 3);
3152 assert_eq!(found(tester, "item 0"), 1);
3153 assert_eq!(found(tester, "item 1"), 1);
3154 assert_eq!(found(tester, "item 2"), 1);
3155 assert_eq!(found(tester, "item 3"), 0);
3156
3157 build_frame(tester, 4);
3158 assert_eq!(found(tester, "item 0"), 1);
3159 assert_eq!(found(tester, "item 1"), 1);
3160 assert_eq!(found(tester, "item 2"), 1);
3161 assert_eq!(found(tester, "item 3"), 1);
3162
3163 build_frame(tester, 2);
3164 assert_eq!(found(tester, "item 0"), 1);
3165 assert_eq!(found(tester, "item 1"), 1);
3166 assert_eq!(found(tester, "item 2"), 0);
3167 assert_eq!(found(tester, "item 3"), 0);
3168 });
3169 }
3170
3171 #[test]
3172 fn bottom_navigation_bar_change_background_color_test() {
3173 test_widgets(|tester| {
3174 let red = Colors::RED.primary();
3176 let green = Colors::GREEN.primary();
3177 let background_color = Rc::new(Cell::new(red));
3178 let shared = Rc::clone(&background_color);
3179 pump_app(tester, m3, move |_app| {
3180 waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
3181 let background_color = shared.get();
3182 let pressed = Rc::clone(&shared);
3183 Scaffold::new()
3184 .body(waft_widgets::Center::new().child(
3185 crate::elevated_button::ElevatedButton::new(
3186 Some(Listener::new(move |app| {
3187 let pressed = Rc::clone(&pressed);
3188 set_state(app, &mut |_app| pressed.set(green));
3189 })),
3190 Some(Text::new("green")),
3191 ),
3192 ))
3193 .bottom_navigation_bar(
3194 BottomNavigationBar::new(vec![
3195 item(Icons::dashboard(), "Page 1")
3196 .background_color(background_color),
3197 item(Icons::menu(), "Page 2").background_color(background_color),
3198 ])
3199 .r#type(BottomNavigationBarType::Shifting),
3200 )
3201 .into_widget()
3202 })
3203 .into_widget()
3204 });
3205
3206 let background_material_color = |tester: &WidgetTester| {
3207 let bar = find::by_type::<BottomNavigationBar>().evaluate(tester)[0];
3208 tester
3209 .descendants_of_type::<Material>(bar)
3210 .into_iter()
3211 .find_map(|material| {
3212 tester.widget(material, |material: &Material| {
3213 (material.r#type == MaterialType::Canvas).then_some(material.color)
3214 })
3215 })
3216 .expect("a canvas material")
3217 };
3218
3219 assert_eq!(background_color.get(), red);
3220 assert_eq!(background_material_color(tester), Some(red));
3221 let at = text_center(tester, "green");
3222 tester.tap_at(at, 1);
3223 tester.pump_and_settle();
3224 assert_eq!(background_color.get(), green);
3225 assert_eq!(background_material_color(tester), Some(green));
3226 });
3227 }
3228
3229 #[test]
3230 #[should_panic(expected = "Every item must have a non-null label")]
3231 fn bottom_navigation_bar_item_label_should_not_be_nullable() {
3232 BottomNavigationBar::new(vec![
3233 item(Icons::ac_unit(), "AC"),
3234 BottomNavigationBarItem::new(Icon::new(Some(Icons::access_alarm()))),
3235 ])
3236 .r#type(BottomNavigationBarType::Shifting)
3237 .into_widget();
3238 }
3239
3240 fn no_labels_render_no_text(tester: &mut WidgetTester, r#type: BottomNavigationBarType) {
3241 pump_bar(tester, m3, move || {
3242 BottomNavigationBar::new(vec![
3243 item(Icons::dashboard(), "Red").background_color(Colors::RED.primary()),
3244 item(Icons::menu(), "Green").background_color(Colors::GREEN.primary()),
3245 ])
3246 .show_selected_labels(false)
3247 .show_unselected_labels(false)
3248 .r#type(r#type)
3249 });
3250 expect(tester, &find::text("Red"), finds_one_widget());
3251 expect(tester, &find::text("Green"), finds_one_widget());
3252 let visibilities = find::by_type::<Visibility>().evaluate(tester);
3253 let visible = |element: AnyElement| {
3254 tester.widget(element, |visibility: &Visibility| visibility.visible)
3255 };
3256 assert!(!visible(*visibilities.first().expect("a Visibility")));
3257 assert!(!visible(*visibilities.last().expect("a Visibility")));
3258 }
3259
3260 #[test]
3261 fn bottom_navigation_bar_show_no_labels_for_shifting_navbar_renders_no_text() {
3262 test_widgets(|tester| no_labels_render_no_text(tester, BottomNavigationBarType::Shifting));
3263 }
3264
3265 #[test]
3266 fn bottom_navigation_bar_show_no_labels_for_fixed_navbar_renders_no_text() {
3267 test_widgets(|tester| no_labels_render_no_text(tester, BottomNavigationBarType::Fixed));
3268 }
3269
3270 #[test]
3271 fn bottom_navigation_bar_changes_mouse_cursor_when_the_tile_is_hovered_over() {
3272 test_widgets(|tester| {
3273 let text: MouseCursorRef = waft_services::SystemMouseCursors::TEXT.into();
3274 let click: MouseCursorRef = waft_services::SystemMouseCursors::CLICK.into();
3275 let pump = |tester: &mut WidgetTester, mouse_cursor: Option<MouseCursorRef>| {
3277 pump_app(tester, m3, move |_app| {
3278 let mut bar = BottomNavigationBar::new(ac_alarm());
3279 if let Some(mouse_cursor) = mouse_cursor {
3280 bar = bar.mouse_cursor(mouse_cursor);
3281 }
3282 Scaffold::new()
3283 .bottom_navigation_bar(
3284 waft_widgets::MouseRegion::new()
3285 .cursor(waft_services::SystemMouseCursors::FORBIDDEN.into())
3286 .child(bar),
3287 )
3288 .into_widget()
3289 });
3290 };
3291 pump(tester, Some(text.clone()));
3292
3293 let mut gesture = TestPointer::mouse(1, 0);
3294 let at = text_center(tester, "AC");
3295 tester.add_pointer(&mut gesture, at);
3296
3297 tester.pump_and_settle();
3298
3299 assert!(*tester.active_cursor(1) == *text);
3300
3301 pump(tester, None);
3303
3304 assert!(*tester.active_cursor(1) == *click);
3305 });
3306 }
3307
3308 fn titled_bar(
3311 icon_size: Size,
3312 icon0: &KeyRef,
3313 icon1: &KeyRef,
3314 landscape_layout: Option<BottomNavigationBarLandscapeLayout>,
3315 ) -> BottomNavigationBar {
3316 let icon = |key: &KeyRef| {
3317 SizedBox::new()
3318 .key(key.clone())
3319 .width(icon_size.width())
3320 .height(icon_size.height())
3321 };
3322 let mut bar = BottomNavigationBar::new(vec![
3323 BottomNavigationBarItem::new(icon(icon0)).label("Title0"),
3324 BottomNavigationBarItem::new(icon(icon1)).label("Title1"),
3325 ]);
3326 if let Some(landscape_layout) = landscape_layout {
3327 bar = bar.landscape_layout(landscape_layout);
3328 }
3329 bar
3330 }
3331
3332 fn unique_key() -> KeyRef {
3333 waft_foundation::UniqueKey::new().into()
3334 }
3335
3336 fn rect_of_key(tester: &WidgetTester, key: &KeyRef) -> Rect {
3337 let element = tester.element(find::by_key(key.clone()));
3338 tester.get_rect(tester.render_box_of(element))
3339 }
3340
3341 fn text_size(tester: &WidgetTester, text: &str) -> Size {
3344 tester
3345 .render_box_of(first_text(tester, text))
3346 .size(&tester.cell.borrow())
3347 }
3348
3349 fn rect_of_text(tester: &WidgetTester, text: &str) -> Rect {
3350 tester.get_rect(tester.render_box_of(first_text(tester, text)))
3351 }
3352
3353 fn pump_titled_bar(
3354 tester: &mut WidgetTester,
3355 theme: fn(&App) -> ThemeData,
3356 icon_size: Size,
3357 landscape_layout: Option<BottomNavigationBarLandscapeLayout>,
3358 ) -> (KeyRef, KeyRef) {
3359 let (icon0, icon1) = (unique_key(), unique_key());
3360 let (key0, key1) = (icon0.clone(), icon1.clone());
3361 pump_bar(tester, theme, move || {
3362 titled_bar(icon_size, &key0, &key1, landscape_layout)
3363 });
3364 assert_eq!(
3365 bar_size(tester),
3366 Size::new(800.0, K_BOTTOM_NAVIGATION_BAR_HEIGHT)
3367 );
3368 assert_eq!(
3369 tester.get_rect(bar_box(tester)),
3370 Rect::from_ltrb(0.0, 600.0 - K_BOTTOM_NAVIGATION_BAR_HEIGHT, 800.0, 600.0)
3371 );
3372 (icon0, icon1)
3373 }
3374
3375 fn m3_tile_extents(content_height: impl Fn(f64) -> f64) -> (f64, f64, f64) {
3378 let navigation_bar_top = 600.0 - K_BOTTOM_NAVIGATION_BAR_HEIGHT; let selected_font_size: f64 = 14.0;
3380 let m3_line_height = 1.43;
3381 let label_height = (selected_font_size * m3_line_height).floor(); let navigation_tile_vertical_padding = selected_font_size / 2.0; let navigation_tile_height =
3384 content_height(label_height) + 2.0 * navigation_tile_vertical_padding;
3385
3386 let navigation_tile_vertical_offset =
3388 (K_BOTTOM_NAVIGATION_BAR_HEIGHT - navigation_tile_height) / 2.0;
3389
3390 let icon_top =
3391 navigation_bar_top + navigation_tile_vertical_offset + navigation_tile_vertical_padding;
3392 let label_bottom =
3393 600.0 - (navigation_tile_vertical_offset + navigation_tile_vertical_padding);
3394 (icon_top, label_bottom, label_height)
3395 }
3396
3397 #[test]
3398 fn material2_bottom_navigation_bar_default_layout() {
3399 test_widgets(|tester| {
3400 let (icon0, icon1) = pump_titled_bar(tester, m2, Size::new(200.0, 10.0), None);
3401
3402 assert_eq!(rect_of_key(tester, &icon0).top, 560.0);
3408 assert_eq!(rect_of_text(tester, "Title0").bottom, 584.0);
3409
3410 assert_eq!(
3416 rect_of_text(tester, "Title0"),
3417 Rect::from_ltrb(158.0, 570.0, 242.0, 584.0)
3418 );
3419 assert_eq!(
3420 rect_of_key(tester, &icon0),
3421 Rect::from_ltrb(100.0, 560.0, 300.0, 570.0)
3422 );
3423 assert_eq!(
3424 rect_of_key(tester, &icon1),
3425 Rect::from_ltrb(500.0, 560.0, 700.0, 570.0)
3426 );
3427 });
3428 }
3429
3430 #[test]
3431 fn material3_bottom_navigation_bar_default_layout() {
3432 test_widgets(|tester| {
3433 let icon_height = 10.0;
3434 let (icon0, icon1) = pump_titled_bar(tester, m3, Size::new(200.0, icon_height), None);
3435
3436 let (icon_top, label_bottom, label_height) =
3437 m3_tile_extents(|label_height| icon_height + label_height);
3438
3439 assert_eq!(rect_of_key(tester, &icon0).top, icon_top);
3440 assert_eq!(rect_of_text(tester, "Title0").bottom, label_bottom);
3441
3442 let first_label_width = text_size(tester, "Title0").width();
3448 let items_width = 800.0 / 2.0; let first_label_center = items_width / 2.0;
3450 assert_eq!(
3451 rect_of_text(tester, "Title0"),
3452 Rect::from_ltrb(
3453 first_label_center - first_label_width / 2.0,
3454 label_bottom - label_height,
3455 first_label_center + first_label_width / 2.0,
3456 label_bottom,
3457 )
3458 );
3459 assert_eq!(
3460 rect_of_key(tester, &icon0),
3461 Rect::from_ltrb(100.0, icon_top, 300.0, icon_top + icon_height)
3462 );
3463 assert_eq!(
3464 rect_of_key(tester, &icon1),
3465 Rect::from_ltrb(500.0, icon_top, 700.0, icon_top + icon_height)
3466 );
3467 });
3468 }
3469
3470 #[test]
3471 fn material2_bottom_navigation_bar_centered_landscape_layout() {
3472 test_widgets(|tester| {
3473 let (icon0, icon1) = pump_titled_bar(
3474 tester,
3475 m2,
3476 Size::new(200.0, 10.0),
3477 Some(BottomNavigationBarLandscapeLayout::Centered),
3478 );
3479
3480 assert_eq!(
3490 rect_of_text(tester, "Title0"),
3491 Rect::from_ltrb(208.0, 570.0, 292.0, 584.0)
3492 );
3493 assert_eq!(
3494 rect_of_key(tester, &icon0),
3495 Rect::from_ltrb(150.0, 560.0, 350.0, 570.0)
3496 );
3497 assert_eq!(
3498 rect_of_key(tester, &icon1),
3499 Rect::from_ltrb(450.0, 560.0, 650.0, 570.0)
3500 );
3501 });
3502 }
3503
3504 #[test]
3505 fn material3_bottom_navigation_bar_centered_landscape_layout() {
3506 test_widgets(|tester| {
3507 let (icon_width, icon_height) = (200.0, 10.0);
3508 let (icon0, icon1) = pump_titled_bar(
3509 tester,
3510 m3,
3511 Size::new(icon_width, icon_height),
3512 Some(BottomNavigationBarLandscapeLayout::Centered),
3513 );
3514
3515 let (icon_top, label_bottom, label_height) =
3516 m3_tile_extents(|label_height| icon_height + label_height);
3517
3518 let first_label_width = text_size(tester, "Title0").width();
3528 let item_width = icon_width; let first_item_left = 150.0;
3530 let first_label_center = first_item_left + item_width / 2.0; assert_eq!(
3533 rect_of_text(tester, "Title0"),
3534 Rect::from_ltrb(
3535 first_label_center - first_label_width / 2.0,
3536 label_bottom - label_height,
3537 first_label_center + first_label_width / 2.0,
3538 label_bottom,
3539 )
3540 );
3541 assert_eq!(
3542 rect_of_key(tester, &icon0),
3543 Rect::from_ltrb(150.0, icon_top, 350.0, icon_top + icon_height)
3544 );
3545 assert_eq!(
3546 rect_of_key(tester, &icon1),
3547 Rect::from_ltrb(450.0, icon_top, 650.0, icon_top + icon_height)
3548 );
3549 });
3550 }
3551
3552 #[test]
3553 fn material2_bottom_navigation_bar_linear_landscape_layout() {
3554 test_widgets(|tester| {
3555 let (icon0, icon1) = pump_titled_bar(
3556 tester,
3557 m2,
3558 Size::new(100.0, 20.0),
3559 Some(BottomNavigationBarLandscapeLayout::Linear),
3560 );
3561
3562 assert_eq!(
3567 rect_of_text(tester, "Title0"),
3568 Rect::from_ltrb(212.0, 565.0, 296.0, 579.0)
3569 );
3570 assert_eq!(
3571 rect_of_key(tester, &icon0),
3572 Rect::from_ltrb(104.0, 562.0, 204.0, 582.0)
3573 );
3574 assert_eq!(
3575 rect_of_key(tester, &icon1),
3576 Rect::from_ltrb(504.0, 562.0, 604.0, 582.0)
3577 );
3578 });
3579 }
3580
3581 #[test]
3582 fn material3_bottom_navigation_bar_linear_landscape_layout() {
3583 test_widgets(|tester| {
3584 let (icon_width, icon_height) = (100.0, 20.0);
3585 let (icon0, icon1) = pump_titled_bar(
3586 tester,
3587 m3,
3588 Size::new(icon_width, icon_height),
3589 Some(BottomNavigationBarLandscapeLayout::Linear),
3590 );
3591
3592 let (icon_top, label_bottom, label_height) =
3594 m3_tile_extents(|label_height: f64| icon_height.max(label_height));
3595
3596 let item_full_with = 800.0 / 2.0; let separator_width = 8.0;
3602 let first_label_width = text_size(tester, "Title0").width();
3603 let first_item_content_width = icon_width + separator_width + first_label_width;
3604 let first_item_left = item_full_with / 2.0 - first_item_content_width / 2.0;
3605 let second_label_width = text_size(tester, "Title1").width();
3606 let second_item_content_width = icon_width + separator_width + second_label_width;
3607 let second_item_left =
3608 item_full_with + item_full_with / 2.0 - second_item_content_width / 2.0;
3609
3610 assert_eq!(
3611 rect_of_text(tester, "Title0"),
3612 Rect::from_ltrb(
3613 first_item_left + icon_width + separator_width,
3614 label_bottom - label_height,
3615 first_item_left + icon_width + separator_width + first_label_width,
3616 label_bottom,
3617 )
3618 );
3619 assert_eq!(
3620 rect_of_key(tester, &icon0),
3621 Rect::from_ltrb(
3622 first_item_left,
3623 icon_top,
3624 first_item_left + icon_width,
3625 icon_top + icon_height
3626 )
3627 );
3628 assert_eq!(
3629 rect_of_key(tester, &icon1),
3630 Rect::from_ltrb(
3631 second_item_left,
3632 icon_top,
3633 second_item_left + icon_width,
3634 icon_top + icon_height
3635 )
3636 );
3637 });
3638 }
3639
3640 #[test]
3641 fn bottom_navigation_bar_keys_passed_through() {
3642 test_widgets(|tester| {
3643 let key1: KeyRef = waft_foundation::ValueKey::new("key1".to_owned()).into();
3644 let key2: KeyRef = waft_foundation::ValueKey::new("key2".to_owned()).into();
3645 let (k1, k2) = (key1.clone(), key2.clone());
3646 pump_bar(tester, m3, move || {
3647 BottomNavigationBar::new(vec![
3648 item(Icons::favorite_border(), "Favorite").key(k1),
3649 item(Icons::access_alarm(), "Alarm").key(k2),
3650 ])
3651 });
3652
3653 expect(tester, &find::by_key(key1.clone()), finds_one_widget());
3654 expect(tester, &find::by_key(key2.clone()), finds_one_widget());
3655 });
3656 }
3657
3658 #[test]
3659 fn bottom_navigation_bar_and_bottom_navigation_bar_item_render_at_zero_size() {
3660 test_widgets(|tester| {
3661 pump_app(tester, m3, |_app| {
3662 waft_widgets::Center::new()
3663 .child(
3664 SizedBox::shrink().child(Scaffold::new().bottom_navigation_bar(
3665 BottomNavigationBar::new(vec![
3666 item(Icons::favorite_border(), "X"),
3667 item(Icons::access_alarm(), "Y"),
3668 ]),
3669 )),
3670 )
3671 .into_widget()
3672 });
3673 assert!(rect_of_text(tester, "X").size().is_empty());
3674 });
3675 }
3676
3677 fn shifting_background_color_with_transition(
3681 tester: &mut WidgetTester,
3682 theme: fn(&App) -> ThemeData,
3683 ) {
3684 let red = Colors::RED.primary();
3685 let green = Colors::GREEN.primary();
3686 pump_app(tester, theme, move |_app| {
3687 let current_index = Rc::new(Cell::new(0));
3688 waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
3689 let tapped = Rc::clone(¤t_index);
3690 Scaffold::new()
3691 .bottom_navigation_bar(
3692 waft_widgets::RepaintBoundary::new().child(
3693 BottomNavigationBar::new(vec![
3694 item(Icons::dashboard(), "Red").background_color(red),
3695 item(Icons::menu(), "Green").background_color(green),
3696 ])
3697 .r#type(BottomNavigationBarType::Shifting)
3698 .current_index(current_index.get())
3699 .on_tap(move |app, index| {
3700 let tapped = Rc::clone(&tapped);
3701 set_state(app, &mut |_app| tapped.set(index));
3702 }),
3703 ),
3704 )
3705 .into_widget()
3706 })
3707 .into_widget()
3708 });
3709 let at = text_center(tester, "Green");
3710 tester.tap_at(at, 1);
3711
3712 for _ in 0..3 {
3713 tester.pump_by(Duration::from_millis(30));
3714 assert_eq!(material_of(tester, |material| material.color), Some(red));
3715 }
3716 tester.pump_and_settle();
3717 assert_eq!(material_of(tester, |material| material.color), Some(green));
3718 }
3719
3720 #[test]
3721 fn material2_bottom_navigation_bar_shifting_background_color_with_transition() {
3722 test_widgets(|tester| shifting_background_color_with_transition(tester, m2));
3723 }
3724
3725 #[test]
3726 fn material3_bottom_navigation_bar_shifting_background_color_with_transition() {
3727 test_widgets(|tester| shifting_background_color_with_transition(tester, m3));
3728 }
3729}