Skip to main content

waft_material/
banner.rs

1//! Flutter counterpart: material_ui's `banner.dart`.
2
3use std::fmt;
4use std::rc::Rc;
5use std::time::Duration;
6use waft_animation::{
7    Animatable, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
8    AnimationStatusListener, Curve, CurvedAnimation, Curves, Threshold, Tween,
9};
10
11use waft_embedder::{Color, Offset};
12use waft_foundation::{App, Handle, OptionRetained, Ref, VoidCallback};
13use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, TextStyle};
14use waft_rendering::BoxConstraints;
15use waft_scheduler::TickerProvider;
16use waft_widgets::{
17    Align, AnimatedBuilder, BuildContext, ClipRect, Column, ConstrainedBox, DefaultTextStyle,
18    Expanded, Hero, IntoWidget, KeyRef, MainAxisSize, MediaQuery, OverflowBar,
19    OverflowBarAlignment, Padding, Row, SafeArea, Semantics, SlideTransition, State, StateData,
20    StatefulWidget, WidgetRef, debug_check_has_media_query,
21};
22
23use crate::banner_theme::{
24    MaterialBannerTheme, MaterialBannerThemeData, MaterialBannerThemeDataGetters,
25};
26use crate::divider::Divider;
27use crate::generated::banner_defaults_m3::BannerDefaultsM3;
28use crate::material::Material;
29use crate::scaffold::ScaffoldMessenger;
30use crate::theme::Theme;
31use crate::theme_data::ThemeData;
32
33const MATERIAL_BANNER_TRANSITION_DURATION: Duration = Duration::from_millis(250);
34
35fn material_banner_height_curve() -> Rc<dyn Curve> {
36    Curves::fast_out_slow_in()
37}
38
39const K_MAX_CONTENT_TEXT_SCALE_FACTOR: f64 = 1.5;
40
41/// Specify how a [`MaterialBanner`] was closed.
42///
43/// The `ScaffoldMessengerState::show_material_banner` function returns a
44/// `ScaffoldFeatureController`. The value of the controller's closed property
45/// is a future that resolves to a [`MaterialBannerClosedReason`]. Applications that need
46/// to know how a [`MaterialBanner`] was closed can use this value.
47///
48/// Example:
49///
50/// ```text
51/// ScaffoldMessenger::of(app, context)
52///     .show_material_banner(app, MaterialBanner::new(Text::new("Message..."), vec![/* ... */]))
53///     .closed()
54///     .then(app, |app, reason: MaterialBannerClosedReason| {
55///         // ...
56///     });
57/// ```
58#[derive(Clone, Copy, PartialEq, Eq, Debug)]
59pub enum MaterialBannerClosedReason {
60    /// The material banner was closed through a `SemanticsAction.dismiss`.
61    Dismiss,
62
63    /// The material banner was closed by a user's swipe.
64    Swipe,
65
66    /// The material banner was closed by the `ScaffoldFeatureController` close callback
67    /// or by calling `ScaffoldMessengerState::hide_current_material_banner` directly.
68    Hide,
69
70    /// The material banner was closed by a call to
71    /// `ScaffoldMessengerState::remove_current_material_banner`.
72    Remove,
73}
74
75/// A Material Design banner.
76///
77/// A banner displays an important, succinct message, and provides actions for
78/// users to address (or dismiss the banner). A user action is required for it
79/// to be dismissed.
80///
81/// Banners should be displayed at the top of the screen, below a top app bar.
82/// They are persistent and non-modal, allowing the user to either ignore them or
83/// interact with them at any time.
84///
85/// Banners placed directly into the widget tree are static.
86///
87/// MaterialBanner's can also be presented through a `ScaffoldMessenger`, with
88/// `ScaffoldMessengerState::show_material_banner`.
89///
90/// The [`actions`](Self::actions) will be placed beside the [`content`](Self::content) if
91/// there is only one. Otherwise, the [`actions`](Self::actions) will be placed below the
92/// [`content`](Self::content). Use [`force_actions_below`](Self::force_actions_below) to
93/// override this behavior.
94///
95/// If the [`actions`](Self::actions) placed below the [`content`](Self::content), they will
96/// be laid out in a row. If there isn't sufficient room to display everything, they are laid
97/// out in a column instead.
98///
99/// The [`actions`](Self::actions) and [`content`](Self::content) must be provided. An
100/// optional leading widget (typically an `Image`) can also be provided. The
101/// [`content_text_style`](Self::content_text_style) and
102/// [`background_color`](Self::background_color) can be provided to customize the banner.
103///
104/// This widget is unrelated to the widgets library `Banner` widget.
105#[derive(Clone)]
106pub struct MaterialBanner {
107    pub key: Option<KeyRef>,
108
109    /// The content of the [`MaterialBanner`].
110    ///
111    /// Typically a `Text` widget.
112    pub content: WidgetRef,
113
114    /// Style for the text in the [`content`](Self::content) of the [`MaterialBanner`].
115    ///
116    /// If `None`, [`MaterialBannerThemeData::content_text_style`] is used. If that is
117    /// also `None`, `TextTheme::body_medium` of `ThemeData::text_theme` is used.
118    pub content_text_style: Option<TextStyle>,
119
120    /// The set of actions that are displayed at the bottom or trailing side of
121    /// the [`MaterialBanner`].
122    ///
123    /// Typically this is a list of `TextButton` widgets.
124    ///
125    /// When a [`MaterialBanner`] is shown by a `ScaffoldMessenger` above the
126    /// `Navigator`, such as the one created by `MaterialApp`, it stays visible
127    /// after the route that showed it is popped, and that route's `BuildContext`
128    /// is deactivated. If an action callback dismisses the banner using
129    /// `ScaffoldMessenger::of`, avoid passing a `BuildContext` from the route that
130    /// showed the banner. Instead, either wrap the action widget in a `Builder` so
131    /// its callback uses the banner's own `BuildContext`, or capture the
132    /// `ScaffoldMessengerState` before calling
133    /// `ScaffoldMessengerState::show_material_banner`.
134    pub actions: Vec<WidgetRef>,
135
136    /// The z-coordinate at which to place the material banner.
137    ///
138    /// This controls the size of the shadow below the material banner.
139    ///
140    /// Defines the banner's `Material::elevation`.
141    ///
142    /// If this property is `None`, then the ambient [`MaterialBannerThemeData::elevation`]
143    /// is used, if that is also `None`, the default value is 0.
144    /// If the elevation is 0, the `Scaffold`'s body will be pushed down by the
145    /// MaterialBanner when used with `ScaffoldMessenger`.
146    pub elevation: Option<f64>,
147
148    /// The (optional) leading widget of the [`MaterialBanner`].
149    ///
150    /// Typically an `Icon` widget.
151    pub leading: Option<WidgetRef>,
152
153    /// The optional minimum action bar height.
154    ///
155    /// Default to 52.0.
156    pub min_action_bar_height: f64,
157
158    /// The color of the surface of this [`MaterialBanner`].
159    ///
160    /// If `None`, [`MaterialBannerThemeData::background_color`] is used. If that is
161    /// also `None`, `ColorScheme::surface_container_low` of `ThemeData::color_scheme` is
162    /// used.
163    pub background_color: Option<Color>,
164
165    /// The color used as an overlay on [`background_color`](Self::background_color) to
166    /// indicate elevation.
167    ///
168    /// If `None`, [`MaterialBannerThemeData::surface_tint_color`] is used. If that
169    /// is also `None`, the default value is `Colors::TRANSPARENT`.
170    ///
171    /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
172    /// introduced a set of tone-based surfaces and surface containers in its `ColorScheme`,
173    /// which provide more flexibility. The intention is to eventually remove surface tint
174    /// color from the framework.
175    pub surface_tint_color: Option<Color>,
176
177    /// The color of the shadow below the [`MaterialBanner`].
178    ///
179    /// If this property is `None`, then the ambient [`MaterialBannerThemeData::shadow_color`]
180    /// is used. If that is also `None`, the default value is `None`.
181    pub shadow_color: Option<Color>,
182
183    /// The color of the divider.
184    ///
185    /// If this property is `None`, then the ambient [`MaterialBannerThemeData::divider_color`]
186    /// is used. If that is also `None`, the default value is `ColorScheme::surface_variant`.
187    pub divider_color: Option<Color>,
188
189    /// The amount of space by which to inset the [`content`](Self::content).
190    ///
191    /// If the [`actions`](Self::actions) are below the [`content`](Self::content), this
192    /// defaults to `EdgeInsetsDirectional.only(start: 16.0, top: 24.0, end: 16.0, bottom: 4.0)`.
193    ///
194    /// If the [`actions`](Self::actions) are trailing the [`content`](Self::content), this
195    /// defaults to `EdgeInsetsDirectional.only(start: 16.0, top: 2.0)`.
196    pub padding: Option<EdgeInsetsGeometry>,
197
198    /// Empty space to surround the [`MaterialBanner`].
199    ///
200    /// If the [`margin`](Self::margin) is `None` then this defaults to
201    /// 0 if the banner's [`elevation`](Self::elevation) is 0, 10 otherwise.
202    pub margin: Option<EdgeInsetsGeometry>,
203
204    /// The amount of space by which to inset the [`leading`](Self::leading) widget.
205    ///
206    /// This defaults to `EdgeInsetsDirectional.only(end: 16.0)`.
207    pub leading_padding: Option<EdgeInsetsGeometry>,
208
209    /// An override to force the [`actions`](Self::actions) to be below the
210    /// [`content`](Self::content) regardless of how many there are.
211    ///
212    /// If this is true, the [`actions`](Self::actions) will be placed below the
213    /// [`content`](Self::content). If this is false, the [`actions`](Self::actions) will be
214    /// placed on the trailing side of the [`content`](Self::content) if
215    /// [`actions`](Self::actions)'s length is 1 and below the [`content`](Self::content) if
216    /// greater than 1.
217    ///
218    /// Defaults to false.
219    pub force_actions_below: bool,
220
221    /// The horizontal alignment of the [`actions`](Self::actions) when the
222    /// [`actions`](Self::actions) laid out in a column.
223    ///
224    /// Defaults to [`OverflowBarAlignment::End`].
225    pub overflow_alignment: OverflowBarAlignment,
226
227    /// The animation driving the entrance and exit of the material banner when presented by
228    /// the `ScaffoldMessenger`.
229    pub animation: Option<AnimationRef<f64>>,
230
231    /// Called the first time that the material banner is visible within a `Scaffold` when
232    /// presented by the `ScaffoldMessenger`.
233    pub on_visible: Option<VoidCallback>,
234}
235
236impl MaterialBanner {
237    /// Creates a [`MaterialBanner`]; Dart's optional arguments are the setters.
238    ///
239    /// The length of the [`actions`](Self::actions) list must not be empty. The
240    /// [`elevation`](Self::elevation) must be `None` or non-negative.
241    #[cfg_attr(debug_assertions, track_caller)]
242    pub fn new<K>(content: impl IntoWidget<K>, actions: Vec<WidgetRef>) -> MaterialBanner {
243        MaterialBanner {
244            key: None,
245            content: content.into_widget(),
246            content_text_style: None,
247            actions,
248            elevation: None,
249            leading: None,
250            min_action_bar_height: 52.0,
251            background_color: None,
252            surface_tint_color: None,
253            shadow_color: None,
254            divider_color: None,
255            padding: None,
256            margin: None,
257            leading_padding: None,
258            force_actions_below: false,
259            overflow_alignment: OverflowBarAlignment::End,
260            animation: None,
261            on_visible: None,
262        }
263    }
264
265    /// Dart `MaterialBanner(key:)`.
266    pub fn key(mut self, key: KeyRef) -> MaterialBanner {
267        self.key = Some(key);
268        self
269    }
270
271    /// Dart `MaterialBanner(contentTextStyle:)`.
272    pub fn content_text_style(mut self, content_text_style: TextStyle) -> MaterialBanner {
273        self.content_text_style = Some(content_text_style);
274        self
275    }
276
277    /// Dart `MaterialBanner(elevation:)`.
278    pub fn elevation(mut self, elevation: f64) -> MaterialBanner {
279        debug_assert!(elevation >= 0.0);
280        self.elevation = Some(elevation);
281        self
282    }
283
284    /// Dart `MaterialBanner(leading:)`.
285    #[cfg_attr(debug_assertions, track_caller)]
286    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> MaterialBanner {
287        self.leading = Some(leading.into_widget());
288        self
289    }
290
291    /// Dart `MaterialBanner(minActionBarHeight:)`.
292    pub fn min_action_bar_height(mut self, min_action_bar_height: f64) -> MaterialBanner {
293        self.min_action_bar_height = min_action_bar_height;
294        self
295    }
296
297    /// Dart `MaterialBanner(backgroundColor:)`.
298    pub fn background_color(mut self, background_color: Color) -> MaterialBanner {
299        self.background_color = Some(background_color);
300        self
301    }
302
303    /// Dart `MaterialBanner(surfaceTintColor:)`.
304    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> MaterialBanner {
305        self.surface_tint_color = Some(surface_tint_color);
306        self
307    }
308
309    /// Dart `MaterialBanner(shadowColor:)`.
310    pub fn shadow_color(mut self, shadow_color: Color) -> MaterialBanner {
311        self.shadow_color = Some(shadow_color);
312        self
313    }
314
315    /// Dart `MaterialBanner(dividerColor:)`.
316    pub fn divider_color(mut self, divider_color: Color) -> MaterialBanner {
317        self.divider_color = Some(divider_color);
318        self
319    }
320
321    /// Dart `MaterialBanner(padding:)`.
322    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> MaterialBanner {
323        self.padding = Some(padding.into());
324        self
325    }
326
327    /// Dart `MaterialBanner(margin:)`.
328    pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> MaterialBanner {
329        self.margin = Some(margin.into());
330        self
331    }
332
333    /// Dart `MaterialBanner(leadingPadding:)`.
334    pub fn leading_padding(
335        mut self,
336        leading_padding: impl Into<EdgeInsetsGeometry>,
337    ) -> MaterialBanner {
338        self.leading_padding = Some(leading_padding.into());
339        self
340    }
341
342    /// Dart `MaterialBanner(forceActionsBelow:)`.
343    pub fn force_actions_below(mut self, force_actions_below: bool) -> MaterialBanner {
344        self.force_actions_below = force_actions_below;
345        self
346    }
347
348    /// Dart `MaterialBanner(overflowAlignment:)`.
349    pub fn overflow_alignment(
350        mut self,
351        overflow_alignment: OverflowBarAlignment,
352    ) -> MaterialBanner {
353        self.overflow_alignment = overflow_alignment;
354        self
355    }
356
357    /// Dart `MaterialBanner(animation:)`.
358    pub fn animation(mut self, animation: AnimationRef<f64>) -> MaterialBanner {
359        self.animation = Some(animation);
360        self
361    }
362
363    /// Dart `MaterialBanner(onVisible:)`.
364    pub fn on_visible(mut self, on_visible: impl Fn(&mut App) + 'static) -> MaterialBanner {
365        self.on_visible = Some(Rc::new(on_visible));
366        self
367    }
368
369    // API for ScaffoldMessengerState.showMaterialBanner():
370
371    /// Creates an animation controller useful for driving a [`MaterialBanner`]'s entrance and
372    /// exit animation.
373    pub fn create_animation_controller(
374        app: &mut App,
375        vsync: impl TickerProvider,
376    ) -> Ref<AnimationController> {
377        AnimationController::new(
378            app,
379            None,
380            Some(MATERIAL_BANNER_TRANSITION_DURATION),
381            None,
382            0.0,
383            1.0,
384            AnimationBehavior::Normal,
385            vsync,
386        )
387    }
388
389    /// Creates a copy of this material banner but with the animation replaced with the given
390    /// animation.
391    ///
392    /// If the original material banner lacks a key, the newly created material banner will
393    /// use the given fallback key.
394    pub fn with_animation(
395        &self,
396        new_animation: AnimationRef<f64>,
397        fallback_key: Option<KeyRef>,
398    ) -> MaterialBanner {
399        MaterialBanner {
400            key: self.key.clone().or(fallback_key),
401            content: self.content.clone(),
402            content_text_style: self.content_text_style.clone(),
403            actions: self.actions.clone(),
404            elevation: self.elevation,
405            leading: self.leading.clone(),
406            min_action_bar_height: self.min_action_bar_height,
407            background_color: self.background_color,
408            surface_tint_color: self.surface_tint_color,
409            shadow_color: self.shadow_color,
410            divider_color: self.divider_color,
411            padding: self.padding,
412            margin: self.margin,
413            leading_padding: self.leading_padding,
414            force_actions_below: self.force_actions_below,
415            overflow_alignment: self.overflow_alignment,
416            animation: Some(new_animation),
417            on_visible: self.on_visible.clone(),
418        }
419    }
420}
421
422impl fmt::Debug for MaterialBanner {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        f.debug_struct("MaterialBanner")
425            .field("key", &self.key)
426            .field("content", &self.content)
427            .field("actions", &self.actions)
428            .field("elevation", &self.elevation)
429            .field("leading", &self.leading)
430            .field("force_actions_below", &self.force_actions_below)
431            .field("overflow_alignment", &self.overflow_alignment)
432            .field("animation", &self.animation)
433            .finish_non_exhaustive()
434    }
435}
436
437impl StatefulWidget for MaterialBanner {
438    type State = MaterialBannerState;
439
440    fn key(&self) -> Option<&KeyRef> {
441        self.key.as_ref()
442    }
443
444    fn create_state(&self) -> MaterialBannerState {
445        MaterialBannerState {
446            state: StateData::new(),
447            was_visible: false,
448            height_animation: None,
449            slide_out_curved_animation: None,
450        }
451    }
452}
453
454/// Dart's `_MaterialBannerState`.
455pub struct MaterialBannerState {
456    state: StateData<MaterialBanner>,
457    was_visible: bool,
458    height_animation: Option<Ref<CurvedAnimation>>,
459    slide_out_curved_animation: Option<Ref<CurvedAnimation>>,
460}
461
462impl MaterialBannerState {
463    fn status_listener(self: Handle<Self>) -> AnimationStatusListener {
464        AnimationStatusListener::handle_method(
465            self,
466            MaterialBannerState::on_animation_status_changed,
467        )
468    }
469
470    /// Dart's `curvedAnimation?.dispose()`.
471    fn dispose_curved_animation(app: &mut App, animation: Option<Handle<CurvedAnimation>>) {
472        if let Some(animation) = animation {
473            animation.dispose(app);
474        }
475    }
476
477    fn set_curved_animations(self: Handle<Self>, app: &mut App) {
478        MaterialBannerState::dispose_curved_animation(app, app.get(self).height_animation.handle());
479        MaterialBannerState::dispose_curved_animation(
480            app,
481            app.get(self).slide_out_curved_animation.handle(),
482        );
483        match self.widget(app).animation.clone() {
484            Some(animation) => {
485                let height_animation = CurvedAnimation::new(
486                    app,
487                    animation.clone(),
488                    material_banner_height_curve(),
489                    None,
490                );
491                let slide_out_curved_animation =
492                    CurvedAnimation::new(app, animation, Rc::new(Threshold::new(0.0)), None);
493                let this = app.get_mut(self);
494                this.height_animation = Some(height_animation);
495                this.slide_out_curved_animation = Some(slide_out_curved_animation);
496            }
497            None => {
498                let this = app.get_mut(self);
499                this.height_animation = None;
500                this.slide_out_curved_animation = None;
501            }
502        }
503    }
504
505    fn on_animation_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
506        if status.is_completed() {
507            let on_visible = self.widget(app).on_visible.clone();
508            if let Some(on_visible) = on_visible
509                && !app.get(self).was_visible
510            {
511                on_visible(app);
512            }
513            app.get_mut(self).was_visible = true;
514        }
515    }
516}
517
518impl State for MaterialBannerState {
519    type Widget = MaterialBanner;
520    waft_widgets::state_accessors!();
521
522    fn init_state(self: Handle<Self>, app: &mut App) {
523        if let Some(animation) = self.widget(app).animation.clone() {
524            animation.add_status_listener(app, self.status_listener());
525        }
526        self.set_curved_animations(app);
527    }
528
529    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MaterialBanner) {
530        let animation = self.widget(app).animation.clone();
531        if animation != old_widget.animation {
532            if let Some(old_animation) = old_widget.animation.clone() {
533                old_animation.remove_status_listener(app, &self.status_listener());
534            }
535            if let Some(animation) = animation {
536                animation.add_status_listener(app, self.status_listener());
537            }
538            self.set_curved_animations(app);
539        }
540    }
541
542    fn dispose(self: Handle<Self>, app: &mut App) {
543        if let Some(animation) = self.widget(app).animation.clone() {
544            animation.remove_status_listener(app, &self.status_listener());
545        }
546        MaterialBannerState::dispose_curved_animation(app, app.get(self).height_animation.handle());
547        MaterialBannerState::dispose_curved_animation(
548            app,
549            app.get(self).slide_out_curved_animation.handle(),
550        );
551    }
552
553    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
554        debug_assert!(debug_check_has_media_query(app, context));
555        let accessible_navigation = MediaQuery::accessible_navigation_of(app, context);
556
557        debug_assert!(!self.widget(app).actions.is_empty());
558
559        let theme = Theme::of(app, context);
560        let banner_theme = MaterialBannerTheme::of(app, context);
561        let defaults: Box<dyn MaterialBannerThemeDataGetters> = if theme.use_material3 {
562            Box::new(BannerDefaultsM3::new(context))
563        } else {
564            Box::new(BannerDefaultsM2::new(app, context))
565        };
566
567        let widget = self.widget(app).clone();
568        let is_single_row = widget.actions.len() == 1 && !widget.force_actions_below;
569        let padding = widget
570            .padding
571            .or(banner_theme.padding)
572            .unwrap_or(if is_single_row {
573                EdgeInsetsGeometry::directional(16.0, 2.0, 0.0, 0.0)
574            } else {
575                EdgeInsetsGeometry::directional(16.0, 24.0, 16.0, 4.0)
576            });
577        let leading_padding = widget
578            .leading_padding
579            .or(banner_theme.leading_padding)
580            .unwrap_or(EdgeInsetsGeometry::directional(0.0, 0.0, 16.0, 0.0));
581
582        let actions_bar =
583            ConstrainedBox::new(BoxConstraints::new().min_height(widget.min_action_bar_height))
584                .child(
585                    Padding::new(EdgeInsetsGeometry::symmetric(0.0, 8.0)).child(
586                        Align::new().alignment(AlignmentGeometry::CENTER_END).child(
587                            OverflowBar::new()
588                                .overflow_alignment(widget.overflow_alignment)
589                                .spacing(8.0)
590                                .children(widget.actions.clone()),
591                        ),
592                    ),
593                )
594                .into_widget();
595
596        let elevation = widget.elevation.or(banner_theme.elevation).unwrap_or(0.0);
597        let margin = widget.margin.unwrap_or(EdgeInsetsGeometry::only(
598            0.0,
599            0.0,
600            0.0,
601            if elevation > 0.0 { 10.0 } else { 0.0 },
602        ));
603        let background_color = widget
604            .background_color
605            .or(banner_theme.background_color)
606            .or_else(|| defaults.background_color(app))
607            .expect("the banner defaults have a background color");
608        let surface_tint_color = widget
609            .surface_tint_color
610            .or(banner_theme.surface_tint_color)
611            .or_else(|| defaults.surface_tint_color(app));
612        let shadow_color = widget.shadow_color.or(banner_theme.shadow_color);
613        let divider_color = widget
614            .divider_color
615            .or(banner_theme.divider_color)
616            .or_else(|| defaults.divider_color(app));
617        let text_style = widget
618            .content_text_style
619            .clone()
620            .or_else(|| banner_theme.content_text_style.clone())
621            .or_else(|| defaults.content_text_style(app));
622
623        let mut row_children: Vec<WidgetRef> = Vec::new();
624        if let Some(leading) = &widget.leading {
625            row_children.push(
626                Padding::new(leading_padding)
627                    .child(leading.clone())
628                    .into_widget(),
629            );
630        }
631        row_children.push(MediaQuery::with_clamped_text_scaling(
632            None,
633            // Set maximum text scale factor to _kMaxContentTextScaleFactor for the
634            // content to keep the visual hierarchy the same even with larger font
635            // sizes.
636            0.0,
637            K_MAX_CONTENT_TEXT_SCALE_FACTOR,
638            Expanded::new(DefaultTextStyle::new(
639                text_style.expect("the banner defaults have a content text style"),
640                widget.content.clone(),
641            )),
642        ));
643        if is_single_row {
644            row_children.push(MediaQuery::with_clamped_text_scaling(
645                None,
646                // Set maximum text scale factor to _kMaxContentTextScaleFactor for the
647                // actionsBar to keep the visual hierarchy the same even with larger font
648                // sizes.
649                0.0,
650                K_MAX_CONTENT_TEXT_SCALE_FACTOR,
651                actions_bar.clone(),
652            ));
653        }
654
655        let mut column_children: Vec<WidgetRef> = vec![
656            Padding::new(padding)
657                .child(Row::new().children(row_children))
658                .into_widget(),
659        ];
660        if !is_single_row {
661            column_children.push(actions_bar);
662        }
663        if elevation == 0.0 {
664            let mut divider = Divider::new().height(0.0);
665            if let Some(divider_color) = divider_color {
666                divider = divider.color(divider_color);
667            }
668            column_children.push(divider.into_widget());
669        }
670
671        let mut material = Material::new()
672            .elevation(elevation)
673            .color(background_color)
674            .child(
675                Column::new()
676                    .main_axis_size(MainAxisSize::Min)
677                    .children(column_children),
678            );
679        material.surface_tint_color = surface_tint_color;
680        material.shadow_color = shadow_color;
681        let mut material_banner = Padding::new(margin).child(material).into_widget();
682
683        // This provides a static banner for backwards compatibility.
684        if widget.animation.is_none() {
685            return material_banner;
686        }
687
688        material_banner = SafeArea::new(material_banner).into_widget();
689
690        let slide_out_curved_animation = app
691            .get(self)
692            .slide_out_curved_animation
693            .clone()
694            .expect("set with the animation");
695        let slide_out_tween = Tween::new(app, Some(Offset::new(0.0, -1.0)), Some(Offset::ZERO));
696        let slide_out_animation = slide_out_tween.animate(app, slide_out_curved_animation.erase());
697
698        material_banner = Semantics::new()
699            .container(true)
700            .live_region(true)
701            .on_dismiss(Rc::new(move |app: &mut App| {
702                ScaffoldMessenger::of(app, context)
703                    .remove_current_material_banner(app, MaterialBannerClosedReason::Dismiss);
704            }))
705            .child(if accessible_navigation {
706                material_banner
707            } else {
708                SlideTransition::new(slide_out_animation)
709                    .child(material_banner)
710                    .into_widget()
711            })
712            .into_widget();
713
714        let material_banner_transition = if accessible_navigation {
715            material_banner
716        } else {
717            let height_animation: AnimationRef<f64> = app
718                .get(self)
719                .height_animation
720                .as_ref()
721                .expect("set with the animation")
722                .erase();
723            AnimatedBuilder::new(
724                Rc::new(height_animation.clone()),
725                move |app, _context, child| {
726                    Align::new()
727                        .alignment(AlignmentGeometry::BOTTOM_START)
728                        .height_factor(height_animation.value(app))
729                        .child(child.cloned().expect("the builder's child"))
730                        .into_widget()
731                },
732            )
733            .child(material_banner)
734            .into_widget()
735        };
736
737        Hero::new(
738            Rc::new(format!("<MaterialBanner Hero tag - {:?}>", widget.content)),
739            ClipRect::new().child(material_banner_transition),
740        )
741        .into_widget()
742    }
743}
744
745/// Dart's `_BannerDefaultsM2`.
746struct BannerDefaultsM2 {
747    /// Dart's `super(..)` arguments.
748    material_banner_theme_data: MaterialBannerThemeData,
749    /// Dart's `_theme`, which the constructor reads.
750    theme: Rc<ThemeData>,
751}
752
753impl BannerDefaultsM2 {
754    fn new(app: &mut App, context: BuildContext) -> BannerDefaultsM2 {
755        BannerDefaultsM2 {
756            material_banner_theme_data: MaterialBannerThemeData::new().elevation(0.0),
757            theme: Theme::of(app, context),
758        }
759    }
760}
761
762impl MaterialBannerThemeDataGetters for BannerDefaultsM2 {
763    fn material_banner_theme_data(&self) -> &MaterialBannerThemeData {
764        &self.material_banner_theme_data
765    }
766
767    fn background_color(&self, _app: &mut App) -> Option<Color> {
768        Some(self.theme.color_scheme.surface())
769    }
770
771    fn content_text_style(&self, _app: &mut App) -> Option<TextStyle> {
772        self.theme.text_theme.body_medium.clone()
773    }
774}
775
776#[cfg(test)]
777mod tests {
778    //! Ported from `test/banner_test.dart` and the widget cases of `test/banner_theme_test.dart`.
779
780    use std::cell::{Cell, RefCell};
781    use std::panic::{AssertUnwindSafe, catch_unwind};
782
783    use waft_embedder::{Rect, Size, TextDirection};
784    use waft_foundation::Listener;
785    use waft_painting::{EdgeInsets, TextScaler};
786    use waft_rendering::HitTestBehavior;
787    use waft_widgets::{
788        AnyElement, Builder, Center, Directionality, GestureDetector, GlobalKey, MediaQueryData,
789        SizedBox, Text,
790    };
791
792    use waft_widgets::testing::{
793        WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
794    };
795
796    use super::*;
797    use crate::bottom_navigation_bar::tests::paragraph_style;
798    use crate::color_scheme::ColorScheme;
799    use crate::colors::Colors;
800    use crate::icons::Icons;
801    use crate::scaffold::{Scaffold, ScaffoldMessenger};
802    use crate::snack_bar::SnackBar;
803    use crate::text_button::TextButton;
804    use crate::theme_data::ThemeData;
805    use crate::tooltip::tests::{m2, m3, pump_app};
806    use crate::typography::Typography;
807
808    /// Dart's `TextButton(child: Text(label), onPressed: () {})`, its label.
809    fn action(label: &str) -> WidgetRef {
810        TextButton::new(Some(Listener::new(|_app| {})), Some(Text::new(label))).into_widget()
811    }
812
813    /// Dart's `TextButton(child: Text('DISMISS'), onPressed: () =>
814    /// ScaffoldMessenger.of(context).hideCurrentMaterialBanner())`.
815    fn dismiss(context: BuildContext) -> TextButton {
816        TextButton::new(
817            Some(Listener::new(move |app| {
818                ScaffoldMessenger::of(app, context)
819                    .hide_current_material_banner(app, MaterialBannerClosedReason::Hide);
820            })),
821            Some(Text::new("DISMISS")),
822        )
823    }
824
825    /// Dart's `Scaffold(body: Builder(builder: (context) => GestureDetector(key: tapTarget,
826    /// onTap: () => ScaffoldMessenger.of(context).showMaterialBanner(banner(app, context)),
827    /// behavior: HitTestBehavior.opaque, child: SizedBox(height: 100.0, width: 100.0))))`;
828    /// without `opaque`, the detector has neither the behavior nor the child.
829    fn messenger_home(
830        tap_target: &GlobalKey,
831        opaque: bool,
832        banner: impl Fn(&mut App, BuildContext) -> MaterialBanner + 'static,
833    ) -> WidgetRef {
834        let banner = Rc::new(banner);
835        let tap_target = tap_target.clone();
836        Scaffold::new()
837            .body(Builder::new(move |_app, context| {
838                let banner = Rc::clone(&banner);
839                let detector = GestureDetector::new()
840                    .key(tap_target.clone().into())
841                    .on_tap(Listener::new(move |app| {
842                        let banner = banner(app, context);
843                        ScaffoldMessenger::of(app, context).show_material_banner(app, banner);
844                    }));
845                if opaque {
846                    detector
847                        .behavior(HitTestBehavior::Opaque)
848                        .child(SizedBox::new().height(100.0).width(100.0))
849                        .into_widget()
850                } else {
851                    detector.into_widget()
852                }
853            }))
854            .into_widget()
855    }
856
857    /// Dart's `tester.tap(find.byKey(key))`.
858    fn tap_key(tester: &mut WidgetTester, key: &GlobalKey) {
859        let center = tester.get_center(key);
860        tester.tap_at(center, 1);
861    }
862
863    fn rect(tester: &WidgetTester, element: AnyElement) -> Rect {
864        tester.get_rect(element)
865    }
866
867    fn key_rect(tester: &WidgetTester, key: &GlobalKey) -> Rect {
868        let render = tester.render_object(key).as_box().expect("a render box");
869        tester.get_rect(render)
870    }
871
872    fn banner(tester: &WidgetTester) -> AnyElement {
873        *find::by_type::<MaterialBanner>()
874            .evaluate(tester)
875            .first()
876            .expect("a MaterialBanner")
877    }
878
879    /// Dart's `find.descendant(of: find.byType(MaterialBanner), matching: find.byType(W))`.
880    fn in_banner<W: 'static>(tester: &WidgetTester) -> Vec<AnyElement> {
881        let banner = banner(tester);
882        find::by_type::<W>()
883            .evaluate(tester)
884            .into_iter()
885            .filter(|element| tester.ancestors(*element).contains(&banner))
886            .collect()
887    }
888
889    /// Dart's `_getMaterialFromBanner` and `_materialFinder`.
890    fn banner_material(tester: &WidgetTester) -> AnyElement {
891        in_banner::<Material>(tester)[0]
892    }
893
894    /// Dart's `_getMaterialFromText`: the nearest `Material` around the content.
895    fn material_around(tester: &WidgetTester, text: &str) -> AnyElement {
896        let content = *find::text(text)
897            .evaluate(tester)
898            .first()
899            .expect("the content");
900        tester.ancestor_of_type::<Material>(content)
901    }
902
903    /// A material's `(elevation, color, surfaceTintColor, shadowColor)`.
904    fn material_values(
905        tester: &WidgetTester,
906        material: AnyElement,
907    ) -> (f64, Option<Color>, Option<Color>, Option<Color>) {
908        tester.widget(material, |material: &Material| {
909            (
910                material.elevation,
911                material.color,
912                material.surface_tint_color,
913                material.shadow_color,
914            )
915        })
916    }
917
918    fn divider_color(tester: &WidgetTester) -> Option<Color> {
919        let divider = *find::by_type::<Divider>()
920            .evaluate(tester)
921            .first()
922            .expect("a Divider");
923        tester.widget(divider, |divider: &Divider| divider.color)
924    }
925
926    fn content_rect(tester: &WidgetTester, text: &str) -> Rect {
927        let content = *find::text(text)
928            .evaluate(tester)
929            .first()
930            .expect("the content");
931        rect(tester, content)
932    }
933
934    fn overflow_bar_rect(tester: &WidgetTester) -> Rect {
935        let bar = *find::by_type::<OverflowBar>()
936            .evaluate(tester)
937            .first()
938            .expect("an OverflowBar");
939        rect(tester, bar)
940    }
941
942    #[test]
943    fn a_banner_respects_its_properties() {
944        test_widgets(|tester| {
945            // Dart: 'MaterialBanner properties are respected'.
946
947            let content_widget = Text::new("Content").into_widget();
948            let content_text_style = TextStyle::new().color(Colors::PINK.primary());
949            let banner_text_style = content_text_style.clone();
950            pump_app(tester, m3, move |_app| {
951                MaterialBanner::new(content_widget, vec![action("Action")])
952                    .background_color(Colors::PINK.primary())
953                    .surface_tint_color(Colors::GREEN.primary())
954                    .shadow_color(Colors::BLUE.primary())
955                    .divider_color(Colors::YELLOW.primary())
956                    .content_text_style(banner_text_style)
957                    .into_widget()
958            });
959
960            assert_eq!(
961                material_values(tester, banner_material(tester)),
962                (
963                    0.0,
964                    Some(Colors::PINK.primary()),
965                    Some(Colors::GREEN.primary()),
966                    Some(Colors::BLUE.primary())
967                )
968            );
969            assert_eq!(paragraph_style(tester, "Content"), content_text_style);
970            assert_eq!(divider_color(tester), Some(Colors::YELLOW.primary()));
971        });
972    }
973
974    #[test]
975    fn a_banner_shown_by_the_messenger_respects_its_properties() {
976        test_widgets(|tester| {
977            // Dart: 'MaterialBanner properties are respected when presented by ScaffoldMessenger'.
978
979            let tap_target = GlobalKey::new();
980            let content_widget = Text::new("Content").into_widget();
981            let content_text_style = TextStyle::new().color(Colors::PINK.primary());
982            let banner_text_style = content_text_style.clone();
983            pump_app(tester, m3, |_app| {
984                messenger_home(&tap_target, true, move |_app, context| {
985                    MaterialBanner::new(
986                        content_widget.clone(),
987                        vec![dismiss(context).into_widget()],
988                    )
989                    .background_color(Colors::PINK.primary())
990                    .surface_tint_color(Colors::GREEN.primary())
991                    .shadow_color(Colors::BLUE.primary())
992                    .divider_color(Colors::YELLOW.primary())
993                    .content_text_style(banner_text_style.clone())
994                })
995            });
996            tap_key(tester, &tap_target);
997            tester.pump_and_settle();
998
999            assert_eq!(
1000                material_values(tester, material_around(tester, "Content")),
1001                (
1002                    0.0,
1003                    Some(Colors::PINK.primary()),
1004                    Some(Colors::GREEN.primary()),
1005                    Some(Colors::BLUE.primary())
1006                )
1007            );
1008            assert_eq!(paragraph_style(tester, "Content"), content_text_style);
1009            assert_eq!(divider_color(tester), Some(Colors::YELLOW.primary()));
1010        });
1011    }
1012
1013    #[test]
1014    fn more_than_one_action_is_laid_out_below_the_content() {
1015        test_widgets(|tester| {
1016            // Dart: 'Actions laid out below content if more than one action'.
1017
1018            pump_app(tester, m3, |_app| {
1019                MaterialBanner::new(
1020                    Text::new("Content"),
1021                    vec![action("Action 1"), action("Action 2")],
1022                )
1023                .into_widget()
1024            });
1025
1026            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1027            let actions_top_left = overflow_bar_rect(tester).top_left();
1028            assert!(content_bottom_left.dy() < actions_top_left.dy());
1029            assert!(content_bottom_left.dx() < actions_top_left.dx());
1030        });
1031    }
1032
1033    #[test]
1034    fn more_than_one_action_of_a_shown_banner_is_laid_out_below_the_content() {
1035        test_widgets(|tester| {
1036            // Dart: 'Actions laid out below content if more than one action when presented by
1037            // ScaffoldMessenger'.
1038
1039            let tap_target = GlobalKey::new();
1040            pump_app(tester, m3, |_app| {
1041                messenger_home(&tap_target, true, |_app, context| {
1042                    let ok = TextButton::new(
1043                        Some(Listener::new(move |app| {
1044                            ScaffoldMessenger::of(app, context).hide_current_material_banner(
1045                                app,
1046                                MaterialBannerClosedReason::Hide,
1047                            );
1048                        })),
1049                        Some(Text::new("OK")),
1050                    );
1051                    MaterialBanner::new(
1052                        Text::new("Content"),
1053                        vec![ok.into_widget(), dismiss(context).into_widget()],
1054                    )
1055                })
1056            });
1057            tap_key(tester, &tap_target);
1058            tester.pump_and_settle();
1059
1060            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1061            let actions_top_left = overflow_bar_rect(tester).top_left();
1062            assert!(content_bottom_left.dy() < actions_top_left.dy());
1063            assert!(content_bottom_left.dx() < actions_top_left.dx());
1064        });
1065    }
1066
1067    #[test]
1068    fn a_single_action_is_laid_out_beside_the_content() {
1069        test_widgets(|tester| {
1070            // Dart: 'Actions laid out beside content if only one action'.
1071
1072            pump_app(tester, m3, |_app| {
1073                MaterialBanner::new(Text::new("Content"), vec![action("Action")]).into_widget()
1074            });
1075
1076            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1077            let actions_top_right = overflow_bar_rect(tester).top_right();
1078            assert!(content_bottom_left.dy() > actions_top_right.dy());
1079            assert!(content_bottom_left.dx() < actions_top_right.dx());
1080        });
1081    }
1082
1083    #[test]
1084    fn a_single_action_of_a_shown_banner_is_laid_out_beside_the_content() {
1085        test_widgets(|tester| {
1086            // Dart: 'Actions laid out beside content if only one action when presented by
1087            // ScaffoldMessenger'.
1088
1089            let tap_target = GlobalKey::new();
1090            pump_app(tester, m3, |_app| {
1091                messenger_home(&tap_target, true, |_app, context| {
1092                    MaterialBanner::new(Text::new("Content"), vec![dismiss(context).into_widget()])
1093                })
1094            });
1095            tap_key(tester, &tap_target);
1096            tester.pump_and_settle();
1097
1098            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1099            let actions_top_right = overflow_bar_rect(tester).top_right();
1100            assert!(content_bottom_left.dy() > actions_top_right.dy());
1101            assert!(content_bottom_left.dx() < actions_top_right.dx());
1102        });
1103    }
1104
1105    #[test]
1106    fn the_content_scales_with_the_text_up_to_the_maximum_scale_factor() {
1107        test_widgets(|tester| {
1108            // Dart: 'material banner content can scale and has maxScaleFactor'.
1109
1110            fn size_almost_equal(a: Size, b: Size) -> bool {
1111                (a.width() - b.width()).abs() <= 0.05 && (a.height() - b.height()).abs() <= 0.05
1112            }
1113            let build_app = |tester: &mut WidgetTester, text_scaler: TextScaler| {
1114                pump_app(tester, m3, move |_app| {
1115                    MediaQuery::new(
1116                        MediaQueryData::new().text_scaler(text_scaler),
1117                        MaterialBanner::new(
1118                            SizedBox::new().child(Center::new().child(Text::new("A"))),
1119                            vec![action("B")],
1120                        )
1121                        .force_actions_below(true),
1122                    )
1123                    .into_widget()
1124                });
1125            };
1126
1127            build_app(tester, TextScaler::NO_SCALING);
1128            expect(tester, &find::text("A"), finds_one_widget());
1129            assert_eq!(content_rect(tester, "A").size(), Size::new(14.25, 20.0));
1130
1131            build_app(tester, TextScaler::linear(1.1));
1132            tester.pump_and_settle();
1133            assert!(size_almost_equal(
1134                content_rect(tester, "A").size(),
1135                Size::new(15.65, 22.0)
1136            ));
1137
1138            build_app(tester, TextScaler::linear(1.5));
1139            assert!(size_almost_equal(
1140                content_rect(tester, "A").size(),
1141                Size::new(21.25, 30.0)
1142            ));
1143
1144            build_app(tester, TextScaler::linear(4.0));
1145            assert!(size_almost_equal(
1146                content_rect(tester, "A").size(),
1147                Size::new(21.25, 30.0)
1148            ));
1149        });
1150    }
1151
1152    /// Dart's `buildBanner` of the 'MaterialBanner elevation' group.
1153    fn pump_elevation_banner(
1154        tester: &mut WidgetTester,
1155        tap_target: &GlobalKey,
1156        elevation: Option<f64>,
1157        theme_elevation: Option<f64>,
1158    ) {
1159        let mut banner_theme = MaterialBannerThemeData::new();
1160        banner_theme.elevation = theme_elevation;
1161        pump_app(
1162            tester,
1163            move |app| ThemeData::builder().banner_theme(banner_theme).build(app),
1164            |_app| {
1165                messenger_home(tap_target, true, move |_app, context| {
1166                    let mut banner = MaterialBanner::new(
1167                        Text::new("MaterialBanner"),
1168                        vec![dismiss(context).into_widget()],
1169                    );
1170                    banner.elevation = elevation;
1171                    banner
1172                })
1173            },
1174        );
1175    }
1176
1177    fn banner_elevation(tester: &WidgetTester) -> f64 {
1178        material_values(tester, banner_material(tester)).0
1179    }
1180
1181    #[test]
1182    fn the_elevation_defaults_to_zero() {
1183        test_widgets(|tester| {
1184            // Dart: 'MaterialBanner elevation' / 'Elevation defaults to 0'.
1185
1186            let tap_target = GlobalKey::new();
1187
1188            pump_elevation_banner(tester, &tap_target, None, None);
1189            tap_key(tester, &tap_target);
1190            tester.pump_and_settle();
1191            assert_eq!(banner_elevation(tester), 0.0);
1192            tester.tap(find::text("DISMISS"));
1193            tester.pump_and_settle();
1194
1195            pump_elevation_banner(tester, &tap_target, None, Some(6.0));
1196            tap_key(tester, &tap_target);
1197            tester.pump_and_settle();
1198            assert_eq!(banner_elevation(tester), 6.0);
1199            tester.tap(find::text("DISMISS"));
1200            tester.pump_and_settle();
1201
1202            pump_elevation_banner(tester, &tap_target, Some(3.0), Some(6.0));
1203            tap_key(tester, &tap_target);
1204            tester.pump_and_settle();
1205            assert_eq!(banner_elevation(tester), 3.0);
1206            tester.tap(find::text("DISMISS"));
1207            tester.pump_and_settle();
1208        });
1209    }
1210
1211    #[test]
1212    fn the_elevation_of_the_banner_theme_is_used_by_default() {
1213        test_widgets(|tester| {
1214            // Dart: 'MaterialBanner elevation' / 'Uses elevation of MaterialBannerTheme by default'.
1215
1216            let tap_target = GlobalKey::new();
1217
1218            pump_elevation_banner(tester, &tap_target, None, Some(6.0));
1219            tap_key(tester, &tap_target);
1220            tester.pump_and_settle();
1221            assert_eq!(banner_elevation(tester), 6.0);
1222            tester.tap(find::text("DISMISS"));
1223            tester.pump_and_settle();
1224
1225            pump_elevation_banner(tester, &tap_target, Some(3.0), Some(6.0));
1226            tap_key(tester, &tap_target);
1227            tester.pump_and_settle();
1228            assert_eq!(banner_elevation(tester), 3.0);
1229            tester.tap(find::text("DISMISS"));
1230            tester.pump_and_settle();
1231        });
1232    }
1233
1234    #[test]
1235    fn a_banner_of_elevation_zero_pushes_the_scaffold_body_down() {
1236        test_widgets(|tester| {
1237            // Dart: 'MaterialBanner elevation' / 'Scaffold body is pushed down if elevation is 0'.
1238
1239            let tap_target = GlobalKey::new();
1240
1241            pump_elevation_banner(tester, &tap_target, Some(0.0), None);
1242            tap_key(tester, &tap_target);
1243            tester.pump_and_settle();
1244
1245            let content_top_left = key_rect(tester, &tap_target).top_left();
1246            let banner_bottom_left = rect(tester, banner(tester)).bottom_left();
1247
1248            assert_eq!(content_top_left.dx(), 0.0);
1249            assert!(content_top_left.dy() >= banner_bottom_left.dy());
1250        });
1251    }
1252
1253    #[test]
1254    fn a_shown_banner_stays_until_dismissed() {
1255        test_widgets(|tester| {
1256            // Dart: 'MaterialBanner control test'.
1257
1258            const HELLO_MATERIAL_BANNER: &str = "Hello MaterialBanner";
1259            let tap_target = GlobalKey::new();
1260            let dismiss_target = GlobalKey::new();
1261            pump_app(tester, m3, |_app| {
1262                let dismiss_target = dismiss_target.clone();
1263                messenger_home(&tap_target, true, move |_app, context| {
1264                    MaterialBanner::new(
1265                        Text::new(HELLO_MATERIAL_BANNER),
1266                        vec![
1267                            dismiss(context)
1268                                .key(dismiss_target.clone().into())
1269                                .into_widget(),
1270                        ],
1271                    )
1272                })
1273            });
1274            let shown =
1275                |tester: &WidgetTester| find::text(HELLO_MATERIAL_BANNER).evaluate(tester).len();
1276            assert_eq!(shown(tester), 0);
1277            tap_key(tester, &tap_target);
1278            assert_eq!(shown(tester), 0);
1279            tester.pump(); // schedule animation
1280            assert_eq!(shown(tester), 1);
1281            tester.pump(); // begin animation
1282            assert_eq!(shown(tester), 1);
1283            // 0.75s // animation last frame; two second timer starts here
1284            tester.pump_by(Duration::from_millis(750));
1285            assert_eq!(shown(tester), 1);
1286            tester.pump_by(Duration::from_millis(750)); // 1.50s
1287            assert_eq!(shown(tester), 1);
1288            tester.pump_by(Duration::from_millis(750)); // 2.25s
1289            assert_eq!(shown(tester), 1);
1290            tap_key(tester, &dismiss_target);
1291            tester.pump(); // begin animation
1292            assert_eq!(shown(tester), 1); // frame 0 of dismiss animation
1293            // 3.75s // last frame of animation, material banner removed from build
1294            tester.pump_and_settle();
1295            assert_eq!(shown(tester), 0);
1296        });
1297    }
1298
1299    #[test]
1300    fn a_second_banner_waits_for_the_first_to_close() {
1301        test_widgets(|tester| {
1302            // Dart: 'MaterialBanner twice test'.
1303
1304            let material_banner_count = Rc::new(Cell::new(0));
1305            let tap_target = GlobalKey::new();
1306            let dismiss_target = GlobalKey::new();
1307            pump_app(tester, m3, |_app| {
1308                let dismiss_target = dismiss_target.clone();
1309                let material_banner_count = Rc::clone(&material_banner_count);
1310                messenger_home(&tap_target, true, move |_app, context| {
1311                    material_banner_count.set(material_banner_count.get() + 1);
1312                    MaterialBanner::new(
1313                        Text::new(format!("banner{}", material_banner_count.get())),
1314                        vec![
1315                            dismiss(context)
1316                                .key(dismiss_target.clone().into())
1317                                .into_widget(),
1318                        ],
1319                    )
1320                })
1321            });
1322            let shown = |tester: &WidgetTester| {
1323                (
1324                    find::text("banner1").evaluate(tester).len(),
1325                    find::text("banner2").evaluate(tester).len(),
1326                )
1327            };
1328            assert_eq!(shown(tester), (0, 0));
1329            tap_key(tester, &tap_target); // queue banner1
1330            tap_key(tester, &tap_target); // queue banner2
1331            assert_eq!(shown(tester), (0, 0));
1332            tester.pump(); // schedule animation for banner1
1333            assert_eq!(shown(tester), (1, 0));
1334            tester.pump(); // begin animation
1335            assert_eq!(shown(tester), (1, 0));
1336            tester.pump_by(Duration::from_millis(750)); // 0.75s // animation last frame
1337            assert_eq!(shown(tester), (1, 0));
1338            tester.pump_by(Duration::from_millis(750)); // 1.50s
1339            assert_eq!(shown(tester), (1, 0));
1340            tester.pump_by(Duration::from_millis(750)); // 2.25s
1341            assert_eq!(shown(tester), (1, 0));
1342            tap_key(tester, &dismiss_target);
1343            tester.pump(); // begin animation
1344            assert_eq!(shown(tester), (1, 0));
1345            // 3.75s // last frame of animation, material banner removed from build, new
1346            // material banner put in its place
1347            tester.pump_by(Duration::from_millis(750));
1348            assert_eq!(shown(tester), (0, 1));
1349            tester.pump(); // begin animation
1350            assert_eq!(shown(tester), (0, 1));
1351            tester.pump_by(Duration::from_millis(750)); // 4.50s // animation last frame
1352            assert_eq!(shown(tester), (0, 1));
1353            tester.pump_by(Duration::from_millis(750)); // 5.25s
1354            assert_eq!(shown(tester), (0, 1));
1355            tester.pump_by(Duration::from_millis(750)); // 6.00s
1356            assert_eq!(shown(tester), (0, 1));
1357            tap_key(tester, &dismiss_target); // reverse animation is scheduled
1358            tester.pump(); // begin animation
1359            assert_eq!(shown(tester), (0, 1));
1360            // 7.50s // last frame of animation, material banner removed from build
1361            tester.pump_by(Duration::from_millis(750));
1362            assert_eq!(shown(tester), (0, 0));
1363        });
1364    }
1365
1366    #[test]
1367    fn showing_a_snack_bar_does_not_duplicate_the_banner() {
1368        test_widgets(|tester| {
1369            // Dart: 'ScaffoldMessenger does not duplicate a MaterialBanner when presenting a
1370            // SnackBar.'
1371
1372            let material_banner_tap_target = GlobalKey::new();
1373            let snack_bar_tap_target = GlobalKey::new();
1374            pump_app(tester, m3, |_app| {
1375                let material_banner_tap_target = material_banner_tap_target.clone();
1376                let snack_bar_tap_target = snack_bar_tap_target.clone();
1377                Scaffold::new()
1378                    .body(Builder::new(move |_app, context| {
1379                        Column::new()
1380                            .children([
1381                                GestureDetector::new()
1382                                    .key(snack_bar_tap_target.clone().into())
1383                                    .on_tap(Listener::new(move |app| {
1384                                        ScaffoldMessenger::of(app, context).show_snack_bar(
1385                                            app,
1386                                            SnackBar::new(Text::new("SnackBar")),
1387                                            None,
1388                                        );
1389                                    }))
1390                                    .behavior(HitTestBehavior::Opaque)
1391                                    .child(SizedBox::new().height(100.0).width(100.0))
1392                                    .into_widget(),
1393                                GestureDetector::new()
1394                                    .key(material_banner_tap_target.clone().into())
1395                                    .on_tap(Listener::new(move |app| {
1396                                        ScaffoldMessenger::of(app, context).show_material_banner(
1397                                            app,
1398                                            MaterialBanner::new(
1399                                                Text::new("MaterialBanner"),
1400                                                vec![dismiss(context).into_widget()],
1401                                            ),
1402                                        );
1403                                    }))
1404                                    .behavior(HitTestBehavior::Opaque)
1405                                    .child(SizedBox::new().height(100.0).width(100.0))
1406                                    .into_widget(),
1407                            ])
1408                            .into_widget()
1409                    }))
1410                    .into_widget()
1411            });
1412            tap_key(tester, &snack_bar_tap_target);
1413            tap_key(tester, &material_banner_tap_target);
1414            tester.pump_and_settle();
1415
1416            expect(tester, &find::text("SnackBar"), finds_one_widget());
1417            expect(tester, &find::text("MaterialBanner"), finds_one_widget());
1418        });
1419    }
1420
1421    #[test]
1422    fn a_single_action_beside_the_content_is_aligned_to_the_trailing_edge() {
1423        test_widgets(|tester| {
1424            // Dart: 'Single action laid out beside content but aligned to the trailing edge'.
1425
1426            pump_app(tester, m3, |_app| {
1427                MaterialBanner::new(Text::new("Content"), vec![action("Action")]).into_widget()
1428            });
1429
1430            let actions_top_right = overflow_bar_rect(tester).top_right();
1431            let banner_top_right = rect(tester, banner(tester)).top_right();
1432            // actions OverflowBar is padded by 8
1433            // Within f32: global positions go through valo's f32 matrices (waft-gestures'
1434            // `Matrix4` entry), where Dart's are f64 and compare equal.
1435            assert!((actions_top_right.dx() + 8.0 - banner_top_right.dx()).abs() < 1e-4);
1436        });
1437    }
1438
1439    #[test]
1440    fn a_single_action_beside_the_content_of_a_shown_banner_is_aligned_to_the_trailing_edge() {
1441        test_widgets(|tester| {
1442            // Dart: 'Single action laid out beside content but aligned to the trailing edge when
1443            // presented by ScaffoldMessenger'.
1444
1445            let tap_target = GlobalKey::new();
1446            pump_app(tester, m3, |_app| {
1447                messenger_home(&tap_target, true, |_app, context| {
1448                    MaterialBanner::new(Text::new("Content"), vec![dismiss(context).into_widget()])
1449                })
1450            });
1451            tap_key(tester, &tap_target);
1452            tester.pump_and_settle();
1453
1454            let actions_top_right = overflow_bar_rect(tester).top_right();
1455            let banner_top_right = rect(tester, banner(tester)).top_right();
1456            // actions OverflowBar is padded by 8
1457            // Within f32: global positions go through valo's f32 matrices (waft-gestures'
1458            // `Matrix4` entry), where Dart's are f64 and compare equal.
1459            assert!((actions_top_right.dx() + 8.0 - banner_top_right.dx()).abs() < 1e-4);
1460        });
1461    }
1462
1463    #[test]
1464    fn a_single_action_beside_the_content_is_aligned_to_the_trailing_edge_in_rtl() {
1465        test_widgets(|tester| {
1466            // Dart: 'Single action laid out beside content but aligned to the trailing edge - RTL'.
1467
1468            pump_app(tester, m3, |_app| {
1469                Directionality::new(
1470                    TextDirection::Rtl,
1471                    MaterialBanner::new(Text::new("Content"), vec![action("Action")]),
1472                )
1473                .into_widget()
1474            });
1475
1476            let actions_top_left = overflow_bar_rect(tester).top_left();
1477            let banner_top_left = rect(tester, banner(tester)).top_left();
1478            // actions OverflowBar is padded by 8
1479            assert!((actions_top_left.dx() - 8.0 - banner_top_left.dx()).abs() < 1e-10);
1480        });
1481    }
1482
1483    #[test]
1484    fn a_single_action_beside_the_content_of_a_shown_banner_is_aligned_to_the_trailing_edge_in_rtl()
1485    {
1486        test_widgets(|tester| {
1487            // Dart: 'Single action laid out beside content but aligned to the trailing edge when
1488            // presented by ScaffoldMessenger - RTL'.
1489
1490            let tap_target = GlobalKey::new();
1491            pump_app(tester, m3, |_app| {
1492                Directionality::new(
1493                    TextDirection::Rtl,
1494                    messenger_home(&tap_target, true, |_app, context| {
1495                        MaterialBanner::new(
1496                            Text::new("Content"),
1497                            vec![dismiss(context).into_widget()],
1498                        )
1499                    }),
1500                )
1501                .into_widget()
1502            });
1503            tap_key(tester, &tap_target);
1504            tester.pump_and_settle();
1505
1506            let actions_top_left = overflow_bar_rect(tester).top_left();
1507            let banner_top_left = rect(tester, banner(tester)).top_left();
1508            // actions OverflowBar is padded by 8
1509            assert!((actions_top_left.dx() - 8.0 - banner_top_left.dx()).abs() < 1e-10);
1510        });
1511    }
1512
1513    #[test]
1514    fn forcing_actions_below_lays_one_action_out_below_the_content() {
1515        test_widgets(|tester| {
1516            // Dart: 'Actions laid out below content if forced override'.
1517
1518            pump_app(tester, m3, |_app| {
1519                MaterialBanner::new(Text::new("Content"), vec![action("Action")])
1520                    .force_actions_below(true)
1521                    .into_widget()
1522            });
1523
1524            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1525            let actions_top_left = overflow_bar_rect(tester).top_left();
1526            assert!(content_bottom_left.dy() < actions_top_left.dy());
1527            assert!(content_bottom_left.dx() < actions_top_left.dx());
1528        });
1529    }
1530
1531    #[test]
1532    fn forcing_actions_below_lays_one_action_of_a_shown_banner_out_below_the_content() {
1533        test_widgets(|tester| {
1534            // Dart: 'Actions laid out below content if forced override when presented by
1535            // ScaffoldMessenger'.
1536
1537            let tap_target = GlobalKey::new();
1538            pump_app(tester, m3, |_app| {
1539                messenger_home(&tap_target, true, |_app, context| {
1540                    MaterialBanner::new(Text::new("Content"), vec![dismiss(context).into_widget()])
1541                        .force_actions_below(true)
1542                })
1543            });
1544            tap_key(tester, &tap_target);
1545            tester.pump_and_settle();
1546
1547            let content_bottom_left = content_rect(tester, "Content").bottom_left();
1548            let actions_top_left = overflow_bar_rect(tester).top_left();
1549            assert!(content_bottom_left.dy() < actions_top_left.dy());
1550            assert!(content_bottom_left.dx() < actions_top_left.dx());
1551        });
1552    }
1553
1554    /// Dart's `SizedBox(width:, height:, key: ValueKey<int>(index))` actions, the first holding
1555    /// `first_child` when one is given; the keys find them.
1556    fn sized_actions(
1557        keys: &[GlobalKey],
1558        width: f64,
1559        height: f64,
1560        first_child: Option<WidgetRef>,
1561    ) -> Vec<WidgetRef> {
1562        keys.iter()
1563            .enumerate()
1564            .map(|(index, key)| {
1565                let action = SizedBox::new()
1566                    .width(width)
1567                    .height(height)
1568                    .key(key.clone().into());
1569                match (&first_child, index) {
1570                    (Some(child), 0) => action.child(child.clone()).into_widget(),
1571                    _ => action.into_widget(),
1572                }
1573            })
1574            .collect()
1575    }
1576
1577    /// Dart's `GestureDetector(key: dismissTarget, onTap: () =>
1578    /// ScaffoldMessenger.of(context).hideCurrentMaterialBanner())`.
1579    fn dismiss_detector(dismiss_target: &GlobalKey, context: BuildContext) -> WidgetRef {
1580        GestureDetector::new()
1581            .key(dismiss_target.clone().into())
1582            .on_tap(Listener::new(move |app| {
1583                ScaffoldMessenger::of(app, context)
1584                    .hide_current_material_banner(app, MaterialBannerClosedReason::Hide);
1585            }))
1586            .into_widget()
1587    }
1588
1589    fn keys(count: usize) -> Vec<GlobalKey> {
1590        (0..count).map(|_| GlobalKey::new()).collect()
1591    }
1592
1593    fn top_left(tester: &WidgetTester, key: &GlobalKey) -> waft_embedder::Offset {
1594        key_rect(tester, key).top_left()
1595    }
1596
1597    #[test]
1598    fn the_action_widgets_are_laid_out_as_the_button_bar_laid_them_out() {
1599        test_widgets(|tester| {
1600            // Dart: 'Action widgets layout'.
1601
1602            let build_frame = |tester: &mut WidgetTester,
1603                               actions: &[GlobalKey],
1604                               text_direction: TextDirection| {
1605                let actions = sized_actions(actions, 64.0, 48.0, None);
1606                pump_app(tester, m3, move |_app| {
1607                    Directionality::new(
1608                        text_direction,
1609                        MaterialBanner::new(SizedBox::new().width(100.0).height(100.0), actions),
1610                    )
1611                    .into_widget()
1612                });
1613            };
1614            let one = keys(1);
1615            let three = keys(3);
1616            // The action coordinates that follow were obtained by running
1617            // the test code, before ButtonBar was replaced by OverflowBar.
1618
1619            build_frame(tester, &one, TextDirection::Ltr);
1620            assert_eq!(
1621                top_left(tester, &one[0]),
1622                waft_embedder::Offset::new(728.0, 28.0)
1623            );
1624
1625            build_frame(tester, &one, TextDirection::Rtl);
1626            assert_eq!(
1627                top_left(tester, &one[0]),
1628                waft_embedder::Offset::new(8.0, 28.0)
1629            );
1630
1631            build_frame(tester, &three, TextDirection::Ltr);
1632            assert_eq!(
1633                top_left(tester, &three[0]),
1634                waft_embedder::Offset::new(584.0, 130.0)
1635            );
1636            assert_eq!(
1637                top_left(tester, &three[1]),
1638                waft_embedder::Offset::new(656.0, 130.0)
1639            );
1640            assert_eq!(
1641                top_left(tester, &three[2]),
1642                waft_embedder::Offset::new(728.0, 130.0)
1643            );
1644
1645            build_frame(tester, &three, TextDirection::Rtl);
1646            assert_eq!(
1647                top_left(tester, &three[0]),
1648                waft_embedder::Offset::new(152.0, 130.0)
1649            );
1650            assert_eq!(
1651                top_left(tester, &three[1]),
1652                waft_embedder::Offset::new(80.0, 130.0)
1653            );
1654            assert_eq!(
1655                top_left(tester, &three[2]),
1656                waft_embedder::Offset::new(8.0, 130.0)
1657            );
1658        });
1659    }
1660
1661    /// Pumps Dart's `buildFrame` of the cases presented by the messenger: a scaffold whose
1662    /// body shows a banner of `actions`, the first of which dismisses it, then taps to show it.
1663    fn show_sized_actions(
1664        tester: &mut WidgetTester,
1665        tap_target: &GlobalKey,
1666        dismiss_target: &GlobalKey,
1667        actions: &[GlobalKey],
1668        size: (f64, f64),
1669        text_direction: TextDirection,
1670        overflow_alignment: Option<OverflowBarAlignment>,
1671    ) {
1672        let actions = actions.to_vec();
1673        let dismiss_target = dismiss_target.clone();
1674        pump_app(tester, m3, |_app| {
1675            Directionality::new(
1676                text_direction,
1677                messenger_home(tap_target, false, move |_app, context| {
1678                    let mut banner = MaterialBanner::new(
1679                        SizedBox::new().width(100.0).height(100.0),
1680                        sized_actions(
1681                            &actions,
1682                            size.0,
1683                            size.1,
1684                            Some(dismiss_detector(&dismiss_target, context)),
1685                        ),
1686                    );
1687                    if let Some(overflow_alignment) = overflow_alignment {
1688                        banner = banner.overflow_alignment(overflow_alignment);
1689                    }
1690                    banner
1691                }),
1692            )
1693            .into_widget()
1694        });
1695        tap_key(tester, tap_target);
1696        tester.pump_and_settle();
1697    }
1698
1699    #[test]
1700    fn the_action_widgets_of_a_shown_banner_are_laid_out_as_the_button_bar_laid_them_out() {
1701        test_widgets(|tester| {
1702            // Dart: 'Action widgets layout when presented by ScaffoldMessenger'.
1703
1704            let tap_target = GlobalKey::new();
1705            let dismiss_target = GlobalKey::new();
1706            let one = keys(1);
1707            let three = keys(3);
1708            let size = (64.0, 48.0);
1709            // The action coordinates that follow were obtained by running
1710            // the test code, before ButtonBar was replaced by OverflowBar.
1711
1712            show_sized_actions(
1713                tester,
1714                &tap_target,
1715                &dismiss_target,
1716                &one,
1717                size,
1718                TextDirection::Ltr,
1719                None,
1720            );
1721            assert_eq!(
1722                top_left(tester, &one[0]),
1723                waft_embedder::Offset::new(728.0, 28.0)
1724            );
1725            tap_key(tester, &dismiss_target);
1726            tester.pump_and_settle();
1727
1728            show_sized_actions(
1729                tester,
1730                &tap_target,
1731                &dismiss_target,
1732                &one,
1733                size,
1734                TextDirection::Rtl,
1735                None,
1736            );
1737            assert_eq!(
1738                top_left(tester, &one[0]),
1739                waft_embedder::Offset::new(8.0, 28.0)
1740            );
1741            tap_key(tester, &dismiss_target);
1742            tester.pump_and_settle();
1743
1744            show_sized_actions(
1745                tester,
1746                &tap_target,
1747                &dismiss_target,
1748                &three,
1749                size,
1750                TextDirection::Ltr,
1751                None,
1752            );
1753            assert_eq!(
1754                top_left(tester, &three[0]),
1755                waft_embedder::Offset::new(584.0, 130.0)
1756            );
1757            assert_eq!(
1758                top_left(tester, &three[1]),
1759                waft_embedder::Offset::new(656.0, 130.0)
1760            );
1761            assert_eq!(
1762                top_left(tester, &three[2]),
1763                waft_embedder::Offset::new(728.0, 130.0)
1764            );
1765            tap_key(tester, &dismiss_target);
1766            tester.pump_and_settle();
1767
1768            show_sized_actions(
1769                tester,
1770                &tap_target,
1771                &dismiss_target,
1772                &three,
1773                size,
1774                TextDirection::Rtl,
1775                None,
1776            );
1777            assert_eq!(
1778                top_left(tester, &three[0]),
1779                waft_embedder::Offset::new(152.0, 130.0)
1780            );
1781            assert_eq!(
1782                top_left(tester, &three[1]),
1783                waft_embedder::Offset::new(80.0, 130.0)
1784            );
1785            assert_eq!(
1786                top_left(tester, &three[2]),
1787                waft_embedder::Offset::new(8.0, 130.0)
1788            );
1789            tap_key(tester, &dismiss_target);
1790            tester.pump_and_settle();
1791        });
1792    }
1793
1794    fn assert_stacked(tester: &WidgetTester, actions: &[GlobalKey], dx: f64) {
1795        for (index, key) in actions.iter().enumerate() {
1796            assert_eq!(
1797                top_left(tester, key),
1798                waft_embedder::Offset::new(dx, 134.0 + index as f64 * 10.0)
1799            );
1800        }
1801    }
1802
1803    /// Pumps a banner of four 200x10 actions straight under the app: Dart's `buildFrame` of
1804    /// the overflow cases.
1805    fn pump_overflowing_actions(
1806        tester: &mut WidgetTester,
1807        actions: &[GlobalKey],
1808        text_direction: TextDirection,
1809        overflow_alignment: Option<OverflowBarAlignment>,
1810    ) {
1811        let actions = sized_actions(actions, 200.0, 10.0, None);
1812        pump_app(tester, m3, move |_app| {
1813            let mut banner =
1814                MaterialBanner::new(SizedBox::new().width(100.0).height(100.0), actions);
1815            if let Some(overflow_alignment) = overflow_alignment {
1816                banner = banner.overflow_alignment(overflow_alignment);
1817            }
1818            Directionality::new(text_direction, banner).into_widget()
1819        });
1820    }
1821
1822    #[test]
1823    fn overflowing_action_widgets_are_laid_out_as_the_button_bar_laid_them_out() {
1824        test_widgets(|tester| {
1825            // Dart: 'Action widgets layout with overflow'.
1826
1827            let actions = keys(4);
1828            // The action coordinates that follow were obtained by running
1829            // the test code, before ButtonBar was replaced by OverflowBar.
1830
1831            pump_overflowing_actions(tester, &actions, TextDirection::Ltr, None);
1832            assert_stacked(tester, &actions, 592.0);
1833
1834            pump_overflowing_actions(tester, &actions, TextDirection::Rtl, None);
1835            assert_stacked(tester, &actions, 8.0);
1836        });
1837    }
1838
1839    #[test]
1840    fn overflowing_action_widgets_of_a_shown_banner_are_laid_out_as_the_button_bar_laid_them_out() {
1841        test_widgets(|tester| {
1842            // Dart: 'Action widgets layout with overflow when presented by ScaffoldMessenger'.
1843
1844            let tap_target = GlobalKey::new();
1845            let dismiss_target = GlobalKey::new();
1846            let actions = keys(4);
1847            let size = (200.0, 10.0);
1848            // The action coordinates that follow were obtained by running
1849            // the test code, before ButtonBar was replaced by OverflowBar.
1850
1851            show_sized_actions(
1852                tester,
1853                &tap_target,
1854                &dismiss_target,
1855                &actions,
1856                size,
1857                TextDirection::Ltr,
1858                None,
1859            );
1860            assert_stacked(tester, &actions, 592.0);
1861            tap_key(tester, &dismiss_target);
1862            tester.pump_and_settle();
1863
1864            show_sized_actions(
1865                tester,
1866                &tap_target,
1867                &dismiss_target,
1868                &actions,
1869                size,
1870                TextDirection::Rtl,
1871                None,
1872            );
1873            assert_stacked(tester, &actions, 8.0);
1874            tap_key(tester, &dismiss_target);
1875            tester.pump_and_settle();
1876        });
1877    }
1878
1879    #[test]
1880    fn the_overflow_alignment_aligns_the_overflowing_actions() {
1881        test_widgets(|tester| {
1882            // Dart: '[overflowAlignment] test'.
1883
1884            let actions = keys(4);
1885
1886            pump_overflowing_actions(
1887                tester,
1888                &actions,
1889                TextDirection::Ltr,
1890                Some(OverflowBarAlignment::Start),
1891            );
1892            assert_stacked(tester, &actions, 8.0);
1893
1894            pump_overflowing_actions(
1895                tester,
1896                &actions,
1897                TextDirection::Ltr,
1898                Some(OverflowBarAlignment::Center),
1899            );
1900            assert_stacked(tester, &actions, 300.0);
1901
1902            pump_overflowing_actions(
1903                tester,
1904                &actions,
1905                TextDirection::Ltr,
1906                Some(OverflowBarAlignment::End),
1907            );
1908            assert_stacked(tester, &actions, 592.0);
1909        });
1910    }
1911
1912    #[test]
1913    fn the_overflow_alignment_aligns_the_overflowing_actions_of_a_shown_banner() {
1914        test_widgets(|tester| {
1915            // Dart: '[overflowAlignment] test when presented by ScaffoldMessenger'.
1916
1917            let tap_target = GlobalKey::new();
1918            let dismiss_target = GlobalKey::new();
1919            let actions = keys(4);
1920            let size = (200.0, 10.0);
1921
1922            for (overflow_alignment, dx) in [
1923                (OverflowBarAlignment::Start, 8.0),
1924                (OverflowBarAlignment::Center, 300.0),
1925                (OverflowBarAlignment::End, 592.0),
1926            ] {
1927                show_sized_actions(
1928                    tester,
1929                    &tap_target,
1930                    &dismiss_target,
1931                    &actions,
1932                    size,
1933                    TextDirection::Ltr,
1934                    Some(overflow_alignment),
1935                );
1936                assert_stacked(tester, &actions, dx);
1937                tap_key(tester, &dismiss_target);
1938                tester.pump_and_settle();
1939            }
1940        });
1941    }
1942
1943    #[test]
1944    fn the_messenger_asserts_when_it_has_no_scaffold_to_show_a_banner_in() {
1945        test_widgets(|tester| {
1946            // Dart: 'ScaffoldMessenger will alert for MaterialBanners that cannot be presented'.
1947
1948            let context = Rc::new(Cell::new(None));
1949            let seen = Rc::clone(&context);
1950            pump_app(tester, m3, move |_app| {
1951                Builder::new(move |_app, context| {
1952                    seen.set(Some(context));
1953                    Center::new().into_widget()
1954                })
1955                .into_widget()
1956            });
1957            let context = context.get().expect("the home built");
1958
1959            let result = catch_unwind(AssertUnwindSafe(|| {
1960                let mut app = tester.cell.borrow_mut();
1961                let scaffold_messenger_state = ScaffoldMessenger::of(&mut app, context);
1962                scaffold_messenger_state.show_material_banner(
1963                    &mut app,
1964                    MaterialBanner::new(Text::new("Banner"), Vec::new()),
1965                );
1966            }));
1967            let panic = result.expect_err("the assert fires");
1968            let message = panic
1969                .downcast_ref::<String>()
1970                .cloned()
1971                .or_else(|| {
1972                    panic
1973                        .downcast_ref::<&str>()
1974                        .map(|message| message.to_string())
1975                })
1976                .expect("a panic message");
1977            assert!(message.contains(
1978                "ScaffoldMessenger.showMaterialBanner was called, but there are currently no \
1979                 descendant Scaffolds to present to."
1980            ));
1981        });
1982    }
1983
1984    #[test]
1985    fn a_custom_margin_is_respected() {
1986        test_widgets(|tester| {
1987            // Dart: 'Custom Margin respected'.
1988
1989            let margin = EdgeInsets::all(30.0);
1990            pump_app(tester, m3, move |_app| {
1991                MaterialBanner::new(Text::new("I am a banner"), vec![action("Action")])
1992                    .margin(margin)
1993                    .into_widget()
1994            });
1995
1996            let top_left = rect(tester, banner_material(tester)).top_left();
1997
1998            // Compare the offset of banner from top left
1999            assert_eq!(top_left.dx(), margin.left);
2000        });
2001    }
2002
2003    #[test]
2004    fn the_minimum_action_bar_height_is_respected() {
2005        test_widgets(|tester| {
2006            // Dart: 'minActionBarHeight is respected'.
2007
2008            const MIN_ACTION_BAR_HEIGHT: f64 = 20.0;
2009            pump_app(tester, m3, |_app| {
2010                crate::scaffold::Scaffold::new()
2011                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
2012                        crate::app_bar::AppBar::new(),
2013                    ))
2014                    .body(
2015                        MaterialBanner::new(
2016                            SizedBox::shrink(),
2017                            vec![SizedBox::shrink().into_widget()],
2018                        )
2019                        .min_action_bar_height(MIN_ACTION_BAR_HEIGHT)
2020                        .padding(EdgeInsets::ZERO)
2021                        .margin(EdgeInsets::ZERO),
2022                    )
2023                    .into_widget()
2024            });
2025
2026            let size = rect(tester, banner(tester)).size();
2027            assert_eq!(size.height(), MIN_ACTION_BAR_HEIGHT);
2028        });
2029    }
2030
2031    #[test]
2032    fn the_minimum_action_bar_height_of_a_shown_banner_is_respected() {
2033        test_widgets(|tester| {
2034            // Dart: 'minimumActionBarHeight is respected when presented by ScaffoldMessenger'.
2035
2036            const MIN_ACTION_BAR_HEIGHT: f64 = 20.0;
2037            let tap_target = GlobalKey::new();
2038            pump_app(tester, m3, |_app| {
2039                messenger_home(&tap_target, true, |_app, _context| {
2040                    MaterialBanner::new(SizedBox::shrink(), vec![SizedBox::shrink().into_widget()])
2041                        .padding(EdgeInsets::ZERO)
2042                        .margin(EdgeInsets::ZERO)
2043                        .min_action_bar_height(MIN_ACTION_BAR_HEIGHT)
2044                })
2045            });
2046            tap_key(tester, &tap_target);
2047            tester.pump_and_settle();
2048
2049            let material_bar_size = rect(tester, banner(tester)).size();
2050            assert_eq!(material_bar_size.height(), MIN_ACTION_BAR_HEIGHT);
2051        });
2052    }
2053
2054    #[test]
2055    fn a_banner_renders_at_zero_size() {
2056        test_widgets(|tester| {
2057            // Dart: 'MaterialBanner renders at zero size'.
2058
2059            pump_app(tester, m3, |_app| {
2060                Center::new()
2061                    .child(SizedBox::shrink().child(MaterialBanner::new(
2062                        Text::new("X"),
2063                        vec![SizedBox::shrink().into_widget()],
2064                    )))
2065                    .into_widget()
2066            });
2067            assert!(content_rect(tester, "X").size().is_empty());
2068        });
2069    }
2070
2071    // banner_theme_test.dart
2072
2073    /// Dart's `_bannerTheme()`.
2074    fn theme_banner() -> MaterialBannerThemeData {
2075        MaterialBannerThemeData::new()
2076            .background_color(Colors::ORANGE.primary())
2077            .surface_tint_color(Colors::YELLOW.primary())
2078            .shadow_color(Colors::RED.primary())
2079            .divider_color(Colors::GREEN.primary())
2080            .content_text_style(TextStyle::new().color(Colors::PINK.primary()))
2081            .elevation(4.0)
2082            .padding(EdgeInsetsGeometry::all(5.0))
2083            .leading_padding(EdgeInsetsGeometry::all(6.0))
2084    }
2085
2086    fn row_rect(tester: &WidgetTester) -> Rect {
2087        rect(tester, in_banner::<Row>(tester)[0])
2088    }
2089
2090    fn icon_rect(tester: &WidgetTester, icon: &waft_widgets::IconData) -> Rect {
2091        rect(tester, tester.element(find::by_icon(icon).first()))
2092    }
2093
2094    /// Asserts the default single-line paddings Dart's defaults cases check.
2095    fn assert_default_paddings(tester: &WidgetTester) {
2096        let row_top_left = row_rect(tester).top_left();
2097        let material_top_left = rect(tester, banner_material(tester)).top_left();
2098        let leading_top_left = icon_rect(tester, &Icons::umbrella()).top_left();
2099        // Default single line top padding.
2100        assert_eq!(row_top_left.dy() - material_top_left.dy(), 2.0);
2101        // Default single line start padding.
2102        assert_eq!(row_top_left.dx() - material_top_left.dx(), 16.0);
2103        // Default leading padding.
2104        assert_eq!(leading_top_left.dy() - material_top_left.dy(), 16.0);
2105        assert_eq!(leading_top_left.dx() - material_top_left.dx(), 16.0);
2106    }
2107
2108    /// Asserts where the content and the leading `Icons.ac_unit` sit inside the material.
2109    fn assert_content_and_leading(tester: &WidgetTester, content: (f64, f64), leading: (f64, f64)) {
2110        let content_top_left = content_rect(tester, "Content").top_left();
2111        let material_top_left = rect(tester, banner_material(tester)).top_left();
2112        let leading_top_left = icon_rect(tester, &Icons::ac_unit()).top_left();
2113        assert_eq!(content_top_left.dy() - material_top_left.dy(), content.0);
2114        assert_eq!(content_top_left.dx() - material_top_left.dx(), content.1);
2115        assert_eq!(leading_top_left.dy() - material_top_left.dy(), leading.0);
2116        assert_eq!(leading_top_left.dx() - material_top_left.dx(), leading.1);
2117    }
2118
2119    #[test]
2120    fn material3_without_a_banner_theme_uses_the_defaults() {
2121        test_widgets(|tester| {
2122            // Dart: 'Material3 - Passing no MaterialBannerThemeData returns defaults'.
2123
2124            let content_widget = Text::new("Content").into_widget();
2125            let localized_theme = Rc::new(RefCell::new(None));
2126            let seen = Rc::clone(&localized_theme);
2127            pump_app(tester, m3, move |_app| {
2128                Scaffold::new()
2129                    .body(Builder::new(move |app, context| {
2130                        *seen.borrow_mut() = Some(Theme::of(app, context));
2131                        MaterialBanner::new(content_widget.clone(), vec![action("Action")])
2132                            .leading(waft_widgets::Icon::new(Some(Icons::umbrella())))
2133                            .into_widget()
2134                    }))
2135                    .into_widget()
2136            });
2137            let theme = ThemeData::new(&tester.cell.borrow());
2138            let localized_theme = localized_theme.borrow().clone().expect("the body built");
2139
2140            let (elevation, color, surface_tint_color, shadow_color) =
2141                material_values(tester, material_around(tester, "Content"));
2142            assert_eq!(color, Some(theme.color_scheme.surface_container_low()));
2143            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
2144            assert_eq!(shadow_color, None);
2145            assert_eq!(elevation, 0.0);
2146
2147            assert_eq!(
2148                Some(paragraph_style(tester, "Content")),
2149                localized_theme.text_theme.body_medium
2150            );
2151
2152            assert_default_paddings(tester);
2153
2154            assert_eq!(
2155                divider_color(tester),
2156                Some(theme.color_scheme.outline_variant())
2157            );
2158        });
2159    }
2160
2161    #[test]
2162    fn material3_without_a_banner_theme_uses_the_defaults_for_a_shown_banner() {
2163        test_widgets(|tester| {
2164            // Dart: 'Material3 - Passing no MaterialBannerThemeData returns defaults when presented
2165            // by ScaffoldMessenger'.
2166
2167            let tap_target = GlobalKey::new();
2168            let content_widget = Text::new("Content").into_widget();
2169            let localized_theme = Rc::new(RefCell::new(None));
2170            let seen = Rc::clone(&localized_theme);
2171            pump_app(tester, m3, |_app| {
2172                messenger_home(&tap_target, true, move |app, _context| {
2173                    // Dart reads `localizedTheme` in the body's builder, whose context this is.
2174                    *seen.borrow_mut() = Some(Theme::of(app, _context));
2175                    MaterialBanner::new(content_widget.clone(), vec![action("Action")])
2176                        .leading(waft_widgets::Icon::new(Some(Icons::umbrella())))
2177                })
2178            });
2179            tap_key(tester, &tap_target);
2180            tester.pump_and_settle();
2181            let theme = ThemeData::new(&tester.cell.borrow());
2182            let localized_theme = localized_theme
2183                .borrow()
2184                .clone()
2185                .expect("the banner was shown");
2186
2187            let (elevation, color, surface_tint_color, shadow_color) =
2188                material_values(tester, material_around(tester, "Content"));
2189            assert_eq!(color, Some(theme.color_scheme.surface_container_low()));
2190            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
2191            assert_eq!(shadow_color, None);
2192            assert_eq!(elevation, 0.0);
2193
2194            assert_eq!(
2195                Some(paragraph_style(tester, "Content")),
2196                localized_theme.text_theme.body_medium
2197            );
2198
2199            assert_default_paddings(tester);
2200
2201            assert_eq!(
2202                divider_color(tester),
2203                Some(theme.color_scheme.outline_variant())
2204            );
2205        });
2206    }
2207
2208    fn banner_theme_app(app: &App) -> ThemeData {
2209        ThemeData::builder().banner_theme(theme_banner()).build(app)
2210    }
2211
2212    #[test]
2213    fn a_banner_uses_the_values_of_the_banner_theme() {
2214        test_widgets(|tester| {
2215            // Dart: 'MaterialBanner uses values from MaterialBannerThemeData'.
2216
2217            let banner_theme = theme_banner();
2218            let content_widget = Text::new("Content").into_widget();
2219            pump_app(tester, banner_theme_app, move |_app| {
2220                Scaffold::new()
2221                    .body(
2222                        MaterialBanner::new(content_widget, vec![action("Action")])
2223                            .leading(waft_widgets::Icon::new(Some(Icons::ac_unit()))),
2224                    )
2225                    .into_widget()
2226            });
2227
2228            assert_eq!(
2229                material_values(tester, material_around(tester, "Content")),
2230                (
2231                    banner_theme.elevation.expect("set"),
2232                    banner_theme.background_color,
2233                    banner_theme.surface_tint_color,
2234                    banner_theme.shadow_color
2235                )
2236            );
2237            assert_eq!(
2238                Some(paragraph_style(tester, "Content")),
2239                banner_theme.content_text_style
2240            );
2241
2242            assert_content_and_leading(tester, (24.0, 41.0), (19.0, 11.0));
2243
2244            expect(tester, &find::by_type::<Divider>(), finds_nothing());
2245        });
2246    }
2247
2248    #[test]
2249    fn a_shown_banner_uses_the_values_of_the_banner_theme() {
2250        test_widgets(|tester| {
2251            // Dart: 'MaterialBanner uses values from MaterialBannerThemeData when presented by
2252            // ScaffoldMessenger'.
2253
2254            let banner_theme = theme_banner();
2255            let tap_target = GlobalKey::new();
2256            let content_widget = Text::new("Content").into_widget();
2257            pump_app(tester, banner_theme_app, |_app| {
2258                messenger_home(&tap_target, true, move |_app, _context| {
2259                    MaterialBanner::new(content_widget.clone(), vec![action("Action")])
2260                        .leading(waft_widgets::Icon::new(Some(Icons::ac_unit())))
2261                })
2262            });
2263            tap_key(tester, &tap_target);
2264            tester.pump_and_settle();
2265
2266            assert_eq!(
2267                material_values(tester, material_around(tester, "Content")),
2268                (
2269                    banner_theme.elevation.expect("set"),
2270                    banner_theme.background_color,
2271                    banner_theme.surface_tint_color,
2272                    banner_theme.shadow_color
2273                )
2274            );
2275            assert_eq!(
2276                Some(paragraph_style(tester, "Content")),
2277                banner_theme.content_text_style
2278            );
2279
2280            assert_content_and_leading(tester, (24.0, 41.0), (19.0, 11.0));
2281
2282            expect(tester, &find::by_type::<Divider>(), finds_nothing());
2283        });
2284    }
2285
2286    #[test]
2287    fn the_banner_properties_take_priority_over_the_theme() {
2288        test_widgets(|tester| {
2289            // Dart: 'MaterialBanner widget properties take priority over theme'.
2290
2291            let text_style = TextStyle::new().color(Colors::GREEN.primary());
2292            let banner_text_style = text_style.clone();
2293            let content_widget = Text::new("Content").into_widget();
2294            pump_app(tester, banner_theme_app, move |_app| {
2295                Scaffold::new()
2296                    .body(
2297                        MaterialBanner::new(content_widget, vec![action("Action")])
2298                            .background_color(Colors::PURPLE.primary())
2299                            .surface_tint_color(Colors::RED.primary())
2300                            .shadow_color(Colors::ORANGE.primary())
2301                            .elevation(6.0)
2302                            .leading(waft_widgets::Icon::new(Some(Icons::ac_unit())))
2303                            .content_text_style(banner_text_style)
2304                            .padding(EdgeInsets::all(10.0))
2305                            .leading_padding(EdgeInsets::all(12.0)),
2306                    )
2307                    .into_widget()
2308            });
2309
2310            assert_eq!(
2311                material_values(tester, material_around(tester, "Content")),
2312                (
2313                    6.0,
2314                    Some(Colors::PURPLE.primary()),
2315                    Some(Colors::RED.primary()),
2316                    Some(Colors::ORANGE.primary())
2317                )
2318            );
2319            assert_eq!(Some(paragraph_style(tester, "Content")), Some(text_style));
2320
2321            assert_content_and_leading(tester, (29.0, 58.0), (24.0, 22.0));
2322
2323            expect(tester, &find::by_type::<Divider>(), finds_nothing());
2324        });
2325    }
2326
2327    #[test]
2328    fn the_properties_of_a_shown_banner_take_priority_over_the_theme() {
2329        test_widgets(|tester| {
2330            // Dart: 'MaterialBanner widget properties take priority over theme when presented by
2331            // ScaffoldMessenger'.
2332
2333            const ELEVATION: f64 = 6.0;
2334            let text_style = TextStyle::new().color(Colors::GREEN.primary());
2335            let banner_text_style = text_style.clone();
2336            let tap_target = GlobalKey::new();
2337            let content_widget = Text::new("Content").into_widget();
2338            pump_app(tester, banner_theme_app, |_app| {
2339                messenger_home(&tap_target, true, move |_app, _context| {
2340                    MaterialBanner::new(content_widget.clone(), vec![action("Action")])
2341                        .background_color(Colors::PURPLE.primary())
2342                        .elevation(ELEVATION)
2343                        .leading(waft_widgets::Icon::new(Some(Icons::ac_unit())))
2344                        .content_text_style(banner_text_style.clone())
2345                        .padding(EdgeInsets::all(10.0))
2346                        .leading_padding(EdgeInsets::all(12.0))
2347                })
2348            });
2349            tap_key(tester, &tap_target);
2350            tester.pump_and_settle();
2351
2352            let (elevation, color, _, _) =
2353                material_values(tester, material_around(tester, "Content"));
2354            assert_eq!(color, Some(Colors::PURPLE.primary()));
2355            assert_eq!(elevation, ELEVATION);
2356            assert_eq!(Some(paragraph_style(tester, "Content")), Some(text_style));
2357
2358            assert_content_and_leading(tester, (29.0, 58.0), (24.0, 22.0));
2359
2360            expect(tester, &find::by_type::<Divider>(), finds_nothing());
2361        });
2362    }
2363
2364    fn purple_surface_scheme() -> ColorScheme {
2365        ColorScheme::light()
2366            .copy_with()
2367            .with_surface(Colors::PURPLE.primary())
2368    }
2369
2370    #[test]
2371    fn a_banner_uses_the_color_scheme_when_necessary() {
2372        test_widgets(|tester| {
2373            // Dart: 'MaterialBanner uses color scheme when necessary'.
2374
2375            pump_app(
2376                tester,
2377                |app| {
2378                    ThemeData::builder()
2379                        .color_scheme(purple_surface_scheme())
2380                        .build(app)
2381                },
2382                |_app| {
2383                    Scaffold::new()
2384                        .body(MaterialBanner::new(
2385                            Text::new("Content"),
2386                            vec![action("Action")],
2387                        ))
2388                        .into_widget()
2389                },
2390            );
2391
2392            let (_, color, _, _) = material_values(tester, material_around(tester, "Content"));
2393            assert_eq!(color, Some(purple_surface_scheme().surface_container_low()));
2394        });
2395    }
2396
2397    #[test]
2398    fn a_shown_banner_uses_the_color_scheme_when_necessary() {
2399        test_widgets(|tester| {
2400            // Dart: 'MaterialBanner uses color scheme when necessary when presented by
2401            // ScaffoldMessenger'.
2402
2403            let tap_target = GlobalKey::new();
2404            pump_app(
2405                tester,
2406                |app| {
2407                    ThemeData::builder()
2408                        .color_scheme(purple_surface_scheme())
2409                        .build(app)
2410                },
2411                |_app| {
2412                    messenger_home(&tap_target, true, |_app, _context| {
2413                        MaterialBanner::new(Text::new("Content"), vec![action("Action")])
2414                    })
2415                },
2416            );
2417            tap_key(tester, &tap_target);
2418            tester.pump_and_settle();
2419
2420            let (_, color, _, _) = material_values(tester, material_around(tester, "Content"));
2421            assert_eq!(color, Some(purple_surface_scheme().surface_container_low()));
2422        });
2423    }
2424
2425    /// Dart's `Typography.material2014().englishLike.bodyMedium!.merge(
2426    /// Typography.material2014().black.bodyMedium)`.
2427    fn material2014_body_medium() -> Option<TextStyle> {
2428        let typography = Typography::material2014().build();
2429        Some(
2430            typography
2431                .english_like
2432                .body_medium
2433                .as_ref()
2434                .expect("a body medium style")
2435                .merge(typography.black.body_medium.as_ref()),
2436        )
2437    }
2438
2439    /// The Material 2 defaults Dart's 'Material 2' cases check.
2440    fn assert_material2_defaults(tester: &WidgetTester) {
2441        assert_eq!(
2442            material_values(tester, material_around(tester, "Content")),
2443            (0.0, Some(Color::new(0xffffffff)), None, None)
2444        );
2445
2446        // Default value for ThemeData.typography is Typography.material2014()
2447        assert_eq!(
2448            Some(paragraph_style(tester, "Content")),
2449            material2014_body_medium()
2450        );
2451
2452        assert_default_paddings(tester);
2453
2454        assert_eq!(divider_color(tester), None);
2455    }
2456
2457    #[test]
2458    fn material2_without_a_banner_theme_uses_the_defaults() {
2459        test_widgets(|tester| {
2460            // Dart: 'Material 2' / 'Material2 - Passing no MaterialBannerThemeData returns
2461            // defaults'.
2462
2463            let content_widget = Text::new("Content").into_widget();
2464            pump_app(tester, m2, move |_app| {
2465                Scaffold::new()
2466                    .body(
2467                        MaterialBanner::new(content_widget, vec![action("Action")])
2468                            .leading(waft_widgets::Icon::new(Some(Icons::umbrella()))),
2469                    )
2470                    .into_widget()
2471            });
2472
2473            assert_material2_defaults(tester);
2474        });
2475    }
2476
2477    #[test]
2478    fn material2_without_a_banner_theme_uses_the_defaults_for_a_shown_banner() {
2479        test_widgets(|tester| {
2480            // Dart: 'Material 2' / 'Material2 - Passing no MaterialBannerThemeData returns defaults
2481            // when presented by ScaffoldMessenger'.
2482
2483            let tap_target = GlobalKey::new();
2484            let content_widget = Text::new("Content").into_widget();
2485            pump_app(tester, m2, |_app| {
2486                messenger_home(&tap_target, true, move |_app, _context| {
2487                    MaterialBanner::new(content_widget.clone(), vec![action("Action")])
2488                        .leading(waft_widgets::Icon::new(Some(Icons::umbrella())))
2489                })
2490            });
2491            tap_key(tester, &tap_target);
2492            tester.pump_and_settle();
2493
2494            assert_material2_defaults(tester);
2495        });
2496    }
2497}