1use std::fmt;
4use std::rc::Rc;
5use std::time::Duration;
6use waft_foundation::{App, Handle, Listenable, Listener, Ref, UniqueKey, VoidCallback};
7
8use waft_animation::{
9 Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
10 AnimationStatusListener, AnyAnimation, Curve, CurvedAnimation, Curves, Interval, Threshold,
11};
12use waft_embedder::{Brightness, Clip, Color, Radius, TextDirection};
13use waft_painting::{
14 AlignmentGeometry, AnyColor, BorderRadiusGeometry, BorderSide, EdgeInsets, EdgeInsetsGeometry,
15 PaintingBinding, RoundedRectangleBorder, ShapeBorderRef, TextPainter, TextSpan, TextStyle,
16};
17use waft_rendering::{HitTestBehavior, MainAxisAlignment};
18use waft_scheduler::TickerProvider;
19use waft_widgets::{
20 Align, BuildContext, ClipRect, DefaultTextStyle, DismissDirection, Dismissible, Expanded,
21 FadeTransition, Hero, Icon, IntoWidget, KeyRef, ListenableBuilder, MediaQuery, Padding, Row,
22 SafeArea, Semantics, SizedBox, StandardComponentType, State, StateData, StatefulWidget, Text,
23 WidgetRef, WidgetState, WidgetStateColor, WidgetStateProperty, WidgetStatePropertyRef, Wrap,
24 debug_check_has_media_query,
25};
26
27use crate::color_scheme::ColorScheme;
28use crate::colors::Colors;
29use crate::generated::snackbar_defaults_m3::SnackbarDefaultsM3;
30use crate::icon_button::IconButton;
31use crate::icons::Icons;
32use crate::material::Material;
33use crate::material_localizations::MaterialLocalizations;
34use crate::scaffold::ScaffoldMessenger;
35use crate::snack_bar_theme::{
36 SnackBarBehavior, SnackBarTheme, SnackBarThemeData, SnackBarThemeDataGetters,
37};
38use crate::text_button::TextButton;
39use crate::text_button_theme::{TextButtonTheme, TextButtonThemeData};
40use crate::theme::Theme;
41use crate::theme_data::ThemeData;
42
43const SINGLE_LINE_VERTICAL_PADDING: f64 = 14.0;
44const SNACK_BAR_TRANSITION_DURATION: Duration = Duration::from_millis(250);
45const SNACK_BAR_DISPLAY_DURATION: Duration = Duration::from_millis(4000);
46
47fn snack_bar_height_curve() -> Rc<dyn Curve> {
48 Curves::fast_out_slow_in()
49}
50
51fn snack_bar_m3_height_curve() -> Rc<dyn Curve> {
52 Curves::ease_in_out_quart()
53}
54
55fn snack_bar_fade_in_curve() -> Rc<dyn Curve> {
56 Rc::new(Interval::new(0.4, 1.0, Curves::linear()))
57}
58
59fn snack_bar_m3_fade_in_curve() -> Rc<dyn Curve> {
60 Rc::new(Interval::new(0.4, 0.6, Curves::ease_in_circ()))
61}
62
63fn snack_bar_fade_out_curve() -> Rc<dyn Curve> {
64 Rc::new(Interval::new(0.72, 1.0, Curves::fast_out_slow_in()))
65}
66
67#[derive(Clone, Copy, PartialEq, Eq, Debug)]
85pub enum SnackBarClosedReason {
86 Action,
88
89 Dismiss,
91
92 Swipe,
94
95 Hide,
98
99 Remove,
102
103 Timeout,
105}
106
107#[derive(Clone)]
119pub struct SnackBarAction {
120 pub key: Option<KeyRef>,
121
122 pub text_color: Option<AnyColor>,
130
131 pub background_color: Option<AnyColor>,
138
139 pub disabled_text_color: Option<Color>,
142
143 pub disabled_background_color: Option<Color>,
148
149 pub label: String,
151
152 pub on_pressed: VoidCallback,
157}
158
159impl SnackBarAction {
160 pub fn new(
162 label: impl Into<String>,
163 on_pressed: impl Fn(&mut App) + 'static,
164 ) -> SnackBarAction {
165 SnackBarAction {
166 key: None,
167 text_color: None,
168 background_color: None,
169 disabled_text_color: None,
170 disabled_background_color: None,
171 label: label.into(),
172 on_pressed: Rc::new(on_pressed),
173 }
174 }
175
176 pub fn key(mut self, key: KeyRef) -> SnackBarAction {
178 self.key = Some(key);
179 self
180 }
181
182 pub fn text_color(mut self, text_color: impl Into<AnyColor>) -> SnackBarAction {
184 self.text_color = Some(text_color.into());
185 self
186 }
187
188 pub fn disabled_text_color(mut self, disabled_text_color: Color) -> SnackBarAction {
190 self.disabled_text_color = Some(disabled_text_color);
191 self
192 }
193
194 pub fn background_color(mut self, background_color: impl Into<AnyColor>) -> SnackBarAction {
196 let background_color = background_color.into();
197 debug_assert!(
198 !is_widget_state_color(&background_color) || self.disabled_background_color.is_none(),
199 "disabledBackgroundColor must not be provided when background color is a \
200 WidgetStateColor"
201 );
202 self.background_color = Some(background_color);
203 self
204 }
205
206 pub fn disabled_background_color(mut self, disabled_background_color: Color) -> SnackBarAction {
208 debug_assert!(
209 !self
210 .background_color
211 .as_ref()
212 .is_some_and(is_widget_state_color),
213 "disabledBackgroundColor must not be provided when background color is a \
214 WidgetStateColor"
215 );
216 self.disabled_background_color = Some(disabled_background_color);
217 self
218 }
219}
220
221impl fmt::Debug for SnackBarAction {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 f.debug_struct("SnackBarAction")
224 .field("key", &self.key)
225 .field("label", &self.label)
226 .finish_non_exhaustive()
227 }
228}
229
230impl StatefulWidget for SnackBarAction {
231 type State = SnackBarActionState;
232
233 fn key(&self) -> Option<&KeyRef> {
234 self.key.as_ref()
235 }
236
237 fn create_state(&self) -> SnackBarActionState {
238 SnackBarActionState {
239 state: StateData::new(),
240 have_triggered_action: false,
241 }
242 }
243}
244
245pub struct SnackBarActionState {
247 state: StateData<SnackBarAction>,
248 have_triggered_action: bool,
249}
250
251impl SnackBarActionState {
252 fn handle_pressed(self: Handle<Self>, app: &mut App) {
253 if app.get(self).have_triggered_action {
254 return;
255 }
256 self.set_state(app, |this| {
257 this.have_triggered_action = true;
258 });
259 let on_pressed = Rc::clone(&self.widget(app).on_pressed);
260 on_pressed(app);
261 let context = self.context(app);
262 ScaffoldMessenger::of(app, context)
263 .hide_current_snack_bar(app, SnackBarClosedReason::Action);
264 }
265}
266
267impl State for SnackBarActionState {
268 type Widget = SnackBarAction;
269 waft_widgets::state_accessors!();
270
271 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
272 let defaults: Box<dyn SnackBarThemeDataGetters> = if Theme::of(app, context).use_material3 {
273 Box::new(SnackbarDefaultsM3::new(context))
274 } else {
275 Box::new(SnackbarDefaultsM2::new(app, context))
276 };
277 let snack_bar_theme = SnackBarTheme::of(app, context);
278 let widget = self.widget(app).clone();
279
280 let resolve_foreground_color = |app: &mut App| -> AnyColor {
281 if let Some(text_color) = &widget.text_color {
282 if is_widget_state_color(text_color) {
283 return text_color.clone();
284 }
285 } else if let Some(action_text_color) = &snack_bar_theme.action_text_color {
286 if is_widget_state_color(action_text_color) {
287 return action_text_color.clone();
288 }
289 } else if let Some(action_text_color) = defaults.action_text_color(app)
290 && is_widget_state_color(&action_text_color)
291 {
292 return action_text_color;
293 }
294
295 let disabled_text_color = widget
296 .disabled_text_color
297 .or(snack_bar_theme.disabled_action_text_color)
298 .or_else(|| defaults.disabled_action_text_color(app));
299 let text_color = widget
300 .text_color
301 .clone()
302 .or_else(|| snack_bar_theme.action_text_color.clone())
303 .or_else(|| defaults.action_text_color(app))
304 .map(|color| color.color());
305 WidgetStateColor::resolve_with(move |states| {
306 if states.contains(&WidgetState::Disabled) {
307 return disabled_text_color
308 .expect("the defaults have a disabled action text color");
309 }
310 text_color.expect("the defaults have an action text color")
311 })
312 .into_any()
313 };
314
315 let resolve_background_color = || -> AnyColor {
316 if let Some(background_color) = &widget.background_color
317 && is_widget_state_color(background_color)
318 {
319 return background_color.clone();
320 }
321 if let Some(action_background_color) = &snack_bar_theme.action_background_color
322 && is_widget_state_color(action_background_color)
323 {
324 return action_background_color.clone();
325 }
326 let disabled_background_color = widget
327 .disabled_background_color
328 .or(snack_bar_theme.disabled_action_background_color)
329 .unwrap_or(Colors::TRANSPARENT);
330 let background_color = widget
331 .background_color
332 .as_ref()
333 .or(snack_bar_theme.action_background_color.as_ref())
334 .map_or(Colors::TRANSPARENT, AnyColor::color);
335 WidgetStateColor::resolve_with(move |states| {
336 if states.contains(&WidgetState::Disabled) {
337 return disabled_background_color;
338 }
339 background_color
340 })
341 .into_any()
342 };
343
344 let style = TextButton::style_from()
345 .overlay_color(resolve_foreground_color(app).color())
346 .build()
347 .copy_with();
348 let style = crate::button_style::ButtonStyle {
349 foreground_color: Some(widget_state_color_property(resolve_foreground_color(app))),
350 background_color: Some(widget_state_color_property(resolve_background_color())),
351 ..style
352 };
353 let label = widget.label.clone();
354 let on_pressed = if app.get(self).have_triggered_action {
355 None
356 } else {
357 Some(Listener::handle_method(self, Self::handle_pressed))
358 };
359 TextButton::new(on_pressed, Some(Text::new(label)))
360 .style(style)
361 .into_widget()
362 }
363}
364
365fn is_widget_state_color(color: &AnyColor) -> bool {
367 color.extension::<WidgetStateColor>().is_some()
368}
369
370fn widget_state_color_property(color: AnyColor) -> WidgetStatePropertyRef<Option<Color>> {
372 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
373 Some(
374 color
375 .extension::<WidgetStateColor>()
376 .expect("resolved as a WidgetStateColor")
377 .resolve(states),
378 )
379 })
380}
381
382#[derive(Clone)]
416pub struct SnackBar {
417 pub key: Option<KeyRef>,
418
419 pub content: WidgetRef,
423
424 pub background_color: Option<Color>,
431
432 pub elevation: Option<f64>,
440
441 pub margin: Option<EdgeInsetsGeometry>,
455
456 pub padding: Option<EdgeInsetsGeometry>,
484
485 pub width: Option<f64>,
496
497 pub shape: Option<ShapeBorderRef>,
508
509 pub hit_test_behavior: Option<HitTestBehavior>,
517
518 pub behavior: Option<SnackBarBehavior>,
530
531 pub action: Option<SnackBarAction>,
538
539 pub action_overflow_threshold: Option<f64>,
551
552 pub show_close_icon: Option<bool>,
556
557 pub close_icon_color: Option<AnyColor>,
568
569 pub duration: Duration,
580
581 pub persist: Option<bool>,
592
593 pub animation: Option<AnimationRef<f64>>,
595
596 pub on_visible: Option<VoidCallback>,
605
606 pub dismiss_direction: Option<DismissDirection>,
611
612 pub clip_behavior: Clip,
618}
619
620impl SnackBar {
621 #[cfg_attr(debug_assertions, track_caller)]
625 pub fn new<K>(content: impl IntoWidget<K>) -> SnackBar {
626 SnackBar {
627 key: None,
628 content: content.into_widget(),
629 background_color: None,
630 elevation: None,
631 margin: None,
632 padding: None,
633 width: None,
634 shape: None,
635 hit_test_behavior: None,
636 behavior: None,
637 action: None,
638 action_overflow_threshold: None,
639 show_close_icon: None,
640 close_icon_color: None,
641 duration: SNACK_BAR_DISPLAY_DURATION,
642 persist: None,
643 animation: None,
644 on_visible: None,
645 dismiss_direction: None,
646 clip_behavior: Clip::HardEdge,
647 }
648 }
649
650 pub fn key(mut self, key: KeyRef) -> SnackBar {
652 self.key = Some(key);
653 self
654 }
655
656 pub fn background_color(mut self, background_color: Color) -> SnackBar {
658 self.background_color = Some(background_color);
659 self
660 }
661
662 pub fn elevation(mut self, elevation: f64) -> SnackBar {
664 debug_assert!(elevation >= 0.0);
665 self.elevation = Some(elevation);
666 self
667 }
668
669 pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> SnackBar {
671 debug_assert!(
672 self.width.is_none(),
673 "Width and margin can not be used together"
674 );
675 self.margin = Some(margin.into());
676 self
677 }
678
679 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> SnackBar {
681 self.padding = Some(padding.into());
682 self
683 }
684
685 pub fn width(mut self, width: f64) -> SnackBar {
687 debug_assert!(
688 self.margin.is_none(),
689 "Width and margin can not be used together"
690 );
691 self.width = Some(width);
692 self
693 }
694
695 pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> SnackBar {
697 self.shape = Some(shape.into());
698 self
699 }
700
701 pub fn hit_test_behavior(mut self, hit_test_behavior: HitTestBehavior) -> SnackBar {
703 self.hit_test_behavior = Some(hit_test_behavior);
704 self
705 }
706
707 pub fn behavior(mut self, behavior: SnackBarBehavior) -> SnackBar {
709 self.behavior = Some(behavior);
710 self
711 }
712
713 pub fn action(mut self, action: SnackBarAction) -> SnackBar {
715 self.action = Some(action);
716 self
717 }
718
719 pub fn action_overflow_threshold(mut self, action_overflow_threshold: f64) -> SnackBar {
721 debug_assert!(
722 (0.0..=1.0).contains(&action_overflow_threshold),
723 "Action overflow threshold must be between 0 and 1 inclusive"
724 );
725 self.action_overflow_threshold = Some(action_overflow_threshold);
726 self
727 }
728
729 pub fn show_close_icon(mut self, show_close_icon: bool) -> SnackBar {
731 self.show_close_icon = Some(show_close_icon);
732 self
733 }
734
735 pub fn close_icon_color(mut self, close_icon_color: impl Into<AnyColor>) -> SnackBar {
737 self.close_icon_color = Some(close_icon_color.into());
738 self
739 }
740
741 pub fn duration(mut self, duration: Duration) -> SnackBar {
743 self.duration = duration;
744 self
745 }
746
747 pub fn persist(mut self, persist: bool) -> SnackBar {
749 self.persist = Some(persist);
750 self
751 }
752
753 pub fn animation(mut self, animation: AnimationRef<f64>) -> SnackBar {
755 self.animation = Some(animation);
756 self
757 }
758
759 pub fn on_visible(mut self, on_visible: impl Fn(&mut App) + 'static) -> SnackBar {
761 self.on_visible = Some(Rc::new(on_visible));
762 self
763 }
764
765 pub fn dismiss_direction(mut self, dismiss_direction: DismissDirection) -> SnackBar {
767 self.dismiss_direction = Some(dismiss_direction);
768 self
769 }
770
771 pub fn clip_behavior(mut self, clip_behavior: Clip) -> SnackBar {
773 self.clip_behavior = clip_behavior;
774 self
775 }
776
777 pub fn effective_persist(&self) -> bool {
779 self.persist.unwrap_or(self.action.is_some())
780 }
781
782 pub fn create_animation_controller(
787 app: &mut App,
788 vsync: impl TickerProvider,
789 duration: Option<Duration>,
790 reverse_duration: Option<Duration>,
791 ) -> Ref<AnimationController> {
792 AnimationController::new(
793 app,
794 None,
795 Some(duration.unwrap_or(SNACK_BAR_TRANSITION_DURATION)),
796 reverse_duration,
797 0.0,
798 1.0,
799 AnimationBehavior::Normal,
800 vsync,
801 )
802 }
803
804 pub fn with_animation(
810 &self,
811 new_animation: AnimationRef<f64>,
812 fallback_key: Option<KeyRef>,
813 ) -> SnackBar {
814 SnackBar {
815 key: self.key.clone().or(fallback_key),
816 content: Rc::clone(&self.content),
817 background_color: self.background_color,
818 elevation: self.elevation,
819 margin: self.margin,
820 padding: self.padding,
821 width: self.width,
822 shape: self.shape.clone(),
823 hit_test_behavior: self.hit_test_behavior,
824 behavior: self.behavior,
825 action: self.action.clone(),
826 action_overflow_threshold: self.action_overflow_threshold,
827 show_close_icon: self.show_close_icon,
828 close_icon_color: self.close_icon_color.clone(),
829 duration: self.duration,
830 persist: Some(self.effective_persist()),
831 animation: Some(new_animation),
832 on_visible: self.on_visible.clone(),
833 dismiss_direction: self.dismiss_direction,
834 clip_behavior: self.clip_behavior,
835 }
836 }
837}
838
839impl fmt::Debug for SnackBar {
840 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
841 f.debug_struct("SnackBar")
842 .field("key", &self.key)
843 .field("content", &self.content)
844 .field("behavior", &self.behavior)
845 .field("action", &self.action)
846 .field("duration", &self.duration)
847 .finish_non_exhaustive()
848 }
849}
850
851impl StatefulWidget for SnackBar {
852 type State = SnackBarState;
853
854 fn key(&self) -> Option<&KeyRef> {
855 self.key.as_ref()
856 }
857
858 fn create_state(&self) -> SnackBarState {
859 SnackBarState {
860 state: StateData::new(),
861 was_visible: false,
862 height_animation: None,
863 fade_in_animation: None,
864 fade_in_m3_animation: None,
865 fade_out_animation: None,
866 height_m3_animation: None,
867 dismissible_key: UniqueKey::new().into(),
868 }
869 }
870}
871
872pub struct SnackBarState {
874 state: StateData<SnackBar>,
875 was_visible: bool,
876
877 height_animation: Option<Ref<CurvedAnimation>>,
878 fade_in_animation: Option<Ref<CurvedAnimation>>,
879 fade_in_m3_animation: Option<Ref<CurvedAnimation>>,
880 fade_out_animation: Option<Ref<CurvedAnimation>>,
881 height_m3_animation: Option<Ref<CurvedAnimation>>,
882
883 dismissible_key: KeyRef,
884}
885
886impl SnackBarState {
887 fn animation(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
888 self.widget(app)
889 .animation
890 .clone()
891 .expect("a SnackBar is shown with an animation")
892 }
893
894 fn set_animations(self: Handle<Self>, app: &mut App) {
895 debug_assert!(self.widget(app).animation.is_some());
896 let animation = self.animation(app);
897 let height_animation =
898 CurvedAnimation::new(app, animation.clone(), snack_bar_height_curve(), None);
899 let fade_in_animation =
900 CurvedAnimation::new(app, animation.clone(), snack_bar_fade_in_curve(), None);
901 let fade_in_m3_animation =
902 CurvedAnimation::new(app, animation.clone(), snack_bar_m3_fade_in_curve(), None);
903 let fade_out_animation = CurvedAnimation::new(
904 app,
905 animation.clone(),
906 snack_bar_fade_out_curve(),
907 Some(Rc::new(Threshold::new(0.0))),
908 );
909 let height_m3_animation = CurvedAnimation::new(
911 app,
912 animation,
913 snack_bar_m3_height_curve(),
914 Some(Rc::new(Threshold::new(0.0))),
915 );
916 let this = app.get_mut(self);
917 this.height_animation = Some(height_animation);
918 this.fade_in_animation = Some(fade_in_animation);
919 this.fade_in_m3_animation = Some(fade_in_m3_animation);
920 this.fade_out_animation = Some(fade_out_animation);
921 this.height_m3_animation = Some(height_m3_animation);
922 }
923
924 fn dispose_animations(self: Handle<Self>, app: &mut App) {
925 let this = app.get_mut(self);
926 let animations = [
927 this.height_animation.take(),
928 this.fade_in_animation.take(),
929 this.fade_in_m3_animation.take(),
930 this.fade_out_animation.take(),
931 this.height_m3_animation.take(),
932 ];
933 for animation in animations.into_iter().flatten() {
934 animation.dispose(app);
935 }
936 }
937
938 fn on_animation_status_changed(
939 self: Handle<Self>,
940 app: &mut App,
941 animation_status: AnimationStatus,
942 ) {
943 if animation_status.is_completed() {
944 if let Some(on_visible) = self.widget(app).on_visible.clone()
945 && !app.get(self).was_visible
946 {
947 on_visible(app);
948 }
949 app.get_mut(self).was_visible = true;
950 }
951 }
952
953 fn status_listener(self: Handle<Self>) -> AnimationStatusListener {
954 AnimationStatusListener::handle_method(self, Self::on_animation_status_changed)
955 }
956}
957
958impl State for SnackBarState {
959 type Widget = SnackBar;
960 waft_widgets::state_accessors!();
961
962 fn init_state(self: Handle<Self>, app: &mut App) {
963 let animation = self.animation(app);
964 animation.add_status_listener(app, self.status_listener());
965 self.set_animations(app);
966 }
967
968 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SnackBar) {
969 if self.widget(app).animation != old_widget.animation {
970 let old_animation = old_widget
971 .animation
972 .clone()
973 .expect("a SnackBar is shown with an animation");
974 old_animation.remove_status_listener(app, &self.status_listener());
975 let animation = self.animation(app);
976 animation.add_status_listener(app, self.status_listener());
977 self.dispose_animations(app);
978 self.set_animations(app);
979 }
980 }
981
982 fn dispose(self: Handle<Self>, app: &mut App) {
983 let animation = self.animation(app);
984 animation.remove_status_listener(app, &self.status_listener());
985 self.dispose_animations(app);
986 }
987
988 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
989 debug_assert!(debug_check_has_media_query(app, context));
990 let accessible_navigation = MediaQuery::accessible_navigation_of(app, context);
991 debug_assert!(self.widget(app).animation.is_some());
992 let theme = Theme::of(app, context);
993 let color_scheme = theme.color_scheme.clone();
994 let snack_bar_theme = SnackBarTheme::of(app, context);
995 let is_theme_dark = theme.brightness() == Brightness::Dark;
996 let button_color = if is_theme_dark {
997 color_scheme.primary()
998 } else {
999 color_scheme.secondary()
1000 };
1001 let defaults: Box<dyn SnackBarThemeDataGetters> = if theme.use_material3 {
1002 Box::new(SnackbarDefaultsM3::new(context))
1003 } else {
1004 Box::new(SnackbarDefaultsM2::new(app, context))
1005 };
1006
1007 let brightness = if is_theme_dark {
1010 Brightness::Light
1011 } else {
1012 Brightness::Dark
1013 };
1014
1015 let effective_theme = if theme.use_material3 {
1018 Rc::clone(&theme)
1019 } else {
1020 Rc::new(
1021 theme
1022 .copy_with()
1023 .color_scheme(inverted_color_scheme(
1024 &color_scheme,
1025 button_color,
1026 defaults.background_color(app),
1027 brightness,
1028 ))
1029 .build(),
1030 )
1031 };
1032
1033 let widget = self.widget(app).clone();
1034 let content_text_style = snack_bar_theme
1035 .content_text_style
1036 .clone()
1037 .or_else(|| defaults.content_text_style(app));
1038 let snack_bar_behavior = widget
1039 .behavior
1040 .or(snack_bar_theme.behavior)
1041 .or_else(|| defaults.behavior(app))
1042 .expect("the defaults have a behavior");
1043 let width = widget.width.or(snack_bar_theme.width);
1044 if cfg!(debug_assertions) {
1045 if snack_bar_behavior != SnackBarBehavior::Floating {
1048 let message = |parameter: &str| {
1049 let prefix = format!("{parameter} can only be used with floating behavior.");
1050 if widget.behavior.is_some() {
1051 format!(
1052 "{prefix} SnackBarBehavior.fixed was set in the SnackBar constructor."
1053 )
1054 } else if snack_bar_theme.behavior.is_some() {
1055 format!(
1056 "{prefix} SnackBarBehavior.fixed was set by the inherited \
1057 SnackBarThemeData."
1058 )
1059 } else {
1060 format!("{prefix} SnackBarBehavior.fixed was set by default.")
1061 }
1062 };
1063 assert!(widget.margin.is_none(), "{}", message("Margin"));
1064 assert!(width.is_none(), "{}", message("Width"));
1065 }
1066 }
1067
1068 let show_close_icon = widget
1069 .show_close_icon
1070 .or(snack_bar_theme.show_close_icon)
1071 .or_else(|| defaults.show_close_icon(app))
1072 .expect("the defaults have a show close icon");
1073
1074 let is_floating_snack_bar = snack_bar_behavior == SnackBarBehavior::Floating;
1075 let horizontal_padding = if is_floating_snack_bar { 16.0 } else { 24.0 };
1076 let padding = widget.padding.unwrap_or(EdgeInsetsGeometry::directional(
1077 horizontal_padding,
1078 0.0,
1079 if widget.action.is_some() || show_close_icon {
1080 0.0
1081 } else {
1082 horizontal_padding
1083 },
1084 0.0,
1085 ));
1086
1087 let action_horizontal_margin = widget.padding.map_or(horizontal_padding, |padding| {
1088 padding.resolve(Some(TextDirection::Ltr)).right
1089 }) / 2.0;
1090 let icon_horizontal_margin = widget.padding.map_or(horizontal_padding, |padding| {
1091 padding.resolve(Some(TextDirection::Ltr)).right
1092 }) / 12.0;
1093
1094 let icon_button = if show_close_icon {
1095 let close_icon_color = widget
1096 .close_icon_color
1097 .clone()
1098 .or(snack_bar_theme.close_icon_color.clone())
1099 .or_else(|| defaults.close_icon_color(app));
1100 let tooltip = <dyn MaterialLocalizations>::of(app, context).close_button_tooltip();
1101 let mut icon_button = IconButton::new(
1102 Some(Listener::new(move |app| {
1103 ScaffoldMessenger::of(app, context)
1104 .hide_current_snack_bar(app, SnackBarClosedReason::Dismiss);
1105 })),
1106 Icon::new(Some(Icons::close())),
1107 )
1108 .key(StandardComponentType::CloseButton.key())
1109 .icon_size(24.0)
1110 .tooltip(tooltip);
1111 if let Some(close_icon_color) = close_icon_color {
1112 icon_button = icon_button.color(close_icon_color.color());
1113 }
1114 Some(icon_button)
1115 } else {
1116 None
1117 };
1118
1119 let mut action_text_span = TextSpan::new().text(
1121 widget
1122 .action
1123 .as_ref()
1124 .map(|action| action.label.clone())
1125 .unwrap_or_default(),
1126 );
1127 if let Some(label_large) = Theme::of(app, context).text_theme.label_large.clone() {
1128 action_text_span = action_text_span.style(label_large);
1129 }
1130 let mut action_text_painter = TextPainter::new();
1131 action_text_painter.set_text(Some(action_text_span.into_span()));
1132 action_text_painter.set_max_lines(Some(1));
1133 action_text_painter.set_text_direction(Some(TextDirection::Ltr));
1134 action_text_painter.set_text_scaler(MediaQuery::text_scaler_of(app, context));
1135 let fonts = PaintingBinding::instance(app).fonts(app);
1136 action_text_painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
1137 let action_and_icon_width = action_text_painter.size().width()
1138 + if widget.action.is_some() {
1139 action_horizontal_margin
1140 } else {
1141 0.0
1142 }
1143 + if show_close_icon {
1144 icon_button
1145 .as_ref()
1146 .and_then(|icon_button| icon_button.icon_size)
1147 .unwrap_or(0.0 + icon_horizontal_margin)
1148 } else {
1149 0.0
1150 };
1151 action_text_painter.dispose();
1152
1153 let margin: EdgeInsets = widget
1154 .margin
1155 .map(|margin| margin.resolve(Some(TextDirection::Ltr)))
1156 .or(snack_bar_theme.inset_padding)
1157 .or_else(|| defaults.inset_padding(app))
1158 .expect("the defaults have an inset padding");
1159
1160 let snack_bar_width = widget
1161 .width
1162 .unwrap_or_else(|| MediaQuery::width_of(app, context) - (margin.left + margin.right));
1163 let action_overflow_threshold = widget
1164 .action_overflow_threshold
1165 .or(snack_bar_theme.action_overflow_threshold)
1166 .or_else(|| defaults.action_overflow_threshold(app))
1167 .expect("the defaults have an action overflow threshold");
1168
1169 let will_overflow_action =
1170 action_and_icon_width / snack_bar_width > action_overflow_threshold;
1171
1172 let mut maybe_action_and_icon: Vec<WidgetRef> = Vec::new();
1173 if let Some(action) = &widget.action {
1174 maybe_action_and_icon.push(
1175 Padding::new(EdgeInsetsGeometry::symmetric(0.0, action_horizontal_margin))
1176 .child(TextButtonTheme::new(
1177 TextButtonThemeData::new().style(
1178 TextButton::style_from()
1179 .foreground_color(button_color)
1180 .padding(EdgeInsetsGeometry::symmetric(0.0, horizontal_padding))
1181 .build(),
1182 ),
1183 action.clone(),
1184 ))
1185 .into_widget(),
1186 );
1187 }
1188 if let Some(icon_button) = icon_button {
1189 maybe_action_and_icon.push(
1190 Padding::new(EdgeInsetsGeometry::symmetric(0.0, icon_horizontal_margin))
1191 .child(icon_button)
1192 .into_widget(),
1193 );
1194 }
1195
1196 let mut row_children: Vec<WidgetRef> = vec![
1197 Expanded::new(
1198 Padding::new(if widget.padding.is_none() {
1199 EdgeInsetsGeometry::symmetric(SINGLE_LINE_VERTICAL_PADDING, 0.0)
1200 } else {
1201 EdgeInsetsGeometry::ZERO
1202 })
1203 .child(DefaultTextStyle::new(
1204 content_text_style.expect("the defaults have a content text style"),
1205 Rc::clone(&widget.content),
1206 )),
1207 )
1208 .into_widget(),
1209 ];
1210 if !will_overflow_action {
1211 row_children.extend(maybe_action_and_icon.iter().cloned());
1212 }
1213 if will_overflow_action && widget.padding.is_none() {
1214 row_children.push(SizedBox::new().width(horizontal_padding).into_widget());
1215 }
1216 let mut wrap_children: Vec<WidgetRef> =
1217 vec![Row::new().children(row_children).into_widget()];
1218 if will_overflow_action {
1219 wrap_children.push(
1220 Padding::new(EdgeInsetsGeometry::only(
1221 0.0,
1222 0.0,
1223 0.0,
1224 SINGLE_LINE_VERTICAL_PADDING,
1225 ))
1226 .child(
1227 Row::new()
1228 .main_axis_alignment(MainAxisAlignment::End)
1229 .children(maybe_action_and_icon),
1230 )
1231 .into_widget(),
1232 );
1233 }
1234 let mut snack_bar: WidgetRef = Padding::new(padding)
1235 .child(Wrap::new().children(wrap_children))
1236 .into_widget();
1237
1238 if !is_floating_snack_bar {
1239 snack_bar = SafeArea::new(snack_bar).top(false).into_widget();
1240 }
1241
1242 let elevation = widget
1243 .elevation
1244 .or(snack_bar_theme.elevation)
1245 .or_else(|| defaults.elevation(app))
1246 .expect("the defaults have an elevation");
1247 let background_color = widget
1248 .background_color
1249 .or(snack_bar_theme.background_color)
1250 .or_else(|| defaults.background_color(app))
1251 .expect("the defaults have a background color");
1252 let shape = widget
1253 .shape
1254 .clone()
1255 .or(snack_bar_theme.shape.clone())
1256 .or_else(|| {
1257 if is_floating_snack_bar {
1258 defaults.shape(app)
1259 } else {
1260 None
1261 }
1262 });
1263 let dismiss_direction = widget
1264 .dismiss_direction
1265 .or(snack_bar_theme.dismiss_direction)
1266 .unwrap_or(DismissDirection::Down);
1267
1268 let themed_child = if accessible_navigation || theme.use_material3 {
1269 snack_bar
1270 } else {
1271 let fade_out_animation = app
1272 .get(self)
1273 .fade_out_animation
1274 .clone()
1275 .expect("set by set_animations");
1276 FadeTransition::new(fade_out_animation.erase())
1277 .child(snack_bar)
1278 .into_widget()
1279 };
1280 let mut material = Material::new()
1281 .elevation(elevation)
1282 .color(background_color)
1283 .clip_behavior(widget.clip_behavior);
1284 if let Some(shape) = shape {
1285 material = material.shape(shape);
1286 }
1287 snack_bar = material
1288 .child(Theme::new(effective_theme, themed_child))
1289 .into_widget();
1290
1291 if is_floating_snack_bar {
1292 if let Some(width) = width {
1294 snack_bar = Padding::new(EdgeInsetsGeometry::only(
1295 0.0,
1296 margin.top,
1297 0.0,
1298 margin.bottom,
1299 ))
1300 .child(SizedBox::new().width(width).child(snack_bar))
1301 .into_widget();
1302 } else {
1303 snack_bar = Padding::new(EdgeInsetsGeometry::Insets(margin))
1304 .child(snack_bar)
1305 .into_widget();
1306 }
1307 snack_bar = SafeArea::new(snack_bar)
1308 .top(false)
1309 .bottom(false)
1310 .into_widget();
1311 }
1312
1313 let dismissible_key = app.get(self).dismissible_key.clone();
1314 let dismissible = Dismissible::new(dismissible_key, snack_bar)
1315 .direction(dismiss_direction)
1316 .resize_duration(None)
1317 .behavior(widget.hit_test_behavior.unwrap_or(
1318 if widget.margin.is_some() || snack_bar_theme.inset_padding.is_some() {
1319 HitTestBehavior::DeferToChild
1320 } else {
1321 HitTestBehavior::Opaque
1322 },
1323 ))
1324 .on_dismissed(move |app, _direction| {
1325 ScaffoldMessenger::of(app, context)
1326 .remove_current_snack_bar(app, SnackBarClosedReason::Swipe);
1327 });
1328 let snack_bar = Semantics::new()
1329 .container(true)
1330 .live_region(true)
1331 .on_dismiss(Rc::new(move |app: &mut App| {
1332 ScaffoldMessenger::of(app, context)
1333 .remove_current_snack_bar(app, SnackBarClosedReason::Dismiss);
1334 }))
1335 .child(dismissible)
1336 .into_widget();
1337
1338 let snack_bar_transition: WidgetRef = if accessible_navigation {
1339 snack_bar
1340 } else if is_floating_snack_bar && !theme.use_material3 {
1341 let fade_in_animation = app
1342 .get(self)
1343 .fade_in_animation
1344 .clone()
1345 .expect("set by set_animations");
1346 FadeTransition::new(fade_in_animation.erase())
1347 .child(snack_bar)
1348 .into_widget()
1349 } else if is_floating_snack_bar && theme.use_material3 {
1351 let this = app.get(self);
1352 let fade_in_m3_animation = this
1353 .fade_in_m3_animation
1354 .clone()
1355 .expect("set by set_animations");
1356 let height_m3_animation = this
1357 .height_m3_animation
1358 .clone()
1359 .expect("set by set_animations");
1360 FadeTransition::new(fade_in_m3_animation.erase())
1361 .child(
1362 height_factor_builder(height_m3_animation, AlignmentGeometry::BOTTOM_LEFT)
1363 .child(snack_bar),
1364 )
1365 .into_widget()
1366 } else {
1367 let height_animation = app
1368 .get(self)
1369 .height_animation
1370 .clone()
1371 .expect("set by set_animations");
1372 height_factor_builder(height_animation, AlignmentGeometry::TOP_START)
1373 .child(snack_bar)
1374 .into_widget()
1375 };
1376
1377 Hero::new(
1378 Rc::new(format!("<SnackBar Hero tag - {:?}>", widget.content)),
1379 ClipRect::new()
1380 .clip_behavior(widget.clip_behavior)
1381 .child(snack_bar_transition),
1382 )
1383 .transition_on_user_gestures(true)
1384 .into_widget()
1385 }
1386}
1387
1388fn height_factor_builder(
1391 animation: Ref<CurvedAnimation>,
1392 alignment: AlignmentGeometry,
1393) -> ListenableBuilder {
1394 let listenable: Rc<dyn Listenable> = Rc::new(animation.erase::<AnyAnimation<f64>>());
1395 ListenableBuilder::new(listenable, move |app, _context, child| {
1396 let mut align = Align::new()
1397 .alignment(alignment)
1398 .height_factor(animation.value(app));
1399 if let Some(child) = child {
1400 align = align.child(Rc::clone(child));
1401 }
1402 align.into_widget()
1403 })
1404}
1405
1406#[allow(deprecated)]
1408fn inverted_color_scheme(
1409 color_scheme: &ColorScheme,
1410 button_color: Color,
1411 background: Option<Color>,
1412 brightness: Brightness,
1413) -> ColorScheme {
1414 let mut inverted = ColorScheme::new(
1415 brightness,
1416 color_scheme.on_primary(),
1417 color_scheme.primary(),
1418 button_color,
1419 color_scheme.secondary(),
1420 color_scheme.on_error(),
1421 color_scheme.error(),
1422 color_scheme.on_surface(),
1423 color_scheme.surface(),
1424 )
1425 .with_on_background(color_scheme.background());
1426 if let Some(background) = background {
1427 inverted = inverted.with_background(background);
1428 }
1429 inverted
1430}
1431
1432#[allow(deprecated)]
1434struct SnackbarDefaultsM2 {
1436 snack_bar_theme_data: SnackBarThemeData,
1438 theme: Rc<ThemeData>,
1440}
1441
1442impl SnackbarDefaultsM2 {
1443 fn new(app: &mut App, context: BuildContext) -> SnackbarDefaultsM2 {
1444 SnackbarDefaultsM2 {
1445 snack_bar_theme_data: SnackBarThemeData::new().elevation(6.0),
1446 theme: Theme::of(app, context),
1447 }
1448 }
1449
1450 fn colors(&self) -> &ColorScheme {
1452 &self.theme.color_scheme
1453 }
1454
1455 fn is_light(&self) -> bool {
1456 self.theme.brightness() == Brightness::Light
1457 }
1458}
1459
1460#[allow(deprecated)]
1461impl SnackBarThemeDataGetters for SnackbarDefaultsM2 {
1462 fn snack_bar_theme_data(&self) -> &SnackBarThemeData {
1463 &self.snack_bar_theme_data
1464 }
1465
1466 fn background_color(&self, _app: &mut App) -> Option<Color> {
1467 let colors = self.colors();
1468 Some(if self.is_light() {
1469 Color::alpha_blend(colors.on_surface().with_opacity(0.80), colors.surface())
1470 } else {
1471 colors.on_surface()
1472 })
1473 }
1474
1475 fn content_text_style(&self, app: &mut App) -> Option<TextStyle> {
1476 ThemeData::builder()
1477 .use_material3(self.theme.use_material3)
1478 .brightness(if self.is_light() {
1479 Brightness::Dark
1480 } else {
1481 Brightness::Light
1482 })
1483 .build(app)
1484 .text_theme
1485 .title_medium
1486 }
1487
1488 fn behavior(&self, _app: &mut App) -> Option<SnackBarBehavior> {
1489 Some(SnackBarBehavior::Fixed)
1490 }
1491
1492 fn action_text_color(&self, _app: &mut App) -> Option<AnyColor> {
1493 Some(self.colors().secondary().into())
1494 }
1495
1496 fn disabled_action_text_color(&self, _app: &mut App) -> Option<Color> {
1497 Some(
1498 self.colors()
1499 .on_surface()
1500 .with_opacity(if self.is_light() { 0.38 } else { 0.3 }),
1501 )
1502 }
1503
1504 fn shape(&self, _app: &mut App) -> Option<ShapeBorderRef> {
1505 Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
1506 BorderSide::NONE,
1507 BorderRadiusGeometry::all(Radius::circular(4.0)),
1508 )))
1509 }
1510
1511 fn inset_padding(&self, _app: &mut App) -> Option<EdgeInsets> {
1512 Some(EdgeInsets::from_ltrb(15.0, 5.0, 15.0, 10.0))
1513 }
1514
1515 fn show_close_icon(&self, _app: &mut App) -> Option<bool> {
1516 Some(false)
1517 }
1518
1519 fn close_icon_color(&self, _app: &mut App) -> Option<AnyColor> {
1520 Some(self.colors().on_surface().into())
1521 }
1522
1523 fn action_overflow_threshold(&self, _app: &mut App) -> Option<f64> {
1524 Some(0.25)
1525 }
1526}
1527
1528#[cfg(test)]
1529mod tests {
1530 use std::cell::{Cell, RefCell};
1531
1532 use waft_embedder::{Offset, Rect, Size};
1533 use waft_widgets::{Builder, Directionality, GestureDetector, GlobalKey, SizedBox};
1534
1535 use waft_widgets::testing::{
1536 WidgetTester, assert_f32_equals, expect, find, finds_n_widgets, finds_nothing,
1537 finds_one_widget, test_widgets,
1538 };
1539
1540 use super::*;
1541 use crate::scaffold::{Scaffold, ScaffoldFeatureController};
1542 use crate::test_support::material_app;
1543
1544 fn m3(app: &App) -> ThemeData {
1546 ThemeData::builder().build(app)
1547 }
1548
1549 fn m2(app: &App) -> ThemeData {
1551 ThemeData::builder().use_material3(false).build(app)
1552 }
1553
1554 fn pump_app(tester: &mut WidgetTester, theme: impl FnOnce(&App) -> ThemeData, home: WidgetRef) {
1556 let theme = theme(&tester.cell.borrow());
1557 tester.pump_widget(material_app(theme, home));
1558 }
1559
1560 fn tap_target_scaffold(
1564 tap_target: &GlobalKey,
1565 show: impl Fn(&mut App, BuildContext) + 'static,
1566 ) -> Scaffold {
1567 let tap_target = tap_target.clone();
1568 let show = Rc::new(show);
1569 Scaffold::new().body(Builder::new(move |_app, context| {
1570 let show = Rc::clone(&show);
1571 GestureDetector::new()
1572 .key(tap_target.clone().into())
1573 .on_tap(Listener::new(move |app| show(app, context)))
1574 .behavior(HitTestBehavior::Opaque)
1575 .child(SizedBox::new().height(100.0).width(100.0))
1576 .into_widget()
1577 }))
1578 }
1579
1580 type SnackBarController = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>;
1581
1582 fn show(app: &mut App, context: BuildContext, snack_bar: SnackBar) -> Rc<SnackBarController> {
1584 ScaffoldMessenger::of(app, context).show_snack_bar(app, snack_bar, None)
1585 }
1586
1587 fn tap_key(tester: &mut WidgetTester, key: &GlobalKey) {
1589 let center = tester.get_center(key);
1590 tester.tap_at(center, 1);
1591 }
1592
1593 fn drag_text(tester: &mut WidgetTester, text: &str, offset: Offset) {
1595 let center = tester.get_rect(find::text(text)).center();
1596 tester.drag_from(center, offset, 1);
1597 }
1598
1599 fn ms(millis: u64) -> Duration {
1600 Duration::from_millis(millis)
1601 }
1602
1603 fn x_scaffold(show: impl Fn(&mut App, BuildContext) + 'static) -> Scaffold {
1606 let show = Rc::new(show);
1607 Scaffold::new().body(Builder::new(move |_app, context| {
1608 let show = Rc::clone(&show);
1609 GestureDetector::new()
1610 .on_tap(Listener::new(move |app| show(app, context)))
1611 .child(Text::new("X"))
1612 .into_widget()
1613 }))
1614 }
1615
1616 fn tap_x_and_settle_entrance(tester: &mut WidgetTester) {
1619 tester.tap(find::text("X"));
1620 tester.pump(); tester.pump_by(ms(750));
1622 }
1623
1624 fn snack_bar_material(tester: &WidgetTester) -> waft_widgets::AnyElement {
1627 let snack_bar = find::by_type::<SnackBar>().evaluate(tester)[0];
1628 find::by_type::<Material>()
1629 .evaluate(tester)
1630 .into_iter()
1631 .find(|material| tester.ancestors(*material).contains(&snack_bar))
1632 .expect("a SnackBar builds a Material")
1633 }
1634
1635 fn snack_bar_material_rect(tester: &WidgetTester) -> Rect {
1637 tester.get_rect(snack_bar_material(tester))
1638 }
1639
1640 fn snack_bar_color(tester: &WidgetTester) -> Color {
1643 use waft_rendering::{RenderPhysicalModel, RenderPhysicalModelBase, RenderPhysicalShape};
1644 let mut render = Some(tester.render_box_of(snack_bar_material(tester)).as_object());
1645 let app = tester.cell.borrow();
1646 while let Some(node) = render {
1647 if let Some(model) = node.downcast::<RenderPhysicalModel>(&app) {
1648 return model.color(&app);
1649 }
1650 if let Some(shape) = node.downcast::<RenderPhysicalShape>(&app) {
1651 return shape.color(&app);
1652 }
1653 let mut child = None;
1654 node.visit_children(&app, &mut |next| child = child.or(Some(next)));
1655 render = child;
1656 }
1657 panic!("a Material paints with a physical model");
1658 }
1659
1660 #[test]
1662 fn a_snack_bar_shows_on_tap_and_leaves_after_its_duration() {
1663 test_widgets(|tester| {
1664 const HELLO_SNACK_BAR: &str = "Hello SnackBar";
1665 let tap_target = GlobalKey::new();
1666 let home = tap_target_scaffold(&tap_target, |app, context| {
1667 show(
1668 app,
1669 context,
1670 SnackBar::new(Text::new(HELLO_SNACK_BAR)).duration(Duration::from_secs(2)),
1671 );
1672 });
1673 pump_app(tester, m3, home.into_widget());
1674 expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
1675 tap_key(tester, &tap_target);
1676 expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
1677 tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
1679 tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
1681 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
1683 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
1685 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
1687 tester.pump_by(ms(750)); tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget()); tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
1692 });
1693 }
1694
1695 #[test]
1697 fn a_second_snack_bar_waits_for_the_first_to_leave() {
1698 test_widgets(|tester| {
1699 let snack_bar_count = Rc::new(Cell::new(0));
1700 let tap_target = GlobalKey::new();
1701 let home = tap_target_scaffold(&tap_target, {
1702 let snack_bar_count = Rc::clone(&snack_bar_count);
1703 move |app, context| {
1704 snack_bar_count.set(snack_bar_count.get() + 1);
1705 show(
1706 app,
1707 context,
1708 SnackBar::new(Text::new(format!("bar{}", snack_bar_count.get())))
1709 .duration(Duration::from_secs(2)),
1710 );
1711 }
1712 });
1713 pump_app(tester, m3, home.into_widget());
1714 let expect_counts = |tester: &WidgetTester, bar1: usize, bar2: usize| {
1715 expect(tester, &find::text("bar1"), finds_n_widgets(bar1));
1716 expect(tester, &find::text("bar2"), finds_n_widgets(bar2));
1717 };
1718 expect_counts(tester, 0, 0);
1719 tap_key(tester, &tap_target); tap_key(tester, &tap_target); expect_counts(tester, 0, 0);
1722 tester.pump(); expect_counts(tester, 1, 0);
1724 tester.pump(); expect_counts(tester, 1, 0);
1726 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1728 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1730 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1732 tester.pump_by(ms(750)); tester.pump(); expect_counts(tester, 1, 0);
1735 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1737 tester.pump(); expect_counts(tester, 0, 1);
1739 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1741 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1743 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1745 tester.pump_by(ms(750)); tester.pump(); expect_counts(tester, 0, 1);
1748 tester.pump_by(ms(750)); expect_counts(tester, 0, 0);
1750 });
1751 }
1752
1753 #[test]
1755 fn closing_a_controller_hides_its_snack_bar_before_its_timeout() {
1756 test_widgets(|tester| {
1757 let snack_bar_count = Rc::new(Cell::new(0));
1758 let time = Rc::new(Cell::new(0));
1759 let last_controller: Rc<RefCell<Option<Rc<SnackBarController>>>> =
1760 Rc::new(RefCell::new(None));
1761 let tap_target = GlobalKey::new();
1762 let home = tap_target_scaffold(&tap_target, {
1763 let snack_bar_count = Rc::clone(&snack_bar_count);
1764 let time = Rc::clone(&time);
1765 let last_controller = Rc::clone(&last_controller);
1766 move |app, context| {
1767 snack_bar_count.set(snack_bar_count.get() + 1);
1768 let controller = show(
1769 app,
1770 context,
1771 SnackBar::new(Text::new(format!("bar{}", snack_bar_count.get())))
1772 .duration(Duration::from_secs(time.get())),
1773 );
1774 *last_controller.borrow_mut() = Some(controller);
1775 }
1776 });
1777 pump_app(tester, m3, home.into_widget());
1778 let expect_counts = |tester: &WidgetTester, bar1: usize, bar2: usize| {
1779 expect(tester, &find::text("bar1"), finds_n_widgets(bar1));
1780 expect(tester, &find::text("bar2"), finds_n_widgets(bar2));
1781 };
1782 expect_counts(tester, 0, 0);
1783 time.set(1000);
1784 tap_key(tester, &tap_target); let first_controller = last_controller.borrow().clone().expect("shown");
1786 time.set(2);
1787 tap_key(tester, &tap_target); expect_counts(tester, 0, 0);
1789 tester.pump(); expect_counts(tester, 1, 0);
1791 tester.pump(); expect_counts(tester, 1, 0);
1793 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1795 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1797 tester.pump_by(ms(750)); expect_counts(tester, 1, 0);
1799 tester.pump_by(ms(10000)); expect_counts(tester, 1, 0);
1801
1802 (first_controller.close)(&mut tester.cell.borrow_mut()); tester.pump_by(ms(750)); tester.pump(); expect_counts(tester, 1, 0);
1807 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1809 tester.pump(); expect_counts(tester, 0, 1);
1811 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1813 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1815 tester.pump_by(ms(750)); expect_counts(tester, 0, 1);
1817 tester.pump_by(ms(750)); tester.pump(); expect_counts(tester, 0, 1);
1820 tester.pump_by(ms(750)); expect_counts(tester, 0, 0);
1822 });
1823 }
1824
1825 fn drag_gestures_of_dismiss_directions(
1827 scaffold_width: f64,
1828 ) -> Vec<(DismissDirection, Vec<Offset>)> {
1829 vec![
1830 (
1831 DismissDirection::Vertical,
1832 vec![
1833 Offset::new(0.0, 50.0), Offset::new(0.0, -50.0), ],
1836 ),
1837 (
1838 DismissDirection::Horizontal,
1839 vec![
1840 Offset::new(scaffold_width, 0.0), Offset::new(-scaffold_width, 0.0), ],
1843 ),
1844 (
1845 DismissDirection::EndToStart,
1846 vec![Offset::new(-scaffold_width, 0.0)], ),
1848 (
1849 DismissDirection::StartToEnd,
1850 vec![Offset::new(scaffold_width, 0.0)], ),
1852 (DismissDirection::Up, vec![Offset::new(0.0, -50.0)]), (DismissDirection::Down, vec![Offset::new(0.0, 50.0)]), ]
1855 }
1856
1857 #[test]
1859 fn a_snack_bar_is_dismissed_by_a_drag_in_each_of_its_directions() {
1860 test_widgets(|tester| {
1861 let tap_target = GlobalKey::new();
1862 let dismiss_direction = Rc::new(Cell::new(DismissDirection::Down));
1863 let width = Rc::new(Cell::new(0.0));
1864 let snack_bar_count = Rc::new(Cell::new(0));
1865 let home = Scaffold::new().body(Builder::new({
1866 let tap_target = tap_target.clone();
1867 let dismiss_direction = Rc::clone(&dismiss_direction);
1868 let width = Rc::clone(&width);
1869 let snack_bar_count = Rc::clone(&snack_bar_count);
1870 move |app, context| {
1871 width.set(MediaQuery::size_of(app, context).width());
1872 let dismiss_direction = Rc::clone(&dismiss_direction);
1873 let snack_bar_count = Rc::clone(&snack_bar_count);
1874 GestureDetector::new()
1875 .key(tap_target.clone().into())
1876 .on_tap(Listener::new(move |app| {
1877 snack_bar_count.set(snack_bar_count.get() + 1);
1878 show(
1879 app,
1880 context,
1881 SnackBar::new(Text::new(format!("bar{}", snack_bar_count.get())))
1882 .duration(Duration::from_secs(2))
1883 .dismiss_direction(dismiss_direction.get()),
1884 );
1885 }))
1886 .behavior(HitTestBehavior::Opaque)
1887 .child(SizedBox::new().height(100.0).width(100.0))
1888 .into_widget()
1889 }
1890 }));
1891 pump_app(tester, m3, home.into_widget());
1892
1893 for (direction, gestures) in drag_gestures_of_dismiss_directions(width.get()) {
1894 dismiss_direction.set(direction);
1895 for drag_gesture in gestures {
1896 snack_bar_count.set(0);
1897 let expect_counts = |tester: &WidgetTester, bar1: usize, bar2: usize| {
1898 expect(tester, &find::text("bar1"), finds_n_widgets(bar1));
1899 expect(tester, &find::text("bar2"), finds_n_widgets(bar2));
1900 };
1901 expect_counts(tester, 0, 0);
1902 tap_key(tester, &tap_target); tap_key(tester, &tap_target); expect_counts(tester, 0, 0);
1905 tester.pump(); expect_counts(tester, 1, 0);
1907 tester.pump(); expect_counts(tester, 1, 0);
1909 tester.pump_by(ms(750)); drag_text(tester, "bar1", drag_gesture);
1911 tester.pump(); expect_counts(tester, 0, 1);
1913 tester.pump_by(ms(750)); drag_text(tester, "bar2", drag_gesture);
1915 tester.pump(); expect_counts(tester, 0, 0);
1917 }
1918 }
1919 });
1920 }
1921
1922 fn dismisses_by_dragging(
1925 tester: &mut WidgetTester,
1926 snack_bar: impl Fn() -> SnackBar + 'static,
1927 label: &str,
1928 drag: f64,
1929 ) {
1930 let tap_target = GlobalKey::new();
1931 let home = tap_target_scaffold(&tap_target, move |app, context| {
1932 show(app, context, snack_bar());
1933 });
1934 pump_app(
1935 tester,
1936 |app| {
1937 ThemeData::builder()
1938 .snack_bar_theme(
1939 SnackBarThemeData::new().dismiss_direction(DismissDirection::StartToEnd),
1940 )
1941 .build(app)
1942 },
1943 home.into_widget(),
1944 );
1945 expect(tester, &find::text(label), finds_nothing());
1946 tap_key(tester, &tap_target);
1947 expect(tester, &find::text(label), finds_nothing());
1948 tester.pump(); expect(tester, &find::text(label), finds_one_widget());
1950 tester.pump(); expect(tester, &find::text(label), finds_one_widget());
1952 tester.pump_by(ms(750));
1953 drag_text(tester, label, Offset::new(drag * 800.0, 0.0));
1954 tester.pump(); expect(tester, &find::text(label), finds_nothing());
1956 }
1957
1958 #[test]
1960 fn the_theme_sets_the_dismiss_direction() {
1961 test_widgets(|tester| {
1962 dismisses_by_dragging(
1963 tester,
1964 || SnackBar::new(Text::new("swipe ltr")).duration(Duration::from_secs(2)),
1965 "swipe ltr",
1966 1.0,
1967 );
1968 });
1969 }
1970
1971 #[test]
1973 fn the_snack_bar_s_dismiss_direction_wins_over_the_theme_s() {
1974 test_widgets(|tester| {
1975 dismisses_by_dragging(
1976 tester,
1977 || {
1978 SnackBar::new(Text::new("swipe rtl"))
1979 .duration(Duration::from_secs(2))
1980 .dismiss_direction(DismissDirection::EndToStart)
1981 },
1982 "swipe rtl",
1983 -1.0,
1984 );
1985 });
1986 }
1987
1988 fn snack_bar_with_action() -> SnackBar {
1991 SnackBar::new(Text::new("I am a snack bar."))
1992 .duration(Duration::from_secs(2))
1993 .action(SnackBarAction::new("ACTION", |_app| {}))
1994 }
1995
1996 #[test]
1998 fn a_snack_bar_action_fires_only_once() {
1999 test_widgets(|tester| {
2000 let tap_count = Rc::new(Cell::new(0));
2001 let home = x_scaffold({
2002 let tap_count = Rc::clone(&tap_count);
2003 move |app, context| {
2004 let tap_count = Rc::clone(&tap_count);
2005 show(
2006 app,
2007 context,
2008 SnackBar::new(Text::new("I am a snack bar."))
2009 .duration(Duration::from_secs(2))
2010 .action(SnackBarAction::new("ACTION", move |_app| {
2011 tap_count.set(tap_count.get() + 1);
2012 })),
2013 );
2014 }
2015 });
2016 pump_app(tester, m3, home.into_widget());
2017 tap_x_and_settle_entrance(tester);
2018
2019 assert_eq!(tap_count.get(), 0);
2020 tester.tap(find::text("ACTION"));
2021 assert_eq!(tap_count.get(), 1);
2022 tester.tap(find::text("ACTION"));
2023 assert_eq!(tap_count.get(), 1);
2024 tester.pump();
2025 tester.tap(find::text("ACTION"));
2026 assert_eq!(tap_count.get(), 1);
2027 });
2028 }
2029
2030 fn with_action_under(tester: &mut WidgetTester, theme: impl FnOnce(&App) -> ThemeData) {
2032 let home = x_scaffold(|app, context| {
2033 show(app, context, snack_bar_with_action());
2034 });
2035 pump_app(tester, theme, home.into_widget());
2036 tap_x_and_settle_entrance(tester);
2037 }
2038
2039 #[test]
2041 fn a_material_2_light_theme_snack_bar_has_a_dark_background() {
2042 test_widgets(|tester| {
2043 with_action_under(tester, |app| ThemeData::light(app, Some(false)));
2044 assert!(crate::test_support::is_same_color_as(
2048 snack_bar_color(tester),
2049 Color::new(0xFF333333)
2050 ));
2051 });
2052 }
2053
2054 #[test]
2056 fn a_material_3_light_theme_snack_bar_has_the_inverse_surface_background() {
2057 test_widgets(|tester| {
2058 with_action_under(tester, m3);
2059 let inverse_surface = m3(&tester.cell.borrow()).color_scheme.inverse_surface();
2060 assert_eq!(snack_bar_color(tester), inverse_surface);
2061 });
2062 }
2063
2064 #[test]
2066 fn a_dark_theme_snack_bar_has_a_light_background() {
2067 test_widgets(|tester| {
2068 with_action_under(tester, |app| ThemeData::dark(app, None));
2069 let on_surface = ThemeData::dark(&tester.cell.borrow(), None)
2070 .color_scheme
2071 .on_surface();
2072 assert_eq!(snack_bar_color(tester), on_surface);
2073 });
2074 }
2075
2076 #[test]
2078 fn a_material_2_dark_theme_snack_bar_has_primary_text_buttons() {
2079 test_widgets(|tester| {
2080 with_action_under(tester, |app| ThemeData::dark(app, Some(false)));
2081 let primary = ThemeData::dark(&tester.cell.borrow(), Some(false))
2082 .color_scheme
2083 .primary();
2084 assert_eq!(tester.text_color("ACTION"), primary);
2085 });
2086 }
2087
2088 #[test]
2090 fn a_material_3_dark_theme_snack_bar_has_inverse_primary_text_buttons() {
2091 test_widgets(|tester| {
2092 with_action_under(tester, |app| ThemeData::dark(app, None));
2093 let inverse_primary = ThemeData::dark(&tester.cell.borrow(), None)
2094 .color_scheme
2095 .inverse_primary();
2096 assert_eq!(tester.text_color("ACTION"), inverse_primary);
2097 });
2098 }
2099
2100 #[test]
2102 fn a_snack_bar_inherits_its_ancestor_s_theme_but_for_the_colour_scheme() {
2103 test_widgets(|tester| {
2104 let theme_before_snack_bar: Rc<RefCell<Option<Rc<ThemeData>>>> = Rc::default();
2105 let theme_after_snack_bar: Rc<RefCell<Option<Rc<ThemeData>>>> = Rc::default();
2106 let home = Scaffold::new().body(Builder::new({
2107 let theme_before_snack_bar = Rc::clone(&theme_before_snack_bar);
2108 let theme_after_snack_bar = Rc::clone(&theme_after_snack_bar);
2109 move |app, context| {
2110 *theme_before_snack_bar.borrow_mut() = Some(Theme::of(app, context));
2111 let theme_after_snack_bar = Rc::clone(&theme_after_snack_bar);
2112 GestureDetector::new()
2113 .on_tap(Listener::new(move |app| {
2114 let theme_after_snack_bar = Rc::clone(&theme_after_snack_bar);
2115 show(
2116 app,
2117 context,
2118 SnackBar::new(Builder::new(move |app, context| {
2119 *theme_after_snack_bar.borrow_mut() =
2120 Some(Theme::of(app, context));
2121 Text::new("I am a snack bar.").into_widget()
2122 }))
2123 .duration(Duration::from_secs(2))
2124 .action(SnackBarAction::new("ACTION", |_app| {})),
2125 );
2126 }))
2127 .child(Text::new("X"))
2128 .into_widget()
2129 }
2130 }));
2131 pump_app(
2132 tester,
2133 |app| {
2134 ThemeData::builder()
2135 .color_scheme(
2136 ColorScheme::from_seed(Colors::GREEN.primary())
2137 .brightness(Brightness::Dark)
2138 .build(),
2139 )
2140 .build(app)
2141 },
2142 home.into_widget(),
2143 );
2144 tap_x_and_settle_entrance(tester);
2145
2146 let theme_after_snack_bar = theme_after_snack_bar.borrow().clone().expect("built");
2147 let compared_theme = theme_before_snack_bar
2148 .borrow()
2149 .as_ref()
2150 .expect("built")
2151 .copy_with()
2152 .color_scheme(theme_after_snack_bar.color_scheme.clone())
2153 .build(); assert!(compared_theme == *theme_after_snack_bar);
2155 });
2156 }
2157
2158 fn showing(
2161 tester: &mut WidgetTester,
2162 theme: impl FnOnce(&App) -> ThemeData,
2163 snack_bar: impl Fn() -> SnackBar + 'static,
2164 ) {
2165 let home = x_scaffold(move |app, context| {
2166 show(app, context, snack_bar());
2167 });
2168 pump_app(tester, theme, home.into_widget());
2169 tap_x_and_settle_entrance(tester);
2170 }
2171
2172 #[test]
2174 fn a_floating_snack_bar_s_margin_can_be_customized() {
2175 test_widgets(|tester| {
2176 const PADDING: f64 = 20.0;
2177 showing(tester, m3, || {
2178 SnackBar::new(Text::new("I am a snack bar."))
2179 .margin(EdgeInsets::all(PADDING))
2180 .behavior(SnackBarBehavior::Floating)
2181 });
2182 let material = snack_bar_material_rect(tester);
2183 assert_eq!(material.bottom_left().dx(), PADDING);
2184 assert_eq!(material.bottom_left().dy(), 600.0 - PADDING); assert_eq!(material.bottom_right().dx(), 800.0 - PADDING); });
2187 }
2188
2189 #[test]
2191 fn a_floating_snack_bar_is_positioned_within_the_safe_area() {
2192 test_widgets(|tester| {
2193 const VIEW_PADDING: f64 = 50.0;
2194 const FLOATING_SNACK_BAR_DEFAULT_BOTTOM_MARGIN: f64 = 10.0;
2195 let home = waft_widgets::MediaQuery::new(
2196 waft_widgets::MediaQueryData::new().view_padding(EdgeInsets::only(
2198 0.0,
2199 0.0,
2200 0.0,
2201 VIEW_PADDING,
2202 )),
2203 x_scaffold(|app, context| {
2204 show(
2205 app,
2206 context,
2207 SnackBar::new(Text::new("I am a snack bar."))
2208 .behavior(SnackBarBehavior::Floating),
2209 );
2210 }),
2211 );
2212 pump_app(tester, m3, home.into_widget());
2213 tap_x_and_settle_entrance(tester);
2214 assert_eq!(
2215 snack_bar_material_rect(tester).bottom_left().dy(),
2216 600.0 - VIEW_PADDING - FLOATING_SNACK_BAR_DEFAULT_BOTTOM_MARGIN
2218 );
2219 });
2220 }
2221
2222 #[test]
2224 fn a_snack_bar_s_padding_can_be_customized() {
2225 test_widgets(|tester| {
2226 const PADDING: f64 = 20.0;
2227 showing(tester, m3, || {
2228 SnackBar::new(Text::new("I am a snack bar.")).padding(EdgeInsets::all(PADDING))
2229 });
2230 let text = tester.get_rect(find::text("I am a snack bar."));
2231 let material = snack_bar_material_rect(tester);
2232 assert_eq!(
2233 text.bottom_left().dx() - material.bottom_left().dx(),
2234 PADDING
2235 );
2236 assert_eq!(material.top_right().dx() - text.top_right().dx(), PADDING);
2237 assert_eq!(
2238 material.bottom_left().dy() - text.bottom_left().dy(),
2239 PADDING
2240 );
2241 assert_eq!(text.top_right().dy() - material.top_right().dy(), PADDING);
2242 });
2243 }
2244
2245 fn assert_centred_with_width(tester: &WidgetTester, width: f64) {
2247 let material = snack_bar_material_rect(tester);
2248 assert_eq!(material.bottom_left().dx(), (800.0 - width) / 2.0); assert_eq!(material.bottom_right().dx(), (800.0 + width) / 2.0); }
2251
2252 #[test]
2254 fn a_floating_snack_bar_s_width_can_be_customized() {
2255 test_widgets(|tester| {
2256 const WIDTH: f64 = 200.0;
2257 showing(tester, m3, || {
2258 SnackBar::new(Text::new("I am a snack bar."))
2259 .width(WIDTH)
2260 .behavior(SnackBarBehavior::Floating)
2261 });
2262 assert_centred_with_width(tester, WIDTH);
2263 });
2264 }
2265
2266 #[test]
2268 fn a_floating_snack_bar_s_width_can_come_from_the_theme() {
2269 test_widgets(|tester| {
2270 const WIDTH: f64 = 200.0;
2271 showing(
2272 tester,
2273 |app| {
2274 ThemeData::builder()
2275 .snack_bar_theme(
2276 SnackBarThemeData::new()
2277 .width(WIDTH)
2278 .behavior(SnackBarBehavior::Floating),
2279 )
2280 .build(app)
2281 },
2282 || SnackBar::new(Text::new("Feeling snackish")),
2283 );
2284 assert_centred_with_width(tester, WIDTH);
2285 });
2286 }
2287
2288 #[test]
2290 fn the_snack_bar_s_width_wins_over_the_theme_s() {
2291 test_widgets(|tester| {
2292 const THEME_WIDTH: f64 = 200.0;
2293 const WIDGET_WIDTH: f64 = 400.0;
2294 showing(
2295 tester,
2296 |app| {
2297 ThemeData::builder()
2298 .snack_bar_theme(
2299 SnackBarThemeData::new()
2300 .width(THEME_WIDTH)
2301 .behavior(SnackBarBehavior::Floating),
2302 )
2303 .build(app)
2304 },
2305 || SnackBar::new(Text::new("Feeling super snackish")).width(WIDGET_WIDTH),
2306 );
2307 assert_centred_with_width(tester, WIDGET_WIDTH);
2308 });
2309 }
2310
2311 fn action_button_style(tester: &WidgetTester) -> crate::button_style::ButtonStyle {
2313 use crate::button_style_button::ButtonStyleButton;
2314 let action = find::text("ACTION").evaluate(tester)[0];
2315 let button = tester.ancestor_of_type::<TextButton>(action);
2316 tester.widget(button, |button: &TextButton| {
2317 button
2318 .button_style_button_data()
2319 .style
2320 .clone()
2321 .expect("the action's style")
2322 })
2323 }
2324
2325 fn states(states: &[WidgetState]) -> waft_widgets::WidgetStates {
2326 states.iter().copied().collect()
2327 }
2328
2329 #[test]
2331 fn a_material_2_snack_bar_action_label_takes_its_text_color() {
2332 test_widgets(|tester| {
2333 showing(tester, m2, || {
2334 SnackBar::new(Text::new("I am a snack bar."))
2335 .duration(Duration::from_secs(2))
2336 .action(
2337 SnackBarAction::new("ACTION", |_app| {})
2338 .text_color(Colors::LIGHT_BLUE.primary())
2339 .disabled_text_color(Colors::RED.primary()),
2340 )
2341 });
2342 assert_eq!(tester.text_color("ACTION"), Colors::LIGHT_BLUE.primary());
2343 });
2344 }
2345
2346 #[test]
2348 fn a_material_3_snack_bar_action_resolves_its_text_color_in_every_state() {
2349 test_widgets(|tester| {
2350 let used_color = Colors::TEAL.primary();
2351 showing(tester, m3, move || {
2352 SnackBar::new(Text::new("I am a snack bar."))
2353 .duration(Duration::from_secs(2))
2354 .action(SnackBarAction::new("ACTION", |_app| {}).text_color(used_color))
2355 });
2356 let style = action_button_style(tester);
2357 assert_eq!(
2359 style
2360 .foreground_color
2361 .expect("a foreground color")
2362 .resolve(&states(&[])),
2363 Some(used_color)
2364 );
2365 });
2366 }
2367
2368 #[test]
2370 fn a_widget_state_text_color_resolves_the_action_label_by_state() {
2371 test_widgets(|tester| {
2372 const COLOR_RED: u32 = 0xFFF44336;
2373 const COLOR_BLUE: u32 = 0xFF2196F3;
2374 showing(tester, m3, || {
2375 let used_color = WidgetStateColor::resolve_with(|states| {
2377 if states.contains(&WidgetState::Pressed) {
2378 return Color::new(COLOR_BLUE);
2379 }
2380 Color::new(COLOR_RED)
2381 });
2382 SnackBar::new(Text::new("I am a snack bar."))
2383 .duration(Duration::from_secs(2))
2384 .action(SnackBarAction::new("ACTION", |_app| {}).text_color(used_color))
2385 });
2386 let foreground_color = action_button_style(tester)
2387 .foreground_color
2388 .expect("a foreground color");
2389 assert_eq!(
2390 foreground_color.resolve(&states(&[WidgetState::Pressed])),
2391 Some(Color::new(COLOR_BLUE))
2392 );
2393 assert_eq!(
2394 foreground_color.resolve(&states(&[])),
2395 Some(Color::new(COLOR_RED))
2396 );
2397 });
2398 }
2399
2400 #[test]
2402 fn a_snack_bar_pushes_the_floating_action_button_above_it() {
2403 test_widgets(|tester| {
2404 let home = waft_widgets::MediaQuery::new(
2405 waft_widgets::MediaQueryData::new()
2406 .padding(EdgeInsets::only(10.0, 20.0, 30.0, 40.0)),
2407 x_scaffold(|app, context| {
2408 show(app, context, snack_bar_with_action());
2409 })
2410 .floating_action_button(
2411 crate::floating_action_button::FloatingActionButton::new(Some(Listener::new(
2412 |_app| {},
2413 )))
2414 .child(Icon::new(Some(Icons::send()))),
2415 ),
2416 );
2417 pump_app(tester, m3, home.into_widget());
2418 let fab_rect = |tester: &WidgetTester| {
2419 let fab = find::by_type::<crate::floating_action_button::FloatingActionButton>()
2420 .evaluate(tester)[0];
2421 tester.get_rect(fab)
2422 };
2423
2424 let original_fab_rect = fab_rect(tester);
2426
2427 tap_x_and_settle_entrance(tester); let fab_rect = fab_rect(tester);
2430
2431 assert!(fab_rect.center().dy() < original_fab_rect.center().dy());
2433
2434 let snack_bar = find::by_type::<SnackBar>().evaluate(tester)[0];
2435 let snack_bar_top_right = tester.get_rect(snack_bar).top_right();
2436
2437 const DEFAULT_FAB_PADDING: f64 = 16.0;
2439
2440 assert_f32_equals(
2443 fab_rect.bottom_right().dy(),
2444 snack_bar_top_right.dy() - DEFAULT_FAB_PADDING,
2445 );
2446 });
2447 }
2448
2449 #[test]
2451 fn the_closed_future_tells_how_the_snack_bar_closed() {
2452 test_widgets(|tester| {
2453 let action_pressed = Rc::new(Cell::new(false));
2454 let closed_reason: Rc<Cell<Option<SnackBarClosedReason>>> = Rc::default();
2455 let body_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
2456 let home = |with_action: bool| {
2457 let action_pressed = Rc::clone(&action_pressed);
2458 let closed_reason = Rc::clone(&closed_reason);
2459 let body_context = Rc::clone(&body_context);
2460 Scaffold::new().body(Builder::new(move |_app, context| {
2461 body_context.set(Some(context));
2462 let action_pressed = Rc::clone(&action_pressed);
2463 let closed_reason = Rc::clone(&closed_reason);
2464 GestureDetector::new()
2465 .on_tap(Listener::new(move |app| {
2466 let mut snack_bar =
2467 SnackBar::new(Text::new("snack")).duration(Duration::from_secs(2));
2468 if with_action {
2469 let action_pressed = Rc::clone(&action_pressed);
2470 snack_bar = snack_bar
2471 .action(SnackBarAction::new("ACTION", move |_app| {
2472 action_pressed.set(true)
2473 }));
2474 }
2475 let closed_reason = Rc::clone(&closed_reason);
2476 show(app, context, snack_bar)
2477 .closed()
2478 .then(app, move |_app, reason| closed_reason.set(Some(reason)));
2479 }))
2480 .child(Text::new("X"))
2481 .into_widget()
2482 }))
2483 };
2484 let messenger = |tester: &WidgetTester| {
2485 let mut app = tester.cell.borrow_mut();
2486 let context = body_context.get().expect("built");
2487 ScaffoldMessenger::of(&mut app, context)
2488 };
2489 pump_app(tester, m3, home(true).into_widget());
2490
2491 tap_x_and_settle_entrance(tester);
2493 assert!(!action_pressed.get());
2494 tester.tap(find::text("ACTION"));
2495 assert!(action_pressed.get());
2496 tester.pump_by(ms(250));
2498 assert_eq!(closed_reason.get(), None);
2499 tester.pump_and_settle_by(Duration::from_secs(1));
2501 assert_eq!(closed_reason.get(), Some(SnackBarClosedReason::Action));
2502
2503 tester.tap(find::text("X"));
2505 tester.pump_by(ms(750));
2506 tester.pump_by(ms(750));
2507 drag_text(tester, "snack", Offset::new(0.0, 50.0));
2508 tester.pump_and_settle_by(Duration::from_secs(1));
2509 assert_eq!(closed_reason.get(), Some(SnackBarClosedReason::Swipe));
2510
2511 tester.tap(find::text("X"));
2513 tester.pump_by(ms(750));
2514 let scaffold_messenger = messenger(tester);
2515 scaffold_messenger.remove_current_snack_bar(
2516 &mut tester.cell.borrow_mut(),
2517 SnackBarClosedReason::Remove,
2518 );
2519 tester.pump_and_settle_by(Duration::from_secs(1));
2520 assert_eq!(closed_reason.get(), Some(SnackBarClosedReason::Remove));
2521
2522 tester.tap(find::text("X"));
2524 tester.pump_by(ms(750));
2525 let scaffold_messenger = messenger(tester);
2526 scaffold_messenger
2527 .hide_current_snack_bar(&mut tester.cell.borrow_mut(), SnackBarClosedReason::Hide);
2528 tester.pump_and_settle_by(Duration::from_secs(1));
2529 assert_eq!(closed_reason.get(), Some(SnackBarClosedReason::Hide));
2530
2531 pump_app(tester, m3, home(false).into_widget());
2534
2535 tester.tap(find::text("X"));
2537 tester.pump_by(ms(750));
2538 tester.pump_by(ms(750));
2539 tester.pump_by(ms(1500));
2540 tester.pump(); tester.pump_and_settle_by(Duration::from_secs(1));
2542 assert_eq!(closed_reason.get(), Some(SnackBarClosedReason::Timeout));
2543 });
2544 }
2545
2546 #[test]
2548 fn under_accessible_navigation_a_snack_bar_with_an_action_shows_at_once_and_stays() {
2549 test_widgets(|tester| {
2550 let scaffold_key = GlobalKey::new();
2551 let home = waft_widgets::MediaQuery::new(
2552 waft_widgets::MediaQueryData::new().accessible_navigation(true),
2553 ScaffoldMessenger::new(Builder::new({
2554 let scaffold_key = scaffold_key.clone();
2555 move |_app, context| {
2556 Scaffold::new()
2557 .key(scaffold_key.clone().into())
2558 .body(
2559 GestureDetector::new()
2560 .on_tap(Listener::new(move |app| {
2561 show(
2562 app,
2563 context,
2564 SnackBar::new(Text::new("snack"))
2565 .duration(Duration::from_secs(1))
2566 .action(SnackBarAction::new("ACTION", |_app| {})),
2567 );
2568 }))
2569 .child(Text::new("X")),
2570 )
2571 .into_widget()
2572 }
2573 })),
2574 );
2575 pump_app(tester, m3, home.into_widget());
2576 tester.tap(find::text("X"));
2577 tester.pump();
2578 expect(tester, &find::text("ACTION"), finds_one_widget());
2580 tester.pump_by(Duration::from_secs(10));
2582 expect(tester, &find::text("ACTION"), finds_one_widget());
2583 tester.tap(find::text("ACTION"));
2584 tester.pump();
2585 expect(tester, &find::text("ACTION"), finds_nothing());
2587 });
2588 }
2589
2590 #[test]
2592 fn a_snack_bar_shows_for_four_seconds_by_default() {
2593 test_widgets(|tester| {
2594 const HELLO_SNACK_BAR: &str = "Hello SnackBar";
2595 let tap_target = GlobalKey::new();
2596 let home = tap_target_scaffold(&tap_target, |app, context| {
2597 show(app, context, SnackBar::new(Text::new(HELLO_SNACK_BAR)));
2598 });
2599 pump_app(tester, m3, home.into_widget());
2600 expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
2601 tap_key(tester, &tap_target);
2602 expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
2603 tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2605 tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2607 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2609 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2611 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2613 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2615 tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget());
2617 tester.pump_by(ms(1000)); tester.pump(); expect(tester, &find::text(HELLO_SNACK_BAR), finds_one_widget()); tester.pump_by(ms(750)); expect(tester, &find::text(HELLO_SNACK_BAR), finds_nothing());
2622 });
2623 }
2624
2625 #[test]
2627 fn a_snack_bar_follows_changes_to_accessible_navigation() {
2628 test_widgets(|tester| {
2629 let boilerplate = |tester: &mut WidgetTester, accessible_navigation: bool| {
2630 let theme = m3(&tester.cell.borrow());
2631 tester.pump_widget(
2632 waft_widgets::MediaQuery::new(
2633 waft_widgets::MediaQueryData::new()
2634 .accessible_navigation(accessible_navigation),
2635 material_app(
2636 theme,
2637 Scaffold::new()
2638 .body(Builder::new(|_app, context| {
2639 GestureDetector::new()
2640 .on_tap(Listener::new(move |app| {
2641 show(
2642 app,
2643 context,
2644 SnackBar::new(Text::new("test"))
2645 .action(SnackBarAction::new("foo", |_app| {})),
2646 );
2647 }))
2648 .behavior(HitTestBehavior::Opaque)
2649 .child(Text::new("X"))
2650 .into_widget()
2651 }))
2652 .into_widget(),
2653 ),
2654 )
2655 .into_widget(),
2656 );
2657 };
2658
2659 boilerplate(tester, false);
2660 expect(tester, &find::text("test"), finds_nothing());
2661 tester.tap(find::text("X"));
2662 tester.pump(); expect(tester, &find::text("test"), finds_one_widget());
2664 tester.pump(); tester.pump_by(ms(4750)); expect(tester, &find::text("test"), finds_one_widget());
2667
2668 boilerplate(tester, true);
2670
2671 tester.pump_by(ms(4000)); tester.pump();
2673 expect(tester, &find::text("test"), finds_one_widget());
2674
2675 boilerplate(tester, false);
2677 tester.pump_and_settle_by(ms(5750));
2678 expect(tester, &find::text("test"), finds_one_widget());
2679
2680 tester.tap(find::text("foo"));
2681 tester.pump_and_settle();
2682 expect(tester, &find::text("test"), finds_nothing());
2683 });
2684 }
2685
2686 fn count_on_visible(
2689 tester: &mut WidgetTester,
2690 labels: &'static [&'static str],
2691 ) -> Rc<Cell<i32>> {
2692 let called = Rc::new(Cell::new(0));
2693 let tap_target = GlobalKey::new();
2694 let home = tap_target_scaffold(&tap_target, {
2695 let called = Rc::clone(&called);
2696 move |app, context| {
2697 for label in labels {
2698 let called = Rc::clone(&called);
2699 show(
2700 app,
2701 context,
2702 SnackBar::new(Text::new(*label))
2703 .duration(Duration::from_secs(1))
2704 .on_visible(move |_app| called.set(called.get() + 1)),
2705 );
2706 }
2707 }
2708 });
2709 pump_app(tester, m3, home.into_widget());
2710 tap_key(tester, &tap_target);
2711 tester.pump(); tester.pump_and_settle();
2713 called
2714 }
2715
2716 #[test]
2718 fn a_snack_bar_calls_on_visible_once() {
2719 test_widgets(|tester| {
2720 let called = count_on_visible(tester, &["hello"]);
2721 expect(tester, &find::text("hello"), finds_one_widget());
2722 assert_eq!(called.get(), 1);
2723 });
2724 }
2725
2726 #[test]
2728 fn a_queued_snack_bar_does_not_call_on_visible() {
2729 test_widgets(|tester| {
2730 let called = count_on_visible(tester, &["hello", "hello 2"]);
2731 expect(tester, &find::text("hello"), finds_one_widget());
2732 assert_eq!(called.get(), 1);
2733 });
2734 }
2735
2736 fn rect_of_type<W: 'static>(tester: &WidgetTester) -> Rect {
2740 let element = find::by_type::<W>().evaluate(tester)[0];
2741 tester.get_rect(element)
2742 }
2743
2744 fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
2746 tester.get_rect(key)
2747 }
2748
2749 fn show_from_messenger_and_settle(tester: &mut WidgetTester, snack_bar: SnackBar) {
2752 let messenger = find::by_type::<ScaffoldMessenger>().evaluate(tester)[0];
2753 {
2754 let mut app = tester.cell.borrow_mut();
2755 let state = messenger
2756 .state_handle::<crate::scaffold::ScaffoldMessengerState>(&app)
2757 .expect("a ScaffoldMessengerState");
2758 state.show_snack_bar(&mut app, snack_bar, None);
2759 }
2760 tester.pump_and_settle(); }
2762
2763 fn fab() -> crate::floating_action_button::FloatingActionButton {
2764 crate::floating_action_button::FloatingActionButton::new(Some(Listener::new(|_app| {})))
2765 }
2766
2767 fn fab_with_icon() -> crate::floating_action_button::FloatingActionButton {
2768 fab().child(Icon::new(Some(Icons::send())))
2769 }
2770
2771 #[test]
2774 fn a_snack_bar_aligns_with_the_bottom_of_an_empty_scaffold() {
2775 test_widgets(|tester| {
2776 for behavior in [SnackBarBehavior::Fixed, SnackBarBehavior::Floating] {
2777 pump_app(
2778 tester,
2779 m3,
2780 Scaffold::new()
2781 .body(waft_widgets::Container::new())
2782 .into_widget(),
2783 );
2784 show_from_messenger_and_settle(
2785 tester,
2786 SnackBar::new(Text::new("SnackBar text")).behavior(behavior),
2787 );
2788 let snack_bar = rect_of_type::<SnackBar>(tester);
2789 let scaffold = rect_of_type::<Scaffold>(tester);
2790 assert_eq!(
2791 snack_bar.bottom_right(),
2792 scaffold.bottom_right(),
2793 "{behavior:?}"
2794 );
2795 assert_eq!(
2796 snack_bar.bottom_left(),
2797 scaffold.bottom_left(),
2798 "{behavior:?}"
2799 );
2800 }
2801 });
2802 }
2803
2804 #[test]
2807 fn a_snack_bar_aligns_with_the_top_of_the_bottom_navigation_bar() {
2808 test_widgets(|tester| {
2809 for behavior in [SnackBarBehavior::Fixed, SnackBarBehavior::Floating] {
2810 let box_key = GlobalKey::new();
2811 pump_app(
2812 tester,
2813 m3,
2814 Scaffold::new()
2815 .body(waft_widgets::Container::new())
2816 .bottom_navigation_bar(
2817 SizedBox::new()
2818 .key(box_key.clone().into())
2819 .width(800.0)
2820 .height(60.0),
2821 )
2822 .into_widget(),
2823 );
2824 show_from_messenger_and_settle(
2825 tester,
2826 SnackBar::new(Text::new("SnackBar text")).behavior(behavior),
2827 );
2828 let snack_bar = rect_of_type::<SnackBar>(tester);
2829 let bottom_navigation_bar = rect_of_key(tester, &box_key);
2830 assert_eq!(snack_bar.bottom_right(), bottom_navigation_bar.top_right());
2831 assert_eq!(snack_bar.bottom_left(), bottom_navigation_bar.top_left());
2832 }
2833 });
2834 }
2835
2836 #[test]
2838 fn a_fixed_snack_bar_s_padding_is_not_consumed_by_view_insets() {
2839 test_widgets(|tester| {
2840 let child = |tester: &WidgetTester| {
2841 material_app(
2842 m3(&tester.cell.borrow()),
2843 Scaffold::new()
2844 .resize_to_avoid_bottom_inset(false)
2845 .floating_action_button(fab_with_icon())
2846 .body(Builder::new(|_app, context| {
2847 GestureDetector::new()
2848 .on_tap(Listener::new(move |app| {
2849 show(
2850 app,
2851 context,
2852 snack_bar_with_action().behavior(SnackBarBehavior::Fixed),
2853 );
2854 }))
2855 .child(Text::new("X"))
2856 .into_widget()
2857 }))
2858 .into_widget(),
2859 )
2860 };
2861 let app = child(tester);
2862 tester.pump_widget(
2863 waft_widgets::MediaQuery::new(
2864 waft_widgets::MediaQueryData::new()
2865 .padding(EdgeInsets::only(0.0, 0.0, 0.0, 20.0)),
2866 app,
2867 )
2868 .into_widget(),
2869 );
2870 tester.tap(find::text("X"));
2871 tester.pump_and_settle(); let initial = rect_of_type::<SnackBar>(tester);
2873 let app = child(tester);
2875 tester.pump_widget(
2876 waft_widgets::MediaQuery::new(
2877 waft_widgets::MediaQueryData::new()
2878 .view_padding(EdgeInsets::all(20.0))
2879 .view_insets(EdgeInsets::all(100.0)),
2880 app,
2881 )
2882 .into_widget(),
2883 );
2884 tester.tap(find::text("X"));
2885 tester.pump_and_settle(); let last = rect_of_type::<SnackBar>(tester);
2887 assert_eq!(initial.bottom_left(), last.bottom_left());
2888 assert_eq!(initial.bottom_right(), last.bottom_right());
2889 });
2890 }
2891
2892 #[test]
2895 fn a_fixed_snack_bar_aligns_with_the_bottom_of_a_scaffold_with_a_floating_action_button() {
2896 test_widgets(|tester| {
2897 pump_app(
2898 tester,
2899 m3,
2900 Scaffold::new()
2901 .body(waft_widgets::Container::new())
2902 .floating_action_button(fab())
2903 .into_widget(),
2904 );
2905 show_from_messenger_and_settle(
2906 tester,
2907 SnackBar::new(Text::new("Snackbar text")).behavior(SnackBarBehavior::Fixed),
2908 );
2909 let snack_bar = rect_of_type::<SnackBar>(tester);
2910 let scaffold = rect_of_type::<Scaffold>(tester);
2911 assert_eq!(snack_bar.bottom_right(), scaffold.bottom_right());
2912 assert_eq!(snack_bar.bottom_left(), scaffold.bottom_left());
2913 });
2914 }
2915
2916 fn floating_with_fab(
2919 tester: &mut WidgetTester,
2920 fab_location: Option<
2921 crate::floating_action_button_location::FloatingActionButtonLocationRef,
2922 >,
2923 ) {
2924 let mut scaffold = x_scaffold(|app, context| {
2925 show(
2926 app,
2927 context,
2928 snack_bar_with_action().behavior(SnackBarBehavior::Floating),
2929 );
2930 })
2931 .floating_action_button(fab_with_icon());
2932 if let Some(fab_location) = fab_location {
2933 scaffold = scaffold.floating_action_button_location(fab_location);
2934 }
2935 pump_app(tester, m3, scaffold.into_widget());
2936 tester.tap(find::text("X"));
2937 tester.pump_and_settle(); }
2939
2940 #[test]
2943 fn a_floating_snack_bar_sits_on_top_of_the_floating_action_button() {
2944 test_widgets(|tester| {
2945 floating_with_fab(tester, None);
2946 assert_eq!(
2949 rect_of_type::<SnackBar>(tester).bottom_left().dy(),
2950 rect_of_type::<crate::floating_action_button::FloatingActionButton>(tester)
2951 .top_left()
2952 .dy()
2953 );
2954 });
2955 }
2956
2957 #[test]
2961 fn a_floating_snack_bar_ignores_a_floating_action_button_at_a_top_location() {
2962 test_widgets(|tester| {
2963 use crate::floating_action_button_location::FloatingActionButtonLocation;
2964 let top_locations = [
2965 <dyn FloatingActionButtonLocation>::start_top(),
2966 <dyn FloatingActionButtonLocation>::center_top(),
2967 <dyn FloatingActionButtonLocation>::end_top(),
2968 <dyn FloatingActionButtonLocation>::mini_start_top(),
2969 <dyn FloatingActionButtonLocation>::mini_center_top(),
2970 <dyn FloatingActionButtonLocation>::mini_end_top(),
2971 ];
2972 for location in top_locations {
2973 floating_with_fab(tester, Some(Rc::clone(&location)));
2974 assert_eq!(
2975 rect_of_type::<SnackBar>(tester).bottom_left().dy(),
2976 600.0, "{location:?}"
2978 );
2979 }
2980 });
2981 }
2982
2983 #[derive(Debug)]
2985 struct CustomFloatingActionButtonLocation;
2986
2987 impl crate::floating_action_button_location::FloatingActionButtonLocation
2988 for CustomFloatingActionButtonLocation
2989 {
2990 fn get_offset(
2991 &self,
2992 scaffold_geometry: &crate::scaffold::ScaffoldPrelayoutGeometry,
2993 ) -> Offset {
2994 crate::floating_action_button_location::StandardFabLocation::get_offset(
2995 self,
2996 scaffold_geometry,
2997 )
2998 }
2999 }
3000
3001 impl crate::floating_action_button_location::StandardFabLocation
3002 for CustomFloatingActionButtonLocation
3003 {
3004 fn get_offset_x(
3005 &self,
3006 scaffold_geometry: &crate::scaffold::ScaffoldPrelayoutGeometry,
3007 adjustment: f64,
3008 ) -> f64 {
3009 crate::floating_action_button_location::FabEndOffsetX::get_offset_x(
3010 self,
3011 scaffold_geometry,
3012 adjustment,
3013 )
3014 }
3015
3016 fn get_offset_y(
3017 &self,
3018 scaffold_geometry: &crate::scaffold::ScaffoldPrelayoutGeometry,
3019 adjustment: f64,
3020 ) -> f64 {
3021 crate::floating_action_button_location::FabFloatOffsetY::get_offset_y(
3022 self,
3023 scaffold_geometry,
3024 adjustment,
3025 )
3026 }
3027 }
3028
3029 impl crate::floating_action_button_location::FabEndOffsetX for CustomFloatingActionButtonLocation {}
3030 impl crate::floating_action_button_location::FabFloatOffsetY
3031 for CustomFloatingActionButtonLocation
3032 {
3033 }
3034
3035 #[test]
3039 fn a_floating_snack_bar_sits_on_top_of_a_floating_action_button_at_any_other_location() {
3040 test_widgets(|tester| {
3041 use crate::floating_action_button_location::FloatingActionButtonLocation;
3042 let non_top_locations: Vec<
3043 crate::floating_action_button_location::FloatingActionButtonLocationRef,
3044 > = vec![
3045 <dyn FloatingActionButtonLocation>::start_docked(),
3046 <dyn FloatingActionButtonLocation>::start_float(),
3047 <dyn FloatingActionButtonLocation>::center_docked(),
3048 <dyn FloatingActionButtonLocation>::center_float(),
3049 <dyn FloatingActionButtonLocation>::end_contained(),
3050 <dyn FloatingActionButtonLocation>::end_docked(),
3051 <dyn FloatingActionButtonLocation>::end_float(),
3052 <dyn FloatingActionButtonLocation>::mini_start_docked(),
3053 <dyn FloatingActionButtonLocation>::mini_start_float(),
3054 <dyn FloatingActionButtonLocation>::mini_center_docked(),
3055 <dyn FloatingActionButtonLocation>::mini_center_float(),
3056 <dyn FloatingActionButtonLocation>::mini_end_docked(),
3057 <dyn FloatingActionButtonLocation>::mini_end_float(),
3058 Rc::new(CustomFloatingActionButtonLocation),
3060 ];
3061 for location in non_top_locations {
3062 floating_with_fab(tester, Some(Rc::clone(&location)));
3063 assert_eq!(
3066 rect_of_type::<SnackBar>(tester).bottom_left().dy(),
3067 rect_of_type::<crate::floating_action_button::FloatingActionButton>(tester)
3068 .top_left()
3069 .dy(),
3070 "{location:?}"
3071 );
3072 }
3073 });
3074 }
3075
3076 fn with_bottom_bar_and_fab(
3078 box_key: &GlobalKey,
3079 bar_height: f64,
3080 fab_location: Option<
3081 crate::floating_action_button_location::FloatingActionButtonLocationRef,
3082 >,
3083 ) -> WidgetRef {
3084 let mut scaffold = Scaffold::new()
3085 .body(waft_widgets::Container::new())
3086 .bottom_navigation_bar(
3087 SizedBox::new()
3088 .key(box_key.clone().into())
3089 .width(800.0)
3090 .height(bar_height),
3091 )
3092 .floating_action_button(fab());
3093 if let Some(fab_location) = fab_location {
3094 scaffold = scaffold.floating_action_button_location(fab_location);
3095 }
3096 scaffold.into_widget()
3097 }
3098
3099 #[test]
3102 fn a_fixed_snack_bar_sits_on_the_bottom_navigation_bar_beside_a_floating_action_button() {
3103 test_widgets(|tester| {
3104 let box_key = GlobalKey::new();
3105 pump_app(tester, m3, with_bottom_bar_and_fab(&box_key, 60.0, None));
3106 show_from_messenger_and_settle(
3107 tester,
3108 SnackBar::new(Text::new("SnackBar text")).behavior(SnackBarBehavior::Fixed),
3109 );
3110 let snack_bar = rect_of_type::<SnackBar>(tester);
3111 let bottom_navigation_bar = rect_of_key(tester, &box_key);
3112 assert_eq!(snack_bar.bottom_right(), bottom_navigation_bar.top_right());
3113 assert_eq!(snack_bar.bottom_left(), bottom_navigation_bar.top_left());
3114 });
3115 }
3116
3117 #[test]
3120 fn a_floating_snack_bar_sits_on_the_floating_action_button_above_a_bottom_navigation_bar() {
3121 test_widgets(|tester| {
3122 let box_key = GlobalKey::new();
3123 pump_app(tester, m3, with_bottom_bar_and_fab(&box_key, 60.0, None));
3124 show_from_messenger_and_settle(
3125 tester,
3126 SnackBar::new(Text::new("SnackBar text")).behavior(SnackBarBehavior::Floating),
3127 );
3128 assert_eq!(
3129 rect_of_type::<SnackBar>(tester).bottom_right().dy(),
3130 rect_of_type::<crate::floating_action_button::FloatingActionButton>(tester)
3131 .top_right()
3132 .dy()
3133 );
3134 });
3135 }
3136
3137 #[test]
3141 fn a_floating_snack_bar_sits_on_a_bottom_navigation_bar_higher_than_the_button() {
3142 test_widgets(|tester| {
3143 use crate::floating_action_button_location::FloatingActionButtonLocation;
3144 let box_key = GlobalKey::new();
3145 pump_app(
3146 tester,
3147 m3,
3148 with_bottom_bar_and_fab(
3149 &box_key,
3150 200.0,
3151 Some(<dyn FloatingActionButtonLocation>::end_contained()),
3152 ),
3153 );
3154 show_from_messenger_and_settle(
3155 tester,
3156 SnackBar::new(Text::new("SnackBar text")).behavior(SnackBarBehavior::Floating),
3157 );
3158 let snack_bar_bottom_right = rect_of_type::<SnackBar>(tester).bottom_right();
3159 let fab_top_right =
3160 rect_of_type::<crate::floating_action_button::FloatingActionButton>(tester)
3161 .top_right();
3162 let nav_bar_top_right = rect_of_key(tester, &box_key).top_right();
3163
3164 assert!(fab_top_right.dy() > nav_bar_top_right.dy());
3166
3167 assert_eq!(snack_bar_bottom_right.dy(), nav_bar_top_right.dy());
3168 });
3169 }
3170
3171 fn open_floating_snack_bar(tester: &mut WidgetTester) {
3173 show_from_messenger_and_settle(
3174 tester,
3175 SnackBar::new(Text::new("SnackBar text")).behavior(SnackBarBehavior::Floating),
3176 );
3177 }
3178
3179 fn with_fab_height(tester: &mut WidgetTester, fab_height: f64) {
3181 pump_app(
3182 tester,
3183 m3,
3184 Scaffold::new()
3185 .floating_action_button(waft_widgets::Container::new().height(fab_height))
3186 .into_widget(),
3187 );
3188 }
3189
3190 const MEDIUM_FAB_HEIGHT: f64 = 100.0;
3191
3192 fn space_above_snack_bar(tester: &mut WidgetTester) -> f64 {
3194 with_fab_height(tester, MEDIUM_FAB_HEIGHT);
3195 open_floating_snack_bar(tester);
3196 rect_of_type::<SnackBar>(tester).top_left().dy()
3197 }
3198
3199 #[test]
3202 fn a_floating_snack_bar_right_at_the_top_of_the_screen_does_not_assert() {
3203 test_widgets(|tester| {
3204 let space_above_snack_bar = space_above_snack_bar(tester);
3205 with_fab_height(tester, space_above_snack_bar + MEDIUM_FAB_HEIGHT);
3207 open_floating_snack_bar(tester);
3208 });
3209 }
3210
3211 #[test]
3213 #[should_panic(
3214 expected = "Floating SnackBar presented off screen.\nA SnackBar with behavior property \
3215 set to SnackBarBehavior.floating is fully or partially off screen because \
3216 some or all the widgets provided to Scaffold.floatingActionButton, \
3217 Scaffold.persistentFooterButtons and Scaffold.bottomNavigationBar take up \
3218 too much vertical space.\nConsider constraining the size of these widgets \
3219 to allow room for the SnackBar to be visible."
3220 )]
3221 fn a_floating_snack_bar_pushed_fully_off_screen_by_a_large_button_asserts() {
3222 test_widgets(|tester| {
3223 let space_above_snack_bar = space_above_snack_bar(tester);
3224 with_fab_height(tester, space_above_snack_bar + MEDIUM_FAB_HEIGHT * 2.0);
3225 open_floating_snack_bar(tester);
3226 });
3227 }
3228
3229 #[test]
3231 #[should_panic(expected = "Floating SnackBar presented off screen.")]
3232 fn a_floating_snack_bar_pushed_partly_off_screen_by_a_large_button_asserts() {
3233 test_widgets(|tester| {
3234 let space_above_snack_bar = space_above_snack_bar(tester);
3235 with_fab_height(tester, space_above_snack_bar + MEDIUM_FAB_HEIGHT + 10.0);
3236 open_floating_snack_bar(tester);
3237 });
3238 }
3239
3240 #[test]
3243 #[should_panic(expected = "Floating SnackBar presented off screen.")]
3244 fn a_material_2_floating_snack_bar_pushed_off_screen_by_large_footer_buttons_asserts() {
3245 test_widgets(|tester| {
3246 pump_app(
3247 tester,
3248 m2,
3249 Scaffold::new()
3250 .persistent_footer_buttons(vec![SizedBox::new().height(1000.0).into_widget()])
3251 .into_widget(),
3252 );
3253 open_floating_snack_bar(tester);
3254 tester.pump_and_settle(); });
3256 }
3257
3258 #[test]
3261 #[should_panic(expected = "Floating SnackBar presented off screen.")]
3262 fn a_material_2_floating_snack_bar_pushed_off_screen_by_a_large_bottom_bar_asserts() {
3263 test_widgets(|tester| {
3264 pump_app(
3265 tester,
3266 m2,
3267 Scaffold::new()
3268 .bottom_navigation_bar(SizedBox::new().height(1000.0))
3269 .into_widget(),
3270 );
3271 open_floating_snack_bar(tester);
3272 tester.pump_and_settle(); });
3274 }
3275
3276 #[test]
3279 #[should_panic(expected = "Floating SnackBar presented off screen.")]
3280 fn a_material_3_floating_snack_bar_pushed_off_screen_by_large_footer_buttons_asserts() {
3281 test_widgets(|tester| {
3282 pump_app(
3283 tester,
3284 m3,
3285 Scaffold::new()
3286 .persistent_footer_buttons(vec![SizedBox::new().height(1000.0).into_widget()])
3287 .into_widget(),
3288 );
3289 open_floating_snack_bar(tester);
3290 tester.pump_and_settle(); });
3292 }
3293
3294 #[test]
3297 #[should_panic(expected = "Floating SnackBar presented off screen.")]
3298 fn a_material_3_floating_snack_bar_pushed_off_screen_by_a_large_bottom_bar_asserts() {
3299 test_widgets(|tester| {
3300 pump_app(
3301 tester,
3302 m3,
3303 Scaffold::new()
3304 .bottom_navigation_bar(SizedBox::new().height(1000.0))
3305 .into_widget(),
3306 );
3307 open_floating_snack_bar(tester);
3308 tester.pump_and_settle(); });
3310 }
3311
3312 fn assert_more_or_less_equals(actual: f64, expected: f64) {
3315 assert!(
3316 (actual - expected).abs() < 1e-3,
3317 "{actual} is not more or less {expected}"
3318 );
3319 }
3320
3321 fn action_end_padding(tester: &mut WidgetTester, behavior: SnackBarBehavior) -> f64 {
3323 let home = x_scaffold(move |app, context| {
3324 show(
3325 app,
3326 context,
3327 SnackBar::new(Text::new("Some content"))
3328 .behavior(behavior)
3329 .action(SnackBarAction::new("ACTION", |_app| {})),
3330 );
3331 });
3332 pump_app(tester, m3, home.into_widget());
3333 tester.tap(find::text("X"));
3334 tester.pump_and_settle();
3335 rect_of_type::<SnackBar>(tester).top_right().dx()
3336 - rect_of_type::<SnackBarAction>(tester).top_right().dx()
3337 }
3338
3339 #[test]
3341 fn a_fixed_snack_bar_s_action_sits_12_from_its_end() {
3342 test_widgets(|tester| {
3343 assert_more_or_less_equals(action_end_padding(tester, SnackBarBehavior::Fixed), 12.0);
3344 });
3345 }
3346
3347 #[test]
3350 fn a_floating_snack_bar_s_action_sits_23_from_its_end() {
3351 test_widgets(|tester| {
3352 assert_more_or_less_equals(
3353 action_end_padding(tester, SnackBarBehavior::Floating),
3354 8.0 + 15.0, );
3356 });
3357 }
3358
3359 fn centred_right_to_left(tester: &mut WidgetTester, theme: fn(&App) -> ThemeData) {
3361 const CUSTOM_WIDTH: f64 = 400.0;
3362 let home = Directionality::new(
3363 TextDirection::Rtl,
3364 x_scaffold(|app, context| {
3365 show(
3366 app,
3367 context,
3368 SnackBar::new(Text::new("Feeling super snackish"))
3369 .behavior(SnackBarBehavior::Floating)
3370 .width(CUSTOM_WIDTH),
3371 );
3372 }),
3373 );
3374 pump_app(tester, theme, home.into_widget());
3375 tap_x_and_settle_entrance(tester);
3376 assert_centred_with_width(tester, CUSTOM_WIDTH);
3377 }
3378
3379 #[test]
3382 fn a_material_3_floating_snack_bar_of_custom_width_is_centred_right_to_left() {
3383 test_widgets(|tester| centred_right_to_left(tester, m3));
3384 }
3385
3386 #[test]
3389 fn a_material_2_floating_snack_bar_of_custom_width_is_centred_right_to_left() {
3390 test_widgets(|tester| centred_right_to_left(tester, m2));
3391 }
3392
3393 #[test]
3396 fn presenting_a_material_banner_does_not_duplicate_the_snack_bar() {
3397 test_widgets(|tester| {
3398 const SNACK_BAR_TEXT: &str = "SnackBar";
3399 const MATERIAL_BANNER_TEXT: &str = "MaterialBanner";
3400 let material_banner_tap_target = GlobalKey::new();
3401 let snack_bar_tap_target = GlobalKey::new();
3402 let home = Scaffold::new().body(Builder::new({
3403 let material_banner_tap_target = material_banner_tap_target.clone();
3404 let snack_bar_tap_target = snack_bar_tap_target.clone();
3405 move |_app, context| {
3406 waft_widgets::Column::new()
3407 .children([
3408 GestureDetector::new()
3409 .key(snack_bar_tap_target.clone().into())
3410 .on_tap(Listener::new(move |app| {
3411 show(app, context, SnackBar::new(Text::new(SNACK_BAR_TEXT)));
3412 }))
3413 .behavior(HitTestBehavior::Opaque)
3414 .child(SizedBox::new().height(100.0).width(100.0))
3415 .into_widget(),
3416 GestureDetector::new()
3417 .key(material_banner_tap_target.clone().into())
3418 .on_tap(Listener::new(move |app| {
3419 let banner = crate::banner::MaterialBanner::new(
3420 Text::new(MATERIAL_BANNER_TEXT),
3421 vec![
3422 TextButton::new(
3423 Some(Listener::new(move |app| {
3424 ScaffoldMessenger::of(app, context)
3425 .hide_current_material_banner(
3426 app,
3427 crate::banner::MaterialBannerClosedReason::Hide,
3428 );
3429 })),
3430 Some(Text::new("DISMISS")),
3431 )
3432 .into_widget(),
3433 ],
3434 );
3435 ScaffoldMessenger::of(app, context)
3436 .show_material_banner(app, banner);
3437 }))
3438 .behavior(HitTestBehavior::Opaque)
3439 .child(SizedBox::new().height(100.0).width(100.0))
3440 .into_widget(),
3441 ])
3442 .into_widget()
3443 }
3444 }));
3445 pump_app(tester, m3, home.into_widget());
3446 tap_key(tester, &snack_bar_tap_target);
3447 tap_key(tester, &material_banner_tap_target);
3448 tester.pump_and_settle();
3449
3450 expect(tester, &find::text(SNACK_BAR_TEXT), finds_one_widget());
3451 expect(
3452 tester,
3453 &find::text(MATERIAL_BANNER_TEXT),
3454 finds_one_widget(),
3455 );
3456 });
3457 }
3458
3459 fn top_of_snack_bar_over_nested_scaffolds(
3461 tester: &mut WidgetTester,
3462 theme: fn(&App) -> ThemeData,
3463 ) -> f64 {
3464 pump_app(
3465 tester,
3466 theme,
3467 Scaffold::new()
3468 .body(Scaffold::new())
3469 .floating_action_button(fab())
3470 .into_widget(),
3471 );
3472 show_from_messenger_and_settle(
3473 tester,
3474 SnackBar::new(Text::new("ScaffoldMessenger"))
3475 .duration(Duration::from_secs(2))
3476 .action(SnackBarAction::new("ACTION", |_app| {}))
3477 .behavior(SnackBarBehavior::Floating),
3478 );
3479 expect(tester, &find::by_type::<SnackBar>(), finds_one_widget());
3480 rect_of_type::<SnackBar>(tester).top_right().dy()
3485 }
3486
3487 #[test]
3490 fn a_material_2_snack_bar_shows_only_in_the_root_of_nested_scaffolds() {
3491 test_widgets(|tester| {
3492 assert_eq!(top_of_snack_bar_over_nested_scaffolds(tester, m2), 465.0);
3493 });
3494 }
3495
3496 #[test]
3499 fn a_material_3_snack_bar_shows_only_in_the_root_of_nested_scaffolds() {
3500 test_widgets(|tester| {
3501 assert_eq!(top_of_snack_bar_over_nested_scaffolds(tester, m3), 465.0);
3502 });
3503 }
3504
3505 #[test]
3507 fn clear_snack_bars_hides_the_current_snack_bar_and_drops_the_queue() {
3508 test_widgets(|tester| {
3509 const SNACK_BARS: [&str; 3] = ["Hello Snackbar", "Hi Snackbar", "Bye Snackbar"];
3510 let snack_bar_counter = Rc::new(Cell::new(0));
3511 let tap_target = GlobalKey::new();
3512 let scaffold_messenger_key = GlobalKey::new();
3513 let home = ScaffoldMessenger::new(tap_target_scaffold(&tap_target, {
3514 let snack_bar_counter = Rc::clone(&snack_bar_counter);
3515 move |app, context| {
3516 let index = snack_bar_counter.get();
3517 snack_bar_counter.set(index + 1);
3518 show(
3519 app,
3520 context,
3521 SnackBar::new(Text::new(SNACK_BARS[index]))
3522 .duration(Duration::from_secs(2)),
3523 );
3524 }
3525 }))
3526 .key(scaffold_messenger_key.clone().into());
3527 pump_app(tester, m3, home.into_widget());
3528 let expect_counts = |tester: &WidgetTester, counts: [usize; 3]| {
3529 for (text, count) in SNACK_BARS.iter().zip(counts) {
3530 expect(tester, &find::text(text), finds_n_widgets(count));
3531 }
3532 };
3533 expect_counts(tester, [0, 0, 0]);
3534 tap_key(tester, &tap_target);
3535 tap_key(tester, &tap_target);
3536 tap_key(tester, &tap_target);
3537 expect_counts(tester, [0, 0, 0]);
3538 tester.pump(); expect(tester, &find::text(SNACK_BARS[0]), finds_one_widget());
3540 {
3541 let mut app = tester.cell.borrow_mut();
3542 let messenger = scaffold_messenger_key
3543 .current_state::<crate::scaffold::ScaffoldMessengerState>(&app)
3544 .expect("mounted");
3545 messenger.clear_snack_bars(&mut app);
3546 }
3547 expect(tester, &find::text(SNACK_BARS[0]), finds_one_widget());
3548 tester.pump_by(Duration::from_secs(2));
3549 expect_counts(tester, [0, 0, 0]);
3550 });
3551 }
3552
3553 fn do_build_app(tester: &mut WidgetTester, configure: impl Fn(SnackBar) -> SnackBar + 'static) {
3556 let home = x_scaffold(move |app, context| {
3557 show(app, context, configure(snack_bar_with_action()));
3558 })
3559 .floating_action_button(fab_with_icon());
3560 pump_app(tester, m3, home.into_widget());
3561 }
3562
3563 fn shows(tester: &mut WidgetTester, configure: impl Fn(SnackBar) -> SnackBar + 'static) {
3566 do_build_app(tester, configure);
3567 tap_x_and_settle_entrance(tester);
3568 }
3569
3570 #[test]
3572 #[should_panic(
3573 expected = "Margin can only be used with floating behavior. SnackBarBehavior.fixed was \
3574 set in the SnackBar constructor."
3575 )]
3576 fn a_fixed_snack_bar_asserts_against_a_margin() {
3577 test_widgets(|tester| {
3578 shows(tester, |snack_bar| {
3579 snack_bar
3580 .behavior(SnackBarBehavior::Fixed)
3581 .margin(EdgeInsets::all(8.0))
3582 });
3583 });
3584 }
3585
3586 #[test]
3588 #[should_panic(
3589 expected = "Margin can only be used with floating behavior. SnackBarBehavior.fixed was \
3590 set by default."
3591 )]
3592 fn a_snack_bar_fixed_by_default_asserts_against_a_margin() {
3593 test_widgets(|tester| {
3594 shows(tester, |snack_bar| snack_bar.margin(EdgeInsets::all(8.0)));
3595 });
3596 }
3597
3598 #[test]
3600 #[should_panic(
3601 expected = "Width can only be used with floating behavior. SnackBarBehavior.fixed was \
3602 set in the SnackBar constructor."
3603 )]
3604 fn a_fixed_snack_bar_asserts_against_a_width() {
3605 test_widgets(|tester| {
3606 shows(tester, |snack_bar| {
3607 snack_bar.behavior(SnackBarBehavior::Fixed).width(5.0)
3608 });
3609 });
3610 }
3611
3612 #[test]
3614 #[should_panic(
3615 expected = "Width can only be used with floating behavior. SnackBarBehavior.fixed was \
3616 set by default."
3617 )]
3618 fn a_snack_bar_fixed_by_default_asserts_against_a_width() {
3619 test_widgets(|tester| {
3620 shows(tester, |snack_bar| snack_bar.width(5.0));
3621 });
3622 }
3623
3624 #[test]
3627 fn a_snack_bar_asserts_for_an_action_overflow_threshold_outside_0_to_1() {
3628 for overflow_threshold in [-1.0, -0.0001, 1.000001, 5.0] {
3629 let outcome = std::panic::catch_unwind(|| {
3630 test_widgets(|tester| {
3631 shows(tester, move |snack_bar| {
3632 snack_bar
3633 .action_overflow_threshold(overflow_threshold)
3634 .behavior(SnackBarBehavior::Fixed)
3635 });
3636 });
3637 });
3638 let panic = outcome.expect_err("the threshold asserts");
3639 let message = panic
3640 .downcast_ref::<String>()
3641 .cloned()
3642 .or_else(|| {
3643 panic
3644 .downcast_ref::<&str>()
3645 .map(|message| message.to_string())
3646 })
3647 .expect("a message");
3648 assert_eq!(
3649 message, "Action overflow threshold must be between 0 and 1 inclusive",
3650 "{overflow_threshold}"
3651 );
3652 }
3653 }
3654
3655 #[test]
3657 fn a_snack_bar_s_close_button_has_a_tooltip() {
3658 test_widgets(|tester| {
3659 pump_app(
3660 tester,
3661 m2,
3662 Scaffold::new()
3663 .bottom_sheet(
3664 SizedBox::new()
3665 .width(200.0)
3666 .height(50.0)
3667 .child(waft_widgets::ColoredBox::new(Colors::PINK.primary())),
3668 )
3669 .into_widget(),
3670 );
3671 show_from_messenger_and_settle(
3672 tester,
3673 SnackBar::new(Text::new("Snackbar with close button"))
3674 .duration(Duration::from_secs(365 * 24 * 60 * 60))
3675 .action(SnackBarAction::new("ACTION", |_app| {}))
3676 .behavior(SnackBarBehavior::Floating)
3677 .show_close_icon(true),
3678 ); let close_button_label = {
3680 let messenger = find::by_type::<ScaffoldMessenger>().evaluate(tester)[0];
3681 let mut app = tester.cell.borrow_mut();
3682 let context = messenger
3683 .state_handle::<crate::scaffold::ScaffoldMessengerState>(&app)
3684 .expect("a ScaffoldMessengerState")
3685 .context(&app);
3686 <dyn MaterialLocalizations>::of(&mut app, context).close_button_label()
3687 };
3688 let tooltips = find::by_type::<crate::tooltip::Tooltip>().evaluate(tester);
3689 let with_label = tooltips
3690 .into_iter()
3691 .filter(|tooltip| {
3692 tester.widget(*tooltip, |tooltip: &crate::tooltip::Tooltip| {
3693 tooltip.message.as_deref() == Some(close_button_label.as_str())
3694 })
3695 })
3696 .count();
3697 assert_eq!(with_label, 1);
3698 });
3699 }
3700
3701 #[test]
3703 #[should_panic(
3704 expected = "ScaffoldMessenger.showSnackBar was called, but there are currently no \
3705 descendant Scaffolds to present to."
3706 )]
3707 fn showing_a_snack_bar_with_no_scaffold_to_present_it_asserts() {
3708 test_widgets(|tester| {
3709 pump_app(tester, m3, waft_widgets::Center::new().into_widget());
3710 let messenger = find::by_type::<ScaffoldMessenger>().evaluate(tester)[0];
3711 let mut app = tester.cell.borrow_mut();
3712 let state = messenger
3713 .state_handle::<crate::scaffold::ScaffoldMessengerState>(&app)
3714 .expect("a ScaffoldMessengerState");
3715 state.show_snack_bar(&mut app, SnackBar::new(Text::new("SnackBar")), None);
3716 });
3717 }
3718
3719 fn action_material_color(tester: &WidgetTester) -> Option<Color> {
3722 let action = find::text("ACTION").evaluate(tester)[0];
3723 let button = tester.ancestor_of_type::<TextButton>(action);
3724 let material = find::by_type::<Material>()
3725 .evaluate(tester)
3726 .into_iter()
3727 .find(|material| tester.ancestors(*material).contains(&button))
3728 .expect("a TextButton builds a Material");
3729 tester.widget(material, |material: &Material| material.color)
3730 }
3731
3732 fn action_background_before_and_after_press(
3735 tester: &mut WidgetTester,
3736 action: impl Fn() -> SnackBarAction + 'static,
3737 ) -> (Option<Color>, Option<Color>) {
3738 let home = Scaffold::new().body(Builder::new({
3739 let action = Rc::new(action);
3740 move |_app, context| {
3741 let action = Rc::clone(&action);
3742 GestureDetector::new()
3743 .on_tap(Listener::new(move |app| {
3744 show(
3745 app,
3746 context,
3747 SnackBar::new(Text::new("I am a snack bar."))
3748 .duration(Duration::from_secs(2))
3749 .action(action()),
3750 );
3751 }))
3752 .child(Text::new("Tap"))
3753 .into_widget()
3754 }
3755 }));
3756 pump_app(tester, m3, home.into_widget());
3757 tester.tap(find::text("Tap"));
3758 tester.pump_and_settle();
3759 let before = action_material_color(tester);
3760 tester.tap(find::text("ACTION"));
3761 tester.pump();
3762 let after = action_material_color(tester);
3763 (before, after)
3764 }
3765
3766 #[test]
3768 fn a_snack_bar_action_s_background_color_turns_transparent_once_pressed() {
3769 test_widgets(|tester| {
3770 let background_color = Colors::BLUE.primary();
3771 let (before, after) = action_background_before_and_after_press(tester, move || {
3772 SnackBarAction::new("ACTION", |_app| {}).background_color(background_color)
3773 });
3774 assert_eq!(before, Some(background_color));
3775 assert_eq!(after, Some(Colors::TRANSPARENT));
3776 });
3777 }
3778
3779 #[test]
3781 fn a_snack_bar_action_s_widget_state_background_color_resolves_by_state() {
3782 test_widgets(|tester| {
3783 let (before, after) = action_background_before_and_after_press(tester, || {
3784 let background_color = WidgetStateColor::resolve_with(|states| {
3785 if states.contains(&WidgetState::Disabled) {
3786 return Colors::BLUE.primary();
3787 }
3788 Colors::PURPLE.primary()
3789 });
3790 SnackBarAction::new("ACTION", |_app| {}).background_color(background_color)
3791 });
3792 assert_eq!(before, Some(Colors::PURPLE.primary()));
3793 assert_eq!(after, Some(Colors::BLUE.primary()));
3794 });
3795 }
3796
3797 #[test]
3799 fn a_snack_bar_action_shows_its_disabled_background_color_once_pressed() {
3800 test_widgets(|tester| {
3801 let background_color = Colors::BLUE.primary();
3802 let disabled_background_color = Colors::RED.primary();
3803 let (before, after) = action_background_before_and_after_press(tester, move || {
3804 SnackBarAction::new("ACTION", |_app| {})
3805 .background_color(background_color)
3806 .disabled_background_color(disabled_background_color)
3807 });
3808 assert_eq!(before, Some(background_color));
3809 assert_eq!(after, Some(disabled_background_color));
3810 });
3811 }
3812
3813 #[test]
3816 #[should_panic(
3817 expected = "disabledBackgroundColor must not be provided when background color is a \
3818 WidgetStateColor"
3819 )]
3820 fn a_widget_state_action_background_with_a_disabled_background_asserts() {
3821 test_widgets(|tester| {
3822 action_background_before_and_after_press(tester, || {
3823 let background_color = WidgetStateColor::resolve_with(|states| {
3824 if states.contains(&WidgetState::Disabled) {
3825 return Colors::BLUE.primary();
3826 }
3827 Colors::PURPLE.primary()
3828 });
3829 SnackBarAction::new("ACTION", |_app| {})
3830 .background_color(background_color)
3831 .disabled_background_color(Colors::RED.primary())
3832 });
3833 });
3834 }
3835
3836 #[test]
3838 fn a_snack_bar_s_material_takes_its_clip_behavior() {
3839 test_widgets(|tester| {
3840 pump_app(
3841 tester,
3842 m3,
3843 Scaffold::new()
3844 .body(waft_widgets::Container::new())
3845 .into_widget(),
3846 );
3847 let clip_behavior = |tester: &WidgetTester| {
3848 tester.widget(snack_bar_material(tester), |material: &Material| {
3849 material.clip_behavior
3850 })
3851 };
3852 show_from_messenger_and_settle(tester, SnackBar::new(Text::new("I am a snack bar.")));
3853 assert_eq!(clip_behavior(tester), Clip::HardEdge);
3854 {
3855 let messenger = find::by_type::<ScaffoldMessenger>().evaluate(tester)[0];
3856 let mut app = tester.cell.borrow_mut();
3857 let state = messenger
3858 .state_handle::<crate::scaffold::ScaffoldMessengerState>(&app)
3859 .expect("a ScaffoldMessengerState");
3860 state.hide_current_snack_bar(&mut app, SnackBarClosedReason::Hide); }
3862 tester.pump_and_settle(); show_from_messenger_and_settle(
3864 tester,
3865 SnackBar::new(Text::new("I am a snack bar.")).clip_behavior(Clip::AntiAlias),
3866 ); assert_eq!(clip_behavior(tester), Clip::AntiAlias);
3868 });
3869 }
3870
3871 fn taps_behind_the_snack_bar(
3875 tester: &mut WidgetTester,
3876 theme: impl FnOnce(&App) -> ThemeData,
3877 snack_bar: impl Fn() -> SnackBar + 'static,
3878 ) -> bool {
3879 const BUTTON_TEXT: &str = "Show snackbar";
3880 const SNACKBAR_CONTENT: &str = "Snackbar";
3881 const BUTTON_TEXT2: &str = "Try press me";
3882 let completed = Rc::new(Cell::new(false));
3883 tester.view().set_physical_size(Size::square(200.0));
3884 tester.view().set_device_pixel_ratio(1.0);
3885 let snack_bar = Rc::new(snack_bar);
3886 let home = Scaffold::new().body(Builder::new({
3887 let completed = Rc::clone(&completed);
3888 move |_app, context| {
3889 let snack_bar = Rc::clone(&snack_bar);
3890 let completed = Rc::clone(&completed);
3891 waft_widgets::Column::new()
3892 .main_axis_alignment(MainAxisAlignment::SpaceBetween)
3893 .cross_axis_alignment(waft_widgets::CrossAxisAlignment::Stretch)
3894 .children([
3895 crate::elevated_button::ElevatedButton::new(
3896 Some(Listener::new(move |app| {
3897 show(app, context, snack_bar());
3898 })),
3899 Some(Text::new(BUTTON_TEXT)),
3900 )
3901 .into_widget(),
3902 crate::elevated_button::ElevatedButton::new(
3903 Some(Listener::new(move |_app| completed.set(true))),
3904 Some(Text::new(BUTTON_TEXT2)),
3905 )
3906 .into_widget(),
3907 ])
3908 .into_widget()
3909 }
3910 }));
3911 pump_app(tester, theme, home.into_widget());
3912 tester.tap(find::text(BUTTON_TEXT));
3913 tester.pump_and_settle();
3914 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
3915 let top_left = tester.get_rect(find::text(BUTTON_TEXT2)).top_left();
3916 tester.tap_at(top_left, 1);
3917 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
3918 completed.get()
3919 }
3920
3921 #[test]
3923 fn a_button_beside_a_snack_bar_of_custom_width_can_be_tapped() {
3924 test_widgets(|tester| {
3925 assert!(taps_behind_the_snack_bar(tester, m3, || {
3926 SnackBar::new(Text::new("Snackbar"))
3927 .behavior(SnackBarBehavior::Floating)
3928 .width(100.0)
3929 }));
3930 });
3931 }
3932
3933 #[test]
3935 fn a_button_in_a_snack_bar_s_margin_can_be_tapped() {
3936 test_widgets(|tester| {
3937 assert!(taps_behind_the_snack_bar(tester, m3, || {
3938 SnackBar::new(Text::new("Snackbar"))
3939 .behavior(SnackBarBehavior::Floating)
3940 .margin(EdgeInsets::only(100.0, 0.0, 0.0, 0.0))
3941 }));
3942 });
3943 }
3944
3945 #[test]
3947 fn a_button_in_the_margin_of_an_opaque_snack_bar_cannot_be_tapped() {
3948 test_widgets(|tester| {
3949 assert!(!taps_behind_the_snack_bar(tester, m3, || {
3950 SnackBar::new(Text::new("Snackbar"))
3951 .hit_test_behavior(HitTestBehavior::Opaque)
3952 .behavior(SnackBarBehavior::Floating)
3953 .margin(EdgeInsets::only(100.0, 0.0, 0.0, 0.0))
3954 }));
3955 });
3956 }
3957
3958 #[test]
3961 fn a_button_in_the_theme_s_inset_padding_can_be_tapped() {
3962 test_widgets(|tester| {
3963 assert!(taps_behind_the_snack_bar(
3964 tester,
3965 |app| {
3966 ThemeData::builder()
3967 .snack_bar_theme(
3968 SnackBarThemeData::new()
3969 .inset_padding(EdgeInsets::only(100.0, 0.0, 0.0, 0.0)),
3970 )
3971 .build(app)
3972 },
3973 || SnackBar::new(Text::new("Snackbar")).behavior(SnackBarBehavior::Floating),
3974 ));
3975 });
3976 }
3977
3978 #[test]
3980 #[allow(deprecated)]
3981 fn the_action_s_overlay_is_the_inverse_primary_colour() {
3982 test_widgets(|tester| {
3983 let home = x_scaffold(|app, context| {
3984 show(
3985 app,
3986 context,
3987 SnackBar::new(Text::new("I am a snack bar."))
3988 .action(SnackBarAction::new("ACTION", |_app| {})),
3989 );
3990 });
3991 pump_app(tester, m3, home.into_widget());
3992 tester.tap(find::text("X"));
3993 tester.pump_and_settle();
3994 let theme = m3(&tester.cell.borrow());
3995 let overlay_color = action_button_style(tester)
3996 .overlay_color
3997 .expect("an overlay color")
3998 .resolve(&states(&[WidgetState::Hovered]));
3999 assert_eq!(
4000 overlay_color,
4001 Some(theme.color_scheme.inverse_primary().with_opacity(0.08))
4002 );
4003 });
4004 }
4005
4006 fn elevated_button_scaffold(snack_bar: impl Fn() -> SnackBar + 'static) -> Scaffold {
4008 let snack_bar = Rc::new(snack_bar);
4009 Scaffold::new().body(Builder::new(move |_app, context| {
4010 let snack_bar = Rc::clone(&snack_bar);
4011 crate::elevated_button::ElevatedButton::new(
4012 Some(Listener::new(move |app| {
4013 show(app, context, snack_bar());
4014 })),
4015 Some(Text::new("Show snackbar")),
4016 )
4017 .into_widget()
4018 }))
4019 }
4020
4021 #[test]
4023 fn a_persisting_snack_bar_does_not_time_out() {
4024 test_widgets(|tester| {
4025 const SNACKBAR_CONTENT: &str = "Snackbar";
4026 let home = elevated_button_scaffold(|| {
4027 SnackBar::new(Text::new(SNACKBAR_CONTENT))
4028 .duration(Duration::from_secs(1))
4029 .persist(true)
4030 .show_close_icon(true)
4031 });
4032 pump_app(tester, m3, home.into_widget());
4033 tester.tap(find::text("Show snackbar"));
4034 tester.pump_by(ms(750));
4035 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
4037 tester.pump_by(ms(1500));
4038 tester.pump_and_settle();
4039 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
4041 let close = tester.element(find::by_icon(&Icons::close()).first());
4042 let center = tester.get_rect(close).center();
4043 tester.tap_at(center, 1);
4044 tester.pump_and_settle();
4045 expect(tester, &find::text(SNACKBAR_CONTENT), finds_nothing());
4047 });
4048 }
4049
4050 #[test]
4052 fn a_snack_bar_that_does_not_persist_times_out_despite_its_close_icon() {
4053 test_widgets(|tester| {
4054 const SNACKBAR_CONTENT: &str = "SnackbarContent";
4055 let home = elevated_button_scaffold(|| {
4056 SnackBar::new(Text::new(SNACKBAR_CONTENT))
4057 .duration(Duration::from_secs(1))
4058 .persist(false)
4059 .show_close_icon(true)
4060 });
4061 pump_app(tester, m3, home.into_widget());
4062 let button = rect_of_type::<crate::elevated_button::ElevatedButton>(tester).center();
4063 tester.tap_at(button, 1);
4064 tester.pump();
4065 tester.pump_by(ms(750));
4066 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
4068 tester.pump_by(ms(1500));
4069 tester.pump_and_settle();
4070 expect(tester, &find::text(SNACKBAR_CONTENT), finds_nothing());
4072 });
4073 }
4074
4075 #[test]
4077 fn a_snack_bar_that_does_not_persist_times_out_under_accessible_navigation() {
4078 test_widgets(|tester| {
4079 const SNACKBAR_CONTENT: &str = "SnackbarContent";
4080 let theme = m3(&tester.cell.borrow());
4081 tester.pump_widget(
4082 waft_widgets::MediaQuery::new(
4083 waft_widgets::MediaQueryData::new().accessible_navigation(true),
4084 material_app(
4085 theme,
4086 elevated_button_scaffold(|| {
4087 SnackBar::new(Text::new(SNACKBAR_CONTENT))
4088 .duration(Duration::from_secs(1))
4089 .persist(false)
4090 .action(SnackBarAction::new("Action", |_app| {}))
4091 })
4092 .into_widget(),
4093 ),
4094 )
4095 .into_widget(),
4096 );
4097 let button = rect_of_type::<crate::elevated_button::ElevatedButton>(tester).center();
4098 tester.tap_at(button, 1);
4099 tester.pump_and_settle();
4100 expect(tester, &find::text(SNACKBAR_CONTENT), finds_one_widget());
4101 tester.pump_by(Duration::from_secs(10));
4102 tester.pump_and_settle();
4103 expect(tester, &find::text(SNACKBAR_CONTENT), finds_nothing());
4105 });
4106 }
4107
4108 #[test]
4110 fn a_snack_bar_action_lays_out_at_zero_area() {
4111 test_widgets(|tester| {
4112 pump_app(
4113 tester,
4114 m3,
4115 waft_widgets::Center::new()
4116 .child(SizedBox::shrink().child(SnackBarAction::new("X", |_app| {})))
4117 .into_widget(),
4118 );
4119 assert_eq!(
4120 rect_of_type::<SnackBarAction>(tester).size(),
4121 waft_embedder::Size::ZERO
4122 );
4123 });
4124 }
4125
4126 #[test]
4128 fn the_action_overflow_measures_the_label_with_the_text_scaler() {
4129 test_widgets(|tester| {
4130 let build_snack_bar =
4131 |tester: &mut WidgetTester, text_scaler: waft_painting::TextScaler| {
4132 let home = waft_widgets::MediaQuery::new(
4133 waft_widgets::MediaQueryData::new()
4134 .size(waft_embedder::Size::new(800.0, 600.0))
4135 .text_scaler(text_scaler),
4136 Scaffold::new().body(Builder::new(|_app, context| {
4137 GestureDetector::new()
4138 .on_tap(Listener::new(move |app| {
4139 show(
4140 app,
4141 context,
4142 SnackBar::new(Text::new("Message"))
4143 .action(SnackBarAction::new("Action Label", |_app| {})),
4144 );
4145 }))
4146 .child(Text::new("Show"))
4147 .into_widget()
4148 })),
4149 );
4150 pump_app(tester, m3, home.into_widget());
4151 };
4152
4153 build_snack_bar(tester, waft_painting::TextScaler::NO_SCALING);
4155 tester.tap(find::text("Show"));
4156 tester.pump_and_settle();
4157 let action_top_left1 = tester.get_rect(find::text("Action Label")).top_left();
4158 assert!(
4160 action_top_left1.dy() <= tester.get_rect(find::text("Message")).bottom_left().dy()
4161 );
4162 {
4163 let show = find::text("Show").evaluate(tester)[0];
4164 let mut app = tester.cell.borrow_mut();
4165 let context = show;
4166 ScaffoldMessenger::of(&mut app, context).clear_snack_bars(&mut app);
4167 }
4168 tester.pump_and_settle();
4169
4170 build_snack_bar(tester, waft_painting::TextScaler::linear(3.0));
4173 tester.tap(find::text("Show"));
4174 tester.pump_and_settle();
4175 let content_bottom_left2 = tester.get_rect(find::text("Message")).bottom_left();
4176 let action_top_left2 = tester.get_rect(find::text("Action Label")).top_left();
4177 assert!(action_top_left2.dy() >= content_bottom_left2.dy());
4179 });
4180 }
4181
4182 fn overflowing_action(tester: &mut WidgetTester, padding: Option<EdgeInsets>) -> Rect {
4185 let content_key = GlobalKey::new();
4186 tester.view().set_physical_size(Size::new(500.0, 800.0));
4187 tester.view().set_device_pixel_ratio(1.0);
4188 let home = Scaffold::new().body(Builder::new({
4189 let content_key = content_key.clone();
4190 move |_app, context| {
4191 let content_key = content_key.clone();
4192 GestureDetector::new()
4193 .on_tap(Listener::new(move |app| {
4194 let mut snack_bar = SnackBar::new(
4195 SizedBox::new().key(content_key.clone().into()).height(20.0),
4196 )
4197 .action(SnackBarAction::new("Overflow Action", |_app| {}))
4198 .action_overflow_threshold(0.1);
4199 if let Some(padding) = padding {
4200 snack_bar = snack_bar.padding(padding);
4201 }
4202 show(app, context, snack_bar);
4203 }))
4204 .child(Text::new("Show"))
4205 .into_widget()
4206 }
4207 }));
4208 pump_app(tester, m3, home.into_widget());
4209 tester.tap(find::text("Show"));
4210 tester.pump_and_settle();
4211 rect_of_key(tester, &content_key)
4212 }
4213
4214 fn content_row_children(tester: &WidgetTester) -> Vec<WidgetRef> {
4217 let snack_bar = find::by_type::<SnackBar>().evaluate(tester)[0];
4218 let row = find::by_type::<Row>()
4219 .evaluate(tester)
4220 .into_iter()
4221 .find(|row| tester.ancestors(*row).contains(&snack_bar))
4222 .expect("a SnackBar lays its content out in a Row");
4223 tester.widget(row, |row: &Row| row.children.clone())
4224 }
4225
4226 #[test]
4228 fn an_overflowing_action_leaves_only_the_end_padding_beside_the_content() {
4229 test_widgets(|tester| {
4230 const SCREEN_WIDTH: f64 = 500.0;
4231 let content = overflowing_action(tester, None);
4232 assert_eq!(content.width(), 452.0);
4234 assert_eq!(content.top_right().dx(), SCREEN_WIDTH - 24.0);
4235 let children = content_row_children(tester);
4237 assert_eq!(children.len(), 2);
4238 assert!(waft_widgets::downcast_widget::<Expanded>(&*children[0]).is_some());
4239 let spacer = waft_widgets::downcast_widget::<SizedBox>(&*children[1])
4240 .expect("a SizedBox spacer");
4241 assert_eq!(spacer.width, Some(24.0));
4242 });
4243 }
4244
4245 #[test]
4247 fn an_overflowing_action_keeps_a_custom_padding_without_a_spacer() {
4248 test_widgets(|tester| {
4249 const SCREEN_WIDTH: f64 = 500.0;
4250 let custom_padding = EdgeInsets::only(36.0, 0.0, 48.0, 0.0);
4251 let content = overflowing_action(tester, Some(custom_padding));
4252 let children = content_row_children(tester);
4255 assert_eq!(children.len(), 1);
4256 assert!(waft_widgets::downcast_widget::<Expanded>(&*children[0]).is_some());
4257 assert_eq!(
4258 content.width(),
4259 SCREEN_WIDTH - (custom_padding.left + custom_padding.right)
4260 );
4261 assert_eq!(content.top_left().dx(), custom_padding.left);
4262 assert_eq!(
4263 content.top_right().dx(),
4264 SCREEN_WIDTH - custom_padding.right
4265 );
4266 });
4267 }
4268
4269 fn snack_bar_theme(show_close_icon: Option<bool>) -> SnackBarThemeData {
4273 let mut theme = SnackBarThemeData::new()
4274 .background_color(Colors::ORANGE.primary())
4275 .action_text_color(Colors::GREEN.primary())
4276 .content_text_style(waft_painting::TextStyle::new().color(Colors::BLUE.primary()))
4277 .elevation(12.0)
4278 .shape(waft_painting::BeveledRectangleBorder::new(
4279 BorderSide::NONE,
4280 BorderRadiusGeometry::all(Radius::circular(12.0)),
4281 ));
4282 if let Some(show_close_icon) = show_close_icon {
4283 theme = theme.show_close_icon(show_close_icon);
4284 }
4285 theme
4286 }
4287
4288 fn with_snack_bar_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
4290 tester.widget(snack_bar_material(tester), read)
4291 }
4292
4293 fn paragraph_style(tester: &WidgetTester, text: &str) -> Option<waft_painting::TextStyle> {
4295 let element = find::text(text).evaluate(tester)[0];
4296 let render = tester.render_box_of(element);
4297 let app = tester.cell.borrow();
4298 let paragraph = render
4299 .as_object()
4300 .downcast::<waft_rendering::RenderParagraph>(&app)
4301 .expect("a Text renders a paragraph");
4302 paragraph.text(&app).style().cloned()
4303 }
4304
4305 fn close_icons_in_snack_bar(tester: &WidgetTester) -> usize {
4307 let snack_bar = find::by_type::<SnackBar>().evaluate(tester)[0];
4308 find::by_type::<Icon>()
4309 .evaluate(tester)
4310 .into_iter()
4311 .filter(|icon| {
4312 tester.ancestors(*icon).contains(&snack_bar)
4313 && tester.widget(*icon, |icon: &Icon| icon.icon == Some(Icons::close()))
4314 })
4315 .count()
4316 }
4317
4318 #[test]
4320 fn a_material_2_snack_bar_with_no_theme_takes_the_defaults() {
4321 test_widgets(|tester| {
4322 const TEXT: &str = "I am a snack bar.";
4323 let home = x_scaffold(|app, context| {
4324 show(
4325 app,
4326 context,
4327 SnackBar::new(Text::new(TEXT))
4328 .duration(Duration::from_secs(2))
4329 .action(SnackBarAction::new("ACTION", |_app| {})),
4330 );
4331 });
4332 pump_app(tester, m2, home.into_widget());
4333 tester.tap(find::text("X"));
4334 tester.pump_and_settle();
4335 assert_eq!(
4336 paragraph_style(tester, TEXT),
4337 crate::typography::Typography::material2018()
4338 .build()
4339 .white
4340 .title_medium
4341 );
4342 with_snack_bar_material(tester, |material| {
4343 assert!(crate::test_support::is_same_color_as(
4344 material.color.expect("a colour"),
4345 Color::new(0xFF333333)
4346 ));
4347 assert_eq!(material.elevation, 6.0);
4348 assert!(material.shape.is_none());
4349 });
4350 });
4351 }
4352
4353 #[test]
4355 fn a_material_3_snack_bar_with_no_theme_takes_the_defaults() {
4356 test_widgets(|tester| {
4357 const TEXT: &str = "I am a snack bar.";
4358 let home = x_scaffold(|app, context| {
4359 show(
4360 app,
4361 context,
4362 SnackBar::new(Text::new(TEXT))
4363 .duration(Duration::from_secs(2))
4364 .action(SnackBarAction::new("ACTION", |_app| {})),
4365 );
4366 });
4367 pump_app(tester, m3, home.into_widget());
4368 tester.tap(find::text("X"));
4369 tester.pump_and_settle();
4370 let theme = m3(&tester.cell.borrow());
4371 let typography = crate::typography::Typography::material2021().build();
4372 let expected = typography
4373 .english_like
4374 .body_medium
4375 .as_ref()
4376 .map(|body_medium| body_medium.merge(typography.black.body_medium.as_ref()))
4377 .map(|style| {
4378 style
4379 .copy_with()
4380 .color(theme.color_scheme.on_inverse_surface())
4381 .decoration_color(theme.color_scheme.on_surface())
4382 });
4383 assert_eq!(paragraph_style(tester, TEXT), expected);
4384 with_snack_bar_material(tester, |material| {
4385 assert_eq!(material.color, Some(theme.color_scheme.inverse_surface()));
4386 assert_eq!(material.elevation, 6.0);
4387 assert!(material.shape.is_none());
4388 });
4389 });
4390 }
4391
4392 #[test]
4394 fn a_snack_bar_takes_its_values_from_the_theme() {
4395 test_widgets(|tester| {
4396 const TEXT: &str = "I am a snack bar.";
4397 const ACTION: &str = "ACTION";
4398 let home = x_scaffold(|app, context| {
4399 show(
4400 app,
4401 context,
4402 SnackBar::new(Text::new(TEXT))
4403 .duration(Duration::from_secs(2))
4404 .action(SnackBarAction::new(ACTION, |_app| {})),
4405 );
4406 });
4407 pump_app(
4408 tester,
4409 |app| {
4410 ThemeData::builder()
4411 .snack_bar_theme(snack_bar_theme(Some(true)))
4412 .build(app)
4413 },
4414 home.into_widget(),
4415 );
4416 tester.tap(find::text("X"));
4417 tester.pump_and_settle();
4418 let theme = snack_bar_theme(Some(true));
4419 assert_eq!(paragraph_style(tester, TEXT), theme.content_text_style);
4420 with_snack_bar_material(tester, |material| {
4421 assert_eq!(material.color, theme.background_color);
4422 assert_eq!(Some(material.elevation), theme.elevation);
4423 assert!(
4424 material
4425 .shape
4426 .as_deref()
4427 .expect("a shape")
4428 .eq_shape(theme.shape.as_deref().expect("a shape"))
4429 );
4430 });
4431 assert_eq!(
4432 Some(tester.text_color(ACTION)),
4433 theme.action_text_color.as_ref().map(AnyColor::color)
4434 );
4435 assert_eq!(close_icons_in_snack_bar(tester), 1);
4436 });
4437 }
4438
4439 fn widget_values_win(
4442 tester: &mut WidgetTester,
4443 theme: impl FnOnce(&App) -> ThemeData,
4444 wrap: impl FnOnce(Scaffold) -> WidgetRef,
4445 configure: impl Fn(SnackBar) -> SnackBar + 'static,
4446 action: impl Fn() -> SnackBarAction + 'static,
4447 ) {
4448 const SNACK_BAR_WIDTH: f64 = 400.0;
4449 let background_color = Colors::PURPLE.primary();
4450 let text_color = Colors::PINK.primary();
4451 let elevation = 7.0;
4452 let shape = || {
4453 RoundedRectangleBorder::new(
4454 BorderSide::NONE,
4455 BorderRadiusGeometry::all(Radius::circular(9.0)),
4456 )
4457 };
4458 let home = x_scaffold(move |app, context| {
4459 show(
4460 app,
4461 context,
4462 configure(SnackBar::new(Text::new("I am a snack bar.")))
4463 .duration(Duration::from_secs(2))
4464 .action(action()),
4465 );
4466 });
4467 pump_app(tester, theme, wrap(home));
4468 tester.tap(find::text("X"));
4469 tester.pump_and_settle();
4470 with_snack_bar_material(tester, |material| {
4471 assert_eq!(material.color, Some(background_color));
4472 assert_eq!(material.elevation, elevation);
4473 assert!(
4474 material
4475 .shape
4476 .as_deref()
4477 .expect("a shape")
4478 .eq_shape(&shape())
4479 );
4480 });
4481 assert_eq!(tester.text_color("ACTION"), text_color);
4482 assert_eq!(close_icons_in_snack_bar(tester), 0);
4483 assert_centred_with_width(tester, SNACK_BAR_WIDTH);
4485 }
4486
4487 fn prioritized(snack_bar: SnackBar) -> SnackBar {
4490 snack_bar
4491 .background_color(Colors::PURPLE.primary())
4492 .behavior(SnackBarBehavior::Floating)
4493 .width(400.0)
4494 .elevation(7.0)
4495 .shape(RoundedRectangleBorder::new(
4496 BorderSide::NONE,
4497 BorderRadiusGeometry::all(Radius::circular(9.0)),
4498 ))
4499 .show_close_icon(false)
4500 }
4501
4502 #[test]
4504 fn a_snack_bar_s_own_values_win_over_the_theme_s() {
4505 test_widgets(|tester| {
4506 widget_values_win(
4507 tester,
4508 |app| {
4509 ThemeData::builder()
4510 .snack_bar_theme(snack_bar_theme(Some(true)))
4511 .build(app)
4512 },
4513 |scaffold| scaffold.into_widget(),
4514 prioritized,
4515 || SnackBarAction::new("ACTION", |_app| {}).text_color(Colors::PINK.primary()),
4516 );
4517 });
4518 }
4519
4520 #[test]
4522 fn a_snack_bar_takes_its_values_from_a_local_snack_bar_theme() {
4523 test_widgets(|tester| {
4524 widget_values_win(
4525 tester,
4526 m3,
4527 |scaffold| {
4528 SnackBarTheme::new(
4529 SnackBarThemeData::new()
4530 .background_color(Colors::PURPLE.primary())
4531 .behavior(SnackBarBehavior::Floating)
4532 .width(400.0)
4533 .elevation(7.0)
4534 .shape(RoundedRectangleBorder::new(
4535 BorderSide::NONE,
4536 BorderRadiusGeometry::all(Radius::circular(9.0)),
4537 ))
4538 .show_close_icon(false)
4539 .action_text_color(Colors::PINK.primary()),
4540 scaffold,
4541 )
4542 .into_widget()
4543 },
4544 |snack_bar| snack_bar,
4545 || SnackBarAction::new("ACTION", |_app| {}),
4546 );
4547 });
4548 }
4549
4550 #[test]
4552 fn a_snack_bar_s_own_values_win_over_a_local_snack_bar_theme_s() {
4553 test_widgets(|tester| {
4554 widget_values_win(
4555 tester,
4556 m3,
4557 |scaffold| SnackBarTheme::new(snack_bar_theme(Some(true)), scaffold).into_widget(),
4558 prioritized,
4559 || SnackBarAction::new("ACTION", |_app| {}).text_color(Colors::PINK.primary()),
4560 );
4561 });
4562 }
4563
4564 fn themed_action_background_before_and_after_press(
4566 tester: &mut WidgetTester,
4567 theme: SnackBarThemeData,
4568 action: impl Fn() -> SnackBarAction + 'static,
4569 ) -> (Option<Color>, Option<Color>) {
4570 let home = x_scaffold(move |app, context| {
4571 show(
4572 app,
4573 context,
4574 SnackBar::new(Text::new("I am a snack bar.")).action(action()),
4575 );
4576 });
4577 pump_app(
4578 tester,
4579 |app| ThemeData::builder().snack_bar_theme(theme).build(app),
4580 home.into_widget(),
4581 );
4582 tester.tap(find::text("X"));
4583 tester.pump_and_settle();
4584 let before = action_material_color(tester);
4585 tester.tap(find::text("ACTION"));
4586 tester.pump();
4587 let after = action_material_color(tester);
4588 (before, after)
4589 }
4590
4591 fn by_disabled(disabled: Color, enabled: Color) -> WidgetStateColor {
4592 WidgetStateColor::resolve_with(move |states| {
4593 if states.contains(&WidgetState::Disabled) {
4594 return disabled;
4595 }
4596 enabled
4597 })
4598 }
4599
4600 #[test]
4602 fn a_snack_bar_action_takes_the_theme_s_action_background_color() {
4603 test_widgets(|tester| {
4604 let (before, after) = themed_action_background_before_and_after_press(
4605 tester,
4606 SnackBarThemeData::new().action_background_color(by_disabled(
4607 Colors::BLUE.primary(),
4608 Colors::PURPLE.primary(),
4609 )),
4610 || SnackBarAction::new("ACTION", |_app| {}),
4611 );
4612 assert_eq!(before, Some(Colors::PURPLE.primary()));
4613 assert_eq!(after, Some(Colors::BLUE.primary()));
4614 });
4615 }
4616
4617 #[test]
4619 fn a_snack_bar_action_s_background_color_wins_over_the_theme_s() {
4620 test_widgets(|tester| {
4621 let (before, after) = themed_action_background_before_and_after_press(
4622 tester,
4623 SnackBarThemeData::new().action_background_color(by_disabled(
4624 Colors::BLUE.primary(),
4625 Colors::PURPLE.primary(),
4626 )),
4627 || {
4628 SnackBarAction::new("ACTION", |_app| {}).background_color(by_disabled(
4629 Colors::AMBER.primary(),
4630 Colors::CYAN.primary(),
4631 ))
4632 },
4633 );
4634 assert_eq!(before, Some(Colors::CYAN.primary()));
4635 assert_eq!(after, Some(Colors::AMBER.primary()));
4636 });
4637 }
4638
4639 #[test]
4642 #[should_panic(
4643 expected = "disabledBackgroundColor must not be provided when background color is a \
4644 WidgetStateColor"
4645 )]
4646 fn a_theme_with_a_widget_state_action_background_and_a_disabled_one_asserts() {
4647 test_widgets(|tester| {
4648 themed_action_background_before_and_after_press(
4649 tester,
4650 SnackBarThemeData::new()
4651 .action_background_color(by_disabled(
4652 Colors::BLUE.primary(),
4653 Colors::PURPLE.primary(),
4654 ))
4655 .disabled_action_background_color(Colors::AMBER.primary()),
4656 || SnackBarAction::new("ACTION", |_app| {}),
4657 );
4658 });
4659 }
4660
4661 fn first_box_rect<W: 'static>(tester: &WidgetTester) -> Rect {
4663 rect_of_type::<W>(tester)
4664 }
4665
4666 fn themed_behavior(tester: &mut WidgetTester, behavior: SnackBarBehavior) {
4668 let home = x_scaffold(|app, context| {
4669 show(app, context, snack_bar_with_action());
4670 })
4671 .floating_action_button(fab_with_icon());
4672 pump_app(
4673 tester,
4674 move |app| {
4675 ThemeData::builder()
4676 .snack_bar_theme(SnackBarThemeData::new().behavior(behavior))
4677 .build(app)
4678 },
4679 home.into_widget(),
4680 );
4681 }
4682
4683 #[test]
4685 fn a_theme_floating_snack_bar_sits_on_top_of_the_button() {
4686 test_widgets(|tester| {
4687 themed_behavior(tester, SnackBarBehavior::Floating);
4688 tester.tap(find::text("X"));
4689 tester.pump_and_settle();
4690 let snack_bar_bottom_center = first_box_rect::<SnackBar>(tester).bottom_center();
4691 let floating_action_button_top_center =
4692 first_box_rect::<crate::floating_action_button::FloatingActionButton>(tester)
4693 .top_center();
4694 assert!(snack_bar_bottom_center.dy() == floating_action_button_top_center.dy());
4697 });
4698 }
4699
4700 #[test]
4702 fn a_theme_fixed_snack_bar_pushes_the_button_above_it() {
4703 test_widgets(|tester| {
4704 themed_behavior(tester, SnackBarBehavior::Fixed);
4705 let floating_action_button_origin_bottom_center =
4706 first_box_rect::<crate::floating_action_button::FloatingActionButton>(tester)
4707 .bottom_center();
4708 tester.tap(find::text("X"));
4709 tester.pump_and_settle();
4710 let snack_bar_top_center = first_box_rect::<SnackBar>(tester).top_center();
4711 let floating_action_button_bottom_center =
4712 first_box_rect::<crate::floating_action_button::FloatingActionButton>(tester)
4713 .bottom_center();
4714 assert!(
4715 floating_action_button_origin_bottom_center.dy()
4716 > floating_action_button_bottom_center.dy()
4717 );
4718 assert!(snack_bar_top_center.dy() > floating_action_button_bottom_center.dy());
4719 });
4720 }
4721
4722 fn themed_and_shown(
4725 tester: &mut WidgetTester,
4726 behavior: SnackBarBehavior,
4727 configure: fn(SnackBar) -> SnackBar,
4728 ) {
4729 let home = x_scaffold(move |app, context| {
4730 show(app, context, configure(snack_bar_with_action()));
4731 })
4732 .floating_action_button(fab_with_icon());
4733 pump_app(
4734 tester,
4735 move |app| {
4736 ThemeData::builder()
4737 .snack_bar_theme(SnackBarThemeData::new().behavior(behavior))
4738 .build(app)
4739 },
4740 home.into_widget(),
4741 );
4742 tap_x_and_settle_entrance(tester);
4743 }
4744
4745 #[test]
4747 fn a_theme_floating_snack_bar_takes_a_margin() {
4748 test_widgets(|tester| {
4749 themed_and_shown(tester, SnackBarBehavior::Floating, |snack_bar| {
4750 snack_bar.margin(EdgeInsets::all(8.0))
4751 });
4752 });
4753 }
4754
4755 #[test]
4757 #[should_panic(
4758 expected = "Margin can only be used with floating behavior. SnackBarBehavior.fixed was \
4759 set by the inherited SnackBarThemeData."
4760 )]
4761 fn a_theme_fixed_snack_bar_asserts_against_a_margin() {
4762 test_widgets(|tester| {
4763 themed_and_shown(tester, SnackBarBehavior::Fixed, |snack_bar| {
4764 snack_bar.margin(EdgeInsets::all(8.0))
4765 });
4766 });
4767 }
4768
4769 #[test]
4771 fn a_theme_floating_snack_bar_takes_a_width() {
4772 test_widgets(|tester| {
4773 themed_and_shown(tester, SnackBarBehavior::Floating, |snack_bar| {
4774 snack_bar.width(5.0)
4775 });
4776 });
4777 }
4778
4779 #[test]
4781 #[should_panic(
4782 expected = "Width can only be used with floating behavior. SnackBarBehavior.fixed was \
4783 set by the inherited SnackBarThemeData."
4784 )]
4785 fn a_theme_fixed_snack_bar_asserts_against_a_width() {
4786 test_widgets(|tester| {
4787 themed_and_shown(tester, SnackBarBehavior::Fixed, |snack_bar| {
4788 snack_bar.width(5.0)
4789 });
4790 });
4791 }
4792
4793 #[test]
4796 fn a_dismissed_snack_bar_frees_its_curved_animations() {
4797 test_widgets(|tester| {
4798 let home = x_scaffold(|app, context| {
4799 show(
4800 app,
4801 context,
4802 SnackBar::new(Text::new("Snack")).duration(Duration::from_secs(1)),
4803 );
4804 });
4805 pump_app(tester, m3, home.into_widget());
4806 tap_x_and_settle_entrance(tester);
4807 let animations = {
4808 let snack_bar = find::by_type::<SnackBar>().evaluate(tester)[0];
4809 let app = tester.cell.borrow();
4810 let state = app.get(
4811 snack_bar
4812 .state_handle::<SnackBarState>(&app)
4813 .expect("a SnackBar is stateful"),
4814 );
4815 [
4816 state.height_animation.clone(),
4817 state.fade_in_animation.clone(),
4818 state.fade_in_m3_animation.clone(),
4819 state.fade_out_animation.clone(),
4820 state.height_m3_animation.clone(),
4821 ]
4822 .map(|animation| animation.expect("made in init_state").handle())
4823 };
4824
4825 tester.pump_by(ms(1500)); tester.pump(); tester.pump_by(ms(750)); expect(tester, &find::by_type::<SnackBar>(), finds_nothing());
4829 tester.cell.checkpoint();
4830 let app = tester.cell.borrow();
4831 assert!(animations.iter().all(|animation| !app.contains(*animation)));
4832 });
4833 }
4834}