1use std::any::Any;
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10use std::time::Duration;
11
12use waft_animation::{Cubic, Curve, Curves, Interval};
13use waft_embedder::{
14 Clip, Color, Offset, Size, SystemUiOverlayStyle, TargetPlatform, TextBaseline, TextDirection,
15 clamp_double,
16};
17use waft_foundation::{App, AsyncCallback, DiagnosticPropertiesBuilder, Handle, Ref};
18use waft_painting::{
19 Alignment, AlignmentDirectional, AlignmentGeometry, AnyColor, EdgeInsets, EdgeInsetsGeometry,
20 ShapeBorderRef, TextOverflow, TextStyle,
21};
22use waft_rendering::{
23 AnyRenderBox, AnyRenderObject, BaselineOffset, BoxConstraints, BoxHitTestResult, BoxParentData,
24 FloatingHeaderSnapConfiguration, OrdinalSortKey, OverScrollHeaderStretchConfiguration,
25 PaintingContext, PersistentHeaderShowOnScreenConfiguration, RenderAligningShiftedBox,
26 RenderAligningShiftedBoxData, RenderBox, RenderBoxData, RenderHandle, RenderObject,
27 RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderShiftedBox,
28 SingleChildLayoutDelegate, TickerProviderRef,
29};
30use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
31use waft_widgets::{
32 Align, AnimatedOpacity, AnnotatedRegion, AnyModalRoute, AnySize, AxisDirection, BuildContext,
33 Center, ClipRect, Column, ConstrainedBox, CrossAxisAlignment, CustomSingleChildLayout,
34 DefaultTextStyle, Directionality, Flexible, IconTheme, IconThemeData, IntoWidget, KeyRef,
35 MainAxisAlignment, MainAxisSize, MediaQuery, NavigationToolbar, Opacity, Padding,
36 PreferredSizeWidget, PreferredSizeWidgetRef, RenderObjectWidget, Row, SafeArea,
37 ScrollNotification, ScrollNotificationCallback, ScrollNotificationObserver,
38 ScrollNotificationObserverState, ScrollNotificationPredicate, ScrollUpdateNotification,
39 Semantics, SingleChildRenderObjectWidget, SizeExtension, SliverPersistentHeader,
40 SliverPersistentHeaderDelegate, Stack, StackFit, State, StateData, StatefulWidget,
41 StatelessWidget, TickerProviderStateMixin, TickerProviderStateMixinData, WidgetRef,
42 WidgetState, WidgetStateProperty, WidgetStates, default_scroll_notification_predicate,
43 downcast_widget,
44};
45
46use crate::action_buttons::{BackButton, CloseButton, DrawerButton, EndDrawerButton};
47use crate::app_bar_theme::{AppBarTheme, AppBarThemeData, AppBarThemeDataGetters};
48use crate::button_style::ButtonStyle;
49use crate::constants::K_TOOLBAR_HEIGHT;
50use crate::debug::debug_check_has_material_localizations;
51use crate::flexible_space_bar::{FlexibleSpaceBar, FlexibleSpaceBarSettings};
52use crate::generated::app_bar_defaults_m3::{
53 AppBarDefaultsM3, LargeScrollUnderFlexibleConfig, MediumScrollUnderFlexibleConfig,
54};
55use crate::icon_button::IconButton;
56use crate::icon_button_theme::{IconButtonTheme, IconButtonThemeData};
57use crate::material::{Material, MaterialType};
58use crate::scaffold::Scaffold;
59use crate::theme::Theme;
60use crate::theme_data::ThemeData;
61use crate::theme_data_getters::DefaultsContext;
62
63type FlexibleConfigBuilder = fn(&mut App, BuildContext) -> Box<dyn ScrollUnderFlexibleConfig>;
65
66const K_LEADING_WIDTH: f64 = K_TOOLBAR_HEIGHT; const K_MAX_TITLE_TEXT_SCALE_FACTOR: f64 = 1.34; #[derive(Clone, Copy, Debug, PartialEq, Eq)]
71enum SliverAppVariant {
72 Small,
73 Medium,
74 Large,
75}
76
77#[derive(Debug)]
80struct ToolbarContainerLayout {
81 toolbar_height: f64,
82}
83
84impl SingleChildLayoutDelegate for ToolbarContainerLayout {
85 fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
86 constraints.tighten(None, Some(self.toolbar_height))
87 }
88
89 fn get_size(&self, constraints: BoxConstraints) -> Size {
90 Size::new(constraints.max_width, self.toolbar_height)
91 }
92
93 fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
94 Offset::new(0.0, size.height() - child_size.height())
95 }
96
97 fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
98 old_delegate
99 .as_any()
100 .downcast_ref::<ToolbarContainerLayout>()
101 .is_none_or(|old_delegate| self.toolbar_height != old_delegate.toolbar_height)
102 }
103
104 fn as_any(&self) -> &dyn Any {
105 self
106 }
107}
108
109#[derive(Debug)]
112struct PreferredAppBarSize {
113 toolbar_height: Option<f64>,
114 bottom_height: Option<f64>,
115}
116
117impl PreferredAppBarSize {
118 fn new(toolbar_height: Option<f64>, bottom_height: Option<f64>) -> PreferredAppBarSize {
119 PreferredAppBarSize {
120 toolbar_height,
121 bottom_height,
122 }
123 }
124
125 fn into_any(self) -> AnySize {
127 let size = Size::from_height(
128 self.toolbar_height.unwrap_or(K_TOOLBAR_HEIGHT) + self.bottom_height.unwrap_or(0.0),
129 );
130 AnySize::with_shared(size, Rc::new(self))
131 }
132}
133
134impl SizeExtension for PreferredAppBarSize {
135 fn as_any(&self) -> &dyn Any {
136 self
137 }
138}
139
140pub struct AppBar {
214 pub key: Option<KeyRef>,
215
216 pub leading: Option<WidgetRef>,
237
238 pub automatically_imply_leading: bool,
244
245 pub title: Option<WidgetRef>,
264
265 pub actions: Option<Vec<WidgetRef>>,
283
284 pub automatically_imply_actions: bool,
291
292 pub flexible_space: Option<WidgetRef>,
301
302 pub bottom: Option<PreferredSizeWidgetRef>,
311
312 pub elevation: Option<f64>,
337
338 pub scrolled_under_elevation: Option<f64>,
347
348 pub notification_predicate: ScrollNotificationPredicate,
354
355 pub shadow_color: Option<Color>,
360
361 pub surface_tint_color: Option<Color>,
366
367 pub shape: Option<ShapeBorderRef>,
377
378 pub background_color: Option<AnyColor>,
393
394 pub foreground_color: Option<Color>,
410
411 pub icon_theme: Option<IconThemeData>,
422
423 pub actions_icon_theme: Option<IconThemeData>,
438
439 pub primary: bool,
446
447 pub center_title: Option<bool>,
453
454 pub exclude_header_semantics: bool,
468
469 pub title_spacing: Option<f64>,
478
479 pub toolbar_opacity: f64,
487
488 pub bottom_opacity: f64,
496
497 pub toolbar_height: Option<f64>,
501
502 pub leading_width: Option<f64>,
506
507 pub toolbar_text_style: Option<TextStyle>,
522
523 pub title_text_style: Option<TextStyle>,
538
539 pub system_overlay_style: Option<SystemUiOverlayStyle>,
559
560 pub force_material_transparency: bool,
573
574 pub use_default_semantics_order: bool,
587
588 pub clip_behavior: Option<Clip>,
592
593 pub actions_padding: Option<EdgeInsetsGeometry>,
597
598 pub animate_color: bool,
600}
601
602impl AppBar {
603 pub fn new() -> AppBar {
609 AppBar {
610 key: None,
611 leading: None,
612 automatically_imply_leading: true,
613 title: None,
614 actions: None,
615 automatically_imply_actions: true,
616 flexible_space: None,
617 bottom: None,
618 elevation: None,
619 scrolled_under_elevation: None,
620 notification_predicate: Rc::new(default_scroll_notification_predicate),
621 shadow_color: None,
622 surface_tint_color: None,
623 shape: None,
624 background_color: None,
625 foreground_color: None,
626 icon_theme: None,
627 actions_icon_theme: None,
628 primary: true,
629 center_title: None,
630 exclude_header_semantics: false,
631 title_spacing: None,
632 toolbar_opacity: 1.0,
633 bottom_opacity: 1.0,
634 toolbar_height: None,
635 leading_width: None,
636 toolbar_text_style: None,
637 title_text_style: None,
638 system_overlay_style: None,
639 force_material_transparency: false,
640 use_default_semantics_order: true,
641 clip_behavior: None,
642 actions_padding: None,
643 animate_color: false,
644 }
645 }
646
647 pub fn key(mut self, key: KeyRef) -> AppBar {
649 self.key = Some(key);
650 self
651 }
652
653 #[cfg_attr(debug_assertions, track_caller)]
655 pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> AppBar {
656 self.leading = Some(leading.into_widget());
657 self
658 }
659
660 pub fn automatically_imply_leading(mut self, automatically_imply_leading: bool) -> AppBar {
662 self.automatically_imply_leading = automatically_imply_leading;
663 self
664 }
665
666 #[cfg_attr(debug_assertions, track_caller)]
668 pub fn title<K>(mut self, title: impl IntoWidget<K>) -> AppBar {
669 self.title = Some(title.into_widget());
670 self
671 }
672
673 pub fn actions(mut self, actions: Vec<WidgetRef>) -> AppBar {
675 self.actions = Some(actions);
676 self
677 }
678
679 pub fn automatically_imply_actions(mut self, automatically_imply_actions: bool) -> AppBar {
681 self.automatically_imply_actions = automatically_imply_actions;
682 self
683 }
684
685 #[cfg_attr(debug_assertions, track_caller)]
687 pub fn flexible_space<K>(mut self, flexible_space: impl IntoWidget<K>) -> AppBar {
688 self.flexible_space = Some(flexible_space.into_widget());
689 self
690 }
691
692 pub fn bottom(mut self, bottom: PreferredSizeWidgetRef) -> AppBar {
694 self.bottom = Some(bottom);
695 self
696 }
697
698 pub fn elevation(mut self, elevation: f64) -> AppBar {
700 debug_assert!(elevation >= 0.0);
701 self.elevation = Some(elevation);
702 self
703 }
704
705 pub fn scrolled_under_elevation(mut self, scrolled_under_elevation: f64) -> AppBar {
707 self.scrolled_under_elevation = Some(scrolled_under_elevation);
708 self
709 }
710
711 pub fn notification_predicate(
713 mut self,
714 notification_predicate: ScrollNotificationPredicate,
715 ) -> AppBar {
716 self.notification_predicate = notification_predicate;
717 self
718 }
719
720 pub fn shadow_color(mut self, shadow_color: Color) -> AppBar {
722 self.shadow_color = Some(shadow_color);
723 self
724 }
725
726 pub fn surface_tint_color(mut self, surface_tint_color: Color) -> AppBar {
728 self.surface_tint_color = Some(surface_tint_color);
729 self
730 }
731
732 pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> AppBar {
734 self.shape = Some(shape.into());
735 self
736 }
737
738 pub fn background_color(mut self, background_color: impl Into<AnyColor>) -> AppBar {
740 self.background_color = Some(background_color.into());
741 self
742 }
743
744 pub fn foreground_color(mut self, foreground_color: Color) -> AppBar {
746 self.foreground_color = Some(foreground_color);
747 self
748 }
749
750 pub fn icon_theme(mut self, icon_theme: IconThemeData) -> AppBar {
752 self.icon_theme = Some(icon_theme);
753 self
754 }
755
756 pub fn actions_icon_theme(mut self, actions_icon_theme: IconThemeData) -> AppBar {
758 self.actions_icon_theme = Some(actions_icon_theme);
759 self
760 }
761
762 pub fn primary(mut self, primary: bool) -> AppBar {
764 self.primary = primary;
765 self
766 }
767
768 pub fn center_title(mut self, center_title: bool) -> AppBar {
770 self.center_title = Some(center_title);
771 self
772 }
773
774 pub fn exclude_header_semantics(mut self, exclude_header_semantics: bool) -> AppBar {
776 self.exclude_header_semantics = exclude_header_semantics;
777 self
778 }
779
780 pub fn title_spacing(mut self, title_spacing: f64) -> AppBar {
782 self.title_spacing = Some(title_spacing);
783 self
784 }
785
786 pub fn toolbar_opacity(mut self, toolbar_opacity: f64) -> AppBar {
788 self.toolbar_opacity = toolbar_opacity;
789 self
790 }
791
792 pub fn bottom_opacity(mut self, bottom_opacity: f64) -> AppBar {
794 self.bottom_opacity = bottom_opacity;
795 self
796 }
797
798 pub fn toolbar_height(mut self, toolbar_height: f64) -> AppBar {
800 self.toolbar_height = Some(toolbar_height);
801 self
802 }
803
804 pub fn leading_width(mut self, leading_width: f64) -> AppBar {
806 self.leading_width = Some(leading_width);
807 self
808 }
809
810 pub fn toolbar_text_style(mut self, toolbar_text_style: TextStyle) -> AppBar {
812 self.toolbar_text_style = Some(toolbar_text_style);
813 self
814 }
815
816 pub fn title_text_style(mut self, title_text_style: TextStyle) -> AppBar {
818 self.title_text_style = Some(title_text_style);
819 self
820 }
821
822 pub fn system_overlay_style(mut self, system_overlay_style: SystemUiOverlayStyle) -> AppBar {
824 self.system_overlay_style = Some(system_overlay_style);
825 self
826 }
827
828 pub fn force_material_transparency(mut self, force_material_transparency: bool) -> AppBar {
830 self.force_material_transparency = force_material_transparency;
831 self
832 }
833
834 pub fn use_default_semantics_order(mut self, use_default_semantics_order: bool) -> AppBar {
836 self.use_default_semantics_order = use_default_semantics_order;
837 self
838 }
839
840 pub fn clip_behavior(mut self, clip_behavior: Clip) -> AppBar {
842 self.clip_behavior = Some(clip_behavior);
843 self
844 }
845
846 pub fn actions_padding(mut self, actions_padding: impl Into<EdgeInsetsGeometry>) -> AppBar {
848 let actions_padding = actions_padding.into();
849 self.actions_padding = Some(actions_padding);
850 self
851 }
852
853 pub fn animate_color(mut self, animate_color: bool) -> AppBar {
855 self.animate_color = animate_color;
856 self
857 }
858
859 pub fn preferred_height_for(
865 app: &mut App,
866 context: BuildContext,
867 preferred_size: &AnySize,
868 ) -> f64 {
869 if let Some(app_bar_size) = preferred_size.extension::<PreferredAppBarSize>()
870 && app_bar_size.toolbar_height.is_none()
871 {
872 return AppBarTheme::of(app, context)
873 .toolbar_height
874 .unwrap_or(K_TOOLBAR_HEIGHT)
875 + app_bar_size.bottom_height.unwrap_or(0.0);
876 }
877 preferred_size.height()
878 }
879
880 fn semantics_in_order(use_default_semantics_order: bool, order: f64) -> Semantics {
883 let semantics = Semantics::new().explicit_child_nodes(true);
884 if use_default_semantics_order {
885 return semantics.sort_key(Rc::new(OrdinalSortKey::new(order)));
886 }
887 semantics
888 }
889
890 fn get_effective_center_title(
891 &self,
892 theme: &ThemeData,
893 appbar_theme: &AppBarThemeData,
894 ) -> bool {
895 let platform_center = || match theme.platform {
896 TargetPlatform::IOS | TargetPlatform::MacOS => self
897 .actions
898 .as_ref()
899 .is_none_or(|actions| actions.len() < 2),
900 TargetPlatform::Android
901 | TargetPlatform::Fuchsia
902 | TargetPlatform::Linux
903 | TargetPlatform::Windows => false,
904 };
905
906 self.center_title
907 .or(appbar_theme.center_title)
908 .unwrap_or_else(platform_center)
909 }
910}
911
912impl Default for AppBar {
913 fn default() -> AppBar {
914 AppBar::new()
915 }
916}
917
918impl PreferredSizeWidget for AppBar {
919 fn preferred_size(&self) -> AnySize {
927 PreferredAppBarSize::new(
928 self.toolbar_height,
929 self.bottom
930 .as_ref()
931 .map(|bottom| bottom.preferred_size().height()),
932 )
933 .into_any()
934 }
935}
936
937impl Debug for AppBar {
938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 f.debug_struct("AppBar")
940 .field("key", &self.key)
941 .field("title", &self.title)
942 .field("toolbar_height", &self.toolbar_height)
943 .finish_non_exhaustive()
944 }
945}
946
947impl StatefulWidget for AppBar {
948 type State = AppBarState;
949
950 fn key(&self) -> Option<&KeyRef> {
951 self.key.as_ref()
952 }
953
954 fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
955 Some(self)
956 }
957
958 fn create_state(&self) -> AppBarState {
959 AppBarState {
960 state: StateData::new(),
961 scroll_notification_observer: None,
962 scrolled_under: false,
963 scroll_notification_listener: None,
964 }
965 }
966}
967
968pub struct AppBarState {
970 state: StateData<AppBar>,
971 scroll_notification_observer: Option<Handle<ScrollNotificationObserverState>>,
972 scrolled_under: bool,
973 scroll_notification_listener: Option<ScrollNotificationCallback>,
975}
976
977impl AppBarState {
978 fn scroll_notification_listener(
980 self: Handle<Self>,
981 app: &mut App,
982 ) -> ScrollNotificationCallback {
983 if let Some(listener) = app.get(self).scroll_notification_listener.clone() {
984 return listener;
985 }
986 let listener: ScrollNotificationCallback =
987 Rc::new(move |app, notification| self.handle_scroll_notification(app, notification));
988 app.get_mut(self).scroll_notification_listener = Some(Rc::clone(&listener));
989 listener
990 }
991
992 fn handle_scroll_notification(
993 self: Handle<Self>,
994 app: &mut App,
995 notification: &dyn ScrollNotification,
996 ) {
997 let Some(update) = notification
998 .as_any()
999 .downcast_ref::<ScrollUpdateNotification>()
1000 else {
1001 return;
1002 };
1003 if !(self.widget(app).notification_predicate)(notification) {
1004 return;
1005 }
1006 let old_scrolled_under = app.get(self).scrolled_under;
1007 let metrics = update.metrics();
1008 match metrics.axis_direction() {
1009 AxisDirection::Up => {
1010 app.get_mut(self).scrolled_under = metrics.extent_after() > 0.0;
1012 }
1013 AxisDirection::Down => {
1014 app.get_mut(self).scrolled_under = metrics.extent_before() > 0.0;
1015 }
1016 AxisDirection::Right | AxisDirection::Left => {
1017 }
1021 }
1022
1023 if app.get(self).scrolled_under != old_scrolled_under {
1024 self.set_state(app, |_| {
1025 });
1027 }
1028 }
1029
1030 fn resolve_color(
1031 states: &WidgetStates,
1032 widget_color: Option<&AnyColor>,
1033 theme_color: Option<Color>,
1034 default_color: Color,
1035 ) -> Color {
1036 <dyn WidgetStateProperty<Color>>::resolve_as(&widget_color.cloned(), states)
1037 .or_else(|| {
1038 <dyn WidgetStateProperty<Color>>::resolve_as(
1039 &theme_color.map(AnyColor::from),
1040 states,
1041 )
1042 })
1043 .unwrap_or_else(|| {
1044 <dyn WidgetStateProperty<Color>>::resolve_as(&AnyColor::from(default_color), states)
1045 })
1046 .color()
1047 }
1048
1049 fn system_overlay_style_for_brightness(
1050 brightness: waft_embedder::Brightness,
1051 background_color: Option<Color>,
1052 ) -> SystemUiOverlayStyle {
1053 let style = if brightness == waft_embedder::Brightness::Dark {
1054 SystemUiOverlayStyle::LIGHT
1055 } else {
1056 SystemUiOverlayStyle::DARK
1057 };
1058 SystemUiOverlayStyle {
1060 status_bar_color: background_color,
1061 status_bar_brightness: style.status_bar_brightness,
1062 status_bar_icon_brightness: style.status_bar_icon_brightness,
1063 system_status_bar_contrast_enforced: style.system_status_bar_contrast_enforced,
1064 ..SystemUiOverlayStyle::new()
1065 }
1066 }
1067}
1068
1069impl State for AppBarState {
1070 type Widget = AppBar;
1071 waft_widgets::state_accessors!();
1072
1073 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1074 let listener = self.scroll_notification_listener(app);
1075 if let Some(observer) = app.get(self).scroll_notification_observer {
1076 observer.remove_listener(app, &listener);
1077 }
1078 let context = self.context(app);
1079 let scaffold_state = Scaffold::maybe_of(app, context);
1080
1081 if let Some(scaffold_state) = scaffold_state
1082 && (scaffold_state.is_drawer_open(app) || scaffold_state.is_end_drawer_open(app))
1083 {
1084 return;
1085 }
1086 let observer = ScrollNotificationObserver::maybe_of(app, context);
1087 app.get_mut(self).scroll_notification_observer = observer;
1088 if let Some(observer) = observer {
1089 observer.add_listener(app, listener);
1090 }
1091 }
1092
1093 fn dispose(self: Handle<Self>, app: &mut App) {
1094 if let Some(observer) = app.get(self).scroll_notification_observer {
1095 let listener = self.scroll_notification_listener(app);
1096 observer.remove_listener(app, &listener);
1097 app.get_mut(self).scroll_notification_observer = None;
1098 }
1099 }
1100
1101 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1102 debug_assert!(
1103 !self.widget(app).primary || waft_widgets::debug_check_has_media_query(app, context)
1104 );
1105 debug_assert!(debug_check_has_material_localizations(app, context));
1106 let theme = Theme::of(app, context);
1107 let icon_button_theme = IconButtonTheme::of(app, context);
1108 let app_bar_theme = AppBarTheme::of(app, context);
1109 let defaults = app_bar_defaults(app, context);
1110 let scaffold = Scaffold::maybe_of(app, context);
1111 let parent_route = AnyModalRoute::of(app, context);
1112
1113 let settings_is_scrolled_under = context
1114 .depend_on_inherited_widget_of_exact_type::<FlexibleSpaceBarSettings>(app)
1115 .and_then(|settings| settings.is_scrolled_under);
1116 let mut states = WidgetStates::new();
1117 if settings_is_scrolled_under.unwrap_or(app.get(self).scrolled_under) {
1118 states.insert(WidgetState::ScrolledUnder);
1119 }
1120
1121 let has_drawer = scaffold.is_some_and(|scaffold| scaffold.has_drawer(app));
1122 let has_end_drawer = scaffold.is_some_and(|scaffold| scaffold.has_end_drawer(app));
1123 let use_close_button = parent_route.is_some_and(|route| route.fullscreen_dialog(app));
1124
1125 let widget_ref = context.widget(app).clone();
1126 let widget = waft_widgets::downcast_widget::<AppBar>(&*widget_ref)
1127 .expect("an AppBarState builds its AppBar");
1128 let toolbar_height = widget
1129 .toolbar_height
1130 .or(app_bar_theme.toolbar_height)
1131 .unwrap_or(K_TOOLBAR_HEIGHT);
1132
1133 let background_color = AppBarState::resolve_color(
1134 &states,
1135 widget.background_color.as_ref(),
1136 app_bar_theme.background_color,
1137 defaults
1138 .background_color(app)
1139 .expect("the defaults give a background color"),
1140 );
1141
1142 let scrolled_under_background = AppBarState::resolve_color(
1143 &states,
1144 widget.background_color.as_ref(),
1145 app_bar_theme.background_color,
1146 theme.color_scheme.surface_container(),
1147 );
1148
1149 let effective_background_color = if states.contains(&WidgetState::ScrolledUnder) {
1150 scrolled_under_background
1151 } else {
1152 background_color
1153 };
1154
1155 let foreground_color = widget
1156 .foreground_color
1157 .or(app_bar_theme.foreground_color)
1158 .or_else(|| defaults.foreground_color(app))
1159 .expect("the defaults give a foreground color");
1160
1161 let elevation = widget
1162 .elevation
1163 .or(app_bar_theme.elevation)
1164 .or_else(|| defaults.elevation(app))
1165 .expect("the defaults give an elevation");
1166
1167 let effective_elevation = if states.contains(&WidgetState::ScrolledUnder) {
1168 widget
1169 .scrolled_under_elevation
1170 .or(app_bar_theme.scrolled_under_elevation)
1171 .or_else(|| defaults.scrolled_under_elevation(app))
1172 .unwrap_or(elevation)
1173 } else {
1174 elevation
1175 };
1176
1177 let mut overall_icon_theme = widget
1178 .icon_theme
1179 .clone()
1180 .or_else(|| app_bar_theme.icon_theme.clone())
1181 .unwrap_or_else(|| {
1182 defaults
1183 .icon_theme(app)
1184 .as_ref()
1185 .expect("the defaults give an icon theme")
1186 .copy_with()
1187 .color(foreground_color)
1188 });
1189
1190 let action_foreground_color = widget.foreground_color.or(app_bar_theme.foreground_color);
1191 let mut actions_icon_theme = widget
1192 .actions_icon_theme
1193 .clone()
1194 .or_else(|| app_bar_theme.actions_icon_theme.clone())
1195 .or_else(|| widget.icon_theme.clone())
1196 .or_else(|| app_bar_theme.icon_theme.clone())
1197 .or_else(|| {
1198 defaults
1199 .actions_icon_theme(app)
1200 .as_ref()
1201 .map(|actions_icon_theme| match action_foreground_color {
1202 Some(color) => actions_icon_theme.copy_with().color(color),
1203 None => actions_icon_theme.copy_with(),
1204 })
1205 })
1206 .unwrap_or_else(|| overall_icon_theme.clone());
1207
1208 let actions_padding = widget
1209 .actions_padding
1210 .or(app_bar_theme.actions_padding)
1211 .or_else(|| defaults.actions_padding(app))
1212 .expect("the defaults give an actions padding");
1213
1214 let mut toolbar_text_style = widget
1215 .toolbar_text_style
1216 .clone()
1217 .or_else(|| app_bar_theme.toolbar_text_style.clone())
1218 .or_else(|| {
1219 defaults
1220 .toolbar_text_style(app)
1221 .as_ref()
1222 .map(|style| style.copy_with().color(foreground_color))
1223 });
1224
1225 let mut title_text_style = widget
1226 .title_text_style
1227 .clone()
1228 .or_else(|| app_bar_theme.title_text_style.clone())
1229 .or_else(|| {
1230 defaults
1231 .title_text_style(app)
1232 .as_ref()
1233 .map(|style| style.copy_with().color(foreground_color))
1234 });
1235
1236 #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1237 if widget.toolbar_opacity != 1.0 {
1238 let opacity = Interval::new(0.25, 1.0, Curves::fast_out_slow_in())
1239 .transform(widget.toolbar_opacity);
1240 if let Some(style) = &title_text_style
1241 && let Some(color) = &style.color
1242 {
1243 title_text_style = Some(style.copy_with().color(color.with_opacity(opacity)));
1244 }
1245 if let Some(style) = &toolbar_text_style
1246 && let Some(color) = &style.color
1247 {
1248 toolbar_text_style = Some(style.copy_with().color(color.with_opacity(opacity)));
1249 }
1250 overall_icon_theme = overall_icon_theme
1251 .copy_with()
1252 .opacity(opacity * overall_icon_theme.opacity.unwrap_or(1.0));
1253 actions_icon_theme = actions_icon_theme
1254 .copy_with()
1255 .opacity(opacity * actions_icon_theme.opacity.unwrap_or(1.0));
1256 }
1257
1258 let mut leading = widget.leading.clone();
1259 if leading.is_none() && widget.automatically_imply_leading {
1260 if has_drawer {
1261 leading = Some(
1262 DrawerButton::new()
1263 .style(
1264 IconButton::style_from()
1265 .icon_size(overall_icon_theme.size.unwrap_or(24.0))
1266 .build(),
1267 )
1268 .into_widget(),
1269 );
1270 } else if parent_route.is_some_and(|route| route.implies_app_bar_dismissal(app)) {
1271 leading = Some(if use_close_button {
1272 CloseButton::new().into_widget()
1273 } else {
1274 BackButton::new().into_widget()
1275 });
1276 }
1277 }
1278 let leading_width = widget
1279 .leading_width
1280 .or(app_bar_theme.leading_width)
1281 .unwrap_or(K_LEADING_WIDTH);
1282 let leading = leading.map(|mut leading| {
1283 if theme.use_material3 {
1284 let effective_icon_button_theme =
1290 if Some(&overall_icon_theme) == defaults.icon_theme(app).as_ref() {
1291 icon_button_theme.clone()
1292 } else {
1293 icon_button_theme_for(&icon_button_theme, &overall_icon_theme)
1296 };
1297
1298 leading = IconButtonTheme::new(
1299 effective_icon_button_theme,
1300 if is_icon_button(&leading) {
1301 Center::new().child(leading).into_widget()
1302 } else {
1303 leading
1304 },
1305 )
1306 .into_widget();
1307
1308 ConstrainedBox::new(BoxConstraints::tight_for(Some(leading_width), None))
1312 .child(leading)
1313 .into_widget()
1314 } else {
1315 ConstrainedBox::new(BoxConstraints::tight_for(Some(leading_width), None))
1316 .child(leading)
1317 .into_widget()
1318 }
1319 });
1320
1321 let names_route = match app.platform().target_platform() {
1322 TargetPlatform::Android
1323 | TargetPlatform::Fuchsia
1324 | TargetPlatform::Linux
1325 | TargetPlatform::Windows => Some(true),
1326 TargetPlatform::IOS | TargetPlatform::MacOS => None,
1327 };
1328 let title = widget.title.clone().map(|title| {
1329 let mut title = AppBarTitleBox { child: title }.into_widget();
1330 if !widget.exclude_header_semantics {
1331 let mut semantics = Semantics::new().header(true);
1332 if let Some(names_route) = names_route {
1333 semantics = semantics.names_route(names_route);
1334 }
1335 title = semantics.child(title).into_widget();
1336 }
1337 let title = DefaultTextStyle::new(
1338 title_text_style
1339 .clone()
1340 .expect("the defaults give a title text style"),
1341 title,
1342 )
1343 .soft_wrap(false)
1344 .overflow(TextOverflow::Ellipsis);
1345
1346 MediaQuery::with_clamped_text_scaling(None, 0.0, K_MAX_TITLE_TEXT_SCALE_FACTOR, title)
1351 });
1352
1353 let mut actions = None;
1354 if let Some(widget_actions) = widget
1355 .actions
1356 .as_ref()
1357 .filter(|actions| !actions.is_empty())
1358 {
1359 actions = Some(
1360 Padding::new(actions_padding)
1361 .child(
1362 Row::new()
1363 .main_axis_size(MainAxisSize::Min)
1364 .cross_axis_alignment(if theme.use_material3 {
1365 CrossAxisAlignment::Center
1366 } else {
1367 CrossAxisAlignment::Stretch
1368 })
1369 .children(widget_actions.iter().cloned()),
1370 )
1371 .into_widget(),
1372 );
1373 } else if has_end_drawer && widget.automatically_imply_actions {
1374 actions = Some(
1375 EndDrawerButton::new()
1376 .style(
1377 IconButton::style_from()
1378 .icon_size(overall_icon_theme.size.unwrap_or(24.0))
1379 .build(),
1380 )
1381 .into_widget(),
1382 );
1383 }
1384
1385 let actions = actions.map(|actions| {
1387 let effective_actions_icon_button_theme =
1388 if Some(&actions_icon_theme) == defaults.actions_icon_theme(app).as_ref() {
1389 icon_button_theme.clone()
1390 } else {
1391 icon_button_theme_for(&icon_button_theme, &actions_icon_theme)
1392 };
1393
1394 IconButtonTheme::new(
1395 effective_actions_icon_button_theme,
1396 IconTheme::merge(None, actions_icon_theme.clone(), actions),
1397 )
1398 .into_widget()
1399 });
1400
1401 let mut toolbar = NavigationToolbar::new()
1402 .center_middle(widget.get_effective_center_title(&theme, &app_bar_theme))
1403 .middle_spacing(
1404 widget
1405 .title_spacing
1406 .or(app_bar_theme.title_spacing)
1407 .unwrap_or(NavigationToolbar::K_MIDDLE_SPACING),
1408 );
1409 toolbar.leading = leading;
1410 toolbar.middle = title;
1411 toolbar.trailing = actions;
1412
1413 let mut app_bar = ClipRect::new()
1416 .clip_behavior(widget.clip_behavior.unwrap_or(Clip::HardEdge))
1417 .child(
1418 CustomSingleChildLayout::new(Rc::new(ToolbarContainerLayout { toolbar_height }))
1419 .child(IconTheme::merge(
1420 None,
1421 overall_icon_theme,
1422 DefaultTextStyle::new(
1423 toolbar_text_style.expect("the defaults give a toolbar text style"),
1424 toolbar,
1425 ),
1426 )),
1427 )
1428 .into_widget();
1429 if let Some(bottom) = &widget.bottom {
1430 let bottom = if widget.bottom_opacity == 1.0 {
1431 bottom.widget().clone()
1432 } else {
1433 Opacity::new(
1434 Interval::new(0.25, 1.0, Curves::fast_out_slow_in())
1435 .transform(widget.bottom_opacity),
1436 )
1437 .child(bottom.clone())
1438 .into_widget()
1439 };
1440 app_bar = Column::new()
1441 .main_axis_alignment(MainAxisAlignment::SpaceBetween)
1442 .children([
1443 Flexible::new(
1444 ConstrainedBox::new(BoxConstraints::new().max_height(toolbar_height))
1445 .child(app_bar),
1446 )
1447 .into_widget(),
1448 bottom,
1449 ])
1450 .into_widget();
1451 }
1452
1453 if widget.primary {
1455 app_bar = SafeArea::new(app_bar).bottom(false).into_widget();
1456 }
1457
1458 app_bar = Align::new()
1459 .alignment(AlignmentGeometry::TOP_CENTER)
1460 .child(app_bar)
1461 .into_widget();
1462
1463 if let Some(flexible_space) = &widget.flexible_space {
1464 app_bar = Stack::new()
1465 .fit(StackFit::Passthrough)
1466 .children([
1467 AppBar::semantics_in_order(widget.use_default_semantics_order, 1.0)
1468 .child(flexible_space.clone())
1469 .into_widget(),
1470 AppBar::semantics_in_order(widget.use_default_semantics_order, 0.0)
1471 .child(
1474 Material::new()
1475 .r#type(MaterialType::Transparency)
1476 .child(app_bar),
1477 )
1478 .into_widget(),
1479 ])
1480 .into_widget();
1481 }
1482
1483 let overlay_style = widget
1484 .system_overlay_style
1485 .or(app_bar_theme.system_overlay_style)
1486 .or_else(|| defaults.system_overlay_style(app))
1487 .unwrap_or_else(|| {
1488 AppBarState::system_overlay_style_for_brightness(
1489 ThemeData::estimate_brightness_for_color(effective_background_color),
1490 theme.use_material3.then_some(Color::new(0x00000000)),
1493 )
1494 });
1495
1496 let mut material = Material::new()
1497 .color(if theme.use_material3 {
1498 effective_background_color
1499 } else {
1500 background_color
1501 })
1502 .elevation(effective_elevation)
1503 .r#type(if widget.force_material_transparency {
1504 MaterialType::Transparency
1505 } else {
1506 MaterialType::Canvas
1507 })
1508 .animate_color(widget.animate_color);
1509 if let Some(shadow_color) = widget
1510 .shadow_color
1511 .or(app_bar_theme.shadow_color)
1512 .or_else(|| defaults.shadow_color(app))
1513 {
1514 material = material.shadow_color(shadow_color);
1515 }
1516 if let Some(surface_tint_color) = widget
1520 .surface_tint_color
1521 .or(app_bar_theme.surface_tint_color)
1522 .or_else(|| {
1523 theme
1524 .use_material3
1525 .then(|| theme.color_scheme.surface_tint())
1526 })
1527 {
1528 material = material.surface_tint_color(surface_tint_color);
1529 }
1530 if let Some(shape) = widget
1531 .shape
1532 .clone()
1533 .or_else(|| app_bar_theme.shape.clone())
1534 .or_else(|| defaults.shape(app))
1535 {
1536 material = material.shape(shape);
1537 }
1538 Semantics::new()
1539 .container(true)
1540 .child(AnnotatedRegion::new(
1541 material.child(Semantics::new().explicit_child_nodes(true).child(app_bar)),
1542 overlay_style,
1543 ))
1544 .into_widget()
1545 }
1546}
1547
1548impl Debug for AppBarState {
1549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550 f.debug_struct("AppBarState")
1551 .field("scrolled_under", &self.scrolled_under)
1552 .finish_non_exhaustive()
1553 }
1554}
1555
1556fn is_icon_button(widget: &WidgetRef) -> bool {
1559 let widget = &**widget;
1560 downcast_widget::<IconButton>(widget).is_some()
1561 || downcast_widget::<BackButton>(widget).is_some()
1562 || downcast_widget::<CloseButton>(widget).is_some()
1563 || downcast_widget::<DrawerButton>(widget).is_some()
1564 || downcast_widget::<EndDrawerButton>(widget).is_some()
1565}
1566
1567fn icon_button_theme_for(
1571 icon_button_theme: &IconButtonThemeData,
1572 icon_theme: &IconThemeData,
1573) -> IconButtonThemeData {
1574 let mut style_from = IconButton::style_from();
1575 if let Some(color) = &icon_theme.color {
1576 style_from = style_from.foreground_color(color.color());
1577 }
1578 if let Some(size) = icon_theme.size {
1579 style_from = style_from.icon_size(size);
1580 }
1581 let icon_button_style = style_from.build();
1582
1583 let mut data = IconButtonThemeData::new();
1584 data.style = icon_button_theme
1585 .style
1586 .as_ref()
1587 .map(|style| copy_with_icon_button_style(style, icon_button_style));
1588 data
1589}
1590
1591fn copy_with_icon_button_style(style: &ButtonStyle, icon_button_style: ButtonStyle) -> ButtonStyle {
1594 let mut style = style.copy_with();
1595 if let Some(foreground_color) = icon_button_style.foreground_color {
1596 style.foreground_color = Some(foreground_color);
1597 }
1598 if let Some(overlay_color) = icon_button_style.overlay_color {
1599 style.overlay_color = Some(overlay_color);
1600 }
1601 if let Some(icon_size) = icon_button_style.icon_size {
1602 style.icon_size = Some(icon_size);
1603 }
1604 style
1605}
1606
1607fn same_optional_widget(a: &Option<WidgetRef>, b: &Option<WidgetRef>) -> bool {
1609 match (a, b) {
1610 (None, None) => true,
1611 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1612 _ => false,
1613 }
1614}
1615
1616fn same_actions(a: &Option<Vec<WidgetRef>>, b: &Option<Vec<WidgetRef>>) -> bool {
1619 match (a, b) {
1620 (None, None) => true,
1621 (Some(a), Some(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Rc::ptr_eq(a, b)),
1622 _ => false,
1623 }
1624}
1625
1626fn same_bottom(a: &Option<PreferredSizeWidgetRef>, b: &Option<PreferredSizeWidgetRef>) -> bool {
1628 match (a, b) {
1629 (None, None) => true,
1630 (Some(a), Some(b)) => Rc::ptr_eq(a.widget(), b.widget()),
1631 _ => false,
1632 }
1633}
1634
1635fn same_configuration<T>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool {
1637 match (a, b) {
1638 (None, None) => true,
1639 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1640 _ => false,
1641 }
1642}
1643
1644fn collapsed_title_fade_curve() -> Rc<dyn Curve> {
1647 thread_local! {
1648 static CURVE: Rc<dyn Curve> = Rc::new(Cubic::new(0.2, 0.0, 0.0, 1.0));
1649 }
1650 CURVE.with(Rc::clone)
1651}
1652
1653struct SliverAppBarDelegate {
1655 leading: Option<WidgetRef>,
1656 automatically_imply_leading: bool,
1657 title: Option<WidgetRef>,
1658 actions: Option<Vec<WidgetRef>>,
1659 automatically_imply_actions: bool,
1660 flexible_space: Option<WidgetRef>,
1661 bottom: Option<PreferredSizeWidgetRef>,
1662 elevation: Option<f64>,
1663 scrolled_under_elevation: Option<f64>,
1664 shadow_color: Option<Color>,
1665 surface_tint_color: Option<Color>,
1666 force_elevated: bool,
1667 background_color: Option<AnyColor>,
1668 foreground_color: Option<Color>,
1669 icon_theme: Option<IconThemeData>,
1670 actions_icon_theme: Option<IconThemeData>,
1671 primary: bool,
1672 center_title: Option<bool>,
1673 exclude_header_semantics: bool,
1674 title_spacing: Option<f64>,
1675 expanded_height: Option<f64>,
1676 collapsed_height: f64,
1677 top_padding: f64,
1678 floating: bool,
1679 pinned: bool,
1680 shape: Option<ShapeBorderRef>,
1681 toolbar_height: Option<f64>,
1682 leading_width: Option<f64>,
1683 toolbar_text_style: Option<TextStyle>,
1684 title_text_style: Option<TextStyle>,
1685 system_overlay_style: Option<SystemUiOverlayStyle>,
1686 bottom_height: f64,
1687 force_material_transparency: bool,
1688 use_default_semantics_order: bool,
1689 clip_behavior: Option<Clip>,
1690 variant: SliverAppVariant,
1691 accessible_navigation: bool,
1692 actions_padding: Option<EdgeInsetsGeometry>,
1693 vsync: TickerProviderRef,
1694 snap_configuration: Option<Rc<FloatingHeaderSnapConfiguration>>,
1695 stretch_configuration: Option<Rc<OverScrollHeaderStretchConfiguration>>,
1696 show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
1697}
1698
1699impl SliverPersistentHeaderDelegate for SliverAppBarDelegate {
1700 fn min_extent(&self) -> f64 {
1701 self.collapsed_height
1702 }
1703
1704 fn max_extent(&self) -> f64 {
1705 f64::max(
1706 self.top_padding
1707 + self.expanded_height.unwrap_or(
1708 self.toolbar_height.unwrap_or(K_TOOLBAR_HEIGHT) + self.bottom_height,
1709 ),
1710 self.min_extent(),
1711 )
1712 }
1713
1714 fn vsync(&self) -> Option<TickerProviderRef> {
1715 Some(self.vsync.clone())
1716 }
1717
1718 fn snap_configuration(&self) -> Option<FloatingHeaderSnapConfiguration> {
1719 self.snap_configuration.as_deref().cloned()
1720 }
1721
1722 fn stretch_configuration(&self) -> Option<OverScrollHeaderStretchConfiguration> {
1723 self.stretch_configuration.as_deref().cloned()
1724 }
1725
1726 fn show_on_screen_configuration(&self) -> Option<PersistentHeaderShowOnScreenConfiguration> {
1727 self.show_on_screen_configuration
1728 }
1729
1730 fn build(
1731 &self,
1732 _app: &mut App,
1733 _context: BuildContext,
1734 shrink_offset: f64,
1735 overlaps_content: bool,
1736 ) -> WidgetRef {
1737 let toolbar_height = self.toolbar_height.unwrap_or(K_TOOLBAR_HEIGHT);
1738 let visible_main_height = self.max_extent() - shrink_offset - self.top_padding;
1739 let extra_toolbar_height = f64::max(
1740 self.min_extent() - self.bottom_height - self.top_padding - toolbar_height,
1741 0.0,
1742 );
1743 let visible_toolbar_height =
1744 visible_main_height - self.bottom_height - extra_toolbar_height;
1745
1746 let is_scrolled_under = overlaps_content
1747 || self.force_elevated
1748 || (self.pinned && shrink_offset > self.max_extent() - self.min_extent());
1749 let is_pinned_with_opacity_fade =
1750 self.pinned && self.floating && self.bottom.is_some() && extra_toolbar_height == 0.0;
1751 let toolbar_opacity =
1752 if !self.accessible_navigation && (!self.pinned || is_pinned_with_opacity_fade) {
1753 clamp_double(visible_toolbar_height / toolbar_height, 0.0, 1.0)
1754 } else {
1755 1.0
1756 };
1757 let effective_title = match self.variant {
1758 SliverAppVariant::Small => self.title.clone(),
1759 SliverAppVariant::Medium | SliverAppVariant::Large => {
1760 let mut fade = AnimatedOpacity::new(
1761 if is_scrolled_under { 1.0 } else { 0.0 },
1762 Duration::from_millis(500),
1763 )
1764 .curve(collapsed_title_fade_curve());
1765 fade.child = self.title.clone();
1766 Some(fade.into_widget())
1767 }
1768 };
1769
1770 let mut app_bar = AppBar::new()
1771 .automatically_imply_leading(self.automatically_imply_leading)
1772 .automatically_imply_actions(self.automatically_imply_actions)
1773 .primary(self.primary)
1774 .exclude_header_semantics(self.exclude_header_semantics)
1775 .toolbar_opacity(toolbar_opacity)
1776 .bottom_opacity(if self.pinned {
1777 1.0
1778 } else {
1779 clamp_double(visible_main_height / self.bottom_height, 0.0, 1.0)
1780 })
1781 .force_material_transparency(self.force_material_transparency)
1782 .use_default_semantics_order(self.use_default_semantics_order);
1783 app_bar.elevation = if is_scrolled_under {
1784 self.elevation
1785 } else {
1786 Some(0.0)
1787 };
1788 debug_assert!(app_bar.elevation.is_none_or(|elevation| elevation >= 0.0));
1789 app_bar.clip_behavior = self.clip_behavior;
1790 app_bar.leading = self.leading.clone();
1791 app_bar.title = effective_title;
1792 app_bar.actions = self.actions.clone();
1793 app_bar.flexible_space = match &self.flexible_space {
1794 Some(flexible_space) if self.title.is_none() && !self.exclude_header_semantics => Some(
1795 Semantics::new()
1796 .header(true)
1797 .child(flexible_space.clone())
1798 .into_widget(),
1799 ),
1800 flexible_space => flexible_space.clone(),
1801 };
1802 app_bar.bottom = self.bottom.clone();
1803 app_bar.scrolled_under_elevation = self.scrolled_under_elevation;
1804 app_bar.shadow_color = self.shadow_color;
1805 app_bar.surface_tint_color = self.surface_tint_color;
1806 app_bar.background_color = self.background_color.clone();
1807 app_bar.foreground_color = self.foreground_color;
1808 app_bar.icon_theme = self.icon_theme.clone();
1809 app_bar.actions_icon_theme = self.actions_icon_theme.clone();
1810 app_bar.center_title = self.center_title;
1811 app_bar.title_spacing = self.title_spacing;
1812 app_bar.shape = self.shape.clone();
1813 app_bar.toolbar_height = self.toolbar_height;
1814 app_bar.leading_width = self.leading_width;
1815 app_bar.toolbar_text_style = self.toolbar_text_style.clone();
1816 app_bar.title_text_style = self.title_text_style.clone();
1817 app_bar.system_overlay_style = self.system_overlay_style;
1818 app_bar.actions_padding = self.actions_padding;
1819
1820 FlexibleSpaceBar::create_settings(
1821 f64::max(self.min_extent(), self.max_extent() - shrink_offset),
1822 app_bar,
1823 )
1824 .min_extent(self.min_extent())
1825 .max_extent(self.max_extent())
1826 .toolbar_opacity(toolbar_opacity)
1827 .is_scrolled_under(is_scrolled_under)
1828 .has_leading(self.leading.is_some() || self.automatically_imply_leading)
1829 .build()
1830 .into_widget()
1831 }
1832
1833 fn should_rebuild(&self, old_delegate: &dyn SliverPersistentHeaderDelegate) -> bool {
1834 let Some(old_delegate) = old_delegate.as_any().downcast_ref::<SliverAppBarDelegate>()
1835 else {
1836 return true;
1837 };
1838 !same_optional_widget(&self.leading, &old_delegate.leading)
1839 || self.automatically_imply_leading != old_delegate.automatically_imply_leading
1840 || !same_optional_widget(&self.title, &old_delegate.title)
1841 || !same_actions(&self.actions, &old_delegate.actions)
1842 || self.automatically_imply_actions != old_delegate.automatically_imply_actions
1843 || !same_optional_widget(&self.flexible_space, &old_delegate.flexible_space)
1844 || !same_bottom(&self.bottom, &old_delegate.bottom)
1845 || self.bottom_height != old_delegate.bottom_height
1846 || self.elevation != old_delegate.elevation
1847 || self.shadow_color != old_delegate.shadow_color
1848 || self.background_color != old_delegate.background_color
1849 || self.foreground_color != old_delegate.foreground_color
1850 || self.icon_theme != old_delegate.icon_theme
1851 || self.actions_icon_theme != old_delegate.actions_icon_theme
1852 || self.primary != old_delegate.primary
1853 || self.center_title != old_delegate.center_title
1854 || self.title_spacing != old_delegate.title_spacing
1855 || self.expanded_height != old_delegate.expanded_height
1856 || self.top_padding != old_delegate.top_padding
1857 || self.pinned != old_delegate.pinned
1858 || self.floating != old_delegate.floating
1859 || self.vsync != old_delegate.vsync
1860 || !same_configuration(&self.snap_configuration, &old_delegate.snap_configuration)
1861 || !same_configuration(
1862 &self.stretch_configuration,
1863 &old_delegate.stretch_configuration,
1864 )
1865 || self.show_on_screen_configuration != old_delegate.show_on_screen_configuration
1866 || self.force_elevated != old_delegate.force_elevated
1867 || self.toolbar_height != old_delegate.toolbar_height
1868 || self.leading_width != old_delegate.leading_width
1869 || self.toolbar_text_style != old_delegate.toolbar_text_style
1870 || self.title_text_style != old_delegate.title_text_style
1871 || self.system_overlay_style != old_delegate.system_overlay_style
1872 || self.force_material_transparency != old_delegate.force_material_transparency
1873 || self.use_default_semantics_order != old_delegate.use_default_semantics_order
1874 || self.accessible_navigation != old_delegate.accessible_navigation
1875 || self.actions_padding != old_delegate.actions_padding
1876 }
1877
1878 fn as_any(&self) -> &dyn Any {
1879 self
1880 }
1881}
1882
1883impl Debug for SliverAppBarDelegate {
1884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1885 write!(
1886 f,
1887 "SliverAppBarDelegate(topPadding: {:.1}, bottomHeight: {:.1}, ...)",
1888 self.top_padding, self.bottom_height
1889 )
1890 }
1891}
1892
1893pub struct SliverAppBar {
1928 pub key: Option<KeyRef>,
1929
1930 pub leading: Option<WidgetRef>,
1934
1935 pub automatically_imply_leading: bool,
1939
1940 pub title: Option<WidgetRef>,
1944
1945 pub actions: Option<Vec<WidgetRef>>,
1949
1950 pub automatically_imply_actions: bool,
1954
1955 pub flexible_space: Option<WidgetRef>,
1959
1960 pub bottom: Option<PreferredSizeWidgetRef>,
1964
1965 pub elevation: Option<f64>,
1969
1970 pub scrolled_under_elevation: Option<f64>,
1974
1975 pub shadow_color: Option<Color>,
1979
1980 pub surface_tint_color: Option<Color>,
1984
1985 pub force_elevated: bool,
1995
1996 pub background_color: Option<AnyColor>,
2000
2001 pub foreground_color: Option<Color>,
2005
2006 pub icon_theme: Option<IconThemeData>,
2010
2011 pub actions_icon_theme: Option<IconThemeData>,
2015
2016 pub primary: bool,
2020
2021 pub center_title: Option<bool>,
2025
2026 pub exclude_header_semantics: bool,
2030
2031 pub title_spacing: Option<f64>,
2035
2036 pub collapsed_height: Option<f64>,
2048
2049 pub expanded_height: Option<f64>,
2058
2059 pub floating: bool,
2069
2070 pub pinned: bool,
2075
2076 pub shape: Option<ShapeBorderRef>,
2080
2081 pub snap: bool,
2097
2098 pub stretch: bool,
2103
2104 pub stretch_trigger_offset: f64,
2108
2109 pub on_stretch_trigger: Option<AsyncCallback>,
2112
2113 pub toolbar_height: f64,
2117
2118 pub leading_width: Option<f64>,
2122
2123 pub toolbar_text_style: Option<TextStyle>,
2127
2128 pub title_text_style: Option<TextStyle>,
2132
2133 pub system_overlay_style: Option<SystemUiOverlayStyle>,
2137
2138 pub force_material_transparency: bool,
2142
2143 pub use_default_semantics_order: bool,
2147
2148 pub clip_behavior: Option<Clip>,
2150
2151 pub actions_padding: Option<EdgeInsetsGeometry>,
2155
2156 variant: SliverAppVariant,
2157}
2158
2159impl SliverAppBar {
2160 pub fn new() -> SliverAppBar {
2162 SliverAppBar::with_variant(SliverAppVariant::Small, false, K_TOOLBAR_HEIGHT)
2163 }
2164
2165 pub fn medium() -> SliverAppBar {
2183 SliverAppBar::with_variant(
2184 SliverAppVariant::Medium,
2185 true,
2186 MediumScrollUnderFlexibleConfig::COLLAPSED_HEIGHT,
2187 )
2188 }
2189
2190 pub fn large() -> SliverAppBar {
2208 SliverAppBar::with_variant(
2209 SliverAppVariant::Large,
2210 true,
2211 LargeScrollUnderFlexibleConfig::COLLAPSED_HEIGHT,
2212 )
2213 }
2214
2215 fn with_variant(variant: SliverAppVariant, pinned: bool, toolbar_height: f64) -> SliverAppBar {
2218 SliverAppBar {
2219 key: None,
2220 leading: None,
2221 automatically_imply_leading: true,
2222 title: None,
2223 actions: None,
2224 automatically_imply_actions: true,
2225 flexible_space: None,
2226 bottom: None,
2227 elevation: None,
2228 scrolled_under_elevation: None,
2229 shadow_color: None,
2230 surface_tint_color: None,
2231 force_elevated: false,
2232 background_color: None,
2233 foreground_color: None,
2234 icon_theme: None,
2235 actions_icon_theme: None,
2236 primary: true,
2237 center_title: None,
2238 exclude_header_semantics: false,
2239 title_spacing: None,
2240 collapsed_height: None,
2241 expanded_height: None,
2242 floating: false,
2243 pinned,
2244 shape: None,
2245 snap: false,
2246 stretch: false,
2247 stretch_trigger_offset: 100.0,
2248 on_stretch_trigger: None,
2249 toolbar_height,
2250 leading_width: None,
2251 toolbar_text_style: None,
2252 title_text_style: None,
2253 system_overlay_style: None,
2254 force_material_transparency: false,
2255 use_default_semantics_order: true,
2256 clip_behavior: None,
2257 actions_padding: None,
2258 variant,
2259 }
2260 }
2261
2262 pub fn key(mut self, key: KeyRef) -> SliverAppBar {
2264 self.key = Some(key);
2265 self
2266 }
2267
2268 #[cfg_attr(debug_assertions, track_caller)]
2270 pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> SliverAppBar {
2271 self.leading = Some(leading.into_widget());
2272 self
2273 }
2274
2275 pub fn automatically_imply_leading(
2277 mut self,
2278 automatically_imply_leading: bool,
2279 ) -> SliverAppBar {
2280 self.automatically_imply_leading = automatically_imply_leading;
2281 self
2282 }
2283
2284 #[cfg_attr(debug_assertions, track_caller)]
2286 pub fn title<K>(mut self, title: impl IntoWidget<K>) -> SliverAppBar {
2287 self.title = Some(title.into_widget());
2288 self
2289 }
2290
2291 pub fn actions(mut self, actions: Vec<WidgetRef>) -> SliverAppBar {
2293 self.actions = Some(actions);
2294 self
2295 }
2296
2297 pub fn automatically_imply_actions(
2299 mut self,
2300 automatically_imply_actions: bool,
2301 ) -> SliverAppBar {
2302 self.automatically_imply_actions = automatically_imply_actions;
2303 self
2304 }
2305
2306 #[cfg_attr(debug_assertions, track_caller)]
2308 pub fn flexible_space<K>(mut self, flexible_space: impl IntoWidget<K>) -> SliverAppBar {
2309 self.flexible_space = Some(flexible_space.into_widget());
2310 self
2311 }
2312
2313 pub fn bottom(mut self, bottom: PreferredSizeWidgetRef) -> SliverAppBar {
2315 self.bottom = Some(bottom);
2316 self
2317 }
2318
2319 pub fn elevation(mut self, elevation: f64) -> SliverAppBar {
2321 self.elevation = Some(elevation);
2322 self
2323 }
2324
2325 pub fn scrolled_under_elevation(mut self, scrolled_under_elevation: f64) -> SliverAppBar {
2327 self.scrolled_under_elevation = Some(scrolled_under_elevation);
2328 self
2329 }
2330
2331 pub fn shadow_color(mut self, shadow_color: Color) -> SliverAppBar {
2333 self.shadow_color = Some(shadow_color);
2334 self
2335 }
2336
2337 pub fn surface_tint_color(mut self, surface_tint_color: Color) -> SliverAppBar {
2339 self.surface_tint_color = Some(surface_tint_color);
2340 self
2341 }
2342
2343 pub fn force_elevated(mut self, force_elevated: bool) -> SliverAppBar {
2345 self.force_elevated = force_elevated;
2346 self
2347 }
2348
2349 pub fn background_color(mut self, background_color: impl Into<AnyColor>) -> SliverAppBar {
2351 self.background_color = Some(background_color.into());
2352 self
2353 }
2354
2355 pub fn foreground_color(mut self, foreground_color: Color) -> SliverAppBar {
2357 self.foreground_color = Some(foreground_color);
2358 self
2359 }
2360
2361 pub fn icon_theme(mut self, icon_theme: IconThemeData) -> SliverAppBar {
2363 self.icon_theme = Some(icon_theme);
2364 self
2365 }
2366
2367 pub fn actions_icon_theme(mut self, actions_icon_theme: IconThemeData) -> SliverAppBar {
2369 self.actions_icon_theme = Some(actions_icon_theme);
2370 self
2371 }
2372
2373 pub fn primary(mut self, primary: bool) -> SliverAppBar {
2375 self.primary = primary;
2376 self
2377 }
2378
2379 pub fn center_title(mut self, center_title: bool) -> SliverAppBar {
2381 self.center_title = Some(center_title);
2382 self
2383 }
2384
2385 pub fn exclude_header_semantics(mut self, exclude_header_semantics: bool) -> SliverAppBar {
2387 self.exclude_header_semantics = exclude_header_semantics;
2388 self
2389 }
2390
2391 pub fn title_spacing(mut self, title_spacing: f64) -> SliverAppBar {
2393 self.title_spacing = Some(title_spacing);
2394 self
2395 }
2396
2397 pub fn collapsed_height(mut self, collapsed_height: f64) -> SliverAppBar {
2399 self.collapsed_height = Some(collapsed_height);
2400 self
2401 }
2402
2403 pub fn expanded_height(mut self, expanded_height: f64) -> SliverAppBar {
2405 self.expanded_height = Some(expanded_height);
2406 self
2407 }
2408
2409 pub fn floating(mut self, floating: bool) -> SliverAppBar {
2411 self.floating = floating;
2412 self
2413 }
2414
2415 pub fn pinned(mut self, pinned: bool) -> SliverAppBar {
2417 self.pinned = pinned;
2418 self
2419 }
2420
2421 pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> SliverAppBar {
2423 self.shape = Some(shape.into());
2424 self
2425 }
2426
2427 pub fn snap(mut self, snap: bool) -> SliverAppBar {
2429 self.snap = snap;
2430 self
2431 }
2432
2433 pub fn stretch(mut self, stretch: bool) -> SliverAppBar {
2435 self.stretch = stretch;
2436 self
2437 }
2438
2439 pub fn stretch_trigger_offset(mut self, stretch_trigger_offset: f64) -> SliverAppBar {
2441 debug_assert!(stretch_trigger_offset > 0.0);
2442 self.stretch_trigger_offset = stretch_trigger_offset;
2443 self
2444 }
2445
2446 pub fn on_stretch_trigger(mut self, on_stretch_trigger: AsyncCallback) -> SliverAppBar {
2448 self.on_stretch_trigger = Some(on_stretch_trigger);
2449 self
2450 }
2451
2452 pub fn toolbar_height(mut self, toolbar_height: f64) -> SliverAppBar {
2454 self.toolbar_height = toolbar_height;
2455 self
2456 }
2457
2458 pub fn leading_width(mut self, leading_width: f64) -> SliverAppBar {
2460 self.leading_width = Some(leading_width);
2461 self
2462 }
2463
2464 pub fn toolbar_text_style(mut self, toolbar_text_style: TextStyle) -> SliverAppBar {
2466 self.toolbar_text_style = Some(toolbar_text_style);
2467 self
2468 }
2469
2470 pub fn title_text_style(mut self, title_text_style: TextStyle) -> SliverAppBar {
2472 self.title_text_style = Some(title_text_style);
2473 self
2474 }
2475
2476 pub fn system_overlay_style(
2478 mut self,
2479 system_overlay_style: SystemUiOverlayStyle,
2480 ) -> SliverAppBar {
2481 self.system_overlay_style = Some(system_overlay_style);
2482 self
2483 }
2484
2485 pub fn force_material_transparency(
2487 mut self,
2488 force_material_transparency: bool,
2489 ) -> SliverAppBar {
2490 self.force_material_transparency = force_material_transparency;
2491 self
2492 }
2493
2494 pub fn use_default_semantics_order(
2496 mut self,
2497 use_default_semantics_order: bool,
2498 ) -> SliverAppBar {
2499 self.use_default_semantics_order = use_default_semantics_order;
2500 self
2501 }
2502
2503 pub fn clip_behavior(mut self, clip_behavior: Clip) -> SliverAppBar {
2505 self.clip_behavior = Some(clip_behavior);
2506 self
2507 }
2508
2509 pub fn actions_padding(
2511 mut self,
2512 actions_padding: impl Into<EdgeInsetsGeometry>,
2513 ) -> SliverAppBar {
2514 let actions_padding = actions_padding.into();
2515 self.actions_padding = Some(actions_padding);
2516 self
2517 }
2518}
2519
2520impl Default for SliverAppBar {
2521 fn default() -> SliverAppBar {
2522 SliverAppBar::new()
2523 }
2524}
2525
2526impl Debug for SliverAppBar {
2527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2528 f.debug_struct("SliverAppBar")
2529 .field("key", &self.key)
2530 .field("title", &self.title)
2531 .field("variant", &self.variant)
2532 .field("floating", &self.floating)
2533 .field("pinned", &self.pinned)
2534 .finish_non_exhaustive()
2535 }
2536}
2537
2538impl StatefulWidget for SliverAppBar {
2539 type State = SliverAppBarState;
2540
2541 fn key(&self) -> Option<&KeyRef> {
2542 self.key.as_ref()
2543 }
2544
2545 fn debug_check_constructor(&self) {
2546 debug_assert!(
2547 self.floating || !self.snap,
2548 "The \"snap\" argument only makes sense for floating app bars."
2549 );
2550 debug_assert!(
2551 self.collapsed_height
2552 .is_none_or(|collapsed_height| collapsed_height >= self.toolbar_height),
2553 "The \"collapsedHeight\" argument has to be larger than or equal to [toolbarHeight]."
2554 );
2555 }
2556
2557 fn create_state(&self) -> SliverAppBarState {
2558 SliverAppBarState {
2559 state: StateData::new(),
2560 ticker_provider: TickerProviderStateMixinData::new(),
2561 snap_configuration: None,
2562 stretch_configuration: None,
2563 show_on_screen_configuration: None,
2564 }
2565 }
2566}
2567
2568pub struct SliverAppBarState {
2572 state: StateData<SliverAppBar>,
2573 ticker_provider: TickerProviderStateMixinData,
2574 snap_configuration: Option<Rc<FloatingHeaderSnapConfiguration>>,
2576 stretch_configuration: Option<Rc<OverScrollHeaderStretchConfiguration>>,
2578 show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
2579}
2580
2581impl SliverAppBarState {
2582 fn update_snap_configuration(self: Handle<Self>, app: &mut App) {
2583 let widget = self.widget(app);
2584 let snap_configuration = (widget.snap && widget.floating).then(|| {
2585 Rc::new(
2586 FloatingHeaderSnapConfiguration::new()
2587 .curve(Curves::ease_out())
2588 .duration(Duration::from_millis(200)),
2589 )
2590 });
2591
2592 let show_on_screen_configuration = (widget.floating & widget.snap).then(|| {
2593 PersistentHeaderShowOnScreenConfiguration::new()
2594 .min_show_on_screen_extent(f64::INFINITY)
2595 });
2596 let this = app.get_mut(self);
2597 this.snap_configuration = snap_configuration;
2598 this.show_on_screen_configuration = show_on_screen_configuration;
2599 }
2600
2601 fn update_stretch_configuration(self: Handle<Self>, app: &mut App) {
2602 let widget = self.widget(app);
2603 let stretch_configuration = widget.stretch.then(|| {
2604 let mut configuration = OverScrollHeaderStretchConfiguration::new()
2605 .stretch_trigger_offset(widget.stretch_trigger_offset);
2606 configuration.on_stretch_trigger = widget.on_stretch_trigger.clone();
2607 Rc::new(configuration)
2608 });
2609 app.get_mut(self).stretch_configuration = stretch_configuration;
2610 }
2611}
2612
2613impl TickerProviderStateMixin for SliverAppBarState {
2614 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
2615 &app.get(self).ticker_provider
2616 }
2617
2618 fn ticker_provider_data_mut(
2619 self: Handle<Self>,
2620 app: &mut App,
2621 ) -> &mut TickerProviderStateMixinData {
2622 &mut app.get_mut(self).ticker_provider
2623 }
2624}
2625
2626impl TickerProviderObject for SliverAppBarState {
2627 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2628 TickerProviderStateMixin::create_ticker(self, app, on_tick)
2629 }
2630}
2631
2632impl State for SliverAppBarState {
2633 type Widget = SliverAppBar;
2634 waft_widgets::state_accessors!();
2635
2636 fn init_state(self: Handle<Self>, app: &mut App) {
2637 self.update_snap_configuration(app);
2638 self.update_stretch_configuration(app);
2639 }
2640
2641 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Self::Widget) {
2642 let widget = self.widget(app);
2643 let snap_changed = widget.snap != old_widget.snap || widget.floating != old_widget.floating;
2644 let stretch_changed = widget.stretch != old_widget.stretch;
2645 if snap_changed {
2646 self.update_snap_configuration(app);
2647 }
2648 if stretch_changed {
2649 self.update_stretch_configuration(app);
2650 }
2651 }
2652
2653 fn dispose(self: Handle<Self>, app: &mut App) {
2654 TickerProviderStateMixin::dispose(self, app);
2655 }
2656
2657 fn activate(self: Handle<Self>, app: &mut App) {
2658 TickerProviderStateMixin::activate(self, app);
2659 }
2660
2661 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2662 debug_assert!(
2663 !self.widget(app).primary || waft_widgets::debug_check_has_media_query(app, context)
2664 );
2665 let bottom_height = self
2666 .widget(app)
2667 .bottom
2668 .as_ref()
2669 .map_or(0.0, |bottom| bottom.preferred_size().height());
2670 let top_padding = if self.widget(app).primary {
2671 MediaQuery::padding_of(app, context).top
2672 } else {
2673 0.0
2674 };
2675 let widget = self.widget(app);
2676 let collapsed_height = if widget.pinned && widget.floating && widget.bottom.is_some() {
2677 widget.collapsed_height.unwrap_or(0.0) + bottom_height + top_padding
2678 } else {
2679 widget.collapsed_height.unwrap_or(widget.toolbar_height) + bottom_height + top_padding
2680 };
2681 let (effective_expanded_height, effective_collapsed_height, effective_flexible_space) =
2682 match widget.variant {
2683 SliverAppVariant::Small => (
2684 widget.expanded_height,
2685 collapsed_height,
2686 widget.flexible_space.clone(),
2687 ),
2688 SliverAppVariant::Medium => (
2689 Some(widget.expanded_height.unwrap_or(
2690 MediumScrollUnderFlexibleConfig::EXPANDED_HEIGHT + bottom_height,
2691 )),
2692 widget.collapsed_height.unwrap_or(
2693 top_padding
2694 + MediumScrollUnderFlexibleConfig::COLLAPSED_HEIGHT
2695 + bottom_height,
2696 ),
2697 Some(widget.flexible_space.clone().unwrap_or_else(|| {
2698 ScrollUnderFlexibleSpace {
2699 title: widget.title.clone(),
2700 foreground_color: widget.foreground_color,
2701 config_builder: |app, context| {
2702 Box::new(MediumScrollUnderFlexibleConfig::new(app, context))
2703 },
2704 title_text_style: widget.title_text_style.clone(),
2705 bottom_height,
2706 }
2707 .into_widget()
2708 })),
2709 ),
2710 SliverAppVariant::Large => (
2711 Some(widget.expanded_height.unwrap_or(
2712 LargeScrollUnderFlexibleConfig::EXPANDED_HEIGHT + bottom_height,
2713 )),
2714 widget.collapsed_height.unwrap_or(
2715 top_padding
2716 + LargeScrollUnderFlexibleConfig::COLLAPSED_HEIGHT
2717 + bottom_height,
2718 ),
2719 Some(widget.flexible_space.clone().unwrap_or_else(|| {
2720 ScrollUnderFlexibleSpace {
2721 title: widget.title.clone(),
2722 foreground_color: widget.foreground_color,
2723 config_builder: |app, context| {
2724 Box::new(LargeScrollUnderFlexibleConfig::new(app, context))
2725 },
2726 title_text_style: widget.title_text_style.clone(),
2727 bottom_height,
2728 }
2729 .into_widget()
2730 })),
2731 ),
2732 };
2733
2734 let accessible_navigation = MediaQuery::of(app, context).accessible_navigation;
2735 let this = app.get(self);
2736 let snap_configuration = this.snap_configuration.clone();
2737 let stretch_configuration = this.stretch_configuration.clone();
2738 let show_on_screen_configuration = this.show_on_screen_configuration;
2739 let widget = self.widget(app);
2740 debug_assert!(widget.primary || top_padding == 0.0);
2741 let delegate = SliverAppBarDelegate {
2742 vsync: TickerProviderRef::new(self),
2743 leading: widget.leading.clone(),
2744 automatically_imply_leading: widget.automatically_imply_leading,
2745 title: widget.title.clone(),
2746 actions: widget.actions.clone(),
2747 automatically_imply_actions: widget.automatically_imply_actions,
2748 flexible_space: effective_flexible_space,
2749 bottom: widget.bottom.clone(),
2750 elevation: widget.elevation,
2751 scrolled_under_elevation: widget.scrolled_under_elevation,
2752 shadow_color: widget.shadow_color,
2753 surface_tint_color: widget.surface_tint_color,
2754 force_elevated: widget.force_elevated,
2755 background_color: widget.background_color.clone(),
2756 foreground_color: widget.foreground_color,
2757 icon_theme: widget.icon_theme.clone(),
2758 actions_icon_theme: widget.actions_icon_theme.clone(),
2759 primary: widget.primary,
2760 center_title: widget.center_title,
2761 exclude_header_semantics: widget.exclude_header_semantics,
2762 title_spacing: widget.title_spacing,
2763 expanded_height: effective_expanded_height,
2764 collapsed_height: effective_collapsed_height,
2765 top_padding,
2766 floating: widget.floating,
2767 pinned: widget.pinned,
2768 shape: widget.shape.clone(),
2769 snap_configuration,
2770 stretch_configuration,
2771 show_on_screen_configuration,
2772 toolbar_height: Some(widget.toolbar_height),
2773 leading_width: widget.leading_width,
2774 toolbar_text_style: widget.toolbar_text_style.clone(),
2775 title_text_style: widget.title_text_style.clone(),
2776 system_overlay_style: widget.system_overlay_style,
2777 force_material_transparency: widget.force_material_transparency,
2778 use_default_semantics_order: widget.use_default_semantics_order,
2779 clip_behavior: widget.clip_behavior,
2780 variant: widget.variant,
2781 accessible_navigation,
2782 actions_padding: widget.actions_padding,
2783 bottom_height,
2785 };
2786 let floating = widget.floating;
2787 let pinned = widget.pinned;
2788
2789 MediaQuery::remove_padding(
2790 app,
2791 context,
2792 false,
2793 false,
2794 false,
2795 true,
2796 SliverPersistentHeader::new(Rc::new(delegate))
2797 .floating(floating)
2798 .pinned(pinned),
2799 )
2800 .into_widget()
2801 }
2802}
2803
2804impl Debug for SliverAppBarState {
2805 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2806 f.write_str("SliverAppBarState")
2807 }
2808}
2809
2810#[derive(Debug)]
2815struct AppBarTitleBox {
2816 child: WidgetRef,
2817}
2818
2819impl RenderObjectWidget for AppBarTitleBox {
2820 type RenderObject = RenderAppBarTitleBox;
2821
2822 fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2823 let text_direction = Directionality::of(app, context);
2824 RenderAppBarTitleBox::new(app, Some(text_direction)).as_object()
2825 }
2826
2827 fn update_render_object(
2828 &self,
2829 app: &mut App,
2830 context: BuildContext,
2831 render_object: RenderHandle<RenderAppBarTitleBox>,
2832 ) {
2833 let text_direction = Directionality::of(app, context);
2834 render_object.set_text_direction(app, Some(text_direction));
2835 }
2836}
2837
2838impl SingleChildRenderObjectWidget for AppBarTitleBox {
2839 fn child(&self) -> Option<&WidgetRef> {
2840 Some(&self.child)
2841 }
2842}
2843
2844struct RenderAppBarTitleBox {
2846 render_object: RenderObjectData,
2847 render_box: RenderBoxData,
2848 child: RenderObjectWithChildData<AnyRenderBox>,
2849 aligning: RenderAligningShiftedBoxData,
2850}
2851
2852impl RenderAppBarTitleBox {
2853 fn new(
2854 app: &mut App,
2855 text_direction: Option<TextDirection>,
2856 ) -> RenderHandle<RenderAppBarTitleBox> {
2857 RenderHandle::new_box(
2858 app,
2859 RenderAppBarTitleBox {
2860 render_object: RenderObjectData::new(),
2861 render_box: RenderBoxData::new(),
2862 child: RenderObjectWithChildData::new(),
2863 aligning: RenderAligningShiftedBoxData::new(
2864 AlignmentGeometry::CENTER,
2865 text_direction,
2866 ),
2867 },
2868 )
2869 }
2870}
2871
2872impl RenderObjectWithChildMixin for RenderAppBarTitleBox {
2873 type ChildType = AnyRenderBox;
2874
2875 fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2876 &self.get(app).child
2877 }
2878
2879 fn child_data_mut(
2880 self: RenderHandle<Self>,
2881 app: &mut App,
2882 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2883 &mut self.get_mut(app).child
2884 }
2885}
2886
2887impl RenderShiftedBox for RenderAppBarTitleBox {}
2888
2889impl RenderAligningShiftedBox for RenderAppBarTitleBox {
2890 fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
2891 &self.get(app).aligning
2892 }
2893
2894 fn aligning_data_mut(
2895 self: RenderHandle<Self>,
2896 app: &mut App,
2897 ) -> &mut RenderAligningShiftedBoxData {
2898 &mut self.get_mut(app).aligning
2899 }
2900}
2901
2902impl RenderObject for RenderAppBarTitleBox {
2903 waft_rendering::render_object_accessors!();
2904
2905 fn debug_fill_properties(
2906 self: RenderHandle<Self>,
2907 app: &App,
2908 properties: &mut DiagnosticPropertiesBuilder,
2909 ) {
2910 RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
2912 }
2913
2914 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2915 let constraints = self.constraints(app);
2916 let inner_constraints = constraints.copy_with().max_height(f64::INFINITY);
2917 let child = self.child(app).expect("the title box has a child");
2918 child.layout(app, inner_constraints, true);
2919 let size = constraints.constrain(child.size(app));
2920 self.set_size(app, size);
2921 self.align_child(app);
2922 }
2923
2924 fn paint(
2925 self: RenderHandle<Self>,
2926 app: &mut App,
2927 context: &mut PaintingContext,
2928 offset: Offset,
2929 ) {
2930 RenderShiftedBox::paint(self, app, context, offset);
2931 }
2932
2933 fn visit_children(
2934 self: RenderHandle<Self>,
2935 app: &App,
2936 visitor: &mut dyn FnMut(AnyRenderObject),
2937 ) {
2938 if let Some(child) = self.child(app) {
2939 visitor(child.as_object());
2940 }
2941 }
2942}
2943
2944impl RenderBox for RenderAppBarTitleBox {
2945 waft_rendering::render_box_accessors!();
2946
2947 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2948 RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
2949 }
2950
2951 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2952 RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
2953 }
2954
2955 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2956 RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
2957 }
2958
2959 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2960 RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
2961 }
2962
2963 fn compute_dry_layout(
2964 self: RenderHandle<Self>,
2965 app: &mut App,
2966 constraints: BoxConstraints,
2967 ) -> Size {
2968 let inner_constraints = constraints.copy_with().max_height(f64::INFINITY);
2969 let child = self.child(app).expect("the title box has a child");
2970 let child_size = child.get_dry_layout(app, inner_constraints);
2971 constraints.constrain(child_size)
2972 }
2973
2974 fn compute_dry_baseline(
2975 self: RenderHandle<Self>,
2976 app: &mut App,
2977 constraints: BoxConstraints,
2978 baseline: TextBaseline,
2979 ) -> Option<f64> {
2980 let inner_constraints = constraints.copy_with().max_height(f64::INFINITY);
2981 let child = self.child(app)?;
2982 let result = child.get_dry_baseline(app, inner_constraints, baseline)?;
2983 let child_size = child.get_dry_layout(app, inner_constraints);
2984 let size = self.get_dry_layout(app, constraints);
2985 Some(
2986 result
2987 + self
2988 .resolved_alignment(app)
2989 .along_offset(size - child_size)
2990 .dy(),
2991 )
2992 }
2993
2994 fn compute_distance_to_actual_baseline(
2995 self: RenderHandle<Self>,
2996 app: &mut App,
2997 baseline: TextBaseline,
2998 ) -> Option<f64> {
2999 RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
3000 }
3001
3002 fn hit_test_children(
3003 self: RenderHandle<Self>,
3004 app: &mut App,
3005 result: &mut BoxHitTestResult<'_>,
3006 position: Offset,
3007 ) -> bool {
3008 RenderShiftedBox::hit_test_children(self, app, result, position)
3009 }
3010}
3011
3012struct ScrollUnderFlexibleSpace {
3014 title: Option<WidgetRef>,
3015 foreground_color: Option<Color>,
3016 config_builder: FlexibleConfigBuilder,
3017 title_text_style: Option<TextStyle>,
3018 bottom_height: f64,
3019}
3020
3021impl StatelessWidget for ScrollUnderFlexibleSpace {
3022 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
3023 let settings = context
3024 .depend_on_inherited_widget_of_exact_type::<FlexibleSpaceBarSettings>(app)
3025 .expect("a FlexibleSpaceBarSettings above the flexible space")
3026 .clone();
3027 let config = (self.config_builder)(app, context);
3028 debug_assert!(
3029 config.expanded_title_padding().is_non_negative(),
3030 "The _ExpandedTitleWithPadding widget assumes that the expanded title padding is \
3031 non-negative. Update its implementation to handle negative padding."
3032 );
3033
3034 let expanded_text_style = match &self.title_text_style {
3035 Some(title_text_style) => Some(title_text_style.clone()),
3036 None => {
3037 let app_bar_theme = AppBarTheme::of(app, context);
3038 match app_bar_theme.title_text_style {
3039 Some(title_text_style) => Some(title_text_style),
3040 None => {
3041 let foreground_color =
3042 match self.foreground_color.or(app_bar_theme.foreground_color) {
3043 Some(foreground_color) => foreground_color,
3044 None => app_bar_defaults(app, context)
3045 .foreground_color(app)
3046 .expect("the defaults give a foreground color"),
3047 };
3048 config
3049 .expanded_text_style()
3050 .map(|style| style.copy_with().color(foreground_color))
3051 }
3052 }
3053 }
3054 };
3055
3056 let expanded_title = match (&self.title, expanded_text_style) {
3057 (None, _) => None,
3058 (Some(title), None) => Some(title.clone()),
3059 (Some(title), Some(text_style)) => {
3060 Some(DefaultTextStyle::new(text_style, title.clone()).into_widget())
3061 }
3062 };
3063
3064 let resolved_title_padding = config
3065 .expanded_title_padding()
3066 .resolve(Some(Directionality::of(app, context)));
3067 let expanded_title_padding: EdgeInsetsGeometry = if self.bottom_height > 0.0 {
3068 resolved_title_padding
3069 .copy_with(None, None, None, Some(0.0))
3070 .into()
3071 } else {
3072 resolved_title_padding.into()
3073 };
3074
3075 let mut children = vec![
3076 Padding::new(EdgeInsetsGeometry::only(
3077 0.0,
3078 settings.min_extent - self.bottom_height,
3079 0.0,
3080 0.0,
3081 ))
3082 .into_widget(),
3083 Flexible::new(ClipRect::new().child(ExpandedTitleWithPadding {
3084 padding: expanded_title_padding,
3085 max_extent: settings.max_extent - settings.min_extent,
3086 child: expanded_title,
3087 }))
3088 .into_widget(),
3089 ];
3090 if self.bottom_height > 0.0 {
3093 children.push(
3094 Padding::new(EdgeInsetsGeometry::only(0.0, 0.0, 0.0, self.bottom_height))
3095 .into_widget(),
3096 );
3097 }
3098
3099 MediaQuery::with_clamped_text_scaling(
3105 None,
3106 0.0,
3107 K_MAX_TITLE_TEXT_SCALE_FACTOR,
3108 Column::new().children(children),
3110 )
3111 }
3112}
3113
3114impl Debug for ScrollUnderFlexibleSpace {
3115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3116 f.debug_struct("ScrollUnderFlexibleSpace")
3117 .field("title", &self.title)
3118 .field("bottom_height", &self.bottom_height)
3119 .finish_non_exhaustive()
3120 }
3121}
3122
3123#[derive(Debug)]
3132struct ExpandedTitleWithPadding {
3133 padding: EdgeInsetsGeometry,
3134 max_extent: f64,
3135 child: Option<WidgetRef>,
3136}
3137
3138impl RenderObjectWidget for ExpandedTitleWithPadding {
3139 type RenderObject = RenderExpandedTitleBox;
3140
3141 fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
3142 let text_direction = Some(Directionality::of(app, context));
3143 RenderExpandedTitleBox::new(
3144 app,
3145 self.padding.resolve(text_direction),
3146 AlignmentDirectional::BOTTOM_START.resolve(text_direction),
3147 self.max_extent,
3148 None,
3149 )
3150 .as_object()
3151 }
3152
3153 fn update_render_object(
3154 &self,
3155 app: &mut App,
3156 context: BuildContext,
3157 render_object: RenderHandle<RenderExpandedTitleBox>,
3158 ) {
3159 let text_direction = Some(Directionality::of(app, context));
3160 render_object.set_padding(app, self.padding.resolve(text_direction));
3161 render_object.set_title_alignment(
3162 app,
3163 AlignmentDirectional::BOTTOM_START.resolve(text_direction),
3164 );
3165 render_object.set_max_extent(app, self.max_extent);
3166 }
3167}
3168
3169impl SingleChildRenderObjectWidget for ExpandedTitleWithPadding {
3170 fn child(&self) -> Option<&WidgetRef> {
3171 self.child.as_ref()
3172 }
3173}
3174
3175struct RenderExpandedTitleBox {
3177 render_object: RenderObjectData,
3178 render_box: RenderBoxData,
3179 child: RenderObjectWithChildData<AnyRenderBox>,
3180 padding: EdgeInsets,
3181 title_alignment: Alignment,
3182 max_extent: f64,
3183}
3184
3185impl RenderExpandedTitleBox {
3186 fn new(
3187 app: &mut App,
3188 padding: EdgeInsets,
3189 title_alignment: Alignment,
3190 max_extent: f64,
3191 child: Option<AnyRenderBox>,
3192 ) -> RenderHandle<RenderExpandedTitleBox> {
3193 let this = RenderHandle::new_box(
3194 app,
3195 RenderExpandedTitleBox {
3196 render_object: RenderObjectData::new(),
3197 render_box: RenderBoxData::new(),
3198 child: RenderObjectWithChildData::new(),
3199 padding,
3200 title_alignment,
3201 max_extent,
3202 },
3203 );
3204 this.set_child(app, child);
3205 this
3206 }
3207
3208 fn padding(self: RenderHandle<Self>, app: &App) -> EdgeInsets {
3209 self.get(app).padding
3210 }
3211
3212 fn set_padding(self: RenderHandle<Self>, app: &mut App, value: EdgeInsets) {
3213 if self.get(app).padding == value {
3214 return;
3215 }
3216 debug_assert!(value.is_non_negative());
3217 self.get_mut(app).padding = value;
3218 self.mark_needs_layout(app);
3219 }
3220
3221 fn title_alignment(self: RenderHandle<Self>, app: &App) -> Alignment {
3222 self.get(app).title_alignment
3223 }
3224
3225 fn set_title_alignment(self: RenderHandle<Self>, app: &mut App, value: Alignment) {
3226 if self.get(app).title_alignment == value {
3227 return;
3228 }
3229 self.get_mut(app).title_alignment = value;
3230 self.mark_needs_layout(app);
3231 }
3232
3233 fn max_extent(self: RenderHandle<Self>, app: &App) -> f64 {
3234 self.get(app).max_extent
3235 }
3236
3237 fn set_max_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
3238 if self.get(app).max_extent == value {
3239 return;
3240 }
3241 self.get_mut(app).max_extent = value;
3242 self.mark_needs_layout(app);
3243 }
3244
3245 fn child_offset_from_size(
3246 self: RenderHandle<Self>,
3247 app: &App,
3248 child_size: Size,
3249 size: Size,
3250 ) -> Offset {
3251 debug_assert!(self.child(app).is_some());
3252 let padding = self.padding(app);
3253 let title_alignment = self.title_alignment(app);
3254 debug_assert!(padding.is_non_negative());
3255 debug_assert_eq!(title_alignment.y, 1.0);
3256 let y_adjustment = clamp_double(
3263 child_size.height() + padding.bottom - self.max_extent(app),
3264 0.0,
3265 padding.bottom,
3266 );
3267 let offset_x = (title_alignment.x + 1.0) / 2.0
3268 * (size.width() - padding.horizontal() - child_size.width())
3269 + padding.left;
3270 let offset_y = size.height() - child_size.height() - padding.bottom + y_adjustment;
3271 Offset::new(offset_x, offset_y)
3272 }
3273}
3274
3275impl RenderObjectWithChildMixin for RenderExpandedTitleBox {
3276 type ChildType = AnyRenderBox;
3277
3278 fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3279 &self.get(app).child
3280 }
3281
3282 fn child_data_mut(
3283 self: RenderHandle<Self>,
3284 app: &mut App,
3285 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3286 &mut self.get_mut(app).child
3287 }
3288}
3289
3290impl RenderShiftedBox for RenderExpandedTitleBox {}
3291
3292impl RenderObject for RenderExpandedTitleBox {
3293 waft_rendering::render_object_accessors!();
3294
3295 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3296 let constraints = self.constraints(app);
3297 let Some(child) = self.child(app) else {
3298 self.set_size(app, constraints.smallest());
3299 return;
3300 };
3301 let size = constraints.biggest();
3302 self.set_size(app, size);
3303 let padding = self.padding(app);
3304 child.layout(
3305 app,
3306 constraints.width_constraints().deflate(padding.into()),
3307 true,
3308 );
3309 let offset = self.child_offset_from_size(app, child.size(app), size);
3310 child
3311 .as_object()
3312 .parent_data_of_mut::<BoxParentData>(app)
3313 .offset = offset;
3314 }
3315
3316 fn paint(
3317 self: RenderHandle<Self>,
3318 app: &mut App,
3319 context: &mut PaintingContext,
3320 offset: Offset,
3321 ) {
3322 RenderShiftedBox::paint(self, app, context, offset);
3323 }
3324
3325 fn visit_children(
3326 self: RenderHandle<Self>,
3327 app: &App,
3328 visitor: &mut dyn FnMut(AnyRenderObject),
3329 ) {
3330 if let Some(child) = self.child(app) {
3331 visitor(child.as_object());
3332 }
3333 }
3334}
3335
3336impl RenderBox for RenderExpandedTitleBox {
3337 waft_rendering::render_box_accessors!();
3338
3339 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3340 let padding = self.padding(app);
3341 match self.child(app) {
3342 None => 0.0,
3343 Some(child) => {
3344 child.get_max_intrinsic_height(app, f64::max(0.0, width - padding.horizontal()))
3345 + padding.vertical()
3346 }
3347 }
3348 }
3349
3350 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
3351 let padding = self.padding(app);
3352 match self.child(app) {
3353 None => 0.0,
3354 Some(child) => child.get_max_intrinsic_width(app, f64::INFINITY) + padding.horizontal(),
3355 }
3356 }
3357
3358 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3359 let padding = self.padding(app);
3360 match self.child(app) {
3361 None => 0.0,
3362 Some(child) => {
3363 child.get_min_intrinsic_height(app, f64::max(0.0, width - padding.horizontal()))
3364 + padding.vertical()
3365 }
3366 }
3367 }
3368
3369 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
3370 let padding = self.padding(app);
3371 match self.child(app) {
3372 None => 0.0,
3373 Some(child) => child.get_min_intrinsic_width(app, f64::INFINITY) + padding.horizontal(),
3374 }
3375 }
3376
3377 fn compute_dry_layout(
3378 self: RenderHandle<Self>,
3379 app: &mut App,
3380 constraints: BoxConstraints,
3381 ) -> Size {
3382 if self.child(app).is_none() {
3383 Size::ZERO
3384 } else {
3385 constraints.biggest()
3386 }
3387 }
3388
3389 fn compute_dry_baseline(
3390 self: RenderHandle<Self>,
3391 app: &mut App,
3392 constraints: BoxConstraints,
3393 baseline: TextBaseline,
3394 ) -> Option<f64> {
3395 let child = self.child(app)?;
3396 let child_constraints = constraints
3397 .width_constraints()
3398 .deflate(self.padding(app).into());
3399 let child_baseline = child.get_dry_baseline(app, child_constraints, baseline);
3400 let child_size = child.get_dry_layout(app, child_constraints);
3401 let size = self.get_dry_layout(app, constraints);
3402 let result = BaselineOffset(child_baseline)
3403 + self.child_offset_from_size(app, child_size, size).dy();
3404 result.offset()
3405 }
3406
3407 fn compute_distance_to_actual_baseline(
3408 self: RenderHandle<Self>,
3409 app: &mut App,
3410 baseline: TextBaseline,
3411 ) -> Option<f64> {
3412 RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
3413 }
3414
3415 fn hit_test_children(
3416 self: RenderHandle<Self>,
3417 app: &mut App,
3418 result: &mut BoxHitTestResult<'_>,
3419 position: Offset,
3420 ) -> bool {
3421 RenderShiftedBox::hit_test_children(self, app, result, position)
3422 }
3423}
3424
3425pub(crate) trait ScrollUnderFlexibleConfig {
3428 #[expect(dead_code, reason = "Dart declares it and reads it nowhere either")]
3429 fn collapsed_text_style(&self) -> Option<TextStyle>;
3430 fn expanded_text_style(&self) -> Option<TextStyle>;
3431 fn expanded_title_padding(&self) -> EdgeInsetsGeometry;
3432}
3433
3434fn app_bar_defaults(app: &mut App, context: BuildContext) -> Box<dyn AppBarThemeDataGetters> {
3436 if Theme::of(app, context).use_material3 {
3437 Box::new(AppBarDefaultsM3::new(context))
3438 } else {
3439 Box::new(AppBarDefaultsM2::new(context))
3440 }
3441}
3442
3443struct AppBarDefaultsM2 {
3447 app_bar_theme_data: AppBarThemeData,
3449 context: DefaultsContext,
3450}
3451
3452impl AppBarDefaultsM2 {
3453 fn new(context: BuildContext) -> AppBarDefaultsM2 {
3454 AppBarDefaultsM2 {
3455 app_bar_theme_data: AppBarThemeData::new()
3456 .elevation(4.0)
3457 .shadow_color(Color::new(0xFF000000))
3458 .title_spacing(NavigationToolbar::K_MIDDLE_SPACING)
3459 .toolbar_height(K_TOOLBAR_HEIGHT),
3460 context: DefaultsContext::new(context),
3461 }
3462 }
3463}
3464
3465impl AppBarThemeDataGetters for AppBarDefaultsM2 {
3466 fn app_bar_theme_data(&self) -> &AppBarThemeData {
3467 &self.app_bar_theme_data
3468 }
3469
3470 fn background_color(&self, app: &mut App) -> Option<Color> {
3471 let theme = self.context.theme(app);
3472 let colors = &theme.color_scheme;
3473 let dark = colors.brightness() == waft_embedder::Brightness::Dark;
3474 Some(if dark {
3475 colors.surface()
3476 } else {
3477 colors.primary()
3478 })
3479 }
3480
3481 fn foreground_color(&self, app: &mut App) -> Option<Color> {
3482 let theme = self.context.theme(app);
3483 let colors = &theme.color_scheme;
3484 let dark = colors.brightness() == waft_embedder::Brightness::Dark;
3485 Some(if dark {
3486 colors.on_surface()
3487 } else {
3488 colors.on_primary()
3489 })
3490 }
3491
3492 fn icon_theme(&self, app: &mut App) -> Option<IconThemeData> {
3493 let theme = self.context.theme(app);
3494 Some(theme.icon_theme.clone())
3495 }
3496
3497 fn toolbar_text_style(&self, app: &mut App) -> Option<TextStyle> {
3498 let theme = self.context.theme(app);
3499 Some(
3500 theme
3501 .text_theme
3502 .body_medium
3503 .clone()
3504 .expect("a theme's text theme has a body medium style"),
3505 )
3506 }
3507
3508 fn title_text_style(&self, app: &mut App) -> Option<TextStyle> {
3509 let theme = self.context.theme(app);
3510 Some(
3511 theme
3512 .text_theme
3513 .title_large
3514 .clone()
3515 .expect("a theme's text theme has a title large style"),
3516 )
3517 }
3518
3519 fn actions_padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
3520 Some(EdgeInsets::ZERO.into())
3521 }
3522}
3523
3524#[cfg(test)]
3525mod tests {
3526 use std::cell::Cell;
3531 use waft_painting::ShapeBorder;
3532
3533 use waft_embedder::{Brightness, Radius, Rect};
3534 use waft_foundation::{Listener, Task};
3535 use waft_painting::{Axis, BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
3536 use waft_services::SystemChrome;
3537 use waft_widgets::{
3538 AnyElement, Builder, Container, CustomScrollView, GlobalKey, Icon, IconData, ListView,
3539 MediaQueryData, PreferredSize, ScrollController, ScrollControllerLeaf,
3540 SingleChildScrollView, SizedBox, SliverToBoxAdapter, Text, WidgetStateColor,
3541 };
3542
3543 use waft_rendering::testing::{PaintCall, assert_paints};
3544 use waft_widgets::testing::{
3545 TestPointer, WidgetTester, assert_f32_equals, expect, find, finds_one_widget, test_widgets,
3546 };
3547
3548 use super::*;
3549 use crate::drawer::Drawer;
3550 use crate::icons::Icons;
3551 use crate::tab_controller::DefaultTabController;
3552 use crate::tabs::{Tab, TabBar};
3553 use crate::test_support::{PaintInspection, material_app};
3554
3555 const K_TEXT_TAB_BAR_HEIGHT: f64 = 48.0;
3557
3558 fn pump_app(
3560 tester: &mut WidgetTester,
3561 theme: impl FnOnce(&App) -> ThemeData,
3562 home: impl FnOnce(&mut App) -> WidgetRef,
3563 ) {
3564 let root = {
3565 let mut app = tester.cell.borrow_mut();
3566 let theme = theme(&app);
3567 material_app(theme, home(&mut app))
3568 };
3569 tester.pump_widget(root);
3570 }
3571
3572 fn m3(app: &App) -> ThemeData {
3573 ThemeData::new(app)
3574 }
3575
3576 fn m2(app: &App) -> ThemeData {
3577 ThemeData::builder().use_material3(false).build(app)
3578 }
3579
3580 fn scaffold_with(app_bar: AppBar) -> Scaffold {
3582 Scaffold::new().app_bar(PreferredSizeWidgetRef::new(app_bar))
3583 }
3584
3585 fn rect_of(tester: &WidgetTester, element: AnyElement) -> Rect {
3586 tester.get_rect(element)
3587 }
3588
3589 fn key_rect(tester: &WidgetTester, key: &GlobalKey) -> Rect {
3590 tester.global_rect(tester.render_object(key).as_box().expect("a render box"))
3591 }
3592
3593 fn app_bar_rect(tester: &WidgetTester) -> Rect {
3595 let app_bar = *find::by_type::<AppBar>()
3596 .skip_offstage(false)
3597 .evaluate(tester)
3598 .first()
3599 .expect("an AppBar");
3600 rect_of(tester, app_bar)
3601 }
3602
3603 fn app_bar_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
3606 let app_bar = *find::by_type::<AppBar>()
3607 .evaluate(tester)
3608 .first()
3609 .expect("an AppBar");
3610 let material = find::by_type::<Material>()
3611 .evaluate(tester)
3612 .into_iter()
3613 .find(|material| tester.ancestors(*material).contains(&app_bar))
3614 .expect("the app bar's Material");
3615 tester.widget(material, read)
3616 }
3617
3618 fn app_bar_elevation(tester: &WidgetTester) -> f64 {
3619 app_bar_material(tester, |material| material.elevation)
3620 }
3621
3622 fn app_bar_background_color(tester: &WidgetTester) -> Option<Color> {
3623 app_bar_material(tester, |material| material.color)
3624 }
3625
3626 fn icon_count(tester: &WidgetTester, icon: &IconData) -> usize {
3628 find::by_type::<Icon>()
3629 .evaluate(tester)
3630 .into_iter()
3631 .filter(|element| {
3632 tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
3633 })
3634 .count()
3635 }
3636
3637 fn icon_color(tester: &WidgetTester, icon: &IconData) -> Option<Color> {
3639 tester
3640 .glyph_style(tester.element(find::by_icon(icon)))
3641 .color
3642 .map(|color| color.color())
3643 }
3644
3645 fn icon_size(tester: &WidgetTester, icon: &IconData) -> Size {
3646 tester.get_size(find::by_icon(icon))
3647 }
3648
3649 fn latest_style(tester: &WidgetTester) -> Option<SystemUiOverlayStyle> {
3651 let mut app = tester.cell.borrow_mut();
3652 let view = app
3653 .platform()
3654 .views()
3655 .into_iter()
3656 .next()
3657 .expect("one view")
3658 .id();
3659 SystemChrome::latest_style(&mut app, view)
3660 }
3661
3662 fn navigation_toolbar<R>(
3664 tester: &WidgetTester,
3665 read: impl FnOnce(&NavigationToolbar) -> R,
3666 ) -> R {
3667 let toolbar = *find::by_type::<NavigationToolbar>()
3668 .evaluate(tester)
3669 .first()
3670 .expect("a NavigationToolbar");
3671 tester.widget(toolbar, read)
3672 }
3673
3674 fn placeholder(key: &GlobalKey) -> WidgetRef {
3676 waft_widgets::LimitedBox::new()
3677 .max_width(400.0)
3678 .max_height(400.0)
3679 .child(SizedBox::expand())
3680 .key(key.clone().into())
3681 .into_widget()
3682 }
3683
3684 #[test]
3688 fn the_title_is_centered_on_ios_and_macos_unless_there_are_two_actions() {
3689 test_widgets(|tester| {
3690 pump_app(tester, m3, |_app| {
3691 scaffold_with(AppBar::new().title(Text::new("X"))).into_widget()
3692 });
3693 let title = tester.get_rect(find::text("X"));
3694 assert!(title.center().dx() < 400.0 - title.width() / 2.0);
3695
3696 for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
3697 let theme = move |app: &App| ThemeData::builder().platform(platform).build(app);
3698 tester.pump_widget(Container::new().into_widget());
3700
3701 pump_app(tester, theme, |_app| {
3702 scaffold_with(AppBar::new().title(Text::new("X"))).into_widget()
3703 });
3704 let title = tester.get_rect(find::text("X"));
3705 assert!(
3706 title.center().dx() > 400.0 - title.width() / 2.0,
3707 "on {platform:?}"
3708 );
3709 assert!(
3710 title.center().dx() < 400.0 + title.width() / 2.0,
3711 "on {platform:?}"
3712 );
3713
3714 pump_app(tester, theme, |_app| {
3716 scaffold_with(
3717 AppBar::new()
3718 .title(Text::new("X"))
3719 .actions(vec![Icon::new(Some(Icons::thumb_up())).into_widget()]),
3720 )
3721 .into_widget()
3722 });
3723 let title = tester.get_rect(find::text("X"));
3724 assert!(
3725 title.center().dx() > 400.0 - title.width() / 2.0,
3726 "on {platform:?}"
3727 );
3728 assert!(
3729 title.center().dx() < 400.0 + title.width() / 2.0,
3730 "on {platform:?}"
3731 );
3732
3733 pump_app(tester, theme, |_app| {
3735 scaffold_with(AppBar::new().title(Text::new("X")).actions(vec![
3736 Icon::new(Some(Icons::thumb_up())).into_widget(),
3737 Icon::new(Some(Icons::thumb_up())).into_widget(),
3738 ]))
3739 .into_widget()
3740 });
3741 let title = tester.get_rect(find::text("X"));
3742 assert!(
3743 title.center().dx() < 400.0 - title.width() / 2.0,
3744 "on {platform:?}"
3745 );
3746 }
3747 });
3748 }
3749
3750 #[test]
3751 fn center_title_true_centers_the_title_on_android() {
3752 test_widgets(|tester| {
3753 pump_app(tester, m3, |_app| {
3754 scaffold_with(AppBar::new().center_title(true).title(Text::new("X"))).into_widget()
3755 });
3756 let title = tester.get_rect(find::text("X"));
3757 assert!(title.center().dx() > 400.0 - title.width() / 2.0);
3758 assert!(title.center().dx() < 400.0 + title.width() / 2.0);
3759 });
3760 }
3761
3762 fn start_aligned_title_rect(direction: TextDirection, title_spacing: Option<f64>) -> Rect {
3763 let mut rect = Rect::ZERO;
3764 test_widgets(|tester| {
3765 let key = GlobalKey::new();
3766 pump_app(tester, m3, |_app| {
3767 let mut app_bar = AppBar::new().center_title(false).title(placeholder(&key));
3768 if let Some(title_spacing) = title_spacing {
3769 app_bar = app_bar.title_spacing(title_spacing);
3770 }
3771 Directionality::new(direction, scaffold_with(app_bar).into_widget()).into_widget()
3772 });
3773 rect = key_rect(tester, &key);
3774 });
3775 rect
3776 }
3777
3778 #[test]
3779 fn a_start_aligned_title_starts_16_from_the_edge_left_to_right() {
3780 let title = start_aligned_title_rect(TextDirection::Ltr, None);
3781 assert_eq!(title.left, 16.0);
3782 assert_eq!(title.right, 800.0 - 16.0);
3783 }
3784
3785 #[test]
3786 fn a_start_aligned_title_starts_16_from_the_edge_right_to_left() {
3787 let title = start_aligned_title_rect(TextDirection::Rtl, None);
3788 assert_eq!(title.right, 800.0 - 16.0);
3789 assert_eq!(title.left, 16.0);
3790 }
3791
3792 #[test]
3793 fn a_title_spacing_of_32_starts_the_title_32_from_the_edge_left_to_right() {
3794 let title = start_aligned_title_rect(TextDirection::Ltr, Some(32.0));
3795 assert_eq!(title.left, 32.0);
3796 assert_eq!(title.right, 800.0 - 32.0);
3797 }
3798
3799 #[test]
3800 fn a_title_spacing_of_32_starts_the_title_32_from_the_edge_right_to_left() {
3801 let title = start_aligned_title_rect(TextDirection::Rtl, Some(32.0));
3802 assert_eq!(title.right, 800.0 - 32.0);
3803 assert_eq!(title.left, 32.0);
3804 }
3805
3806 fn title_rect_after_drawer_button(direction: TextDirection) -> Rect {
3807 let mut rect = Rect::ZERO;
3808 test_widgets(|tester| {
3809 pump_app(tester, m3, |_app| {
3810 Directionality::new(
3811 direction,
3812 scaffold_with(AppBar::new().center_title(false).title(Text::new("X")))
3813 .drawer(Drawer::new())
3815 .into_widget(),
3816 )
3817 .into_widget()
3818 });
3819 rect = tester.get_rect(find::text("X"));
3820 });
3821 rect
3822 }
3823
3824 #[test]
3825 fn a_drawer_button_starts_the_title_at_72_left_to_right() {
3826 assert_eq!(
3827 title_rect_after_drawer_button(TextDirection::Ltr).left,
3828 72.0
3829 );
3830 }
3831
3832 #[test]
3833 fn a_drawer_button_starts_the_title_at_72_right_to_left() {
3834 assert_eq!(
3835 title_rect_after_drawer_button(TextDirection::Rtl).right,
3836 800.0 - 72.0
3837 );
3838 }
3839
3840 #[test]
3841 fn an_app_bar_builds_without_a_scaffold() {
3842 test_widgets(|tester| {
3843 pump_app(tester, m3, |_app| {
3844 SizedBox::new()
3845 .height(K_TOOLBAR_HEIGHT)
3846 .child(
3847 AppBar::new()
3848 .leading(Text::new("L"))
3849 .title(Text::new("No Scaffold"))
3850 .actions(vec![
3851 Text::new("A1").into_widget(),
3852 Text::new("A2").into_widget(),
3853 ]),
3854 )
3855 .into_widget()
3856 });
3857 for text in ["L", "No Scaffold", "A1", "A2"] {
3858 expect(tester, &find::text(text), finds_one_widget());
3859 }
3860 });
3861 }
3862
3863 #[test]
3864 fn an_app_bar_renders_at_zero_size() {
3865 test_widgets(|tester| {
3866 pump_app(tester, m3, |_app| {
3867 waft_widgets::Center::new()
3868 .child(
3869 SizedBox::shrink()
3870 .child(scaffold_with(AppBar::new().title(Text::new("X")))),
3871 )
3872 .into_widget()
3873 });
3874 assert!(tester.get_rect(find::text("X")).size().is_empty());
3875 });
3876 }
3877
3878 #[test]
3879 fn leading_title_and_actions_are_vertically_centered() {
3880 test_widgets(|tester| {
3881 let app_bar_key = GlobalKey::new();
3882 let leading_key = GlobalKey::new();
3883 let title_key = GlobalKey::new();
3884 let action0_key = GlobalKey::new();
3885 let action1_key = GlobalKey::new();
3886 pump_app(tester, m3, |_app| {
3887 let sized = |key: &GlobalKey, height: f64| {
3888 SizedBox::new()
3889 .height(height)
3890 .key(key.clone().into())
3891 .into_widget()
3892 };
3893 scaffold_with(
3894 AppBar::new()
3895 .key(app_bar_key.clone().into())
3896 .leading(sized(&leading_key, 50.0))
3897 .title(sized(&title_key, 40.0))
3898 .actions(vec![sized(&action0_key, 20.0), sized(&action1_key, 30.0)]),
3899 )
3900 .into_widget()
3901 });
3902 let y_center = |key: &GlobalKey| key_rect(tester, key).center().dy();
3904 assert_eq!(y_center(&app_bar_key), y_center(&leading_key));
3905 assert_eq!(y_center(&app_bar_key), y_center(&title_key));
3906 assert_eq!(y_center(&app_bar_key), y_center(&action0_key));
3907 assert_eq!(y_center(&app_bar_key), y_center(&action1_key));
3908 });
3909 }
3910
3911 fn drawer_icon_case<R: Send>(
3914 end: bool,
3915 theme: fn(&App) -> ThemeData,
3916 icon_theme: fn() -> Option<IconThemeData>,
3917 read: impl FnOnce(&WidgetTester) -> R + Send,
3918 ) -> R {
3919 let mut result = None;
3920 test_widgets(|tester| {
3921 pump_app(tester, theme, |_app| {
3922 let mut app_bar = AppBar::new().title(Text::new("Howdy!"));
3923 if let Some(icon_theme) = icon_theme() {
3924 app_bar = app_bar.icon_theme(icon_theme);
3925 }
3926 let scaffold = scaffold_with(app_bar);
3927 if end {
3928 scaffold.end_drawer(Drawer::new())
3929 } else {
3930 scaffold.drawer(Drawer::new())
3931 }
3932 .into_widget()
3933 });
3934 result = Some(read(tester));
3935 });
3936 result.expect("the case ran")
3937 }
3938
3939 fn light_scheme_theme(app: &App) -> ThemeData {
3940 ThemeData::from(crate::color_scheme::ColorScheme::light()).build(app)
3941 }
3942
3943 #[test]
3944 fn the_drawer_icon_has_the_default_size() {
3945 test_widgets(|_tester| {
3946 let size = drawer_icon_case(
3947 false,
3948 m3,
3949 || None,
3950 |tester| icon_size(tester, &Icons::menu()),
3951 );
3952 let icon_size = IconThemeData::fallback().size.expect("a size");
3953 assert_eq!(size, Size::new(icon_size, icon_size));
3954 });
3955 }
3956
3957 #[test]
3958 fn material3_the_drawer_icon_has_the_default_color() {
3959 test_widgets(|_tester| {
3960 let (color, expected) = drawer_icon_case(
3961 false,
3962 light_scheme_theme,
3963 || None,
3964 |tester| {
3965 let app = tester.cell.borrow();
3966 let expected = light_scheme_theme(&app).color_scheme.on_surface_variant();
3967 drop(app);
3968 (icon_color(tester, &Icons::menu()), expected)
3969 },
3970 );
3971 assert_eq!(color, Some(expected));
3972 });
3973 }
3974
3975 #[test]
3976 fn the_drawer_icon_is_sized_by_the_icon_theme() {
3977 test_widgets(|_tester| {
3978 let size = drawer_icon_case(
3979 false,
3980 m3,
3981 || Some(IconThemeData::new().size(30.0)),
3982 |tester| icon_size(tester, &Icons::menu()),
3983 );
3984 assert_eq!(size, Size::new(30.0, 30.0));
3985 });
3986 }
3987
3988 #[test]
3989 fn the_drawer_icon_is_colored_by_the_icon_theme() {
3990 test_widgets(|_tester| {
3991 const COLOR: Color = Color::new(0xFF2196F3);
3992 let color = drawer_icon_case(
3993 false,
3994 light_scheme_theme,
3995 || Some(IconThemeData::new().color(COLOR)),
3996 |tester| icon_color(tester, &Icons::menu()),
3997 );
3998 assert_eq!(color, Some(COLOR));
3999 });
4000 }
4001
4002 #[test]
4003 fn the_end_drawer_icon_has_the_default_size() {
4004 test_widgets(|_tester| {
4005 let size = drawer_icon_case(
4006 true,
4007 m3,
4008 || None,
4009 |tester| icon_size(tester, &Icons::menu()),
4010 );
4011 let icon_size = IconThemeData::fallback().size.expect("a size");
4012 assert_eq!(size, Size::new(icon_size, icon_size));
4013 });
4014 }
4015
4016 #[test]
4017 fn material3_the_end_drawer_icon_has_the_default_color() {
4018 test_widgets(|_tester| {
4019 let (color, expected) = drawer_icon_case(
4020 true,
4021 light_scheme_theme,
4022 || None,
4023 |tester| {
4024 let app = tester.cell.borrow();
4025 let expected = light_scheme_theme(&app).color_scheme.on_surface_variant();
4026 drop(app);
4027 (icon_color(tester, &Icons::menu()), expected)
4028 },
4029 );
4030 assert_eq!(color, Some(expected));
4031 });
4032 }
4033
4034 #[test]
4035 fn the_end_drawer_icon_is_sized_by_the_icon_theme() {
4036 test_widgets(|_tester| {
4037 let size = drawer_icon_case(
4038 true,
4039 m3,
4040 || Some(IconThemeData::new().size(30.0)),
4041 |tester| icon_size(tester, &Icons::menu()),
4042 );
4043 assert_eq!(size, Size::new(30.0, 30.0));
4044 });
4045 }
4046
4047 #[test]
4048 fn the_end_drawer_icon_is_colored_by_the_icon_theme() {
4049 test_widgets(|_tester| {
4050 const COLOR: Color = Color::new(0xFF2196F3);
4051 let color = drawer_icon_case(
4052 true,
4053 light_scheme_theme,
4054 || Some(IconThemeData::new().color(COLOR)),
4055 |tester| icon_color(tester, &Icons::menu()),
4056 );
4057 assert_eq!(color, Some(COLOR));
4058 });
4059 }
4060
4061 #[test]
4062 fn material3_the_leading_widget_extends_to_the_edge_and_is_square() {
4063 test_widgets(|tester| {
4064 pump_app(tester, m3, |_app| {
4065 scaffold_with(
4066 AppBar::new()
4067 .leading(IconButton::new(
4068 Some(Listener::new(|_| {})),
4069 Icon::new(Some(Icons::menu())),
4070 ))
4071 .title(Text::new("X")),
4072 )
4073 .drawer(waft_widgets::Column::new())
4075 .into_widget()
4076 });
4077 let hamburger = rect_of(tester, find::by_type::<IconButton>().evaluate(tester)[0]);
4079 assert_eq!(hamburger.top_left(), Offset::new(4.0, 4.0));
4080 assert_eq!(hamburger.size(), Size::new(48.0, 48.0));
4081
4082 let leading_key = GlobalKey::new();
4083 pump_app(tester, m3, |_app| {
4084 scaffold_with(
4085 AppBar::new()
4086 .leading(Container::new().key(leading_key.clone().into()))
4087 .title(Text::new("X")),
4088 )
4089 .into_widget()
4090 });
4091 let leading_box = key_rect(tester, &leading_key);
4093 assert_eq!(leading_box.top_left(), Offset::ZERO);
4094 assert_eq!(leading_box.size(), Size::new(56.0, 56.0));
4095
4096 let sized_key = GlobalKey::new();
4098 pump_app(tester, m3, |_app| {
4099 scaffold_with(
4100 AppBar::new()
4101 .leading(
4102 SizedBox::new()
4103 .height(36.0)
4104 .width(36.0)
4105 .key(sized_key.clone().into()),
4106 )
4107 .title(Text::new("X")),
4108 )
4109 .into_widget()
4110 });
4111 let leading = key_rect(tester, &sized_key);
4112 assert_eq!(leading.top_left(), Offset::ZERO);
4113 assert_eq!(leading.size(), Size::new(56.0, 56.0));
4114 });
4115 }
4116
4117 #[test]
4118 fn material3_an_action_is_4_from_the_edge_and_at_least_48() {
4119 test_widgets(|tester| {
4120 pump_app(tester, m3, |_app| {
4121 scaffold_with(AppBar::new().title(Text::new("X")).actions(vec![
4122 IconButton::new(None, Icon::new(Some(Icons::share())))
4123 .tooltip("Share")
4124 .icon_size(20.0)
4125 .into_widget(),
4126 IconButton::new(None, Icon::new(Some(Icons::add())))
4127 .tooltip("Add")
4128 .icon_size(60.0)
4129 .into_widget(),
4130 ]))
4131 .into_widget()
4132 });
4133 let add_button = rect_of(
4134 tester,
4135 tester.element(
4136 find::ancestor(find::by_icon(&Icons::add()), find::by_type::<IconButton>())
4137 .first(),
4138 ),
4139 );
4140 assert_eq!(add_button.top_right(), Offset::new(800.0, 0.0));
4141 assert_eq!(add_button.size(), Size::new(60.0 + 2.0 * 8.0, 56.0));
4143
4144 let share_button = rect_of(
4145 tester,
4146 tester.element(
4147 find::ancestor(
4148 find::by_icon(&Icons::share()),
4149 find::by_type::<IconButton>(),
4150 )
4151 .first(),
4152 ),
4153 );
4154 assert_eq!(share_button.size(), Size::new(48.0, 48.0));
4156 });
4157 }
4158
4159 fn elevation_case(theme: fn(&App) -> ThemeData, elevation: Option<f64>) -> f64 {
4160 let mut result = 0.0;
4161 test_widgets(|tester| {
4162 pump_app(tester, theme, |_app| {
4163 let mut app_bar = AppBar::new().title(Text::new("Title"));
4164 if let Some(elevation) = elevation {
4165 app_bar = app_bar.elevation(elevation);
4166 }
4167 scaffold_with(app_bar).into_widget()
4168 });
4169 result = app_bar_elevation(tester);
4170 });
4171 result
4172 }
4173
4174 #[test]
4175 fn material3_the_app_bar_uses_the_given_elevation_or_0() {
4176 assert_eq!(elevation_case(m3, None), 0.0);
4178 assert_eq!(elevation_case(m3, Some(8.0)), 8.0);
4180 }
4181
4182 #[test]
4183 fn material2_the_app_bar_uses_the_given_elevation_or_4() {
4184 assert_eq!(elevation_case(m2, None), 4.0);
4185 assert_eq!(elevation_case(m2, Some(8.0)), 8.0);
4186 }
4187
4188 fn hundred_items() -> WidgetRef {
4191 ListView::builder(|_app, _context, index| {
4192 Some(
4193 SizedBox::new()
4194 .height(56.0)
4195 .child(Text::new(format!("Item {index}")))
4196 .into_widget(),
4197 )
4198 })
4199 .item_count(100)
4200 .into_widget()
4201 }
4202
4203 #[test]
4204 fn the_scrolled_under_elevation_is_used_once_content_scrolls_under() {
4205 test_widgets(|tester| {
4206 pump_app(tester, m3, |_app| {
4207 scaffold_with(
4208 AppBar::new()
4209 .title(Text::new("Title"))
4210 .elevation(2.0)
4211 .scrolled_under_elevation(10.0),
4212 )
4213 .body(hundred_items())
4214 .into_widget()
4215 });
4216 assert_eq!(app_bar_elevation(tester), 2.0);
4218
4219 let start = tester.get_rect(find::text("Item 2")).center();
4220 tester.fling_from(start, Offset::new(0.0, -600.0), 2000.0, 1);
4221 tester.pump_and_settle();
4222
4223 assert_eq!(app_bar_elevation(tester), 10.0);
4225 });
4226 }
4227
4228 #[test]
4229 fn material3_the_scrolled_under_elevation_follows_a_nested_scroll_view_its_predicate_picks() {
4230 test_widgets(|tester| {
4231 pump_app(tester, m3, |_app| {
4232 scaffold_with(
4233 AppBar::new()
4234 .title(Text::new("Title"))
4235 .scrolled_under_elevation(10.0)
4236 .notification_predicate(Rc::new(|notification| notification.depth() == 1)),
4237 )
4238 .body(
4239 ListView::new()
4243 .scroll_direction(Axis::Horizontal)
4244 .children((0..4).map(|_| {
4245 SizedBox::new()
4246 .height(600.0)
4247 .width(800.0)
4248 .child(hundred_items())
4249 .into_widget()
4250 })),
4251 )
4252 .into_widget()
4253 });
4254 assert_eq!(app_bar_elevation(tester), 0.0);
4256
4257 let start = tester.get_rect(find::text("Item 2")).center();
4258 tester.fling_from(start, Offset::new(0.0, -600.0), 2000.0, 1);
4259 tester.pump_and_settle();
4260
4261 assert_eq!(app_bar_elevation(tester), 10.0);
4263 });
4264 }
4265
4266 fn top_padded(child: WidgetRef, padding: EdgeInsets) -> WidgetRef {
4268 waft_widgets::Localizations::new(
4269 waft_embedder::Locale::new("en").country_code("US"),
4270 vec![
4271 crate::material_localizations::DefaultMaterialLocalizations::delegate(),
4272 waft_widgets::DefaultWidgetsLocalizations::delegate(),
4273 ],
4274 )
4275 .child(Directionality::new(
4276 TextDirection::Ltr,
4277 MediaQuery::new(MediaQueryData::new().padding(padding), child).into_widget(),
4278 ))
4279 .into_widget()
4280 }
4281
4282 fn container_bottom(height: f64) -> PreferredSizeWidgetRef {
4283 PreferredSizeWidgetRef::new(PreferredSize::new(
4284 Size::from_height(height),
4285 Container::new(),
4286 ))
4287 }
4288
4289 #[test]
4290 fn the_app_bar_height_adds_the_bottom_and_the_top_padding_when_primary() {
4291 test_widgets(|tester| {
4292 let top_padding_100 = EdgeInsets::only(0.0, 100.0, 0.0, 0.0);
4293
4294 tester.pump_widget(top_padded(
4295 scaffold_with(AppBar::new()).primary(false).into_widget(),
4296 top_padding_100,
4297 ));
4298 assert_eq!(app_bar_rect(tester).top, 0.0);
4299 assert_eq!(app_bar_rect(tester).height(), K_TOOLBAR_HEIGHT);
4300
4301 tester.pump_widget(top_padded(
4302 scaffold_with(AppBar::new().title(Text::new("title"))).into_widget(),
4303 top_padding_100,
4304 ));
4305 assert_eq!(app_bar_rect(tester).top, 0.0);
4306 assert!(tester.get_rect(find::text("title")).top > 100.0);
4307 assert_eq!(app_bar_rect(tester).height(), K_TOOLBAR_HEIGHT + 100.0);
4308
4309 tester.pump_widget(top_padded(
4310 scaffold_with(AppBar::new().bottom(container_bottom(200.0)))
4311 .primary(false)
4312 .into_widget(),
4313 top_padding_100,
4314 ));
4315 assert_eq!(app_bar_rect(tester).top, 0.0);
4316 assert_eq!(app_bar_rect(tester).height(), K_TOOLBAR_HEIGHT + 200.0);
4317
4318 tester.pump_widget(top_padded(
4319 scaffold_with(AppBar::new().bottom(container_bottom(200.0))).into_widget(),
4320 top_padding_100,
4321 ));
4322 assert_eq!(app_bar_rect(tester).top, 0.0);
4323 assert_eq!(
4324 app_bar_rect(tester).height(),
4325 K_TOOLBAR_HEIGHT + 100.0 + 200.0
4326 );
4327
4328 tester.pump_widget(top_padded(
4329 AppBar::new()
4330 .primary(false)
4331 .title(Text::new("title"))
4332 .into_widget(),
4333 top_padding_100,
4334 ));
4335 assert_eq!(app_bar_rect(tester).top, 0.0);
4336 assert!(tester.get_rect(find::text("title")).top < 100.0);
4337 });
4338 }
4339
4340 #[test]
4341 fn an_app_bar_in_the_body_leaves_out_the_bottom_safe_area_padding() {
4342 test_widgets(|tester| {
4343 tester.pump_widget(top_padded(
4344 Scaffold::new()
4345 .body(
4346 waft_widgets::Column::new()
4347 .children([AppBar::new().title(Text::new("title")).into_widget()]),
4348 )
4349 .into_widget(),
4350 EdgeInsets::symmetric(100.0, 0.0),
4351 ));
4352 assert_eq!(app_bar_rect(tester).top, 0.0);
4353 assert_eq!(app_bar_rect(tester).height(), K_TOOLBAR_HEIGHT + 100.0);
4354 });
4355 }
4356
4357 #[test]
4358 fn the_title_sees_no_padding_from_the_media_query() {
4359 test_widgets(|tester| {
4360 let title_built = Rc::new(Cell::new(false));
4361 let seen_padding = Rc::new(Cell::new(None));
4362 let built = Rc::clone(&title_built);
4363 let seen = Rc::clone(&seen_padding);
4364 tester.pump_widget(top_padded(
4365 scaffold_with(AppBar::new().title(Builder::new(move |app, context| {
4366 built.set(true);
4367 seen.set(Some(MediaQuery::padding_of(app, context)));
4368 Text::new("heh").into_widget()
4369 })))
4370 .into_widget(),
4371 EdgeInsets::from_ltrb(12.0, 34.0, 56.0, 78.0),
4372 ));
4373 assert!(title_built.get());
4374 assert_eq!(seen_padding.get(), Some(EdgeInsets::ZERO));
4375 });
4376 }
4377
4378 #[test]
4379 fn the_app_bar_shows_a_menu_button_once_a_drawer_is_added() {
4380 test_widgets(|tester| {
4381 pump_app(tester, m3, |_app| {
4382 scaffold_with(AppBar::new()).into_widget()
4383 });
4384 assert_eq!(icon_count(tester, &Icons::menu()), 0);
4385 pump_app(tester, m3, |_app| {
4386 scaffold_with(AppBar::new())
4387 .drawer(Drawer::new())
4388 .into_widget()
4389 });
4390 assert_eq!(icon_count(tester, &Icons::menu()), 1);
4391 });
4392 }
4393
4394 #[test]
4395 fn no_menu_button_for_the_drawer_without_automatically_imply_leading() {
4396 test_widgets(|tester| {
4397 pump_app(tester, m3, |_app| {
4398 scaffold_with(AppBar::new().automatically_imply_leading(false))
4399 .drawer(Drawer::new())
4400 .into_widget()
4401 });
4402 assert_eq!(icon_count(tester, &Icons::menu()), 0);
4403 });
4404 }
4405
4406 #[test]
4407 fn no_menu_button_for_the_end_drawer_without_automatically_imply_actions() {
4408 test_widgets(|tester| {
4409 pump_app(tester, m3, |_app| {
4410 scaffold_with(AppBar::new().automatically_imply_actions(false))
4411 .end_drawer(Drawer::new())
4412 .into_widget()
4413 });
4414 assert_eq!(icon_count(tester, &Icons::menu()), 0);
4415 });
4416 }
4417
4418 #[test]
4419 fn a_menu_button_for_the_end_drawer_when_actions_are_implied() {
4420 test_widgets(|tester| {
4421 pump_app(tester, m3, |_app| {
4422 scaffold_with(AppBar::new())
4423 .end_drawer(Drawer::new())
4424 .into_widget()
4425 });
4426 assert_eq!(icon_count(tester, &Icons::menu()), 1);
4427 });
4428 }
4429
4430 #[test]
4431 fn given_actions_replace_the_end_drawer_menu_button() {
4432 test_widgets(|tester| {
4433 pump_app(tester, m3, |_app| {
4434 scaffold_with(
4435 AppBar::new().actions(vec![Icon::new(Some(Icons::settings())).into_widget()]),
4436 )
4437 .end_drawer(Drawer::new())
4438 .into_widget()
4439 });
4440 assert_eq!(icon_count(tester, &Icons::menu()), 0);
4441 assert_eq!(icon_count(tester, &Icons::settings()), 1);
4442 });
4443 }
4444
4445 #[test]
4446 fn the_app_bar_uses_its_toolbar_height() {
4447 test_widgets(|tester| {
4448 pump_app(tester, m3, |_app| {
4449 scaffold_with(AppBar::new().title(Text::new("Title")).toolbar_height(48.0))
4450 .body(Container::new())
4451 .into_widget()
4452 });
4453 assert_eq!(app_bar_rect(tester).height(), 48.0);
4454 });
4455 }
4456
4457 #[test]
4458 fn the_app_bar_uses_its_leading_width() {
4459 test_widgets(|tester| {
4460 let key = GlobalKey::new();
4461 pump_app(tester, m3, |_app| {
4462 scaffold_with(
4463 AppBar::new()
4464 .leading(placeholder(&key))
4465 .leading_width(100.0)
4466 .title(Text::new("Title")),
4467 )
4468 .into_widget()
4469 });
4470 assert_eq!(
4472 key_rect(tester, &key),
4473 Rect::from_ltrb(0.0, 0.0, 100.0, 56.0)
4474 );
4475 });
4476 }
4477
4478 #[test]
4479 fn an_end_drawer_gives_the_app_bar_no_leading() {
4480 test_widgets(|tester| {
4481 pump_app(tester, m3, |_app| {
4482 scaffold_with(AppBar::new())
4483 .end_drawer(Drawer::new())
4484 .into_widget()
4485 });
4486 let menu = tester.get_rect(find::by_icon(&Icons::menu())).center();
4487 tester.tap_at(menu, 1);
4488 tester.pump();
4489
4490 assert!(navigation_toolbar(tester, |toolbar| toolbar
4491 .leading
4492 .is_none()));
4493 });
4494 }
4495
4496 #[test]
4497 fn the_title_spacing_defaults_to_the_navigation_toolbars_middle_spacing() {
4498 test_widgets(|tester| {
4499 pump_app(tester, m3, |_app| {
4500 scaffold_with(AppBar::new().title(Text::new("Title"))).into_widget()
4501 });
4502 assert_eq!(
4503 navigation_toolbar(tester, |toolbar| toolbar.middle_spacing),
4504 NavigationToolbar::K_MIDDLE_SPACING
4505 );
4506 });
4507 }
4508
4509 #[test]
4510 fn the_foreground_and_background_colors_reach_the_material_texts_and_icons() {
4511 test_widgets(|tester| {
4512 const FOREGROUND_COLOR: Color = Color::new(0xff00ff00);
4513 const BACKGROUND_COLOR: Color = Color::new(0xff00ffff);
4514 let leading_icon_key = GlobalKey::new();
4515 let action_icon_key = GlobalKey::new();
4516 pump_app(tester, m3, |_app| {
4517 scaffold_with(
4518 AppBar::new()
4519 .foreground_color(FOREGROUND_COLOR)
4520 .background_color(BACKGROUND_COLOR)
4521 .leading(
4522 Icon::new(Some(Icons::add_circle()))
4523 .key(leading_icon_key.clone().into()),
4524 )
4525 .title(Text::new("title"))
4526 .actions(vec![
4527 Icon::new(Some(Icons::ac_unit()))
4528 .key(action_icon_key.clone().into())
4529 .into_widget(),
4530 Text::new("action").into_widget(),
4531 ]),
4532 )
4533 .into_widget()
4534 });
4535
4536 assert_eq!(app_bar_background_color(tester), Some(BACKGROUND_COLOR));
4537
4538 let title = find::text("title").evaluate(tester)[0];
4539 let title_style = tester.ancestor_of_type::<DefaultTextStyle>(title);
4540 assert_eq!(
4541 tester.widget(title_style, |style: &DefaultTextStyle| style
4542 .style
4543 .color
4544 .clone()),
4545 Some(AnyColor::from(FOREGROUND_COLOR))
4546 );
4547
4548 let icon_theme_color = |key: &GlobalKey| {
4549 let element = key
4550 .current_context(&tester.cell.borrow_mut())
4551 .expect("mounted");
4552 let theme = tester.ancestor_of_type::<IconTheme>(element);
4553 tester.widget(theme, |theme: &IconTheme| theme.data.color.clone())
4554 };
4555 assert_eq!(
4556 icon_theme_color(&leading_icon_key),
4557 Some(AnyColor::from(FOREGROUND_COLOR))
4558 );
4559 assert_eq!(
4560 icon_theme_color(&action_icon_key),
4561 Some(AnyColor::from(FOREGROUND_COLOR))
4562 );
4563
4564 assert_eq!(
4566 icon_color(tester, &Icons::add_circle()),
4567 Some(FOREGROUND_COLOR)
4568 );
4569 assert_eq!(
4570 icon_color(tester, &Icons::ac_unit()),
4571 Some(FOREGROUND_COLOR)
4572 );
4573 });
4574 }
4575
4576 fn overlay_style_case(
4577 theme: fn(&App) -> ThemeData,
4578 app_bar: fn() -> AppBar,
4579 ) -> Option<SystemUiOverlayStyle> {
4580 let mut result = None;
4581 test_widgets(|tester| {
4582 pump_app(tester, theme, |_app| scaffold_with(app_bar()).into_widget());
4583 result = latest_style(tester);
4584 });
4585 result
4586 }
4587
4588 #[test]
4589 fn material3_a_dark_background_draws_a_light_system_bar() {
4590 let style = overlay_style_case(
4591 |app| ThemeData::dark(app, None),
4592 || AppBar::new().title(Text::new("test")),
4593 );
4594 assert_eq!(
4595 style,
4596 Some(SystemUiOverlayStyle {
4597 status_bar_color: Some(Color::new(0x00000000)),
4598 status_bar_brightness: Some(Brightness::Dark),
4599 status_bar_icon_brightness: Some(Brightness::Light),
4600 ..SystemUiOverlayStyle::new()
4601 })
4602 );
4603 }
4604
4605 #[test]
4606 fn material3_a_light_background_draws_a_dark_system_bar() {
4607 let style = overlay_style_case(m3, || AppBar::new().title(Text::new("test")));
4608 assert_eq!(
4609 style,
4610 Some(SystemUiOverlayStyle {
4611 status_bar_color: Some(Color::new(0x00000000)),
4612 status_bar_brightness: Some(Brightness::Light),
4613 status_bar_icon_brightness: Some(Brightness::Dark),
4614 ..SystemUiOverlayStyle::new()
4615 })
4616 );
4617 }
4618
4619 #[test]
4620 fn material2_a_dark_background_draws_a_light_system_bar() {
4621 let style = overlay_style_case(
4622 |app| ThemeData::dark(app, Some(false)),
4623 || AppBar::new().title(Text::new("test")),
4624 );
4625 assert_eq!(
4626 style,
4627 Some(SystemUiOverlayStyle {
4628 status_bar_brightness: Some(Brightness::Dark),
4629 status_bar_icon_brightness: Some(Brightness::Light),
4630 ..SystemUiOverlayStyle::new()
4631 })
4632 );
4633 }
4634
4635 #[test]
4636 fn material2_a_light_background_draws_a_dark_system_bar() {
4637 let style = overlay_style_case(
4638 |app| {
4639 ThemeData::builder()
4640 .primary_swatch(crate::colors::Colors::LIGHT_BLUE)
4641 .use_material3(false)
4642 .build(app)
4643 },
4644 || AppBar::new().title(Text::new("test")),
4645 );
4646 assert_eq!(
4647 style,
4648 Some(SystemUiOverlayStyle {
4649 status_bar_brightness: Some(Brightness::Light),
4650 status_bar_icon_brightness: Some(Brightness::Dark),
4651 ..SystemUiOverlayStyle::new()
4652 })
4653 );
4654 }
4655
4656 #[test]
4657 fn material2_the_default_status_bar_color_is_none() {
4658 let style = overlay_style_case(
4659 |app| {
4660 ThemeData::builder()
4661 .use_material3(false)
4662 .app_bar_theme(AppBarThemeData::new())
4663 .build(app)
4664 },
4665 || AppBar::new().title(Text::new("title")),
4666 );
4667 assert_eq!(style.expect("a style").status_bar_color, None);
4668 }
4669
4670 #[test]
4671 fn the_system_overlay_style_styles_the_status_bar_and_the_navigation_bar() {
4672 let style = overlay_style_case(m3, || {
4673 AppBar::new()
4674 .title(Text::new("test"))
4675 .system_overlay_style(SystemUiOverlayStyle {
4676 status_bar_color: Some(crate::colors::Colors::RED.primary()),
4677 system_navigation_bar_color: Some(crate::colors::Colors::GREEN.primary()),
4678 ..SystemUiOverlayStyle::LIGHT
4679 })
4680 })
4681 .expect("a style");
4682 assert_eq!(
4683 style.status_bar_color,
4684 Some(crate::colors::Colors::RED.primary())
4685 );
4686 assert_eq!(
4687 style.system_navigation_bar_color,
4688 Some(crate::colors::Colors::GREEN.primary())
4689 );
4690 }
4691
4692 #[test]
4693 fn the_app_bar_has_no_shape_by_default() {
4694 test_widgets(|tester| {
4695 pump_app(tester, m3, |_app| {
4696 AppBar::new()
4697 .leading(Text::new("L"))
4698 .title(Text::new("No Scaffold"))
4699 .actions(vec![
4700 Text::new("A1").into_widget(),
4701 Text::new("A2").into_widget(),
4702 ])
4703 .into_widget()
4704 });
4705 let app_bar = find::by_type::<AppBar>().evaluate(tester)[0];
4706 assert!(tester.widget(app_bar, |app_bar: &AppBar| app_bar.shape.is_none()));
4707 assert!(app_bar_material(tester, |material| material
4708 .shape
4709 .is_none()));
4710 });
4711 }
4712
4713 #[test]
4714 fn the_app_bar_gives_its_shape_to_its_material() {
4715 test_widgets(|tester| {
4716 let rounded_rectangle_border = || {
4717 RoundedRectangleBorder::new(
4718 BorderSide::NONE,
4719 BorderRadiusGeometry::all(Radius::circular(15.0)),
4720 )
4721 };
4722 pump_app(tester, m3, |_app| {
4723 AppBar::new()
4724 .leading(Text::new("L"))
4725 .title(Text::new("No Scaffold"))
4726 .actions(vec![
4727 Text::new("A1").into_widget(),
4728 Text::new("A2").into_widget(),
4729 ])
4730 .shape(rounded_rectangle_border())
4731 .into_widget()
4732 });
4733 let expected: ShapeBorderRef = ShapeBorderRef::new(rounded_rectangle_border());
4734 let app_bar = find::by_type::<AppBar>().evaluate(tester)[0];
4735 assert!(
4736 tester.widget(app_bar, |app_bar: &AppBar| app_bar.shape.as_deref()
4737 == Some(&*expected))
4738 );
4739 assert!(app_bar_material(tester, |material| material
4740 .shape
4741 .as_deref()
4742 == Some(&*expected)));
4743 });
4744 }
4745
4746 #[test]
4747 fn preferred_height_for_reads_the_themes_toolbar_height_when_the_app_bar_gives_none() {
4748 test_widgets(|tester| {
4749 let preferred_height = Rc::new(Cell::new(0.0));
4750 let preferred_size = Rc::new(Cell::new(Size::ZERO));
4751 let frame = |tester: &mut WidgetTester,
4752 theme_toolbar_height: Option<f64>,
4753 app_bar_toolbar_height: Option<f64>| {
4754 let preferred_height = Rc::clone(&preferred_height);
4755 let preferred_size = Rc::clone(&preferred_size);
4756 pump_app(
4757 tester,
4758 |app| {
4759 let mut theme = AppBarThemeData::new();
4760 theme.toolbar_height = theme_toolbar_height;
4761 ThemeData::builder().app_bar_theme(theme).build(app)
4762 },
4763 move |_app| {
4764 Builder::new(move |app, context| {
4765 let mut app_bar = AppBar::new();
4766 app_bar.toolbar_height = app_bar_toolbar_height;
4767 let app_bar = PreferredSizeWidgetRef::new(app_bar);
4768 preferred_height.set(AppBar::preferred_height_for(
4769 app,
4770 context,
4771 &app_bar.preferred_size(),
4772 ));
4773 preferred_size.set(app_bar.preferred_size().size());
4774 Scaffold::new()
4775 .app_bar(app_bar)
4776 .body(SizedBox::expand())
4777 .into_widget()
4778 })
4779 .into_widget()
4780 },
4781 );
4782 tester.pump_and_settle();
4783 };
4784
4785 frame(tester, None, None);
4786 assert_eq!(app_bar_rect(tester).height(), K_TOOLBAR_HEIGHT);
4787 assert_eq!(preferred_height.get(), K_TOOLBAR_HEIGHT);
4788 assert_eq!(preferred_size.get().height(), K_TOOLBAR_HEIGHT);
4789
4790 frame(tester, Some(96.0), None);
4791 assert_eq!(app_bar_rect(tester).height(), 96.0);
4792 assert_eq!(preferred_height.get(), 96.0);
4793 assert_eq!(preferred_size.get().height(), K_TOOLBAR_HEIGHT);
4796
4797 frame(tester, None, Some(64.0));
4798 assert_eq!(app_bar_rect(tester).height(), 64.0);
4799 assert_eq!(preferred_height.get(), 64.0);
4800 assert_eq!(preferred_size.get().height(), 64.0);
4801
4802 frame(tester, Some(96.0), Some(64.0));
4803 assert_eq!(app_bar_rect(tester).height(), 64.0);
4804 assert_eq!(preferred_height.get(), 64.0);
4805 assert_eq!(preferred_size.get().height(), 64.0);
4806 });
4807 }
4808
4809 #[test]
4810 fn a_preferred_size_that_reuses_an_app_bars_size_still_reads_the_themes_toolbar_height() {
4811 test_widgets(|tester| {
4812 let preferred_height = Rc::new(Cell::new(0.0));
4813 let reused_height = Rc::clone(&preferred_height);
4814 pump_app(
4815 tester,
4816 |app| {
4817 let mut theme = AppBarThemeData::new();
4818 theme.toolbar_height = Some(96.0);
4819 ThemeData::builder().app_bar_theme(theme).build(app)
4820 },
4821 move |_app| {
4822 Builder::new(move |app, context| {
4823 let reused =
4824 PreferredSize::new(AppBar::new().preferred_size(), SizedBox::shrink());
4825 reused_height.set(AppBar::preferred_height_for(
4826 app,
4827 context,
4828 &reused.preferred_size(),
4829 ));
4830 SizedBox::expand().into_widget()
4831 })
4832 .into_widget()
4833 },
4834 );
4835 assert_eq!(preferred_height.get(), 96.0);
4836 });
4837 }
4838
4839 #[test]
4840 fn the_actions_padding_insets_the_actions_from_the_end() {
4841 test_widgets(|tester| {
4842 let app_bar_key = GlobalKey::new();
4843 let action_key = GlobalKey::new();
4844 let frame = |tester: &mut WidgetTester, actions_padding: Option<EdgeInsets>| {
4845 pump_app(tester, m3, |_app| {
4846 let mut app_bar = AppBar::new().key(app_bar_key.clone().into()).actions(vec![
4847 SizedBox::square(Some(40.0))
4848 .key(action_key.clone().into())
4849 .into_widget(),
4850 ]);
4851 if let Some(actions_padding) = actions_padding {
4852 app_bar = app_bar.actions_padding(actions_padding);
4853 }
4854 scaffold_with(app_bar).into_widget()
4855 });
4856 };
4857
4858 frame(tester, None);
4859 let app_bar_right = key_rect(tester, &app_bar_key).right;
4861 assert_eq!(app_bar_right - key_rect(tester, &action_key).right, 0.0);
4862
4863 let actions_padding = EdgeInsets::only(0.0, 0.0, 8.0, 0.0);
4864 frame(tester, Some(actions_padding));
4865 assert_eq!(
4866 key_rect(tester, &action_key).right,
4867 app_bar_right - actions_padding.right
4868 );
4869 });
4870 }
4871
4872 fn scrolled_under_app(
4874 content_height: f64,
4875 reverse: bool,
4876 include_flexible_space: bool,
4877 ) -> impl FnOnce(&mut App) -> WidgetRef {
4878 move |_app| {
4879 let mut app_bar = AppBar::new()
4880 .elevation(0.0)
4881 .background_color(scrolled_under_background())
4882 .title(Text::new("AppBar"));
4883 if include_flexible_space {
4884 app_bar = app_bar
4885 .flexible_space(FlexibleSpaceBar::new().title(Text::new("FlexibleSpace")));
4886 }
4887 scaffold_with(app_bar)
4888 .body(
4889 ListView::new().reverse(reverse).children([Container::new()
4890 .height(content_height)
4891 .color(crate::colors::Colors::TEAL.primary())
4892 .into_widget()]),
4893 )
4894 .into_widget()
4895 }
4896 }
4897
4898 const SCROLLED_COLOR: Color = Color::new(0xff00ff00);
4899 const DEFAULT_COLOR: Color = Color::new(0xff0000ff);
4900
4901 fn scrolled_under_background() -> AnyColor {
4902 WidgetStateColor::resolve_with(|states| {
4903 if states.contains(&WidgetState::ScrolledUnder) {
4904 SCROLLED_COLOR
4905 } else {
4906 DEFAULT_COLOR
4907 }
4908 })
4909 .into_any()
4910 }
4911
4912 fn move_by(tester: &mut WidgetTester, gesture: &mut TestPointer, by: Offset) {
4914 let at = gesture.position + by;
4915 tester.move_to(gesture, at, true);
4916 }
4917
4918 fn drag(tester: &mut WidgetTester, at: Offset, by: Offset, pointer: i64) {
4920 let mut gesture = TestPointer::touch(pointer);
4921 tester.down(&mut gesture, at);
4922 tester.move_to(&mut gesture, at + by, true);
4923 tester.up(&gesture);
4924 tester.pump_and_settle();
4925 }
4926
4927 fn app_bar_material_height(tester: &WidgetTester) -> f64 {
4928 let app_bar = find::by_type::<AppBar>().evaluate(tester)[0];
4929 let material = find::by_type::<Material>()
4930 .evaluate(tester)
4931 .into_iter()
4932 .find(|material| tester.ancestors(*material).contains(&app_bar))
4933 .expect("the app bar's Material");
4934 rect_of(tester, material).height()
4935 }
4936
4937 fn scrolled_under_background_case(include_flexible_space: bool) {
4939 test_widgets(|tester| {
4940 pump_app(
4941 tester,
4942 m3,
4943 scrolled_under_app(1200.0, false, include_flexible_space),
4944 );
4945
4946 assert_eq!(app_bar_background_color(tester), Some(DEFAULT_COLOR));
4947 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
4948
4949 drag(
4950 tester,
4951 Offset::new(50.0, 400.0),
4952 Offset::new(0.0, -K_TOOLBAR_HEIGHT),
4953 1,
4954 );
4955 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
4956 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
4957
4958 drag(
4959 tester,
4960 Offset::new(50.0, 300.0),
4961 Offset::new(0.0, K_TOOLBAR_HEIGHT),
4962 2,
4963 );
4964 assert_eq!(app_bar_background_color(tester), Some(DEFAULT_COLOR));
4965 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
4966 });
4967 }
4968
4969 #[test]
4970 fn a_widget_state_background_color_resolves_against_scrolled_under() {
4971 scrolled_under_background_case(false);
4972 }
4973
4974 #[test]
4975 fn a_widget_state_background_color_resolves_against_scrolled_under_with_a_flexible_space() {
4976 scrolled_under_background_case(true);
4977 }
4978
4979 fn reversed_scrolled_under_background_case(include_flexible_space: bool) {
4981 test_widgets(|tester| {
4982 pump_app(
4983 tester,
4984 m3,
4985 scrolled_under_app(1200.0, true, include_flexible_space),
4986 );
4987 tester.pump();
4988
4989 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
4992 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
4993
4994 drag(
4995 tester,
4996 Offset::new(50.0, 400.0),
4997 Offset::new(0.0, K_TOOLBAR_HEIGHT),
4998 1,
4999 );
5000 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
5001 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5002
5003 drag(
5004 tester,
5005 Offset::new(50.0, 300.0),
5006 Offset::new(0.0, -K_TOOLBAR_HEIGHT),
5007 2,
5008 );
5009 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
5010 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5011 });
5012 }
5013
5014 #[test]
5015 fn a_widget_state_background_color_stays_scrolled_under_in_a_long_reversed_list() {
5016 reversed_scrolled_under_background_case(false);
5017 }
5018
5019 #[test]
5020 fn a_widget_state_background_color_stays_scrolled_under_in_a_long_reversed_list_with_a_flexible_space()
5021 {
5022 reversed_scrolled_under_background_case(true);
5023 }
5024
5025 fn short_reversed_scrolled_under_background_case(include_flexible_space: bool) {
5028 test_widgets(|tester| {
5029 pump_app(
5030 tester,
5031 m3,
5032 scrolled_under_app(200.0, true, include_flexible_space),
5033 );
5034 tester.pump();
5035
5036 assert_eq!(app_bar_background_color(tester), Some(DEFAULT_COLOR));
5039 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5040
5041 drag(
5042 tester,
5043 Offset::new(50.0, 400.0),
5044 Offset::new(0.0, K_TOOLBAR_HEIGHT),
5045 1,
5046 );
5047 assert_eq!(app_bar_background_color(tester), Some(DEFAULT_COLOR));
5048 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5049 });
5050 }
5051
5052 #[test]
5053 fn a_widget_state_background_color_is_not_scrolled_under_in_reverse_for_short_content() {
5054 short_reversed_scrolled_under_background_case(false);
5055 }
5056
5057 #[test]
5058 fn a_widget_state_background_color_is_not_scrolled_under_in_reverse_for_short_content_with_a_flexible_space()
5059 {
5060 short_reversed_scrolled_under_background_case(true);
5061 }
5062
5063 #[test]
5064 fn horizontal_scrolling_does_not_change_the_scrolled_under_background_color() {
5065 test_widgets(|tester| {
5066 pump_app(tester, m3, |_app| {
5067 scaffold_with(
5068 AppBar::new()
5069 .elevation(0.0)
5070 .background_color(scrolled_under_background())
5071 .title(Text::new("AppBar"))
5072 .notification_predicate(Rc::new(|notification| {
5073 notification.depth() <= 1
5076 })),
5077 )
5078 .body(
5079 SingleChildScrollView::new().child(
5080 SingleChildScrollView::new()
5081 .scroll_direction(Axis::Horizontal)
5082 .child(
5083 Container::new()
5084 .height(1200.0)
5085 .width(1200.0)
5086 .color(crate::colors::Colors::TEAL.primary()),
5087 ),
5088 ),
5089 )
5090 .into_widget()
5091 });
5092 assert_eq!(app_bar_background_color(tester), Some(DEFAULT_COLOR));
5093 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5094
5095 let mut gesture = TestPointer::touch(1);
5096 tester.down(&mut gesture, Offset::new(50.0, 400.0));
5097 tester.move_to(
5098 &mut gesture,
5099 Offset::new(50.0, 400.0 - K_TOOLBAR_HEIGHT),
5100 true,
5101 );
5102 tester.pump();
5103 tester.move_to(
5104 &mut gesture,
5105 Offset::new(50.0, 400.0 - 2.0 * K_TOOLBAR_HEIGHT),
5106 true,
5107 );
5108 tester.up(&gesture);
5109 tester.pump_and_settle();
5110 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
5111 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5112
5113 let mut gesture = TestPointer::touch(2);
5114 tester.down(&mut gesture, Offset::new(50.0, 300.0));
5115 tester.move_to(
5117 &mut gesture,
5118 Offset::new(50.0 - K_TOOLBAR_HEIGHT, 300.0),
5119 true,
5120 );
5121 tester.pump();
5122 tester.move_to(
5123 &mut gesture,
5124 Offset::new(50.0 - 2.0 * K_TOOLBAR_HEIGHT, 300.0),
5125 true,
5126 );
5127 tester.up(&gesture);
5128 tester.pump_and_settle();
5129 assert_eq!(app_bar_background_color(tester), Some(SCROLLED_COLOR));
5132 assert_eq!(app_bar_material_height(tester), K_TOOLBAR_HEIGHT);
5133 });
5134 }
5135
5136 #[test]
5137 fn a_toolbar_opacity_fades_the_title_and_the_icons() {
5138 test_widgets(|tester| {
5139 pump_app(tester, m3, |_app| {
5140 scaffold_with(
5141 AppBar::new()
5142 .title(Text::new("title"))
5143 .icon_theme(IconThemeData::new().color(Color::new(0xFF000000)))
5144 .actions(vec![Icon::new(Some(Icons::add())).into_widget()])
5145 .toolbar_opacity(0.5),
5146 )
5147 .into_widget()
5148 });
5149 let opacity = Interval::new(0.25, 1.0, Curves::fast_out_slow_in()).transform(0.5);
5150 let title = find::text("title").evaluate(tester)[0];
5151 let title_style = tester.ancestor_of_type::<DefaultTextStyle>(title);
5152 let title_alpha = tester.widget(title_style, |style: &DefaultTextStyle| {
5153 style.style.color.as_ref().expect("a color").a
5154 });
5155 let app = tester.cell.borrow();
5156 let on_surface = ThemeData::new(&app).color_scheme.on_surface();
5157 drop(app);
5158 #[expect(
5159 deprecated,
5160 reason = "the app bar fades with the deprecated `withOpacity`"
5161 )]
5162 let expected_alpha = on_surface.with_opacity(opacity).a;
5163 assert_eq!(title_alpha, expected_alpha);
5164
5165 let add = tester.element(find::by_icon(&Icons::add()));
5166 let icon_theme = tester.ancestor_of_type::<IconTheme>(add);
5167 let icon_opacity = tester.widget(icon_theme, |theme: &IconTheme| theme.data.opacity);
5168 assert_eq!(icon_opacity, Some(opacity));
5169 });
5170 }
5171
5172 #[test]
5173 fn a_bottom_opacity_fades_the_bottom() {
5174 test_widgets(|tester| {
5175 pump_app(tester, m3, |_app| {
5176 scaffold_with(
5177 AppBar::new()
5178 .bottom(container_bottom(48.0))
5179 .bottom_opacity(0.5),
5180 )
5181 .into_widget()
5182 });
5183 let opacity = find::by_type::<Opacity>().evaluate(tester);
5184 assert_eq!(opacity.len(), 1);
5185 assert_eq!(
5186 tester.widget(opacity[0], |opacity: &Opacity| opacity.opacity),
5187 Interval::new(0.25, 1.0, Curves::fast_out_slow_in()).transform(0.5)
5188 );
5189 });
5190 }
5191
5192 #[derive(Clone, Copy)]
5197 struct SliverAppBarApp {
5198 floating: bool,
5199 pinned: bool,
5200 collapsed_height: Option<f64>,
5201 expanded_height: Option<f64>,
5202 snap: bool,
5203 toolbar_height: f64,
5204 }
5205
5206 impl Default for SliverAppBarApp {
5207 fn default() -> SliverAppBarApp {
5208 SliverAppBarApp {
5209 floating: false,
5210 pinned: false,
5211 collapsed_height: None,
5212 expanded_height: None,
5213 snap: false,
5214 toolbar_height: K_TOOLBAR_HEIGHT,
5215 }
5216 }
5217 }
5218
5219 struct SliverAppBarAppHandles {
5221 controller: Handle<ScrollController>,
5222 tab_bar_key: GlobalKey,
5223 }
5224
5225 fn pump_sliver_app_bar_app(
5228 tester: &mut WidgetTester,
5229 arguments: SliverAppBarApp,
5230 ) -> SliverAppBarAppHandles {
5231 let controller = ScrollController::default(&mut tester.cell.borrow_mut());
5232 let tab_bar_key = GlobalKey::new();
5233 let bottom_key = tab_bar_key.clone();
5234 pump_app(tester, m3, {
5235 let controller = controller.clone();
5236 move |_app| {
5237 let mut sliver_app_bar = SliverAppBar::new()
5238 .title(Text::new("AppBar Title"))
5239 .floating(arguments.floating)
5240 .pinned(arguments.pinned)
5241 .toolbar_height(arguments.toolbar_height)
5242 .snap(arguments.snap)
5243 .bottom(PreferredSizeWidgetRef::new(
5244 TabBar::new(
5245 ["A", "B", "C"]
5246 .map(|t| Tab::new().text(format!("TAB {t}")).into_widget()),
5247 )
5248 .key(bottom_key.into()),
5249 ));
5250 sliver_app_bar.collapsed_height = arguments.collapsed_height;
5251 sliver_app_bar.expanded_height = arguments.expanded_height;
5252 Scaffold::new()
5253 .body(DefaultTabController::new(
5254 3,
5255 CustomScrollView::new()
5256 .controller(controller.erase())
5257 .slivers([
5258 sliver_app_bar.into_widget(),
5259 SliverToBoxAdapter::new()
5260 .child(
5261 Container::new()
5262 .height(1200.0)
5263 .color(crate::colors::Colors::ORANGE.shade400()),
5264 )
5265 .into_widget(),
5266 ]),
5267 ))
5268 .into_widget()
5269 }
5270 });
5271 SliverAppBarAppHandles {
5272 controller: controller.handle(),
5273 tab_bar_key,
5274 }
5275 }
5276
5277 fn jump_to(tester: &mut WidgetTester, controller: Handle<ScrollController>, value: f64) {
5278 controller.jump_to(&mut tester.cell.borrow_mut(), value);
5279 tester.pump();
5280 }
5281
5282 fn scroll_offset(tester: &WidgetTester, controller: Handle<ScrollController>) -> f64 {
5283 controller.as_controller().offset(&tester.cell.borrow())
5284 }
5285
5286 fn sliver_app_bar_geometry(tester: &WidgetTester) -> waft_rendering::SliverGeometry {
5288 let sliver_app_bar = find::by_type::<SliverAppBar>().evaluate(tester)[0];
5289 let app = tester.cell.borrow();
5290 sliver_app_bar
5291 .find_render_object(&app)
5292 .and_then(|render| render.as_sliver())
5293 .expect("a SliverAppBar renders a sliver")
5294 .geometry(&app)
5295 }
5296
5297 fn sliver_app_bar_is_onstage(tester: &WidgetTester) -> bool {
5299 find::by_type::<SliverAppBar>().evaluate(tester).len() == 1
5300 }
5301
5302 fn tab_bar_height(tester: &WidgetTester, handles: &SliverAppBarAppHandles) -> f64 {
5303 key_rect(tester, &handles.tab_bar_key).height()
5304 }
5305
5306 #[test]
5307 fn the_default_sliver_app_bar_scrolls_out_of_view_at_its_height() {
5308 test_widgets(|tester| {
5309 let handles = pump_sliver_app_bar_app(tester, SliverAppBarApp::default());
5310 assert_eq!(scroll_offset(tester, handles.controller), 0.0);
5311 assert!(sliver_app_bar_is_onstage(tester));
5312
5313 let initial_app_bar_height = app_bar_rect(tester).height();
5314 let initial_tab_bar_height = tab_bar_height(tester, &handles);
5315
5316 jump_to(tester, handles.controller, 50.0);
5318 assert!(sliver_app_bar_is_onstage(tester));
5319 assert_eq!(app_bar_rect(tester).height(), initial_app_bar_height);
5320 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5321
5322 jump_to(tester, handles.controller, 600.0);
5324 assert!(!sliver_app_bar_is_onstage(tester));
5325 assert_eq!(app_bar_rect(tester).height(), initial_app_bar_height);
5326 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5327
5328 jump_to(tester, handles.controller, 0.0);
5330 assert!(sliver_app_bar_is_onstage(tester));
5331 assert_eq!(app_bar_rect(tester).height(), initial_app_bar_height);
5332 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5333 });
5334 }
5335
5336 #[test]
5337 fn a_pinned_sliver_app_bar_collapses_its_expanded_height_but_keeps_the_toolbar() {
5338 test_widgets(|tester| {
5339 let handles = pump_sliver_app_bar_app(
5340 tester,
5341 SliverAppBarApp {
5342 pinned: true,
5343 expanded_height: Some(128.0),
5344 ..SliverAppBarApp::default()
5345 },
5346 );
5347 assert_eq!(scroll_offset(tester, handles.controller), 0.0);
5348 assert!(sliver_app_bar_is_onstage(tester));
5349 assert_eq!(app_bar_rect(tester).height(), 128.0);
5350
5351 const INITIAL_APP_BAR_HEIGHT: f64 = 128.0;
5352 let initial_tab_bar_height = tab_bar_height(tester, &handles);
5353
5354 jump_to(tester, handles.controller, 600.0);
5357 assert!(sliver_app_bar_is_onstage(tester));
5358 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5359 assert!(app_bar_rect(tester).height() < INITIAL_APP_BAR_HEIGHT);
5360 assert!(app_bar_rect(tester).height() > initial_tab_bar_height);
5361
5362 jump_to(tester, handles.controller, 0.0);
5364 assert!(sliver_app_bar_is_onstage(tester));
5365 assert_eq!(app_bar_rect(tester).height(), INITIAL_APP_BAR_HEIGHT);
5366 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5367 });
5368 }
5369
5370 #[test]
5371 fn a_pinned_and_floating_sliver_app_bar_collapses_to_its_bottom() {
5372 test_widgets(|tester| {
5373 let handles = pump_sliver_app_bar_app(
5374 tester,
5375 SliverAppBarApp {
5376 floating: true,
5377 pinned: true,
5378 expanded_height: Some(128.0),
5379 ..SliverAppBarApp::default()
5380 },
5381 );
5382 assert_eq!(scroll_offset(tester, handles.controller), 0.0);
5383 assert!(sliver_app_bar_is_onstage(tester));
5384 assert_eq!(app_bar_rect(tester).height(), 128.0);
5385
5386 const INITIAL_APP_BAR_HEIGHT: f64 = 128.0;
5387 let initial_tab_bar_height = tab_bar_height(tester, &handles);
5388
5389 jump_to(tester, handles.controller, 600.0);
5392 assert!(sliver_app_bar_is_onstage(tester));
5393 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5394 assert!(app_bar_rect(tester).height() < INITIAL_APP_BAR_HEIGHT);
5395 assert_eq!(app_bar_rect(tester).height(), initial_tab_bar_height);
5396
5397 jump_to(tester, handles.controller, 0.0);
5399 assert!(sliver_app_bar_is_onstage(tester));
5400 assert_eq!(app_bar_rect(tester).height(), INITIAL_APP_BAR_HEIGHT);
5401 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5402 });
5403 }
5404
5405 #[test]
5406 fn a_floating_sliver_app_bar_with_snap_snaps_open_and_closed() {
5407 test_widgets(|tester| {
5408 let handles = pump_sliver_app_bar_app(
5409 tester,
5410 SliverAppBarApp {
5411 floating: true,
5412 snap: true,
5413 expanded_height: Some(128.0),
5414 ..SliverAppBarApp::default()
5415 },
5416 );
5417 assert!(sliver_app_bar_is_onstage(tester));
5418 assert_eq!(app_bar_rect(tester).top, 0.0);
5419 assert_eq!(app_bar_rect(tester).height(), 128.0);
5420 assert_eq!(app_bar_rect(tester).bottom, 128.0);
5421
5422 handles
5424 .controller
5425 .jump_to(&mut tester.cell.borrow_mut(), 256.0);
5426 tester.pump_and_settle();
5427 assert!(!sliver_app_bar_is_onstage(tester));
5428 assert!(app_bar_rect(tester).top <= -128.0);
5429
5430 let mut gesture = TestPointer::touch(1);
5433 tester.down(&mut gesture, Offset::new(50.0, 256.0));
5434 move_by(tester, &mut gesture, Offset::new(0.0, 128.0));
5436 tester.pump();
5437 assert_eq!(app_bar_rect(tester).top, 0.0);
5438 assert_eq!(app_bar_rect(tester).height(), 128.0);
5439
5440 move_by(tester, &mut gesture, Offset::new(0.0, -50.0));
5441 tester.pump();
5442 assert_eq!(app_bar_rect(tester).bottom, 78.0); move_by(tester, &mut gesture, Offset::new(0.0, 10.0));
5446 tester.up(&gesture);
5447
5448 tester.pump();
5450 tester.pump_by(Duration::from_millis(50));
5451 let bottom = app_bar_rect(tester).bottom;
5452 assert!(bottom > 88.0); tester.pump();
5455 tester.pump_by(Duration::from_millis(50));
5456 assert!(app_bar_rect(tester).bottom > bottom);
5457
5458 tester.pump_and_settle();
5460 assert_eq!(app_bar_rect(tester).height(), 128.0);
5461
5462 let mut gesture = TestPointer::touch(2);
5466 tester.down(&mut gesture, Offset::new(50.0, 256.0));
5467 move_by(tester, &mut gesture, Offset::new(0.0, -128.0));
5469 tester.pump();
5470 assert_eq!(app_bar_rect(tester).bottom, 0.0);
5471
5472 move_by(tester, &mut gesture, Offset::new(0.0, 100.0));
5473 tester.pump();
5474 assert_eq!(app_bar_rect(tester).bottom, 100.0);
5475
5476 move_by(tester, &mut gesture, Offset::new(0.0, -10.0));
5478 tester.up(&gesture);
5479
5480 tester.pump();
5482 tester.pump_by(Duration::from_millis(50));
5483 let bottom = app_bar_rect(tester).bottom;
5484 assert!(bottom < 90.0);
5485
5486 tester.pump();
5487 tester.pump_by(Duration::from_millis(50));
5488 assert!(app_bar_rect(tester).bottom < bottom);
5489
5490 tester.pump_and_settle();
5492 assert!(app_bar_rect(tester).top <= 0.0);
5493 assert!(app_bar_rect(tester).bottom <= 0.0);
5494 });
5495 }
5496
5497 #[test]
5498 fn a_floating_and_pinned_sliver_app_bar_with_snap_snaps_to_its_pinned_height() {
5499 test_widgets(|tester| {
5500 let handles = pump_sliver_app_bar_app(
5501 tester,
5502 SliverAppBarApp {
5503 floating: true,
5504 pinned: true,
5505 snap: true,
5506 expanded_height: Some(128.0),
5507 ..SliverAppBarApp::default()
5508 },
5509 );
5510 assert!(sliver_app_bar_is_onstage(tester));
5511 assert_eq!(app_bar_rect(tester).top, 0.0);
5512 assert_eq!(app_bar_rect(tester).height(), 128.0);
5513 assert_eq!(app_bar_rect(tester).bottom, 128.0);
5514
5515 handles
5518 .controller
5519 .jump_to(&mut tester.cell.borrow_mut(), 256.0);
5520 tester.pump_and_settle();
5521 assert!(sliver_app_bar_is_onstage(tester));
5522 assert_eq!(app_bar_rect(tester).top, 0.0);
5523 assert_eq!(app_bar_rect(tester).height(), K_TEXT_TAB_BAR_HEIGHT);
5524
5525 let mut gesture = TestPointer::touch(1);
5528 tester.down(&mut gesture, Offset::new(50.0, 200.0));
5529 move_by(tester, &mut gesture, Offset::new(0.0, 100.0));
5530 tester.pump();
5531 assert_eq!(app_bar_rect(tester).height(), 100.0);
5532
5533 move_by(tester, &mut gesture, Offset::new(0.0, -25.0));
5534 tester.pump();
5535 assert_eq!(app_bar_rect(tester).height(), 75.0);
5536
5537 move_by(tester, &mut gesture, Offset::new(0.0, 10.0));
5539 tester.up(&gesture);
5540
5541 tester.pump();
5543 tester.pump_by(Duration::from_millis(50));
5544 let height = app_bar_rect(tester).height();
5545 assert!(height > 85.0);
5546 assert!(height < 128.0);
5547
5548 tester.pump();
5549 tester.pump_by(Duration::from_millis(50));
5550 assert!(app_bar_rect(tester).height() > height);
5551 assert!(app_bar_rect(tester).height() < 128.0);
5552
5553 tester.pump_and_settle();
5555 assert_eq!(app_bar_rect(tester).top, 0.0);
5556 assert_eq!(app_bar_rect(tester).height(), 128.0);
5557 assert_eq!(app_bar_rect(tester).bottom, 128.0);
5558
5559 let mut gesture = TestPointer::touch(2);
5563 tester.down(&mut gesture, Offset::new(50.0, 256.0));
5564 move_by(tester, &mut gesture, Offset::new(0.0, -128.0));
5565 tester.pump();
5566 assert_eq!(app_bar_rect(tester).bottom, K_TEXT_TAB_BAR_HEIGHT);
5567
5568 move_by(tester, &mut gesture, Offset::new(0.0, 100.0));
5569 tester.pump();
5570 assert_eq!(app_bar_rect(tester).bottom, 100.0);
5571
5572 move_by(tester, &mut gesture, Offset::new(0.0, -10.0));
5574 tester.up(&gesture);
5575
5576 tester.pump();
5578 tester.pump_by(Duration::from_millis(50));
5579 let bottom = app_bar_rect(tester).bottom;
5580 assert!(bottom < 90.0);
5581
5582 tester.pump();
5583 tester.pump_by(Duration::from_millis(50));
5584 assert!(app_bar_rect(tester).bottom < bottom);
5585
5586 tester.pump_and_settle();
5588 assert!(app_bar_rect(tester).top <= 0.0);
5589 assert_eq!(app_bar_rect(tester).bottom, K_TEXT_TAB_BAR_HEIGHT);
5590 });
5591 }
5592
5593 #[test]
5594 fn a_sliver_app_bar_scrolls_from_its_expanded_height_to_its_collapsed_height() {
5595 test_widgets(|tester| {
5596 const EXPANDED_APP_BAR_HEIGHT: f64 = 400.0;
5597 const COLLAPSED_APP_BAR_HEIGHT: f64 = 200.0;
5598 let handles = pump_sliver_app_bar_app(
5599 tester,
5600 SliverAppBarApp {
5601 collapsed_height: Some(COLLAPSED_APP_BAR_HEIGHT),
5602 expanded_height: Some(EXPANDED_APP_BAR_HEIGHT),
5603 ..SliverAppBarApp::default()
5604 },
5605 );
5606 assert_eq!(scroll_offset(tester, handles.controller), 0.0);
5607 assert!(sliver_app_bar_is_onstage(tester));
5608 assert_eq!(app_bar_rect(tester).height(), EXPANDED_APP_BAR_HEIGHT);
5609
5610 let initial_tab_bar_height = tab_bar_height(tester, &handles);
5611
5612 jump_to(tester, handles.controller, 50.0);
5614 assert!(sliver_app_bar_is_onstage(tester));
5615 assert_eq!(
5616 app_bar_rect(tester).height(),
5617 EXPANDED_APP_BAR_HEIGHT - 50.0
5618 );
5619 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5620
5621 jump_to(tester, handles.controller, 600.0);
5623 assert!(!sliver_app_bar_is_onstage(tester));
5624 assert_eq!(
5625 app_bar_rect(tester).height(),
5626 COLLAPSED_APP_BAR_HEIGHT + initial_tab_bar_height
5627 );
5628 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5629
5630 jump_to(tester, handles.controller, 0.0);
5632 assert!(sliver_app_bar_is_onstage(tester));
5633 assert_eq!(app_bar_rect(tester).height(), EXPANDED_APP_BAR_HEIGHT);
5634 assert_eq!(tab_bar_height(tester, &handles), initial_tab_bar_height);
5635 });
5636 }
5637
5638 fn collapsed_height_case(arguments: SliverAppBarApp, expected_without_bottom: f64) {
5639 test_widgets(|tester| {
5640 let handles = pump_sliver_app_bar_app(tester, arguments);
5641 let initial_tab_bar_height = tab_bar_height(tester, &handles);
5642
5643 jump_to(tester, handles.controller, 300.0);
5645 assert!(!sliver_app_bar_is_onstage(tester));
5646 assert_eq!(
5647 app_bar_rect(tester).height(),
5648 expected_without_bottom + initial_tab_bar_height
5649 );
5650 });
5651 }
5652
5653 #[test]
5654 fn the_default_collapsed_height_is_the_toolbar_height_and_the_bottom() {
5655 collapsed_height_case(
5658 SliverAppBarApp {
5659 toolbar_height: 100.0,
5660 ..SliverAppBarApp::default()
5661 },
5662 100.0,
5663 );
5664 }
5665
5666 #[test]
5667 fn a_collapsed_height_with_a_toolbar_height_collapses_to_the_collapsed_height() {
5668 collapsed_height_case(
5669 SliverAppBarApp {
5670 toolbar_height: 100.0,
5671 collapsed_height: Some(150.0),
5672 ..SliverAppBarApp::default()
5673 },
5674 150.0,
5675 );
5676 }
5677
5678 #[test]
5679 fn a_collapsed_height_collapses_to_itself_and_the_bottom() {
5680 collapsed_height_case(
5681 SliverAppBarApp {
5682 collapsed_height: Some(56.0),
5683 ..SliverAppBarApp::default()
5684 },
5685 56.0,
5686 );
5687 }
5688
5689 fn medium_or_large_defaults_case(
5694 sliver_app_bar: fn() -> SliverAppBar,
5695 expanded_app_bar_height: f64,
5696 expanded_title_bottom: fn(&WidgetTester, Rect) -> f64,
5697 ) {
5698 test_widgets(|tester| {
5699 const COLLAPSED_APP_BAR_HEIGHT: f64 = 64.0;
5700 let controller = ScrollController::default(&mut tester.cell.borrow_mut());
5701 pump_app(tester, m3, {
5702 let controller = controller.clone();
5703 move |_app| {
5704 Scaffold::new()
5705 .body(
5706 CustomScrollView::new()
5707 .controller(controller.erase())
5708 .slivers([
5709 sliver_app_bar()
5710 .title(Text::new("AppBar Title"))
5711 .into_widget(),
5712 SliverToBoxAdapter::new()
5713 .child(
5714 Container::new()
5715 .height(1200.0)
5716 .color(crate::colors::Colors::ORANGE.shade400()),
5717 )
5718 .into_widget(),
5719 ]),
5720 )
5721 .into_widget()
5722 }
5723 });
5724
5725 let titles = find::text("AppBar Title").evaluate(tester);
5731 let expanded_title = titles[0];
5732 let collapsed_title = *titles.last().expect("two titles");
5733 let expanded_title_clip = tester.ancestor_of_type::<ClipRect>(expanded_title);
5734 let collapsed_title_opacity =
5735 tester.ancestor_of_type::<AnimatedOpacity>(collapsed_title);
5736 let opacity = |tester: &WidgetTester| {
5737 tester.widget(collapsed_title_opacity, |opacity: &AnimatedOpacity| {
5738 opacity.opacity
5739 })
5740 };
5741 let clip_height = |tester: &WidgetTester| rect_of(tester, expanded_title_clip).height();
5742
5743 assert_eq!(scroll_offset(tester, controller.handle()), 0.0);
5745 assert!(sliver_app_bar_is_onstage(tester));
5746 assert_eq!(app_bar_rect(tester).height(), expanded_app_bar_height);
5747 assert_eq!(opacity(tester), 0.0);
5748 assert_eq!(
5749 clip_height(tester),
5750 expanded_app_bar_height - COLLAPSED_APP_BAR_HEIGHT
5751 );
5752
5753 let title_rect = rect_of(tester, expanded_title);
5755 assert_eq!(title_rect.left, 16.0);
5756 let expected_bottom = expanded_title_bottom(tester, title_rect);
5757 assert!(
5759 (title_rect.bottom - expected_bottom).abs() < 1e-4,
5760 "{} is not {expected_bottom}",
5761 title_rect.bottom
5762 );
5763
5764 let clip_rect = rect_of(tester, expanded_title_clip);
5766 assert!((clip_rect.top..=clip_rect.bottom).contains(&title_rect.top));
5767 assert!((clip_rect.top..=clip_rect.bottom).contains(&title_rect.bottom));
5768 assert!((clip_rect.left..=clip_rect.right).contains(&title_rect.left));
5769 assert!((clip_rect.left..=clip_rect.right).contains(&title_rect.right));
5770
5771 let on_surface = ThemeData::new(&tester.cell.borrow())
5773 .color_scheme
5774 .on_surface();
5775 assert_eq!(tester.text_color("AppBar Title"), on_surface);
5776
5777 jump_to(tester, controller.handle(), 45.0);
5779 assert!(sliver_app_bar_is_onstage(tester));
5780 assert_eq!(
5781 app_bar_rect(tester).height(),
5782 expanded_app_bar_height - 45.0
5783 );
5784 assert_eq!(opacity(tester), 0.0);
5785 assert_eq!(
5786 clip_height(tester),
5787 expanded_app_bar_height - COLLAPSED_APP_BAR_HEIGHT - 45.0
5788 );
5789
5790 jump_to(tester, controller.handle(), 600.0);
5792 assert!(sliver_app_bar_is_onstage(tester));
5793 assert_eq!(app_bar_rect(tester).height(), COLLAPSED_APP_BAR_HEIGHT);
5794 assert_eq!(opacity(tester), 1.0);
5795 assert_eq!(clip_height(tester), 0.0);
5796
5797 controller.jump_to(&mut tester.cell.borrow_mut(), 0.0);
5799 tester.pump_and_settle();
5800 assert!(sliver_app_bar_is_onstage(tester));
5801 assert_eq!(app_bar_rect(tester).height(), expanded_app_bar_height);
5802 assert_eq!(opacity(tester), 0.0);
5803 assert_eq!(
5804 clip_height(tester),
5805 expanded_app_bar_height - COLLAPSED_APP_BAR_HEIGHT
5806 );
5807 });
5808 }
5809
5810 #[test]
5811 fn material3_a_medium_sliver_app_bar_expands_its_title_below_the_toolbar() {
5812 medium_or_large_defaults_case(SliverAppBar::medium, 112.0, |_tester, _title| 96.0);
5815 }
5816
5817 fn medium_or_large_with_bottom_case(
5819 sliver_app_bar: fn() -> SliverAppBar,
5820 expanded_app_bar_height: f64,
5821 title: &'static str,
5822 collapse_to: f64,
5823 ) {
5824 test_widgets(|tester| {
5825 const COLLAPSED_APP_BAR_HEIGHT: f64 = 64.0;
5827 const BOTTOM_HEIGHT: f64 = 48.0;
5828 let controller = ScrollController::default(&mut tester.cell.borrow_mut());
5829 let tab_bar_key = GlobalKey::new();
5830 let bottom_key = tab_bar_key.clone();
5831 pump_app(tester, m3, {
5832 let controller = controller.clone();
5833 move |_app| {
5834 DefaultTabController::new(
5835 3,
5836 Scaffold::new().body(
5837 CustomScrollView::new()
5838 .controller(controller.erase())
5839 .slivers([
5840 sliver_app_bar()
5841 .leading(IconButton::new(
5842 Some(Listener::new(|_app| {})),
5843 Icon::new(Some(Icons::menu())),
5844 ))
5845 .title(Text::new(title))
5846 .bottom(PreferredSizeWidgetRef::new(
5847 TabBar::new(
5848 ["Tab 1", "Tab 2", "Tab 3"]
5849 .map(|tab| Tab::new().text(tab).into_widget()),
5850 )
5851 .key(bottom_key.into()),
5852 ))
5853 .into_widget(),
5854 SliverToBoxAdapter::new()
5855 .child(
5856 Container::new()
5857 .height(1200.0)
5858 .color(crate::colors::Colors::ORANGE.shade400()),
5859 )
5860 .into_widget(),
5861 ]),
5862 ),
5863 )
5864 .into_widget()
5865 }
5866 });
5867
5868 assert_eq!(find::by_type::<SliverAppBar>().evaluate(tester).len(), 1);
5869 assert_eq!(
5870 app_bar_rect(tester).height(),
5871 expanded_app_bar_height + BOTTOM_HEIGHT
5872 );
5873
5874 let expanded_title_offset = tester.get_bottom_left(find::text(title).first());
5875 let tab_offset = tester.get_top_left(find::by_type::<TabBar>());
5876 assert_f32_equals(expanded_title_offset.dy(), tab_offset.dy());
5877
5878 controller.jump_to(&mut tester.cell.borrow_mut(), collapse_to);
5880 tester.pump_and_settle();
5881
5882 assert_eq!(
5883 app_bar_rect(tester).height(),
5884 COLLAPSED_APP_BAR_HEIGHT + BOTTOM_HEIGHT
5885 );
5886 });
5887 }
5888
5889 #[test]
5891 fn a_medium_sliver_app_bar_puts_its_expanded_title_on_its_tab_bar() {
5892 medium_or_large_with_bottom_case(SliverAppBar::medium, 112.0, "Medium App Bar", 160.0);
5893 }
5894
5895 #[test]
5897 fn a_large_sliver_app_bar_puts_its_expanded_title_on_its_tab_bar() {
5898 medium_or_large_with_bottom_case(SliverAppBar::large, 152.0, "Large App Bar", 200.0);
5899 }
5900
5901 #[test]
5902 fn material3_a_large_sliver_app_bar_expands_its_title_28_above_its_bottom() {
5903 test_widgets(|_tester| {
5904 medium_or_large_defaults_case(SliverAppBar::large, 152.0, |tester, _title| {
5905 sliver_app_bar_geometry(tester).scroll_extent - 28.0
5907 });
5908 });
5909 }
5910
5911 fn pump_elevated_sliver_app_bar(
5913 tester: &mut WidgetTester,
5914 force_elevated: bool,
5915 elevation: Option<f64>,
5916 theme_elevation: Option<f64>,
5917 ) {
5918 pump_app(
5919 tester,
5920 move |app| {
5921 let mut app_bar_theme = AppBarThemeData::new();
5922 app_bar_theme.elevation = theme_elevation;
5923 app_bar_theme.scrolled_under_elevation = theme_elevation;
5924 ThemeData::builder().app_bar_theme(app_bar_theme).build(app)
5925 },
5926 move |_app| {
5927 let mut sliver_app_bar = SliverAppBar::new()
5928 .title(Text::new("Title"))
5929 .force_elevated(force_elevated);
5930 sliver_app_bar.elevation = elevation;
5931 sliver_app_bar.scrolled_under_elevation = elevation;
5932 CustomScrollView::new()
5933 .slivers([sliver_app_bar.into_widget()])
5934 .into_widget()
5935 },
5936 );
5937 }
5938
5939 #[test]
5940 fn a_sliver_app_bar_is_elevated_only_when_forced_or_scrolled_under() {
5941 test_widgets(|tester| {
5942 let app_bar_elevation_field = |tester: &WidgetTester| {
5943 let app_bar = find::by_type::<AppBar>().evaluate(tester)[0];
5944 tester.widget(app_bar, |app_bar: &AppBar| app_bar.elevation)
5945 };
5946
5947 pump_elevated_sliver_app_bar(tester, false, None, None);
5949 assert_eq!(app_bar_elevation(tester), 0.0);
5950
5951 pump_elevated_sliver_app_bar(tester, true, None, None);
5956 assert_eq!(app_bar_elevation(tester), 3.0);
5957 assert_eq!(app_bar_elevation_field(tester), None);
5958
5959 pump_elevated_sliver_app_bar(tester, true, Some(8.0), None);
5961 assert_eq!(app_bar_elevation(tester), 8.0);
5962 });
5963 }
5964
5965 #[test]
5966 fn a_sliver_app_bar_takes_its_elevation_from_the_app_bar_theme() {
5967 test_widgets(|tester| {
5968 pump_elevated_sliver_app_bar(tester, false, None, Some(12.0));
5969 assert_eq!(app_bar_elevation(tester), 0.0);
5970
5971 pump_elevated_sliver_app_bar(tester, true, None, Some(12.0));
5972 assert_eq!(app_bar_elevation(tester), 12.0);
5973
5974 pump_elevated_sliver_app_bar(tester, true, Some(8.0), Some(12.0));
5975 assert_eq!(app_bar_elevation(tester), 8.0);
5976 });
5977 }
5978
5979 #[test]
5980 fn changing_snap_from_true_to_false_keeps_the_floating_bar_working() {
5981 test_widgets(|tester| {
5982 const APP_BAR_HEIGHT: f64 = 256.0;
5983 let snap = Rc::new(Cell::new(true));
5984 let button_key = GlobalKey::new();
5985 let snap_for_build = Rc::clone(&snap);
5986 let key = button_key.clone();
5987 pump_app(tester, m3, move |_app| {
5988 waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
5989 let snap = Rc::clone(&snap_for_build);
5990 let set_state = set_state.clone();
5991 let button = crate::text_button::TextButton::new(
5992 Some(Listener::new(move |app| {
5993 let snap = Rc::clone(&snap);
5994 set_state(app, &mut move |_app| snap.set(false));
5995 })),
5996 Some(Text::new("snap=false")),
5997 )
5998 .key(key.clone().into());
5999 Scaffold::new()
6000 .body(
6001 CustomScrollView::new().slivers([
6002 SliverAppBar::new()
6003 .expanded_height(APP_BAR_HEIGHT)
6004 .floating(true)
6005 .snap(snap_for_build.get())
6006 .actions(vec![button.into_widget()])
6007 .flexible_space(
6008 FlexibleSpaceBar::new().background(
6009 Container::new()
6010 .height(APP_BAR_HEIGHT)
6011 .color(crate::colors::Colors::ORANGE.primary()),
6012 ),
6013 )
6014 .into_widget(),
6015 SliverToBoxAdapter::new()
6016 .child(
6017 Container::new()
6018 .height(1200.0)
6019 .color(crate::colors::Colors::TEAL.primary()),
6020 )
6021 .into_widget(),
6022 ]),
6023 )
6024 .into_widget()
6025 })
6026 .into_widget()
6027 });
6028
6029 let mut gesture = TestPointer::touch(1);
6030 tester.down(&mut gesture, Offset::new(50.0, 400.0));
6031 tester.move_to(&mut gesture, Offset::new(50.0, 300.0), true);
6032 tester.up(&gesture);
6033
6034 let at = tester.get_center(&button_key);
6035 tester.tap_at(at, 2);
6036 tester.pump_and_settle();
6037 assert!(!snap.get());
6038
6039 let mut gesture = TestPointer::touch(3);
6040 tester.down(&mut gesture, Offset::new(50.0, 400.0));
6041 tester.move_to(&mut gesture, Offset::new(50.0, 300.0), true);
6042 tester.up(&gesture);
6043 tester.pump();
6044 });
6045 }
6046
6047 #[test]
6048 fn a_sliver_app_bar_gives_its_delegate_a_show_on_screen_configuration_only_when_it_snaps() {
6049 test_widgets(|tester| {
6050 for (pinned, floating, snap) in [
6051 (false, true, false),
6052 (false, true, true),
6053 (true, true, false),
6054 (true, true, true),
6055 ] {
6056 pump_app(tester, m3, move |_app| {
6057 CustomScrollView::new()
6058 .slivers([SliverAppBar::new()
6059 .title(Text::new("Jumbo"))
6060 .pinned(pinned)
6061 .floating(floating)
6062 .snap(snap)
6063 .into_widget()])
6064 .into_widget()
6065 });
6066 let header = find::by_type::<SliverPersistentHeader>().evaluate(tester)[0];
6067 let (vsync, snap_configuration, show_on_screen_configuration) =
6068 tester.widget(header, |header: &SliverPersistentHeader| {
6069 (
6070 header.delegate.vsync().is_some(),
6071 header.delegate.snap_configuration().is_some(),
6072 header.delegate.show_on_screen_configuration().is_some(),
6073 )
6074 });
6075
6076 if !floating || (!snap_configuration && !show_on_screen_configuration) {
6078 assert!(vsync);
6079 }
6080 assert_eq!(show_on_screen_configuration, snap && floating);
6081 }
6082 });
6083 }
6084
6085 #[test]
6086 fn a_sliver_app_bar_uses_its_leading_width() {
6087 test_widgets(|tester| {
6088 let key = GlobalKey::new();
6089 pump_app(tester, m3, |_app| {
6090 CustomScrollView::new()
6091 .slivers([SliverAppBar::new()
6092 .leading(placeholder(&key))
6093 .leading_width(100.0)
6094 .title(Text::new("Title"))
6095 .into_widget()])
6096 .into_widget()
6097 });
6098 assert_eq!(
6100 key_rect(tester, &key),
6101 Rect::from_ltrb(0.0, 0.0, 100.0, 56.0)
6102 );
6103 });
6104 }
6105
6106 #[test]
6107 fn a_sliver_app_bars_title_spacing_defaults_to_the_middle_spacing() {
6108 test_widgets(|tester| {
6109 pump_sliver_app_bar_app(tester, SliverAppBarApp::default());
6110 assert_eq!(
6111 navigation_toolbar(tester, |toolbar| toolbar.middle_spacing),
6112 NavigationToolbar::K_MIDDLE_SPACING
6113 );
6114 });
6115 }
6116
6117 fn slow_drag(tester: &mut WidgetTester, key: &GlobalKey, offset: Offset, pointer: i64) {
6123 let target = tester.get_center(key);
6124 let mut gesture = TestPointer::touch(pointer);
6125 tester.down(&mut gesture, target);
6126 tester.move_to(&mut gesture, target + offset, true);
6127 tester.pump_by(Duration::from_millis(10));
6128 tester.up(&gesture);
6129 }
6130
6131 fn pump_stretching_sliver_app_bar(
6134 tester: &mut WidgetTester,
6135 anchor: &GlobalKey,
6136 physics: waft_widgets::ScrollPhysicsRef,
6137 stretch_trigger_offset: Option<f64>,
6138 ) -> Rc<Cell<bool>> {
6139 let did_trigger = Rc::new(Cell::new(false));
6140 let triggered = Rc::clone(&did_trigger);
6141 let anchor = anchor.clone();
6142 pump_app(tester, m3, move |_app| {
6143 let mut sliver_app_bar = SliverAppBar::new()
6144 .stretch(true)
6145 .expanded_height(100.0)
6146 .on_stretch_trigger(Rc::new(move |_app| {
6147 triggered.set(true);
6148 Task::ready(())
6149 }));
6150 if let Some(stretch_trigger_offset) = stretch_trigger_offset {
6151 sliver_app_bar = sliver_app_bar.stretch_trigger_offset(stretch_trigger_offset);
6152 }
6153 CustomScrollView::new()
6154 .physics(physics)
6155 .slivers([
6156 sliver_app_bar.into_widget(),
6157 SliverToBoxAdapter::new()
6158 .child(Container::new().key(anchor.into()).height(800.0))
6159 .into_widget(),
6160 SliverToBoxAdapter::new()
6161 .child(Container::new().height(800.0))
6162 .into_widget(),
6163 ])
6164 .into_widget()
6165 });
6166 did_trigger
6167 }
6168
6169 #[test]
6170 fn a_stretching_sliver_app_bar_triggers_past_the_default_offset() {
6171 test_widgets(|tester| {
6172 let anchor = GlobalKey::new();
6173 let did_trigger = pump_stretching_sliver_app_bar(
6174 tester,
6175 &anchor,
6176 Rc::new(waft_widgets::BouncingScrollPhysics::new()),
6177 None,
6178 );
6179
6180 slow_drag(tester, &anchor, Offset::new(0.0, 50.0), 1);
6181 assert!(!did_trigger.get());
6182 tester.pump_and_settle();
6183 slow_drag(tester, &anchor, Offset::new(0.0, 150.0), 2);
6184 assert!(did_trigger.get());
6185 });
6186 }
6187
6188 #[test]
6189 fn a_stretching_sliver_app_bar_triggers_past_a_custom_offset() {
6190 test_widgets(|tester| {
6191 let anchor = GlobalKey::new();
6192 let did_trigger = pump_stretching_sliver_app_bar(
6193 tester,
6194 &anchor,
6195 Rc::new(waft_widgets::BouncingScrollPhysics::new()),
6196 Some(150.0),
6197 );
6198
6199 slow_drag(tester, &anchor, Offset::new(0.0, 100.0), 1);
6200 tester.pump_and_settle();
6201 assert!(!did_trigger.get());
6202 slow_drag(tester, &anchor, Offset::new(0.0, 300.0), 2);
6203 assert!(did_trigger.get());
6204 });
6205 }
6206
6207 #[test]
6208 fn a_stretching_sliver_app_bar_does_not_trigger_without_overscroll_physics() {
6209 test_widgets(|tester| {
6210 let anchor = GlobalKey::new();
6211 let did_trigger = pump_stretching_sliver_app_bar(
6212 tester,
6213 &anchor,
6214 Rc::new(waft_widgets::ClampingScrollPhysics::new()),
6215 Some(150.0),
6216 );
6217
6218 slow_drag(tester, &anchor, Offset::new(0.0, 100.0), 1);
6219 tester.pump_and_settle();
6220 assert!(!did_trigger.get());
6221 slow_drag(tester, &anchor, Offset::new(0.0, 300.0), 2);
6222 assert!(!did_trigger.get());
6223 });
6224 }
6225
6226 fn app_bar_theme() -> AppBarThemeData {
6231 use crate::colors::Colors;
6232 AppBarThemeData::new()
6233 .actions_icon_theme(IconThemeData::new().color(Colors::PINK.primary()))
6234 .system_overlay_style(SystemUiOverlayStyle::DARK)
6235 .background_color(Colors::LIGHT_BLUE.primary())
6236 .elevation(6.0)
6237 .shadow_color(Colors::RED.primary())
6238 .surface_tint_color(Colors::GREEN.primary())
6239 .shape(waft_painting::StadiumBorder::default())
6240 .icon_theme(IconThemeData::new().color(Colors::BLACK))
6241 .toolbar_height(96.0)
6242 .toolbar_text_style(TextStyle::new().color(Colors::YELLOW.primary()))
6243 .title_text_style(TextStyle::new().color(Colors::PINK.primary()))
6244 }
6245
6246 fn first_below<A: 'static, W: 'static>(tester: &WidgetTester) -> AnyElement {
6249 let ancestor = *find::by_type::<A>()
6250 .evaluate(tester)
6251 .first()
6252 .expect("an ancestor");
6253 find::by_type::<W>()
6254 .evaluate(tester)
6255 .into_iter()
6256 .find(|element| tester.ancestors(*element).contains(&ancestor))
6257 .expect("a descendant of that type")
6258 }
6259
6260 fn app_bar_icon_theme(tester: &WidgetTester) -> IconThemeData {
6262 tester.widget(
6263 first_below::<AppBar, IconTheme>(tester),
6264 |theme: &IconTheme| theme.data.clone(),
6265 )
6266 }
6267
6268 fn app_bar_actions_icon_theme(tester: &WidgetTester) -> IconThemeData {
6270 tester.widget(
6271 first_below::<NavigationToolbar, IconTheme>(tester),
6272 |theme: &IconTheme| theme.data.clone(),
6273 )
6274 }
6275
6276 fn app_bar_icon_color(tester: &WidgetTester) -> Option<Color> {
6278 tester
6279 .glyph_style(
6280 *find::by_type::<Icon>()
6281 .evaluate(tester)
6282 .first()
6283 .expect("an Icon"),
6284 )
6285 .color
6286 .map(|color| color.color())
6287 }
6288
6289 fn app_bar_text_style(tester: &WidgetTester) -> TextStyle {
6291 tester.widget(
6292 first_below::<CustomSingleChildLayout, DefaultTextStyle>(tester),
6293 |style: &DefaultTextStyle| style.style.clone(),
6294 )
6295 }
6296
6297 fn share_action() -> Vec<WidgetRef> {
6298 vec![
6299 IconButton::new(Some(Listener::new(|_| {})), Icon::new(Some(Icons::share())))
6300 .into_widget(),
6301 ]
6302 }
6303
6304 fn status_bar_brightness(tester: &WidgetTester) -> Option<Brightness> {
6305 latest_style(tester).expect("a style").status_bar_brightness
6306 }
6307
6308 #[test]
6309 fn the_app_bar_uses_the_values_of_the_app_bar_theme() {
6310 test_widgets(|tester| {
6311 pump_app(
6312 tester,
6313 |app| {
6314 ThemeData::builder()
6315 .app_bar_theme(app_bar_theme())
6316 .build(app)
6317 },
6318 |_app| {
6319 scaffold_with(
6320 AppBar::new()
6321 .title(Text::new("App Bar Title"))
6322 .actions(share_action()),
6323 )
6324 .into_widget()
6325 },
6326 );
6327 let theme = app_bar_theme();
6328
6329 assert_eq!(status_bar_brightness(tester), Some(Brightness::Light));
6330 app_bar_material(tester, |material| {
6331 assert_eq!(material.color, theme.background_color);
6332 assert_eq!(Some(material.elevation), theme.elevation);
6333 assert_eq!(material.shadow_color, theme.shadow_color);
6334 assert_eq!(material.surface_tint_color, theme.surface_tint_color);
6335 assert!(
6336 material.shape.as_deref()
6337 == Some(&waft_painting::StadiumBorder::default() as &dyn ShapeBorder)
6338 );
6339 });
6340 assert_eq!(Some(app_bar_icon_theme(tester)), theme.icon_theme);
6341 assert_eq!(
6342 Some(app_bar_actions_icon_theme(tester)),
6343 theme.actions_icon_theme
6344 );
6345 assert_eq!(
6346 app_bar_icon_color(tester),
6347 theme
6348 .actions_icon_theme
6349 .as_ref()
6350 .and_then(|icon_theme| icon_theme.color.as_ref())
6351 .map(|color| color.color())
6352 );
6353 assert_eq!(Some(app_bar_text_style(tester)), theme.toolbar_text_style);
6354 assert_eq!(Some(app_bar_rect(tester).height()), theme.toolbar_height);
6355 assert_eq!(app_bar_rect(tester).width(), 800.0);
6356 });
6357 }
6358
6359 #[test]
6360 fn the_app_bars_properties_take_priority_over_the_theme() {
6361 test_widgets(|tester| {
6362 use crate::colors::Colors;
6363 let shape = || RoundedRectangleBorder::default();
6364 pump_app(
6365 tester,
6366 |app| {
6367 ThemeData::from(crate::color_scheme::ColorScheme::light())
6368 .build(app)
6369 .copy_with()
6370 .app_bar_theme(app_bar_theme())
6371 .build()
6372 },
6373 move |_app| {
6374 scaffold_with(
6375 AppBar::new()
6376 .background_color(Colors::ORANGE.primary())
6377 .system_overlay_style(SystemUiOverlayStyle::LIGHT)
6378 .elevation(3.0)
6379 .shadow_color(Colors::PURPLE.primary())
6380 .surface_tint_color(Colors::BROWN.primary())
6381 .shape(shape())
6382 .icon_theme(IconThemeData::new().color(Colors::GREEN.primary()))
6383 .actions_icon_theme(
6384 IconThemeData::new().color(Colors::LIGHT_BLUE.primary()),
6385 )
6386 .toolbar_text_style(TextStyle::new().color(Colors::PINK.primary()))
6387 .title_text_style(TextStyle::new().color(Colors::ORANGE.primary()))
6388 .actions(share_action()),
6389 )
6390 .into_widget()
6391 },
6392 );
6393
6394 assert_eq!(status_bar_brightness(tester), Some(Brightness::Dark));
6395 app_bar_material(tester, |material| {
6396 assert_eq!(material.color, Some(Colors::ORANGE.primary()));
6397 assert_eq!(material.elevation, 3.0);
6398 assert_eq!(material.shadow_color, Some(Colors::PURPLE.primary()));
6399 assert_eq!(material.surface_tint_color, Some(Colors::BROWN.primary()));
6400 assert!(material.shape.as_deref() == Some(&shape() as &dyn ShapeBorder));
6401 });
6402 assert_eq!(
6403 app_bar_icon_theme(tester),
6404 IconThemeData::new().color(Colors::GREEN.primary())
6405 );
6406 assert_eq!(
6407 app_bar_actions_icon_theme(tester),
6408 IconThemeData::new().color(Colors::LIGHT_BLUE.primary())
6409 );
6410 assert_eq!(
6411 app_bar_icon_color(tester),
6412 Some(Colors::LIGHT_BLUE.primary())
6413 );
6414 assert_eq!(
6415 app_bar_text_style(tester),
6416 TextStyle::new().color(Colors::PINK.primary())
6417 );
6418 });
6419 }
6420
6421 #[test]
6422 fn an_icon_buttons_color_takes_priority_over_every_icon_theme() {
6423 test_widgets(|tester| {
6424 use crate::colors::Colors;
6425 pump_app(tester, light_scheme_theme, |_app| {
6426 scaffold_with(
6427 AppBar::new()
6428 .icon_theme(IconThemeData::new().color(Colors::GREEN.primary()))
6429 .actions_icon_theme(
6430 IconThemeData::new().color(Colors::LIGHT_BLUE.primary()),
6431 )
6432 .actions(vec![
6433 IconButton::new(
6434 Some(Listener::new(|_| {})),
6435 Icon::new(Some(Icons::share())),
6436 )
6437 .color(Colors::LIME.primary())
6438 .into_widget(),
6439 ]),
6440 )
6441 .into_widget()
6442 });
6443 assert_eq!(app_bar_icon_color(tester), Some(Colors::LIME.primary()));
6444 });
6445 }
6446
6447 #[test]
6448 fn the_app_bar_theme_takes_priority_over_the_theme_datas_colors() {
6449 test_widgets(|tester| {
6450 pump_app(
6451 tester,
6452 |app| {
6453 ThemeData::from(crate::color_scheme::ColorScheme::light())
6454 .build(app)
6455 .copy_with()
6456 .app_bar_theme(app_bar_theme())
6457 .build()
6458 },
6459 |_app| scaffold_with(AppBar::new().actions(share_action())).into_widget(),
6460 );
6461 let theme = app_bar_theme();
6462
6463 assert_eq!(status_bar_brightness(tester), Some(Brightness::Light));
6464 app_bar_material(tester, |material| {
6465 assert_eq!(material.color, theme.background_color);
6466 assert_eq!(Some(material.elevation), theme.elevation);
6467 assert_eq!(material.shadow_color, theme.shadow_color);
6468 assert_eq!(material.surface_tint_color, theme.surface_tint_color);
6469 });
6470 assert_eq!(Some(app_bar_icon_theme(tester)), theme.icon_theme);
6471 assert_eq!(
6472 Some(app_bar_actions_icon_theme(tester)),
6473 theme.actions_icon_theme
6474 );
6475 assert_eq!(
6476 app_bar_icon_color(tester),
6477 theme
6478 .actions_icon_theme
6479 .as_ref()
6480 .and_then(|icon_theme| icon_theme.color.as_ref())
6481 .map(|color| color.color())
6482 );
6483 assert_eq!(Some(app_bar_text_style(tester)), theme.toolbar_text_style);
6484 });
6485 }
6486
6487 fn themed_toolbar<R>(
6488 theme: fn() -> AppBarThemeData,
6489 platform: TargetPlatform,
6490 app_bar: fn() -> AppBar,
6491 read: fn(&NavigationToolbar) -> R,
6492 ) -> R
6493 where
6494 R: Send,
6495 {
6496 let mut result = None;
6497 test_widgets(|tester| {
6498 pump_app(
6499 tester,
6500 move |app| {
6501 ThemeData::builder()
6502 .platform(platform)
6503 .app_bar_theme(theme())
6504 .build(app)
6505 },
6506 move |_app| scaffold_with(app_bar()).into_widget(),
6507 );
6508 result = Some(navigation_toolbar(tester, read));
6509 });
6510 result.expect("the case ran")
6511 }
6512
6513 #[test]
6514 fn the_app_bar_uses_the_themes_center_title_when_it_gives_none() {
6515 let center_middle = themed_toolbar(
6516 || AppBarThemeData::new().center_title(true),
6517 TargetPlatform::Android,
6518 || AppBar::new().title(Text::new("Title")),
6519 |toolbar| toolbar.center_middle,
6520 );
6521 assert!(center_middle);
6522 }
6523
6524 #[test]
6525 fn the_app_bars_center_title_takes_priority_over_the_themes() {
6526 let center_middle = themed_toolbar(
6527 || AppBarThemeData::new().center_title(true),
6528 TargetPlatform::Android,
6529 || AppBar::new().title(Text::new("Title")).center_title(false),
6530 |toolbar| toolbar.center_middle,
6531 );
6532 assert!(!center_middle);
6534 }
6535
6536 #[test]
6537 fn center_title_adapts_to_the_platform_without_one_in_the_theme() {
6538 let center_middle = themed_toolbar(
6539 AppBarThemeData::new,
6540 TargetPlatform::IOS,
6541 || AppBar::new().title(Text::new("Title")),
6542 |toolbar| toolbar.center_middle,
6543 );
6544 assert!(center_middle);
6547 }
6548
6549 #[test]
6550 fn the_app_bar_uses_the_themes_title_spacing() {
6551 let middle_spacing = themed_toolbar(
6552 || AppBarThemeData::new().title_spacing(10.0),
6553 TargetPlatform::Android,
6554 || AppBar::new().title(Text::new("Title")),
6555 |toolbar| toolbar.middle_spacing,
6556 );
6557 assert_eq!(middle_spacing, 10.0);
6558 }
6559
6560 #[test]
6561 fn the_app_bars_title_spacing_takes_priority_over_the_themes() {
6562 let middle_spacing = themed_toolbar(
6563 || AppBarThemeData::new().title_spacing(10.0),
6564 TargetPlatform::Android,
6565 || AppBar::new().title(Text::new("Title")).title_spacing(40.0),
6566 |toolbar| toolbar.middle_spacing,
6567 );
6568 assert_eq!(middle_spacing, 40.0);
6569 }
6570
6571 fn leading_constraints(toolbar: &NavigationToolbar) -> (f64, f64) {
6574 let leading = toolbar.leading.as_ref().expect("a leading widget");
6575 let constraints = downcast_widget::<ConstrainedBox>(&**leading)
6576 .expect("a ConstrainedBox")
6577 .constraints;
6578 (constraints.min_width, constraints.max_width)
6579 }
6580
6581 #[test]
6582 fn the_app_bar_uses_the_themes_leading_width() {
6583 let (min_width, max_width) = themed_toolbar(
6584 || AppBarThemeData::new().leading_width(80.0),
6585 TargetPlatform::Android,
6586 || AppBar::new().leading(Icon::new(Some(Icons::chevron_left()))),
6587 leading_constraints,
6588 );
6589 assert_eq!(max_width, 80.0);
6590 assert_eq!(min_width, 80.0);
6591 }
6592
6593 #[test]
6594 fn the_app_bars_leading_width_takes_priority_over_the_themes() {
6595 let (min_width, max_width) = themed_toolbar(
6596 || AppBarThemeData::new().leading_width(80.0),
6597 TargetPlatform::Android,
6598 || {
6599 AppBar::new()
6600 .leading(Icon::new(Some(Icons::chevron_left())))
6601 .leading_width(40.0)
6602 },
6603 leading_constraints,
6604 );
6605 assert_eq!(max_width, 40.0);
6606 assert_eq!(min_width, 40.0);
6607 }
6608
6609 fn leading_size_case<W: 'static>(leading: fn(KeyRef) -> WidgetRef) {
6613 test_widgets(|tester| {
6614 const TITLE_SPACING: f64 = 16.0;
6615 let leading_key = GlobalKey::new();
6616 let title_key = GlobalKey::new();
6617 pump_app(tester, m3, |_app| {
6618 scaffold_with(
6619 AppBar::new()
6620 .leading(leading(leading_key.clone().into()))
6621 .center_title(false)
6622 .title(Text::new("Title").key(title_key.clone().into())),
6623 )
6624 .into_widget()
6625 });
6626
6627 let button = find::by_type::<W>().evaluate(tester)[0];
6628 let button_rect = rect_of(tester, button);
6629 assert_eq!(button_rect.size(), Size::new(48.0, 48.0));
6630
6631 let mut gesture = TestPointer::mouse(1, 0);
6632 tester.add_pointer(&mut gesture, Offset::ZERO);
6633 tester.move_to(&mut gesture, button_rect.center(), false);
6634 tester.pump_and_settle();
6635 let on_surface = ThemeData::new(&tester.cell.borrow())
6636 .color_scheme
6637 .on_surface();
6638 #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
6639 let hover_color = on_surface.with_opacity(0.08);
6640 let ops = tester.painted_ops(tester.render_box_of(button).as_object());
6641 assert_paints(
6642 &ops,
6643 &[PaintCall::rect_at(
6644 Rect::from_ltrb(0.0, 0.0, 40.0, 40.0),
6645 Some(hover_color),
6646 )],
6647 );
6648
6649 let center = tester.ancestor_of_type::<waft_widgets::Center>(button);
6651 let back_button_right = rect_of(tester, center).right;
6652 let title_left = key_rect(tester, &title_key).left;
6653 assert_eq!(title_left, back_button_right + TITLE_SPACING);
6654 });
6655 }
6656
6657 #[test]
6658 fn a_custom_icon_button_leading_is_48_square_and_centered() {
6659 leading_size_case::<IconButton>(|key| {
6660 IconButton::new(Some(Listener::new(|_| {})), Icon::new(Some(Icons::menu())))
6661 .key(key)
6662 .into_widget()
6663 });
6664 }
6665
6666 #[test]
6667 fn a_custom_back_button_leading_is_48_square_and_centered() {
6668 leading_size_case::<BackButton>(|key| {
6669 BackButton::new()
6670 .key(key)
6671 .on_pressed(Listener::new(|_| {}))
6672 .into_widget()
6673 });
6674 }
6675
6676 #[test]
6677 fn a_custom_close_button_leading_is_48_square_and_centered() {
6678 leading_size_case::<CloseButton>(|key| {
6679 CloseButton::new()
6680 .key(key)
6681 .on_pressed(Listener::new(|_| {}))
6682 .into_widget()
6683 });
6684 }
6685
6686 #[test]
6687 fn a_custom_drawer_button_leading_is_48_square_and_centered() {
6688 leading_size_case::<DrawerButton>(|key| {
6689 DrawerButton::new()
6690 .key(key)
6691 .on_pressed(Listener::new(|_| {}))
6692 .into_widget()
6693 });
6694 }
6695
6696 #[test]
6699 fn a_title_box_fills_the_properties_it_inherits() {
6700 use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
6701
6702 let cell = AppCell::new();
6703 let mut app = cell.borrow_mut();
6704 let title_box = RenderAppBarTitleBox::new(&mut app, Some(TextDirection::Ltr));
6705 let mut properties = DiagnosticPropertiesBuilder::new();
6706 RenderObject::debug_fill_properties(title_box, &app, &mut properties);
6707 let names: Vec<&str> = properties
6708 .properties
6709 .iter()
6710 .filter_map(|property| property.name())
6711 .collect();
6712 assert_eq!(names, ["alignment", "textDirection"]);
6713 }
6714}