Skip to main content

waft_material/
dialog.rs

1//! Flutter counterpart: material_ui's `dialog.dart`, with its parts
2//! `generated/dialog_defaults_m3.g.dart` and `generated/dialog_fullscreen_defaults_m3.g.dart`.
3
4use std::any::Any;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7use std::time::Duration;
8use waft_animation::{
9    AnimationRef, AnimationStyle, AnimationWithParent, Curve, CurvedAnimation, Curves,
10};
11
12use waft_cupertino::{CupertinoAlertDialog, ShowCupertinoDialog};
13use waft_embedder::{Brightness, Clip, Color, SemanticsHitTestBehavior, SemanticsRole};
14use waft_embedder::{TargetPlatform, TextAlign, lerp_double};
15use waft_foundation::{App, CompleterFuture, Handle, OptionRetained, Ref};
16use waft_painting::{
17    AlignmentGeometry, EdgeInsets, EdgeInsetsGeometry, K_DEFAULT_FONT_SIZE, RoundedRectangleBorder,
18    ShapeBorderRef, TextStyle, VerticalDirection,
19};
20use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisAlignment, MainAxisSize};
21use waft_widgets::{
22    Align, AnimatedPadding, AnyRoute, BuildContext, Builder, CapturedThemes, Column,
23    ConstrainedBox, DefaultTextStyle, Directionality, FadeTransition, Flexible,
24    HeroControllerScope, IconTheme, IconThemeData, InheritedTheme, IntoWidget, IntrinsicWidth,
25    KeyRef, ListBody, LocalHistoryRoute, LocalHistoryRouteData, MediaQuery, ModalRoute,
26    ModalRouteData, Navigator, OverflowBar, OverflowBarAlignment, OverlayRoute, OverlayRouteData,
27    Padding, Page, PageRef, PageRouteBuilder, PopScope, PopupRoute, PredictiveBackRoute,
28    RawDialogRoute, RawDialogRouteBuilder, RawDialogRouteData, RawDialogRouteLeaf, Route,
29    RouteData, RoutePageBuilder, RouteRef, RouteResult, RouteSettingsRef, SafeArea,
30    ScrollControllerRef, Semantics, ShowRawDialog, SingleChildScrollView, State, StatelessWidget,
31    TransitionRoute, TransitionRouteData, TraversalEdgeBehavior, WidgetBuilder, WidgetRef,
32};
33
34use crate::colors::Colors;
35use crate::debug::debug_check_has_material_localizations;
36use crate::dialog_theme::DialogThemeDataGetters;
37use crate::dialog_theme::{DialogTheme, DialogThemeData};
38use crate::generated::dialog_defaults_m3::DialogDefaultsM3;
39use crate::generated::dialog_fullscreen_defaults_m3::DialogFullscreenDefaultsM3;
40use crate::ink_well::InkWell;
41use crate::material::{Material, MaterialType};
42use crate::material_localizations::MaterialLocalizations;
43use crate::theme::Theme;
44use crate::theme_data_getters::DefaultsContext;
45
46const DEFAULT_INSET_PADDING: EdgeInsets = EdgeInsets::symmetric(24.0, 40.0);
47
48/// A Material Design dialog.
49///
50/// This dialog widget does not have any opinion about the contents of the
51/// dialog. Rather than using this widget directly, consider using [`AlertDialog`]
52/// or [`SimpleDialog`], which implement specific kinds of Material Design
53/// dialogs.
54///
55/// ## Constraints
56/// The Material 3 guideline recommends that a dialog should have a maximal width of 560dp.
57/// For historical reasons, Flutter's [`Dialog`] widget does not come with this constraint by
58/// default. For applications targeting large screens such as desktop or Web, it is recommended
59/// to set the [`constraints`](Self::constraints) property.
60///
61/// One set of setters serves both of Dart's constructors, [`Dialog::new`] and
62/// [`Dialog::fullscreen`].
63///
64/// See also:
65///
66///  * [`AlertDialog`], for dialogs that have a message and some buttons.
67///  * [`SimpleDialog`], for dialogs that offer a variety of options.
68///  * [`ShowDialog`], which actually displays the dialog and returns its result.
69///  * <https://material.io/design/components/dialogs.html>
70#[derive(Debug)]
71pub struct Dialog {
72    pub key: Option<KeyRef>,
73
74    /// The background color of the surface of this [`Dialog`].
75    ///
76    /// This sets the `Material::color` on this [`Dialog`]'s `Material`.
77    ///
78    /// If null, then the [`DialogThemeData::background_color`] is used. If that is
79    /// also null, defaults to `ColorScheme::surface_container_high`. If
80    /// `ThemeData::use_material3` is false, defaults to `Colors::GREY` with a shade
81    /// of 800 in dark theme and `Colors::WHITE` in light theme.
82    ///
83    /// If [`Dialog::fullscreen`] is used, defaults to `ColorScheme::surface`.
84    pub background_color: Option<Color>,
85
86    /// The z-coordinate of this [`Dialog`].
87    ///
88    /// Controls how far above the parent the dialog will appear. Elevation is
89    /// represented by a drop shadow if [`shadow_color`](Self::shadow_color) is non null,
90    /// and a surface tint overlay on the background color if
91    /// [`surface_tint_color`](Self::surface_tint_color) is non null.
92    ///
93    /// If null then [`DialogThemeData::elevation`] is used, and if that is null then
94    /// the elevation will match the Material Design specification for Dialogs.
95    pub elevation: Option<f64>,
96
97    /// The color used to paint a drop shadow under the dialog's `Material`,
98    /// which reflects the dialog's [`elevation`](Self::elevation).
99    ///
100    /// If null and `ThemeData::use_material3` is true then no drop shadow will
101    /// be rendered.
102    ///
103    /// If null and `ThemeData::use_material3` is false then it will default to
104    /// `ThemeData::shadow_color`.
105    pub shadow_color: Option<Color>,
106
107    /// The color used as a surface tint overlay on the dialog's background color,
108    /// which reflects the dialog's [`elevation`](Self::elevation).
109    ///
110    /// If `ThemeData::use_material3` is false property has no effect.
111    ///
112    /// defaults to `Colors::TRANSPARENT`.
113    ///
114    /// To disable this feature, set [`surface_tint_color`](Self::surface_tint_color) to
115    /// `Colors::TRANSPARENT`.
116    pub surface_tint_color: Option<Color>,
117
118    /// The duration of the animation to show when the system keyboard intrudes
119    /// into the space that the dialog is placed in.
120    ///
121    /// Defaults to 100 milliseconds.
122    pub inset_animation_duration: Duration,
123
124    /// The curve to use for the animation shown when the system keyboard intrudes
125    /// into the space that the dialog is placed in.
126    ///
127    /// Defaults to `Curves::decelerate`.
128    pub inset_animation_curve: Rc<dyn Curve>,
129
130    /// The amount of padding added to `MediaQueryData::view_insets` on the outside
131    /// of the dialog. This defines the minimum space between the screen's edges
132    /// and the dialog.
133    ///
134    /// Defaults to `EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0)`.
135    pub inset_padding: Option<EdgeInsets>,
136
137    /// Controls how the contents of the dialog are clipped (or not) to the given
138    /// [`shape`](Self::shape).
139    ///
140    /// See the enum [`Clip`] for details of all possible options and their common
141    /// use cases.
142    ///
143    /// If null, then [`DialogThemeData::clip_behavior`] is used. If that is also null,
144    /// defaults to [`Clip::None`].
145    pub clip_behavior: Option<Clip>,
146
147    /// The shape of this dialog's border.
148    ///
149    /// Defines the dialog's `Material::shape`.
150    ///
151    /// The default shape is a [`RoundedRectangleBorder`] with a radius of 4.0
152    pub shape: Option<ShapeBorderRef>,
153
154    /// How to align the [`Dialog`].
155    ///
156    /// If null, then [`DialogThemeData::alignment`] is used. If that is also null, the
157    /// default is `Alignment::CENTER`.
158    pub alignment: Option<AlignmentGeometry>,
159
160    /// The widget below this widget in the tree.
161    pub child: Option<WidgetRef>,
162
163    /// This value is used to determine if this is a fullscreen dialog.
164    fullscreen: bool,
165
166    /// The role this dialog represent in assist technologies.
167    ///
168    /// Defaults to [`SemanticsRole::Dialog`].
169    pub semantics_role: SemanticsRole,
170
171    /// Constrains the size of the dialog.
172    ///
173    /// If null, then [`DialogThemeData::constraints`] is used. If that is also null, the
174    /// default is `const BoxConstraints(minWidth: 280.0)`.
175    pub constraints: Option<BoxConstraints>,
176}
177
178impl Dialog {
179    /// Creates a dialog.
180    ///
181    /// Typically used in conjunction with [`ShowDialog`].
182    pub fn new() -> Dialog {
183        Dialog {
184            key: None,
185            background_color: None,
186            elevation: None,
187            shadow_color: None,
188            surface_tint_color: None,
189            inset_animation_duration: Duration::from_millis(100),
190            inset_animation_curve: Curves::decelerate(),
191            inset_padding: None,
192            clip_behavior: None,
193            shape: None,
194            alignment: None,
195            child: None,
196            fullscreen: false,
197            semantics_role: SemanticsRole::Dialog,
198            constraints: None,
199        }
200    }
201
202    /// Creates a fullscreen dialog.
203    ///
204    /// Typically used in conjunction with [`ShowDialog`].
205    ///
206    /// The dialog's `Material` covers the whole screen, including the area
207    /// behind the software keyboard, while [`child`](Self::child) is kept above the keyboard,
208    /// so that a translucent keyboard shows the dialog's
209    /// [`background_color`](Self::background_color) rather than what is behind the dialog.
210    pub fn fullscreen() -> Dialog {
211        Dialog {
212            key: None,
213            background_color: None,
214            elevation: Some(0.0),
215            shadow_color: None,
216            surface_tint_color: None,
217            inset_animation_duration: Duration::ZERO,
218            inset_animation_curve: Curves::decelerate(),
219            inset_padding: Some(EdgeInsets::ZERO),
220            clip_behavior: Some(Clip::None),
221            shape: None,
222            alignment: None,
223            child: None,
224            fullscreen: true,
225            semantics_role: SemanticsRole::Dialog,
226            constraints: None,
227        }
228    }
229
230    /// Dart `Dialog(key:)`.
231    pub fn key(mut self, key: KeyRef) -> Dialog {
232        self.key = Some(key);
233        self
234    }
235
236    /// Dart `Dialog(backgroundColor:)`.
237    pub fn background_color(mut self, background_color: Color) -> Dialog {
238        self.background_color = Some(background_color);
239        self
240    }
241
242    /// Dart `Dialog(elevation:)`.
243    pub fn elevation(mut self, elevation: f64) -> Dialog {
244        debug_assert!(elevation >= 0.0);
245        self.elevation = Some(elevation);
246        self
247    }
248
249    /// Dart `Dialog(shadowColor:)`.
250    pub fn shadow_color(mut self, shadow_color: Color) -> Dialog {
251        self.shadow_color = Some(shadow_color);
252        self
253    }
254
255    /// Dart `Dialog(surfaceTintColor:)`.
256    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> Dialog {
257        self.surface_tint_color = Some(surface_tint_color);
258        self
259    }
260
261    /// Dart `Dialog(insetAnimationDuration:)`.
262    pub fn inset_animation_duration(mut self, inset_animation_duration: Duration) -> Dialog {
263        self.inset_animation_duration = inset_animation_duration;
264        self
265    }
266
267    /// Dart `Dialog(insetAnimationCurve:)`.
268    pub fn inset_animation_curve(mut self, inset_animation_curve: Rc<dyn Curve>) -> Dialog {
269        self.inset_animation_curve = inset_animation_curve;
270        self
271    }
272
273    /// Dart `Dialog(insetPadding:)`.
274    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> Dialog {
275        self.inset_padding = Some(inset_padding);
276        self
277    }
278
279    /// Dart `Dialog(clipBehavior:)`.
280    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Dialog {
281        self.clip_behavior = Some(clip_behavior);
282        self
283    }
284
285    /// Dart `Dialog(shape:)`.
286    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> Dialog {
287        self.shape = Some(shape.into());
288        self
289    }
290
291    /// Dart `Dialog(alignment:)`.
292    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Dialog {
293        self.alignment = Some(alignment);
294        self
295    }
296
297    /// Dart `Dialog(child:)`.
298    #[cfg_attr(debug_assertions, track_caller)]
299    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Dialog {
300        self.child = Some(child.into_widget());
301        self
302    }
303
304    /// Dart `Dialog(semanticsRole:)`.
305    pub fn semantics_role(mut self, semantics_role: SemanticsRole) -> Dialog {
306        self.semantics_role = semantics_role;
307        self
308    }
309
310    /// Dart `Dialog(constraints:)`.
311    pub fn constraints(mut self, constraints: BoxConstraints) -> Dialog {
312        self.constraints = Some(constraints);
313        self
314    }
315
316    // Keeps [child] out of the view insets, such as the software keyboard, which
317    // the child then no longer needs to account for. [padding] is the view
318    // insets plus the dialog's inset padding.
319    fn avoid_view_insets(
320        &self,
321        app: &mut App,
322        context: BuildContext,
323        padding: EdgeInsets,
324        child: WidgetRef,
325    ) -> WidgetRef {
326        AnimatedPadding::new(padding, self.inset_animation_duration)
327            .curve(Rc::clone(&self.inset_animation_curve))
328            .child(
329                MediaQuery::remove_view_insets(app, context, true, true, true, true, child)
330                    .into_widget(),
331            )
332            .into_widget()
333    }
334}
335
336impl Default for Dialog {
337    fn default() -> Dialog {
338        Dialog::new()
339    }
340}
341
342impl StatelessWidget for Dialog {
343    fn key(&self) -> Option<&KeyRef> {
344        self.key.as_ref()
345    }
346
347    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
348        let theme = Theme::of(app, context);
349        let dialog_theme = DialogTheme::of(app, context);
350        let effective_padding = MediaQuery::view_insets_of(app, context)
351            + self
352                .inset_padding
353                .or(dialog_theme.inset_padding)
354                .unwrap_or(DEFAULT_INSET_PADDING);
355        let defaults: Box<dyn DialogThemeDataGetters> = if theme.use_material3 {
356            if self.fullscreen {
357                Box::new(DialogFullscreenDefaultsM3::new(context))
358            } else {
359                Box::new(DialogDefaultsM3::new(context))
360            }
361        } else {
362            Box::new(DialogDefaultsM2::new(context))
363        };
364
365        let box_constraints = self
366            .constraints
367            .or(dialog_theme.constraints)
368            .unwrap_or(BoxConstraints::new().min_width(280.0));
369
370        let dialog_child = if self.fullscreen {
371            // The Material keeps covering the whole screen, including the area
372            // behind the keyboard, so that a translucent keyboard shows the dialog's
373            // surface rather than the modal barrier behind it. Only the content is
374            // kept above the keyboard.
375            let mut material = Material::new();
376            material.color = self
377                .background_color
378                .or(dialog_theme.background_color)
379                .or_else(|| defaults.background_color(app));
380            material.child = self
381                .child
382                .clone()
383                .map(|child| self.avoid_view_insets(app, context, effective_padding, child));
384            material.into_widget()
385        } else {
386            let mut material = Material::new()
387                .elevation(
388                    self.elevation
389                        .or(dialog_theme.elevation)
390                        .or_else(|| defaults.elevation(app))
391                        .expect("the defaults give an elevation"),
392                )
393                .shape(
394                    self.shape
395                        .clone()
396                        .or(dialog_theme.shape.clone())
397                        .or_else(|| defaults.shape(app))
398                        .expect("the defaults give a shape"),
399                )
400                .r#type(MaterialType::Card)
401                .clip_behavior(
402                    self.clip_behavior
403                        .or(dialog_theme.clip_behavior)
404                        .or_else(|| defaults.clip_behavior(app))
405                        .expect("the defaults give a clip behavior"),
406                );
407            material.color = self
408                .background_color
409                .or(dialog_theme.background_color)
410                .or_else(|| defaults.background_color(app));
411            material.shadow_color = self
412                .shadow_color
413                .or(dialog_theme.shadow_color)
414                .or_else(|| defaults.shadow_color(app));
415            material.surface_tint_color = self
416                .surface_tint_color
417                .or(dialog_theme.surface_tint_color)
418                .or_else(|| defaults.surface_tint_color(app));
419            material.child = self.child.clone();
420            let aligned = Align::new()
421                .alignment(
422                    self.alignment
423                        .or(dialog_theme.alignment)
424                        .or_else(|| defaults.alignment(app))
425                        .expect("the defaults give an alignment"),
426                )
427                .child(ConstrainedBox::new(box_constraints).child(material))
428                .into_widget();
429            self.avoid_view_insets(app, context, effective_padding, aligned)
430        };
431
432        Semantics::new()
433            .role(self.semantics_role)
434            .child(dialog_child)
435            .into_widget()
436    }
437}
438
439/// The adaptive half of an [`AlertDialog`]: Dart's private `_AdaptiveAlertDialog`'s own
440/// fields.
441#[derive(Debug)]
442struct AdaptiveAlertDialog {
443    scroll_controller: Option<ScrollControllerRef>,
444    action_scroll_controller: Option<ScrollControllerRef>,
445    inset_animation_duration: Duration,
446    inset_animation_curve: Rc<dyn Curve>,
447}
448
449/// A Material Design alert dialog.
450///
451/// An alert dialog (also known as a basic dialog) informs the user about
452/// situations that require acknowledgment. An alert dialog has an optional
453/// title and an optional list of actions. The title is displayed above the
454/// content and the actions are displayed below the content.
455///
456/// If the content is too large to fit on the screen vertically, the dialog will
457/// display the title and the actions and let the content overflow, which is
458/// rarely desired. Consider using a scrolling widget for
459/// [`content`](Self::content), such as `SingleChildScrollView`, to avoid
460/// overflow. (However, be aware that since [`AlertDialog`] tries to size itself
461/// using the intrinsic dimensions of its children, widgets such as `ListView`,
462/// `GridView`, and `CustomScrollView`, which use lazy viewports, will not work.
463/// If this is a problem, consider using [`Dialog`] directly.)
464///
465/// For dialogs that offer the user a choice between several options, consider
466/// using a [`SimpleDialog`].
467///
468/// Typically passed as the child widget to [`ShowDialog`], which displays the
469/// dialog.
470///
471/// One set of setters serves both of Dart's constructors, [`AlertDialog::new`] and
472/// [`AlertDialog::adaptive`].
473///
474/// See also:
475///
476///  * [`SimpleDialog`], which handles the scrolling of the contents but has no [`actions`](Self::actions).
477///  * [`Dialog`], on which [`AlertDialog`] and [`SimpleDialog`] are based.
478///  * `CupertinoAlertDialog`, an iOS-styled alert dialog.
479///  * [`ShowDialog`], which actually displays the dialog and returns its result.
480///  * <https://material.io/design/components/dialogs.html#alert-dialog>
481#[derive(Debug)]
482pub struct AlertDialog {
483    pub key: Option<KeyRef>,
484
485    /// An optional icon to display at the top of the dialog.
486    ///
487    /// Typically, an `Icon` widget. Providing an icon centers the
488    /// [`title`](Self::title)'s text.
489    pub icon: Option<WidgetRef>,
490
491    /// Color for the `Icon` in the [`icon`](Self::icon) of this [`AlertDialog`].
492    ///
493    /// If null, [`DialogThemeData::icon_color`] is used. If that is null, defaults to
494    /// color scheme's `ColorScheme::secondary` if `ThemeData::use_material3` is
495    /// true, black otherwise.
496    pub icon_color: Option<Color>,
497
498    /// Padding around the [`icon`](Self::icon).
499    ///
500    /// If there is no [`icon`](Self::icon), no padding will be provided. Otherwise,
501    /// this padding is used.
502    ///
503    /// This property defaults to providing 24 pixels on the top, left, and right
504    /// of the [`icon`](Self::icon). If [`title`](Self::title) is _not_ null, 16 pixels of
505    /// bottom padding is added to separate the [`icon`](Self::icon) from the
506    /// [`title`](Self::title). If the [`title`](Self::title) is null but
507    /// [`content`](Self::content) is _not_ null, then no bottom padding is added. If both
508    /// the title and content are null, 24 pixels of padding are added to the bottom.
509    pub icon_padding: Option<EdgeInsetsGeometry>,
510
511    /// The (optional) title of the dialog is displayed in a large font at the top
512    /// of the dialog, below the (optional) [`icon`](Self::icon).
513    ///
514    /// Typically a `Text` widget.
515    pub title: Option<WidgetRef>,
516
517    /// Padding around the title.
518    ///
519    /// If there is no title, no padding will be provided. Otherwise, this padding
520    /// is used.
521    ///
522    /// This property defaults to providing 24 pixels on the top, left, and right
523    /// of the title. If the [`content`](Self::content) is not null, then no bottom padding
524    /// is provided (but see [`content_padding`](Self::content_padding)). If it _is_ null,
525    /// then an extra 20 pixels of bottom padding is added to separate the
526    /// [`title`](Self::title) from the [`actions`](Self::actions).
527    pub title_padding: Option<EdgeInsetsGeometry>,
528
529    /// Style for the text in the [`title`](Self::title) of this [`AlertDialog`].
530    ///
531    /// If null, [`DialogThemeData::title_text_style`] is used. If that's null,
532    /// defaults to `TextTheme::headline_small` of `ThemeData::text_theme` if
533    /// `ThemeData::use_material3` is true, `TextTheme::title_large` otherwise.
534    pub title_text_style: Option<TextStyle>,
535
536    /// The (optional) content of the dialog is displayed in the center of the
537    /// dialog in a lighter font.
538    ///
539    /// Typically this is a `SingleChildScrollView` that contains the dialog's
540    /// message. As noted in the [`AlertDialog`] documentation, it's important
541    /// to use a `SingleChildScrollView` if there's any risk that the content
542    /// will not fit, as the contents will otherwise overflow the dialog.
543    ///
544    /// The horizontal dimension of this widget is defined by the
545    /// [`IntrinsicWidth`] widget. As a result, the content cannot use
546    /// lazy-loading widgets such as `ListView`, `GridView`, or
547    /// `CustomScrollView` without being given a fixed width.
548    pub content: Option<WidgetRef>,
549
550    /// Padding around the content.
551    ///
552    /// If there is no content, no padding will be provided. Otherwise, padding of
553    /// 20 pixels is provided above the content to separate the content from the
554    /// title, and padding of 24 pixels is provided on the left, right, and bottom
555    /// to separate the content from the other edges of the dialog.
556    ///
557    /// If `ThemeData::use_material3` is true, the top padding separating the
558    /// content from the title defaults to 16 pixels instead of 20 pixels.
559    pub content_padding: Option<EdgeInsetsGeometry>,
560
561    /// Style for the text in the [`content`](Self::content) of this [`AlertDialog`].
562    ///
563    /// If null, [`DialogThemeData::content_text_style`] is used. If that's null,
564    /// defaults to `TextTheme::body_medium` of `ThemeData::text_theme` if
565    /// `ThemeData::use_material3` is true, `TextTheme::title_medium` otherwise.
566    pub content_text_style: Option<TextStyle>,
567
568    /// The (optional) set of actions that are displayed at the bottom of the
569    /// dialog with an [`OverflowBar`].
570    ///
571    /// Typically this is a list of `TextButton` widgets. It is recommended to
572    /// set the `Text::text_align` to `TextAlign::End` for the `Text` within the
573    /// `TextButton`, so that buttons whose labels wrap to an extra line align
574    /// with the overall [`OverflowBar`]'s alignment within the dialog.
575    ///
576    /// If the [`title`](Self::title) is not null but the [`content`](Self::content) _is_
577    /// null, then an extra 20 pixels of padding is added above the [`OverflowBar`] to
578    /// separate the [`title`](Self::title) from the [`actions`](Self::actions).
579    pub actions: Option<Vec<WidgetRef>>,
580
581    /// Padding around the set of [`actions`](Self::actions) at the bottom of the dialog.
582    ///
583    /// Typically used to provide padding to the button bar between the button bar
584    /// and the edges of the dialog.
585    ///
586    /// The [`button_padding`](Self::button_padding) may contribute to the padding on the
587    /// edges of [`actions`](Self::actions) as well.
588    ///
589    /// If there are no [`actions`](Self::actions), then no padding will be included.
590    pub actions_padding: Option<EdgeInsetsGeometry>,
591
592    /// Defines the horizontal layout of the [`actions`](Self::actions) according to the
593    /// same rules as for `Row::main_axis_alignment`.
594    ///
595    /// This parameter is passed along to the dialog's [`OverflowBar`].
596    ///
597    /// If this parameter is null (the default) then [`MainAxisAlignment::End`]
598    /// is used.
599    pub actions_alignment: Option<MainAxisAlignment>,
600
601    /// The horizontal alignment of [`actions`](Self::actions) within the vertical
602    /// "overflow" layout.
603    ///
604    /// If the dialog's [`actions`](Self::actions) do not fit into a single row, then they
605    /// are arranged in a column. This parameter controls the horizontal
606    /// alignment of widgets in the case of an overflow.
607    ///
608    /// If this parameter is null (the default) then [`OverflowBarAlignment::End`]
609    /// is used.
610    pub actions_overflow_alignment: Option<OverflowBarAlignment>,
611
612    /// The vertical direction of [`actions`](Self::actions) if the children overflow
613    /// horizontally.
614    ///
615    /// If the dialog's [`actions`](Self::actions) do not fit into a single row, then they
616    /// are arranged in a column. The first action is at the top of the
617    /// column if this property is set to [`VerticalDirection::Down`], since it
618    /// "starts" at the top and "ends" at the bottom. On the other hand,
619    /// the first action will be at the bottom of the column if this
620    /// property is set to [`VerticalDirection::Up`], since it "starts" at the
621    /// bottom and "ends" at the top.
622    pub actions_overflow_direction: Option<VerticalDirection>,
623
624    /// The spacing between [`actions`](Self::actions) when the [`OverflowBar`] switches to
625    /// a column layout because the actions don't fit horizontally.
626    ///
627    /// If the widgets in [`actions`](Self::actions) do not fit into a single row, they are
628    /// arranged into a column. This parameter provides additional vertical space
629    /// between buttons when it does overflow.
630    pub actions_overflow_button_spacing: Option<f64>,
631
632    /// The padding that surrounds each button in [`actions`](Self::actions).
633    ///
634    /// This is different from [`actions_padding`](Self::actions_padding), which defines
635    /// the padding between the entire button bar and the edges of the dialog.
636    ///
637    /// If this property is null, then it will default to
638    /// 8.0 logical pixels on the left and right.
639    pub button_padding: Option<EdgeInsetsGeometry>,
640
641    /// See [`Dialog::background_color`].
642    pub background_color: Option<Color>,
643
644    /// See [`Dialog::elevation`].
645    pub elevation: Option<f64>,
646
647    /// See [`Dialog::shadow_color`].
648    pub shadow_color: Option<Color>,
649
650    /// See [`Dialog::surface_tint_color`].
651    pub surface_tint_color: Option<Color>,
652
653    /// The semantic label of the dialog used by accessibility frameworks to
654    /// announce screen transitions when the dialog is opened and closed.
655    ///
656    /// In iOS, if this label is not provided, a semantic label will be inferred
657    /// from the [`title`](Self::title) if it is not null.
658    ///
659    /// In Android, if this label is not provided, the dialog will use the
660    /// `MaterialLocalizations::alert_dialog_label` as its label.
661    pub semantic_label: Option<String>,
662
663    /// See [`Dialog::inset_padding`].
664    pub inset_padding: Option<EdgeInsets>,
665
666    /// See [`Dialog::clip_behavior`].
667    pub clip_behavior: Option<Clip>,
668
669    /// See [`Dialog::shape`].
670    pub shape: Option<ShapeBorderRef>,
671
672    /// See [`Dialog::alignment`].
673    pub alignment: Option<AlignmentGeometry>,
674
675    /// See [`Dialog::constraints`].
676    pub constraints: Option<BoxConstraints>,
677
678    /// Determines whether the [`title`](Self::title) and [`content`](Self::content) widgets
679    /// are wrapped in a scrollable.
680    ///
681    /// This configuration is used when the [`title`](Self::title) and
682    /// [`content`](Self::content) are expected to overflow. Both [`title`](Self::title) and
683    /// [`content`](Self::content) are wrapped in a scroll view, allowing all overflowed
684    /// content to be visible while still showing the button bar.
685    pub scrollable: bool,
686
687    /// `Some` for Dart's `AlertDialog.adaptive`, holding the fields of its
688    /// `_AdaptiveAlertDialog`.
689    adaptive: Option<AdaptiveAlertDialog>,
690}
691
692impl AlertDialog {
693    /// Creates an alert dialog.
694    ///
695    /// Typically used in conjunction with [`ShowDialog`].
696    ///
697    /// The [`title_padding`](Self::title_padding) and
698    /// [`content_padding`](Self::content_padding) default to null, which implies a default
699    /// that depends on the values of the other properties. See the documentation of
700    /// [`title_padding`](Self::title_padding) and [`content_padding`](Self::content_padding)
701    /// on how the padding is implemented.
702    pub fn new() -> AlertDialog {
703        AlertDialog {
704            key: None,
705            icon: None,
706            icon_color: None,
707            icon_padding: None,
708            title: None,
709            title_padding: None,
710            title_text_style: None,
711            content: None,
712            content_padding: None,
713            content_text_style: None,
714            actions: None,
715            actions_padding: None,
716            actions_alignment: None,
717            actions_overflow_alignment: None,
718            actions_overflow_direction: None,
719            actions_overflow_button_spacing: None,
720            button_padding: None,
721            background_color: None,
722            elevation: None,
723            shadow_color: None,
724            surface_tint_color: None,
725            semantic_label: None,
726            inset_padding: None,
727            clip_behavior: None,
728            shape: None,
729            alignment: None,
730            constraints: None,
731            scrollable: false,
732            adaptive: None,
733        }
734    }
735
736    /// Creates an adaptive [`AlertDialog`] based on whether the target platform is
737    /// iOS or macOS, following Material design's
738    /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
739    ///
740    /// On iOS and macOS, this constructor creates a `CupertinoAlertDialog`. On other
741    /// platforms, this creates a Material design [`AlertDialog`].
742    ///
743    /// Typically passed as a child of [`ShowAdaptiveDialog`], which will display
744    /// the alert differently based on platform.
745    ///
746    /// If a `CupertinoAlertDialog` is created only these parameters are used:
747    /// [`title`](Self::title), [`content`](Self::content), [`actions`](Self::actions),
748    /// `scroll_controller`, `action_scroll_controller`, `inset_animation_duration`, and
749    /// `inset_animation_curve`. If a material [`AlertDialog`] is created,
750    /// `scroll_controller`, `action_scroll_controller`, `inset_animation_duration`, and
751    /// `inset_animation_curve` are ignored.
752    ///
753    /// The target platform is based on the current `Theme`: `ThemeData::platform`.
754    pub fn adaptive() -> AlertDialog {
755        let mut dialog = AlertDialog::new();
756        dialog.adaptive = Some(AdaptiveAlertDialog {
757            scroll_controller: None,
758            action_scroll_controller: None,
759            inset_animation_duration: Duration::from_millis(100),
760            inset_animation_curve: Curves::decelerate(),
761        });
762        dialog
763    }
764
765    /// Dart `AlertDialog(key:)`.
766    pub fn key(mut self, key: KeyRef) -> AlertDialog {
767        self.key = Some(key);
768        self
769    }
770
771    /// Dart `AlertDialog(icon:)`.
772    #[cfg_attr(debug_assertions, track_caller)]
773    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> AlertDialog {
774        self.icon = Some(icon.into_widget());
775        self
776    }
777
778    /// Dart `AlertDialog(iconPadding:)`.
779    pub fn icon_padding(mut self, icon_padding: impl Into<EdgeInsetsGeometry>) -> AlertDialog {
780        let icon_padding = icon_padding.into();
781        self.icon_padding = Some(icon_padding);
782        self
783    }
784
785    /// Dart `AlertDialog(iconColor:)`.
786    pub fn icon_color(mut self, icon_color: Color) -> AlertDialog {
787        self.icon_color = Some(icon_color);
788        self
789    }
790
791    /// Dart `AlertDialog(title:)`.
792    #[cfg_attr(debug_assertions, track_caller)]
793    pub fn title<K>(mut self, title: impl IntoWidget<K>) -> AlertDialog {
794        self.title = Some(title.into_widget());
795        self
796    }
797
798    /// Dart `AlertDialog(titlePadding:)`.
799    pub fn title_padding(mut self, title_padding: impl Into<EdgeInsetsGeometry>) -> AlertDialog {
800        let title_padding = title_padding.into();
801        self.title_padding = Some(title_padding);
802        self
803    }
804
805    /// Dart `AlertDialog(titleTextStyle:)`.
806    pub fn title_text_style(mut self, title_text_style: TextStyle) -> AlertDialog {
807        self.title_text_style = Some(title_text_style);
808        self
809    }
810
811    /// Dart `AlertDialog(content:)`.
812    #[cfg_attr(debug_assertions, track_caller)]
813    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> AlertDialog {
814        self.content = Some(content.into_widget());
815        self
816    }
817
818    /// Dart `AlertDialog(contentPadding:)`.
819    pub fn content_padding(
820        mut self,
821        content_padding: impl Into<EdgeInsetsGeometry>,
822    ) -> AlertDialog {
823        let content_padding = content_padding.into();
824        self.content_padding = Some(content_padding);
825        self
826    }
827
828    /// Dart `AlertDialog(contentTextStyle:)`.
829    pub fn content_text_style(mut self, content_text_style: TextStyle) -> AlertDialog {
830        self.content_text_style = Some(content_text_style);
831        self
832    }
833
834    /// Dart `AlertDialog(actions:)`.
835    pub fn actions(mut self, actions: impl IntoIterator<Item = WidgetRef>) -> AlertDialog {
836        self.actions = Some(actions.into_iter().collect());
837        self
838    }
839
840    /// Dart `AlertDialog(actionsPadding:)`.
841    pub fn actions_padding(
842        mut self,
843        actions_padding: impl Into<EdgeInsetsGeometry>,
844    ) -> AlertDialog {
845        let actions_padding = actions_padding.into();
846        self.actions_padding = Some(actions_padding);
847        self
848    }
849
850    /// Dart `AlertDialog(actionsAlignment:)`.
851    pub fn actions_alignment(mut self, actions_alignment: MainAxisAlignment) -> AlertDialog {
852        self.actions_alignment = Some(actions_alignment);
853        self
854    }
855
856    /// Dart `AlertDialog(actionsOverflowAlignment:)`.
857    pub fn actions_overflow_alignment(
858        mut self,
859        actions_overflow_alignment: OverflowBarAlignment,
860    ) -> AlertDialog {
861        self.actions_overflow_alignment = Some(actions_overflow_alignment);
862        self
863    }
864
865    /// Dart `AlertDialog(actionsOverflowDirection:)`.
866    pub fn actions_overflow_direction(
867        mut self,
868        actions_overflow_direction: VerticalDirection,
869    ) -> AlertDialog {
870        self.actions_overflow_direction = Some(actions_overflow_direction);
871        self
872    }
873
874    /// Dart `AlertDialog(actionsOverflowButtonSpacing:)`.
875    pub fn actions_overflow_button_spacing(
876        mut self,
877        actions_overflow_button_spacing: f64,
878    ) -> AlertDialog {
879        self.actions_overflow_button_spacing = Some(actions_overflow_button_spacing);
880        self
881    }
882
883    /// Dart `AlertDialog(buttonPadding:)`.
884    pub fn button_padding(mut self, button_padding: impl Into<EdgeInsetsGeometry>) -> AlertDialog {
885        let button_padding = button_padding.into();
886        self.button_padding = Some(button_padding);
887        self
888    }
889
890    /// Dart `AlertDialog(backgroundColor:)`.
891    pub fn background_color(mut self, background_color: Color) -> AlertDialog {
892        self.background_color = Some(background_color);
893        self
894    }
895
896    /// Dart `AlertDialog(elevation:)`.
897    pub fn elevation(mut self, elevation: f64) -> AlertDialog {
898        self.elevation = Some(elevation);
899        self
900    }
901
902    /// Dart `AlertDialog(shadowColor:)`.
903    pub fn shadow_color(mut self, shadow_color: Color) -> AlertDialog {
904        self.shadow_color = Some(shadow_color);
905        self
906    }
907
908    /// Dart `AlertDialog(surfaceTintColor:)`.
909    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> AlertDialog {
910        self.surface_tint_color = Some(surface_tint_color);
911        self
912    }
913
914    /// Dart `AlertDialog(semanticLabel:)`.
915    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> AlertDialog {
916        self.semantic_label = Some(semantic_label.into());
917        self
918    }
919
920    /// Dart `AlertDialog(insetPadding:)`.
921    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> AlertDialog {
922        self.inset_padding = Some(inset_padding);
923        self
924    }
925
926    /// Dart `AlertDialog(clipBehavior:)`.
927    pub fn clip_behavior(mut self, clip_behavior: Clip) -> AlertDialog {
928        self.clip_behavior = Some(clip_behavior);
929        self
930    }
931
932    /// Dart `AlertDialog(shape:)`.
933    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> AlertDialog {
934        self.shape = Some(shape.into());
935        self
936    }
937
938    /// Dart `AlertDialog(alignment:)`.
939    pub fn alignment(mut self, alignment: AlignmentGeometry) -> AlertDialog {
940        self.alignment = Some(alignment);
941        self
942    }
943
944    /// Dart `AlertDialog(constraints:)`.
945    pub fn constraints(mut self, constraints: BoxConstraints) -> AlertDialog {
946        self.constraints = Some(constraints);
947        self
948    }
949
950    /// Dart `AlertDialog(scrollable:)`.
951    pub fn scrollable(mut self, scrollable: bool) -> AlertDialog {
952        self.scrollable = scrollable;
953        self
954    }
955
956    /// Dart `AlertDialog.adaptive(scrollController:)`; a dialog made by
957    /// [`new`](Self::new) ignores it.
958    pub fn scroll_controller(mut self, scroll_controller: ScrollControllerRef) -> AlertDialog {
959        if let Some(adaptive) = &mut self.adaptive {
960            adaptive.scroll_controller = Some(scroll_controller);
961        }
962        self
963    }
964
965    /// Dart `AlertDialog.adaptive(actionScrollController:)`; a dialog made by
966    /// [`new`](Self::new) ignores it.
967    pub fn action_scroll_controller(
968        mut self,
969        action_scroll_controller: ScrollControllerRef,
970    ) -> AlertDialog {
971        if let Some(adaptive) = &mut self.adaptive {
972            adaptive.action_scroll_controller = Some(action_scroll_controller);
973        }
974        self
975    }
976
977    /// Dart `AlertDialog.adaptive(insetAnimationDuration:)`; a dialog made by
978    /// [`new`](Self::new) ignores it.
979    pub fn inset_animation_duration(mut self, inset_animation_duration: Duration) -> AlertDialog {
980        if let Some(adaptive) = &mut self.adaptive {
981            adaptive.inset_animation_duration = inset_animation_duration;
982        }
983        self
984    }
985
986    /// Dart `AlertDialog.adaptive(insetAnimationCurve:)`; a dialog made by
987    /// [`new`](Self::new) ignores it.
988    pub fn inset_animation_curve(mut self, inset_animation_curve: Rc<dyn Curve>) -> AlertDialog {
989        if let Some(adaptive) = &mut self.adaptive {
990            adaptive.inset_animation_curve = inset_animation_curve;
991        }
992        self
993    }
994
995    /// Dart's `AlertDialog.build`, which `_AdaptiveAlertDialog.build` reaches through
996    /// `super.build` on the platforms that keep the Material dialog.
997    fn build_material(&self, app: &mut App, context: BuildContext) -> WidgetRef {
998        debug_assert!(debug_check_has_material_localizations(app, context));
999        let theme = Theme::of(app, context);
1000
1001        let dialog_theme = DialogTheme::of(app, context);
1002        let defaults: Box<dyn DialogThemeDataGetters> = if theme.use_material3 {
1003            Box::new(DialogDefaultsM3::new(context))
1004        } else {
1005            Box::new(DialogDefaultsM2::new(context))
1006        };
1007
1008        let target_platform = app.platform().target_platform();
1009        let label = match target_platform {
1010            TargetPlatform::IOS | TargetPlatform::MacOS => self.semantic_label.clone(),
1011            TargetPlatform::Android
1012            | TargetPlatform::Fuchsia
1013            | TargetPlatform::Linux
1014            | TargetPlatform::Windows => Some(self.semantic_label.clone().unwrap_or_else(|| {
1015                <dyn MaterialLocalizations>::of(app, context).alert_dialog_label()
1016            })),
1017        };
1018
1019        // The paddingScaleFactor is used to adjust the padding of Dialog's
1020        // children.
1021        let font_size_to_scale = 14.0;
1022        let effective_text_scale =
1023            MediaQuery::text_scaler_of(app, context).scale(font_size_to_scale) / font_size_to_scale;
1024        let padding_scale_factor = scale_padding(effective_text_scale);
1025        let text_direction = Directionality::maybe_of(app, context);
1026
1027        let mut icon_widget = None;
1028        let mut title_widget = None;
1029        let mut content_widget = None;
1030        let mut actions_widget = None;
1031
1032        if let Some(icon) = &self.icon {
1033            let below_is_title = self.title.is_some();
1034            let below_is_content = !below_is_title && self.content.is_some();
1035            let default_icon_padding = EdgeInsets::only(
1036                24.0,
1037                24.0,
1038                24.0,
1039                if below_is_title {
1040                    16.0
1041                } else if below_is_content {
1042                    0.0
1043                } else {
1044                    24.0
1045                },
1046            );
1047            let effective_icon_padding = self
1048                .icon_padding
1049                .map(|padding| padding.resolve(text_direction))
1050                .unwrap_or(default_icon_padding);
1051            let mut icon_theme = IconThemeData::new();
1052            if let Some(color) = self
1053                .icon_color
1054                .or(dialog_theme.icon_color)
1055                .or_else(|| defaults.icon_color(app))
1056            {
1057                icon_theme = icon_theme.color(color);
1058            }
1059            icon_widget = Some(
1060                Padding::new(EdgeInsets::only(
1061                    effective_icon_padding.left * padding_scale_factor,
1062                    effective_icon_padding.top * padding_scale_factor,
1063                    effective_icon_padding.right * padding_scale_factor,
1064                    effective_icon_padding.bottom,
1065                ))
1066                .child(IconTheme::new(icon_theme, icon.clone()))
1067                .into_widget(),
1068            );
1069        }
1070
1071        if let Some(title) = &self.title {
1072            let default_title_padding = EdgeInsets::only(
1073                24.0,
1074                if self.icon.is_none() { 24.0 } else { 0.0 },
1075                24.0,
1076                if self.content.is_none() { 20.0 } else { 0.0 },
1077            );
1078            let effective_title_padding = self
1079                .title_padding
1080                .map(|padding| padding.resolve(text_direction))
1081                .unwrap_or(default_title_padding);
1082            title_widget = Some(
1083                Padding::new(EdgeInsets::only(
1084                    effective_title_padding.left * padding_scale_factor,
1085                    if self.icon.is_none() {
1086                        effective_title_padding.top * padding_scale_factor
1087                    } else {
1088                        effective_title_padding.top
1089                    },
1090                    effective_title_padding.right * padding_scale_factor,
1091                    effective_title_padding.bottom,
1092                ))
1093                .child(
1094                    DefaultTextStyle::new(
1095                        self.title_text_style
1096                            .clone()
1097                            .or(dialog_theme.title_text_style.clone())
1098                            .or_else(|| defaults.title_text_style(app))
1099                            .expect("the defaults give a title text style"),
1100                        Semantics::new()
1101                            // For iOS platform, the focus always lands on the title.
1102                            // Set nameRoute to false to avoid title being announce twice.
1103                            .names_route(label.is_none() && target_platform != TargetPlatform::IOS)
1104                            .container(true)
1105                            .child(title.clone()),
1106                    )
1107                    .text_align(if self.icon.is_none() {
1108                        TextAlign::Start
1109                    } else {
1110                        TextAlign::Center
1111                    }),
1112                )
1113                .into_widget(),
1114            );
1115        }
1116
1117        if let Some(content) = &self.content {
1118            let default_content_padding = EdgeInsets::only(
1119                24.0,
1120                if theme.use_material3 { 16.0 } else { 20.0 },
1121                24.0,
1122                24.0,
1123            );
1124            let effective_content_padding = self
1125                .content_padding
1126                .map(|padding| padding.resolve(text_direction))
1127                .unwrap_or(default_content_padding);
1128            content_widget = Some(
1129                Padding::new(EdgeInsets::only(
1130                    effective_content_padding.left * padding_scale_factor,
1131                    if self.title.is_none() && self.icon.is_none() {
1132                        effective_content_padding.top * padding_scale_factor
1133                    } else {
1134                        effective_content_padding.top
1135                    },
1136                    effective_content_padding.right * padding_scale_factor,
1137                    effective_content_padding.bottom,
1138                ))
1139                .child(DefaultTextStyle::new(
1140                    self.content_text_style
1141                        .clone()
1142                        .or(dialog_theme.content_text_style.clone())
1143                        .or_else(|| defaults.content_text_style(app))
1144                        .expect("the defaults give a content text style"),
1145                    Semantics::new()
1146                        .container(true)
1147                        .explicit_child_nodes(true)
1148                        .child(content.clone()),
1149                ))
1150                .into_widget(),
1151            );
1152        }
1153
1154        if let Some(actions) = &self.actions {
1155            let spacing = self
1156                .button_padding
1157                .map_or(16.0, |button_padding| button_padding.horizontal())
1158                / 2.0;
1159            let actions_padding = self
1160                .actions_padding
1161                .or(dialog_theme.actions_padding)
1162                .unwrap_or_else(|| {
1163                    let default_padding = defaults
1164                        .actions_padding(app)
1165                        .expect("the defaults give an actions padding");
1166                    if theme.use_material3 {
1167                        default_padding
1168                    } else {
1169                        default_padding.add(EdgeInsetsGeometry::all(spacing))
1170                    }
1171                });
1172            actions_widget = Some(
1173                Padding::new(actions_padding)
1174                    .child(
1175                        OverflowBar::new()
1176                            .alignment(self.actions_alignment.unwrap_or(MainAxisAlignment::End))
1177                            .spacing(spacing)
1178                            .overflow_alignment(
1179                                self.actions_overflow_alignment
1180                                    .unwrap_or(OverflowBarAlignment::End),
1181                            )
1182                            .overflow_direction(
1183                                self.actions_overflow_direction
1184                                    .unwrap_or(VerticalDirection::Down),
1185                            )
1186                            .overflow_spacing(self.actions_overflow_button_spacing.unwrap_or(0.0))
1187                            .children(actions.clone()),
1188                    )
1189                    .into_widget(),
1190            );
1191        }
1192
1193        let column_children: Vec<WidgetRef> = if self.scrollable {
1194            let mut children = Vec::new();
1195            if self.title.is_some() || self.content.is_some() {
1196                children.push(
1197                    Flexible::new(
1198                        SingleChildScrollView::new().child(
1199                            Column::new()
1200                                .main_axis_size(MainAxisSize::Min)
1201                                .cross_axis_alignment(CrossAxisAlignment::Stretch)
1202                                .children(
1203                                    [icon_widget, title_widget, content_widget]
1204                                        .into_iter()
1205                                        .flatten(),
1206                                ),
1207                        ),
1208                    )
1209                    .into_widget(),
1210                );
1211            }
1212            children.extend(actions_widget);
1213            children
1214        } else {
1215            [
1216                icon_widget,
1217                title_widget,
1218                content_widget.map(|content_widget| Flexible::new(content_widget).into_widget()),
1219                actions_widget,
1220            ]
1221            .into_iter()
1222            .flatten()
1223            .collect()
1224        };
1225
1226        let mut dialog_child = IntrinsicWidth::new()
1227            .child(
1228                Column::new()
1229                    .main_axis_size(MainAxisSize::Min)
1230                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
1231                    .children(column_children),
1232            )
1233            .into_widget();
1234
1235        if let Some(label) = label {
1236            dialog_child = Semantics::new()
1237                .scopes_route(true)
1238                .explicit_child_nodes(true)
1239                .names_route(true)
1240                .label(label)
1241                .child(dialog_child)
1242                .into_widget();
1243        }
1244
1245        let mut dialog = Dialog::new().semantics_role(SemanticsRole::AlertDialog);
1246        dialog.background_color = self.background_color;
1247        dialog.elevation = self.elevation;
1248        dialog.shadow_color = self.shadow_color;
1249        dialog.surface_tint_color = self.surface_tint_color;
1250        dialog.inset_padding = self.inset_padding;
1251        dialog.clip_behavior = self.clip_behavior;
1252        dialog.shape = self.shape.clone();
1253        dialog.alignment = self.alignment;
1254        dialog.constraints = self.constraints;
1255        dialog.child = Some(dialog_child);
1256        dialog.into_widget()
1257    }
1258
1259    /// Dart's `_AdaptiveAlertDialog.build`.
1260    fn build_adaptive(
1261        &self,
1262        app: &mut App,
1263        context: BuildContext,
1264        adaptive: &AdaptiveAlertDialog,
1265    ) -> WidgetRef {
1266        let theme = Theme::of(app, context);
1267        match theme.platform {
1268            TargetPlatform::Android
1269            | TargetPlatform::Fuchsia
1270            | TargetPlatform::Linux
1271            | TargetPlatform::Windows => {}
1272            TargetPlatform::IOS | TargetPlatform::MacOS => {
1273                let mut dialog = CupertinoAlertDialog::new()
1274                    .actions(self.actions.clone().unwrap_or_default())
1275                    .inset_animation_duration(adaptive.inset_animation_duration)
1276                    .inset_animation_curve(Rc::clone(&adaptive.inset_animation_curve));
1277                dialog.title = self.title.clone();
1278                dialog.content = self.content.clone();
1279                dialog.scroll_controller = adaptive.scroll_controller.clone();
1280                dialog.action_scroll_controller = adaptive.action_scroll_controller.clone();
1281                return dialog.into_widget();
1282            }
1283        }
1284        self.build_material(app, context)
1285    }
1286}
1287
1288impl Default for AlertDialog {
1289    fn default() -> AlertDialog {
1290        AlertDialog::new()
1291    }
1292}
1293
1294impl StatelessWidget for AlertDialog {
1295    fn key(&self) -> Option<&KeyRef> {
1296        self.key.as_ref()
1297    }
1298
1299    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1300        match &self.adaptive {
1301            Some(adaptive) => self.build_adaptive(app, context, adaptive),
1302            None => self.build_material(app, context),
1303        }
1304    }
1305}
1306
1307/// An option used in a [`SimpleDialog`].
1308///
1309/// A simple dialog offers the user a choice between several options. This
1310/// widget is commonly used to represent each of the options. If the user
1311/// selects this option, the widget will call the [`on_pressed`](Self::on_pressed)
1312/// callback, which typically uses [`Navigator::pop`] to close the dialog.
1313///
1314/// The padding on a [`SimpleDialogOption`] is configured to combine with the
1315/// default [`SimpleDialog::content_padding`] so that each option ends up 8 pixels
1316/// from the other vertically, with 20 pixels of spacing between the dialog's
1317/// title and the first option, and 24 pixels of spacing between the last option
1318/// and the bottom of the dialog.
1319///
1320/// See also:
1321///
1322///  * [`SimpleDialog`], for a dialog in which to use this widget.
1323///  * [`ShowDialog`], which actually displays the dialog and returns its result.
1324///  * `TextButton`, which are commonly used as actions in other kinds of
1325///    dialogs, such as [`AlertDialog`]s.
1326///  * <https://material.io/design/components/dialogs.html#simple-dialog>
1327#[derive(Debug, Default)]
1328pub struct SimpleDialogOption {
1329    pub key: Option<KeyRef>,
1330
1331    /// The callback that is called when this option is selected.
1332    ///
1333    /// If this is set to null, the option cannot be selected.
1334    ///
1335    /// When used in a [`SimpleDialog`], this will typically call [`Navigator::pop`]
1336    /// with a value for [`ShowDialog`] to complete its future with.
1337    pub on_pressed: Option<waft_foundation::Listener>,
1338
1339    /// The widget below this widget in the tree.
1340    ///
1341    /// Typically a `Text` widget.
1342    pub child: Option<WidgetRef>,
1343
1344    /// The amount of space to surround the [`child`](Self::child) with.
1345    ///
1346    /// Defaults to EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0).
1347    pub padding: Option<EdgeInsets>,
1348}
1349
1350impl SimpleDialogOption {
1351    /// Creates an option for a [`SimpleDialog`].
1352    pub fn new() -> SimpleDialogOption {
1353        SimpleDialogOption::default()
1354    }
1355
1356    /// Dart `SimpleDialogOption(key:)`.
1357    pub fn key(mut self, key: KeyRef) -> SimpleDialogOption {
1358        self.key = Some(key);
1359        self
1360    }
1361
1362    /// Dart `SimpleDialogOption(onPressed:)`.
1363    pub fn on_pressed(mut self, on_pressed: waft_foundation::Listener) -> SimpleDialogOption {
1364        self.on_pressed = Some(on_pressed);
1365        self
1366    }
1367
1368    /// Dart `SimpleDialogOption(padding:)`.
1369    pub fn padding(mut self, padding: EdgeInsets) -> SimpleDialogOption {
1370        self.padding = Some(padding);
1371        self
1372    }
1373
1374    /// Dart `SimpleDialogOption(child:)`.
1375    #[cfg_attr(debug_assertions, track_caller)]
1376    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SimpleDialogOption {
1377        self.child = Some(child.into_widget());
1378        self
1379    }
1380}
1381
1382impl StatelessWidget for SimpleDialogOption {
1383    fn key(&self) -> Option<&KeyRef> {
1384        self.key.as_ref()
1385    }
1386
1387    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1388        let mut padding = Padding::new(self.padding.unwrap_or(EdgeInsets::symmetric(8.0, 24.0)));
1389        padding.child = self.child.clone();
1390        let mut ink_well = InkWell::new().child(padding);
1391        ink_well.ink_response.on_tap = self.on_pressed.clone();
1392        ink_well.into_widget()
1393    }
1394}
1395
1396/// A simple Material Design dialog.
1397///
1398/// A simple dialog offers the user a choice between several options. A simple
1399/// dialog has an optional title that is displayed above the choices.
1400///
1401/// Choices are normally represented using [`SimpleDialogOption`] widgets. If
1402/// other widgets are used, see [`content_padding`](Self::content_padding) for notes
1403/// regarding the conventions for obtaining the spacing expected by Material
1404/// Design.
1405///
1406/// For dialogs that inform the user about a situation, consider using an
1407/// [`AlertDialog`].
1408///
1409/// Typically passed as the child widget to [`ShowDialog`], which displays the
1410/// dialog.
1411///
1412/// See also:
1413///
1414///  * [`SimpleDialogOption`], which are options used in this type of dialog.
1415///  * [`AlertDialog`], for dialogs that have a row of buttons below the body.
1416///  * [`Dialog`], on which [`SimpleDialog`] and [`AlertDialog`] are based.
1417///  * [`ShowDialog`], which actually displays the dialog and returns its result.
1418///  * <https://material.io/design/components/dialogs.html#simple-dialog>
1419#[derive(Debug)]
1420pub struct SimpleDialog {
1421    pub key: Option<KeyRef>,
1422
1423    /// The (optional) title of the dialog is displayed in a large font at the top
1424    /// of the dialog.
1425    ///
1426    /// Typically a `Text` widget.
1427    pub title: Option<WidgetRef>,
1428
1429    /// Padding around the title.
1430    ///
1431    /// If there is no title, no padding will be provided.
1432    ///
1433    /// By default, this provides the recommend Material Design padding of 24
1434    /// pixels around the left, top, and right edges of the title.
1435    ///
1436    /// See [`content_padding`](Self::content_padding) for the conventions regarding
1437    /// padding between the [`title`](Self::title) and the [`children`](Self::children).
1438    pub title_padding: EdgeInsetsGeometry,
1439
1440    /// Style for the text in the [`title`](Self::title) of this [`SimpleDialog`].
1441    ///
1442    /// If null, [`DialogThemeData::title_text_style`] is used. If that's null,
1443    /// defaults to `TextTheme::title_large` of `ThemeData::text_theme`.
1444    pub title_text_style: Option<TextStyle>,
1445
1446    /// The (optional) content of the dialog is displayed in a
1447    /// `SingleChildScrollView` underneath the title.
1448    ///
1449    /// Typically a list of [`SimpleDialogOption`]s.
1450    pub children: Option<Vec<WidgetRef>>,
1451
1452    /// Padding around the content.
1453    ///
1454    /// By default, this is 12 pixels on the top and 16 pixels on the bottom. This
1455    /// is intended to be combined with children that have 24 pixels of padding on
1456    /// the left and right, and 8 pixels of padding on the top and bottom, so that
1457    /// the content ends up being indented 20 pixels from the title, 24 pixels from
1458    /// the bottom, and 24 pixels from the sides.
1459    ///
1460    /// The [`SimpleDialogOption`] widget uses such padding.
1461    ///
1462    /// If there is no [`title`](Self::title), the [`content_padding`](Self::content_padding)
1463    /// should be adjusted so that the top padding ends up being 24 pixels.
1464    pub content_padding: EdgeInsetsGeometry,
1465
1466    /// See [`Dialog::background_color`].
1467    pub background_color: Option<Color>,
1468
1469    /// See [`Dialog::elevation`].
1470    pub elevation: Option<f64>,
1471
1472    /// See [`Dialog::shadow_color`].
1473    pub shadow_color: Option<Color>,
1474
1475    /// See [`Dialog::surface_tint_color`].
1476    pub surface_tint_color: Option<Color>,
1477
1478    /// Style for the text in the [`children`](Self::children) of this [`SimpleDialog`].
1479    ///
1480    /// If null, [`DialogThemeData::content_text_style`] is used. If that's null,
1481    /// defaults to `TextTheme::title_medium` of `ThemeData::text_theme`.
1482    pub content_text_style: Option<TextStyle>,
1483
1484    /// The semantic label of the dialog used by accessibility frameworks to
1485    /// announce screen transitions when the dialog is opened and closed.
1486    ///
1487    /// If this label is not provided, a semantic label will be inferred from the
1488    /// [`title`](Self::title) if it is not null. If there is no title, the label will be
1489    /// taken from `MaterialLocalizations::dialog_label`.
1490    pub semantic_label: Option<String>,
1491
1492    /// See [`Dialog::inset_padding`].
1493    pub inset_padding: Option<EdgeInsets>,
1494
1495    /// See [`Dialog::clip_behavior`].
1496    pub clip_behavior: Option<Clip>,
1497
1498    /// See [`Dialog::shape`].
1499    pub shape: Option<ShapeBorderRef>,
1500
1501    /// See [`Dialog::alignment`].
1502    pub alignment: Option<AlignmentGeometry>,
1503
1504    /// See [`Dialog::constraints`].
1505    pub constraints: Option<BoxConstraints>,
1506}
1507
1508impl SimpleDialog {
1509    /// Creates a simple dialog.
1510    ///
1511    /// Typically used in conjunction with [`ShowDialog`].
1512    pub fn new() -> SimpleDialog {
1513        SimpleDialog {
1514            key: None,
1515            title: None,
1516            title_padding: EdgeInsetsGeometry::from_ltrb(24.0, 24.0, 24.0, 0.0),
1517            title_text_style: None,
1518            children: None,
1519            content_padding: EdgeInsetsGeometry::from_ltrb(0.0, 12.0, 0.0, 16.0),
1520            content_text_style: None,
1521            background_color: None,
1522            elevation: None,
1523            shadow_color: None,
1524            surface_tint_color: None,
1525            semantic_label: None,
1526            inset_padding: None,
1527            clip_behavior: None,
1528            shape: None,
1529            alignment: None,
1530            constraints: None,
1531        }
1532    }
1533
1534    /// Dart `SimpleDialog(key:)`.
1535    pub fn key(mut self, key: KeyRef) -> SimpleDialog {
1536        self.key = Some(key);
1537        self
1538    }
1539
1540    /// Dart `SimpleDialog(title:)`.
1541    #[cfg_attr(debug_assertions, track_caller)]
1542    pub fn title<K>(mut self, title: impl IntoWidget<K>) -> SimpleDialog {
1543        self.title = Some(title.into_widget());
1544        self
1545    }
1546
1547    /// Dart `SimpleDialog(titlePadding:)`.
1548    pub fn title_padding(mut self, title_padding: impl Into<EdgeInsetsGeometry>) -> SimpleDialog {
1549        let title_padding = title_padding.into();
1550        self.title_padding = title_padding;
1551        self
1552    }
1553
1554    /// Dart `SimpleDialog(titleTextStyle:)`.
1555    pub fn title_text_style(mut self, title_text_style: TextStyle) -> SimpleDialog {
1556        self.title_text_style = Some(title_text_style);
1557        self
1558    }
1559
1560    /// Dart `SimpleDialog(children:)`.
1561    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> SimpleDialog {
1562        self.children = Some(children.into_iter().collect());
1563        self
1564    }
1565
1566    /// Dart `SimpleDialog(contentPadding:)`.
1567    pub fn content_padding(
1568        mut self,
1569        content_padding: impl Into<EdgeInsetsGeometry>,
1570    ) -> SimpleDialog {
1571        let content_padding = content_padding.into();
1572        self.content_padding = content_padding;
1573        self
1574    }
1575
1576    /// Dart `SimpleDialog(contentTextStyle:)`.
1577    pub fn content_text_style(mut self, content_text_style: TextStyle) -> SimpleDialog {
1578        self.content_text_style = Some(content_text_style);
1579        self
1580    }
1581
1582    /// Dart `SimpleDialog(backgroundColor:)`.
1583    pub fn background_color(mut self, background_color: Color) -> SimpleDialog {
1584        self.background_color = Some(background_color);
1585        self
1586    }
1587
1588    /// Dart `SimpleDialog(elevation:)`.
1589    pub fn elevation(mut self, elevation: f64) -> SimpleDialog {
1590        self.elevation = Some(elevation);
1591        self
1592    }
1593
1594    /// Dart `SimpleDialog(shadowColor:)`.
1595    pub fn shadow_color(mut self, shadow_color: Color) -> SimpleDialog {
1596        self.shadow_color = Some(shadow_color);
1597        self
1598    }
1599
1600    /// Dart `SimpleDialog(surfaceTintColor:)`.
1601    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> SimpleDialog {
1602        self.surface_tint_color = Some(surface_tint_color);
1603        self
1604    }
1605
1606    /// Dart `SimpleDialog(semanticLabel:)`.
1607    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> SimpleDialog {
1608        self.semantic_label = Some(semantic_label.into());
1609        self
1610    }
1611
1612    /// Dart `SimpleDialog(insetPadding:)`.
1613    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> SimpleDialog {
1614        self.inset_padding = Some(inset_padding);
1615        self
1616    }
1617
1618    /// Dart `SimpleDialog(clipBehavior:)`.
1619    pub fn clip_behavior(mut self, clip_behavior: Clip) -> SimpleDialog {
1620        self.clip_behavior = Some(clip_behavior);
1621        self
1622    }
1623
1624    /// Dart `SimpleDialog(shape:)`.
1625    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> SimpleDialog {
1626        self.shape = Some(shape.into());
1627        self
1628    }
1629
1630    /// Dart `SimpleDialog(alignment:)`.
1631    pub fn alignment(mut self, alignment: AlignmentGeometry) -> SimpleDialog {
1632        self.alignment = Some(alignment);
1633        self
1634    }
1635
1636    /// Dart `SimpleDialog(constraints:)`.
1637    pub fn constraints(mut self, constraints: BoxConstraints) -> SimpleDialog {
1638        self.constraints = Some(constraints);
1639        self
1640    }
1641}
1642
1643impl Default for SimpleDialog {
1644    fn default() -> SimpleDialog {
1645        SimpleDialog::new()
1646    }
1647}
1648
1649impl StatelessWidget for SimpleDialog {
1650    fn key(&self) -> Option<&KeyRef> {
1651        self.key.as_ref()
1652    }
1653
1654    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1655        debug_assert!(debug_check_has_material_localizations(app, context));
1656        let theme = Theme::of(app, context);
1657
1658        let dialog_theme = DialogTheme::of(app, context);
1659        let defaults: Box<dyn DialogThemeDataGetters> = if theme.use_material3 {
1660            Box::new(DialogDefaultsM3::new(context))
1661        } else {
1662            Box::new(DialogDefaultsM2::new(context))
1663        };
1664
1665        let target_platform = app.platform().target_platform();
1666        let mut label = self.semantic_label.clone();
1667        match target_platform {
1668            TargetPlatform::MacOS | TargetPlatform::IOS => {}
1669            TargetPlatform::Android
1670            | TargetPlatform::Fuchsia
1671            | TargetPlatform::Linux
1672            | TargetPlatform::Windows => {
1673                if label.is_none() {
1674                    label = Some(<dyn MaterialLocalizations>::of(app, context).dialog_label());
1675                }
1676            }
1677        }
1678
1679        // The paddingScaleFactor is used to adjust the padding of Dialog
1680        // children.
1681        let effective_title_text_style = self
1682            .title_text_style
1683            .clone()
1684            .or(dialog_theme.title_text_style.clone())
1685            .or(theme.text_theme.title_large.clone())
1686            .expect("textTheme.titleLarge");
1687        let font_size = effective_title_text_style
1688            .font_size
1689            .unwrap_or(K_DEFAULT_FONT_SIZE);
1690        let font_size_to_scale = if font_size == 0.0 {
1691            K_DEFAULT_FONT_SIZE
1692        } else {
1693            font_size
1694        };
1695        let effective_text_scale =
1696            MediaQuery::text_scaler_of(app, context).scale(font_size_to_scale) / font_size_to_scale;
1697        let padding_scale_factor = scale_padding(effective_text_scale);
1698        let text_direction = Directionality::maybe_of(app, context);
1699
1700        let mut title_widget = None;
1701        if let Some(title) = &self.title {
1702            let effective_title_padding = self.title_padding.resolve(text_direction);
1703            title_widget = Some(
1704                Padding::new(EdgeInsets::only(
1705                    effective_title_padding.left * padding_scale_factor,
1706                    effective_title_padding.top * padding_scale_factor,
1707                    effective_title_padding.right * padding_scale_factor,
1708                    if self.children.is_none() {
1709                        effective_title_padding.bottom * padding_scale_factor
1710                    } else {
1711                        effective_title_padding.bottom
1712                    },
1713                ))
1714                .child(DefaultTextStyle::new(
1715                    effective_title_text_style,
1716                    Semantics::new()
1717                        // For iOS platform, the focus always lands on the title.
1718                        // Set nameRoute to false to avoid title being announce twice.
1719                        .names_route(label.is_none() && target_platform != TargetPlatform::IOS)
1720                        .container(true)
1721                        .child(title.clone()),
1722                ))
1723                .into_widget(),
1724            );
1725        }
1726
1727        let mut content_widget = None;
1728        if let Some(children) = &self.children {
1729            let effective_content_padding = self.content_padding.resolve(text_direction);
1730            content_widget = Some(
1731                Flexible::new(
1732                    SingleChildScrollView::new()
1733                        .padding(EdgeInsets::only(
1734                            effective_content_padding.left * padding_scale_factor,
1735                            if self.title.is_none() {
1736                                effective_content_padding.top * padding_scale_factor
1737                            } else {
1738                                effective_content_padding.top
1739                            },
1740                            effective_content_padding.right * padding_scale_factor,
1741                            effective_content_padding.bottom * padding_scale_factor,
1742                        ))
1743                        .child(DefaultTextStyle::new(
1744                            self.content_text_style
1745                                .clone()
1746                                .or(dialog_theme.content_text_style.clone())
1747                                .or_else(|| defaults.content_text_style(app))
1748                                .expect("the defaults give a content text style"),
1749                            ListBody::new().children(children.clone()),
1750                        )),
1751                )
1752                .into_widget(),
1753            );
1754        }
1755
1756        let mut dialog_child = IntrinsicWidth::new()
1757            .step_width(56.0)
1758            .child(
1759                Column::new()
1760                    .main_axis_size(MainAxisSize::Min)
1761                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
1762                    .children([title_widget, content_widget].into_iter().flatten()),
1763            )
1764            .into_widget();
1765
1766        if let Some(label) = label {
1767            dialog_child = Semantics::new()
1768                .scopes_route(true)
1769                .explicit_child_nodes(true)
1770                .names_route(true)
1771                .label(label)
1772                .child(dialog_child)
1773                .into_widget();
1774        }
1775        let mut dialog = Dialog::new();
1776        dialog.background_color = self.background_color;
1777        dialog.elevation = self.elevation;
1778        dialog.shadow_color = self.shadow_color;
1779        dialog.surface_tint_color = self.surface_tint_color;
1780        dialog.inset_padding = self.inset_padding;
1781        dialog.clip_behavior = self.clip_behavior;
1782        dialog.shape = self.shape.clone();
1783        dialog.alignment = self.alignment;
1784        dialog.constraints = self.constraints;
1785        dialog.child = Some(dialog_child);
1786        dialog.into_widget()
1787    }
1788}
1789
1790fn build_material_dialog_transitions(
1791    _app: &mut App,
1792    _context: BuildContext,
1793    _animation: AnimationRef<f64>,
1794    _secondary_animation: AnimationRef<f64>,
1795    child: WidgetRef,
1796) -> WidgetRef {
1797    child
1798}
1799
1800// Wrapper that makes dialogs fill the entire window without insets or rounded corners.
1801#[derive(Debug)]
1802struct FullWindowDialogWrapper {
1803    child: WidgetRef,
1804}
1805
1806impl StatelessWidget for FullWindowDialogWrapper {
1807    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1808        let window_dialog_theme = DialogTheme::of(app, context)
1809            .copy_with()
1810            .inset_padding(EdgeInsets::ZERO)
1811            // No rounded corners.
1812            .shape(RoundedRectangleBorder::default())
1813            // Align to top-left so it fills from corner.
1814            .alignment(AlignmentGeometry::TOP_LEFT)
1815            // Remove default constraints so dialog can expand to fill available space.
1816            .constraints(BoxConstraints::expand(None, None));
1817
1818        let without_view_padding = MediaQuery::remove_view_padding(
1819            app,
1820            context,
1821            true,
1822            true,
1823            true,
1824            true,
1825            self.child.clone(),
1826        )
1827        .into_widget();
1828        DialogTheme::new()
1829            .with_data(window_dialog_theme)
1830            .child(
1831                MediaQuery::remove_view_insets(
1832                    app,
1833                    context,
1834                    true,
1835                    true,
1836                    true,
1837                    true,
1838                    without_view_padding,
1839                )
1840                .into_widget(),
1841            )
1842            .into_widget()
1843    }
1844}
1845
1846/// Dart's `void Function(Object?)`, which takes a dialog's result.
1847type DialogPopCallback = Rc<dyn Fn(&mut App, RouteResult)>;
1848
1849// Provides a pop callback that dialog content can use.
1850// Wraps content to provide a Navigator-like interface for popping.
1851struct DialogPopScope {
1852    child: WidgetRef,
1853    on_pop: Option<DialogPopCallback>,
1854}
1855
1856impl Debug for DialogPopScope {
1857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1858        f.debug_struct("DialogPopScope")
1859            .field("child", &self.child)
1860            .finish_non_exhaustive()
1861    }
1862}
1863
1864impl StatelessWidget for DialogPopScope {
1865    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1866        // Wrap with PopupScope to handle back button and provide popNavigator function.
1867        let on_pop = self.on_pop.clone();
1868        let shim_on_pop = self.on_pop.clone();
1869        let child = self.child.clone();
1870        PopScope::new(Builder::new(move |_app, _context| {
1871            // Provide a way for child widgets to pop using Navigator.maybePop(context)
1872            // by wrapping in a minimal Navigator.
1873            NavigatorShim {
1874                on_pop: shim_on_pop.clone(),
1875                child: child.clone(),
1876            }
1877            .into_widget()
1878        }))
1879        .can_pop(false)
1880        .on_pop_invoked_with_result(Rc::new(move |app, did_pop, result| {
1881            if !did_pop && let Some(on_pop) = &on_pop {
1882                on_pop(app, result);
1883            }
1884        }))
1885        .into_widget()
1886    }
1887}
1888
1889// Creates a minimal Navigator that intercepts pop calls.
1890struct NavigatorShim {
1891    on_pop: Option<DialogPopCallback>,
1892    child: WidgetRef,
1893}
1894
1895impl Debug for NavigatorShim {
1896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1897        f.debug_struct("NavigatorShim")
1898            .field("child", &self.child)
1899            .finish_non_exhaustive()
1900    }
1901}
1902
1903impl StatelessWidget for NavigatorShim {
1904    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1905        // Create a Navigator with a single page that contains the child
1906        // This allows Navigator.pop(context) calls from within the dialog to work.
1907        // Wrap in HeroControllerScope.none() to prevent this Navigator from
1908        // inheriting the outer HeroController, which would cause a "HeroController
1909        // can not be shared by multiple Navigators" assertion.
1910        let on_pop = self.on_pop.clone();
1911        let page: PageRef = Rc::new(DialogContentPage {
1912            child: self.child.clone(),
1913        });
1914        HeroControllerScope::none(Navigator::new().pages([page]).on_pop_page(
1915            move |app, _route, result| {
1916                // When the page is popped, call our onPop callback
1917                if let Some(on_pop) = &on_pop {
1918                    on_pop(app, result);
1919                }
1920                // Return false to prevent the route from being removed from the Navigator
1921                // (since we're handling the pop externally by closing the dialog window).
1922                false
1923            },
1924        ))
1925        .into_widget()
1926    }
1927}
1928
1929// A simple page for the dialog content.
1930#[derive(Debug)]
1931struct DialogContentPage {
1932    child: WidgetRef,
1933}
1934
1935impl Page for DialogContentPage {
1936    fn as_any(&self) -> &dyn Any {
1937        self
1938    }
1939
1940    fn create_route(&self, app: &mut App, _context: BuildContext, this: &PageRef) -> RouteRef {
1941        let child = self.child.clone();
1942        let page_builder: RoutePageBuilder =
1943            Rc::new(move |_app, _context, _animation, _secondary_animation| child.clone());
1944        PageRouteBuilder::new(app, page_builder)
1945            .settings(app, RouteSettingsRef::Page(Rc::clone(this)))
1946            .transition_duration(app, Duration::ZERO)
1947            .reverse_transition_duration(app, Duration::ZERO)
1948            .into_erased()
1949    }
1950}
1951
1952/// Displays a Material dialog above the current contents of the app, with
1953/// Material entrance and exit animations, modal barrier color, and modal
1954/// barrier behavior (dialog is dismissible with a tap on the barrier).
1955///
1956/// This function takes a `builder` which typically builds a [`Dialog`] widget.
1957/// Content below the dialog is dimmed with a `ModalBarrier`. The widget
1958/// returned by the `builder` does not share a context with the location that
1959/// [`ShowDialog`] is originally called from. Use a `StatefulBuilder` or a
1960/// custom `StatefulWidget` if the dialog needs to update dynamically.
1961///
1962/// The `context` argument is used to look up the [`Navigator`] and [`Theme`] for
1963/// the dialog. It is only used when the method is called. Its corresponding
1964/// widget can be safely removed from the tree before the dialog is closed.
1965///
1966/// The `barrier_dismissible` argument is used to indicate whether tapping on the
1967/// barrier will dismiss the dialog. It is `true` by default and can not be `null`.
1968///
1969/// The `barrier_color` argument is used to specify the color of the modal
1970/// barrier that darkens everything below the dialog. If `null` the `barrier_color`
1971/// field from `DialogThemeData` is used. If that is `null` the default color
1972/// `Colors::BLACK54` is used.
1973///
1974/// The `use_safe_area` argument is used to indicate if the dialog should only
1975/// display in 'safe' areas of the screen not used by the operating system
1976/// (see [`SafeArea`] for more details). It is `true` by default, which means
1977/// the dialog will not overlap operating system areas. If it is set to `false`
1978/// the dialog will only be constrained by the screen size. It can not be `null`.
1979///
1980/// The `use_root_navigator` argument is used to determine whether to push the
1981/// dialog to the [`Navigator`] furthest from or nearest to the given `context`.
1982/// By default, `use_root_navigator` is `true` and the dialog route created by
1983/// this method is pushed to the root navigator. It can not be `null`.
1984///
1985/// The `route_settings` argument is passed to [`DialogRoute::settings`].
1986///
1987/// If not null, the `traversal_edge_behavior` argument specifies the transfer of
1988/// focus beyond the first and the last items of the dialog route. By default,
1989/// [`TraversalEdgeBehavior::ClosedLoop`] is used, because it's typical for dialogs
1990/// to allow users to cycle through dialog widgets without leaving the dialog.
1991///
1992/// If `animation_style` is provided, it will be used to override the default
1993/// animation duration and curves of the dialog.
1994///
1995/// Returns a future that resolves to the value (if any) that was passed to
1996/// [`Navigator::pop`] when the dialog was closed.
1997///
1998/// See also:
1999///
2000///  * [`AlertDialog`], for dialogs that have a row of buttons below a body.
2001///  * [`SimpleDialog`], which handles the scrolling of the contents and does
2002///    not show buttons below its body.
2003///  * [`Dialog`], on which [`SimpleDialog`] and [`AlertDialog`] are based.
2004///  * `ShowCupertinoDialog`, which displays an iOS-style dialog.
2005///  * `ShowGeneralDialog`, which allows for customization of the dialog popup.
2006///  * [`DialogRoute`], the route this pushes.
2007///  * <https://material.io/design/components/dialogs.html>
2008///  * <https://m3.material.io/components/dialogs>
2009///
2010/// Builder for [`ShowDialog`]'s arguments, in place of Dart's named arguments.
2011///
2012/// Create one with [`ShowDialog::new`], set what differs from Flutter's defaults, and call
2013/// [`show`](Self::show).
2014pub struct ShowDialog {
2015    builder: WidgetBuilder,
2016    barrier_dismissible: bool,
2017    barrier_color: Option<Color>,
2018    barrier_label: Option<String>,
2019    use_safe_area: bool,
2020    use_root_navigator: bool,
2021    route_settings: Option<RouteSettingsRef>,
2022    traversal_edge_behavior: Option<TraversalEdgeBehavior>,
2023    fullscreen_dialog: bool,
2024    request_focus: Option<bool>,
2025    animation_style: Option<AnimationStyle>,
2026}
2027
2028impl ShowDialog {
2029    /// Creates a builder for a Material dialog; Dart's `showDialog` required argument is the
2030    /// `builder`, and every other argument is a setter.
2031    pub fn new(builder: WidgetBuilder) -> ShowDialog {
2032        ShowDialog {
2033            builder,
2034            barrier_dismissible: true,
2035            barrier_color: None,
2036            barrier_label: None,
2037            use_safe_area: true,
2038            use_root_navigator: true,
2039            route_settings: None,
2040            traversal_edge_behavior: None,
2041            fullscreen_dialog: false,
2042            request_focus: None,
2043            animation_style: None,
2044        }
2045    }
2046
2047    /// Whether tapping on the barrier will dismiss the dialog. Defaults to `true`.
2048    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowDialog {
2049        self.barrier_dismissible = barrier_dismissible;
2050        self
2051    }
2052
2053    /// The color of the modal barrier that darkens everything below the dialog.
2054    pub fn barrier_color(mut self, barrier_color: Color) -> ShowDialog {
2055        self.barrier_color = Some(barrier_color);
2056        self
2057    }
2058
2059    /// The semantic label of the dialog's modal barrier.
2060    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowDialog {
2061        self.barrier_label = Some(barrier_label.into());
2062        self
2063    }
2064
2065    /// Whether the dialog should only display in the safe areas of the screen. Defaults to
2066    /// `true`.
2067    pub fn use_safe_area(mut self, use_safe_area: bool) -> ShowDialog {
2068        self.use_safe_area = use_safe_area;
2069        self
2070    }
2071
2072    /// Whether to push the dialog to the root navigator rather than the nearest one. Defaults
2073    /// to `true`.
2074    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowDialog {
2075        self.use_root_navigator = use_root_navigator;
2076        self
2077    }
2078
2079    /// The route settings passed to `DialogRoute::settings`.
2080    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowDialog {
2081        self.route_settings = Some(route_settings);
2082        self
2083    }
2084
2085    /// How focus transfers beyond the first and last items of the dialog route.
2086    pub fn traversal_edge_behavior(
2087        mut self,
2088        traversal_edge_behavior: TraversalEdgeBehavior,
2089    ) -> ShowDialog {
2090        self.traversal_edge_behavior = Some(traversal_edge_behavior);
2091        self
2092    }
2093
2094    /// Whether this is a fullscreen dialog. Defaults to `false`.
2095    pub fn fullscreen_dialog(mut self, fullscreen_dialog: bool) -> ShowDialog {
2096        self.fullscreen_dialog = fullscreen_dialog;
2097        self
2098    }
2099
2100    /// Whether the dialog's route requests focus when it is pushed.
2101    pub fn request_focus(mut self, request_focus: bool) -> ShowDialog {
2102        self.request_focus = Some(request_focus);
2103        self
2104    }
2105
2106    /// An animation style that overrides the default animation duration and curves.
2107    pub fn animation_style(mut self, animation_style: AnimationStyle) -> ShowDialog {
2108        self.animation_style = Some(animation_style);
2109        self
2110    }
2111
2112    /// Displays the dialog and returns a future that resolves to the value passed to
2113    /// [`Navigator::pop`] when it closes.
2114    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
2115        let ShowDialog {
2116            builder,
2117            barrier_dismissible,
2118            barrier_color,
2119            barrier_label,
2120            use_safe_area,
2121            use_root_navigator,
2122            route_settings,
2123            traversal_edge_behavior,
2124            fullscreen_dialog,
2125            request_focus,
2126            animation_style,
2127        } = self;
2128        debug_assert!(debug_is_active(app, context));
2129        debug_assert!(debug_check_has_material_localizations(app, context));
2130
2131        let navigator_context = Navigator::of(app, context, use_root_navigator).context(app);
2132        let themes = Rc::new(<dyn InheritedTheme>::capture(
2133            app,
2134            context,
2135            Some(navigator_context),
2136        ));
2137        let navigator = Navigator::of(app, context, use_root_navigator);
2138
2139        let route_builder_builder = Rc::clone(&builder);
2140        let route_settings_for_route = route_settings.clone();
2141        let route_builder: RawDialogRouteBuilder = Rc::new(move |app, route_context, _builder| {
2142            let barrier_color = barrier_color
2143                .or(DialogTheme::of(app, context).barrier_color)
2144                .or(Theme::of(app, context).dialog_theme.barrier_color)
2145                .unwrap_or(Colors::BLACK54);
2146            let mut route = DialogRoute::new(app, route_context, Rc::clone(&route_builder_builder))
2147                .barrier_color(app, barrier_color)
2148                .barrier_dismissible(app, barrier_dismissible)
2149                .use_safe_area(app, use_safe_area)
2150                .themes(app, Rc::clone(&themes))
2151                .traversal_edge_behavior(
2152                    app,
2153                    traversal_edge_behavior.unwrap_or(TraversalEdgeBehavior::ClosedLoop),
2154                )
2155                .fullscreen_dialog(app, fullscreen_dialog);
2156            if let Some(barrier_label) = barrier_label.clone() {
2157                route = route.barrier_label(app, barrier_label);
2158            }
2159            if let Some(route_settings) = route_settings_for_route.clone() {
2160                route = route.settings(app, route_settings);
2161            }
2162            if let Some(request_focus) = request_focus {
2163                route = route.request_focus(app, request_focus);
2164            }
2165            if let Some(animation_style) = animation_style.clone() {
2166                route = route.animation_style(app, animation_style);
2167            }
2168            route.into_erased()
2169        });
2170        let window_builder: WidgetBuilder = Rc::new(move |app, _route_context| {
2171            // Wrap the build dialog with the theme, text direction, and media
2172            // query data from the caller's context (not the navigator's context,
2173            // which would resolve to the root app theme and override captured themes).
2174            let text_direction = Directionality::of(app, context);
2175            let theme_data = Theme::of(app, context);
2176            let media_query = MediaQuery::of(app, context);
2177            let pop_navigator = Navigator::of(app, navigator.context(app), false);
2178            let content_builder = Rc::clone(&builder);
2179            let dialog_content = DialogPopScope {
2180                on_pop: Some(Rc::new(move |app, result| pop_navigator.pop(app, result))),
2181                child: Builder::new(move |app, inner_context| {
2182                    FullWindowDialogWrapper {
2183                        child: content_builder(app, inner_context),
2184                    }
2185                    .into_widget()
2186                })
2187                .into_widget(),
2188            };
2189
2190            Directionality::new(
2191                text_direction,
2192                Theme::new(
2193                    theme_data,
2194                    MediaQuery::new(media_query, dialog_content).into_widget(),
2195                ),
2196            )
2197            .into_widget()
2198        });
2199
2200        let mut show = ShowRawDialog::new(window_builder)
2201            .route_builder(route_builder)
2202            .use_root_navigator(use_root_navigator)
2203            .fullscreen_dialog(fullscreen_dialog);
2204        if let Some(route_settings) = route_settings {
2205            show = show.route_settings(route_settings);
2206        }
2207        show.show(app, context)
2208    }
2209}
2210
2211/// Builder for a dialog that is Material or Cupertino by platform, in place of Dart's named
2212/// arguments.
2213///
2214/// On most platforms it acts the same as [`ShowDialog`], except for iOS and macOS, where it
2215/// acts more like [`ShowCupertinoDialog`](crate::ShowCupertinoDialog). On Cupertino platforms,
2216/// `barrier_color`, `use_safe_area` and `traversal_edge_behavior` are ignored.
2217pub struct ShowAdaptiveDialog {
2218    builder: WidgetBuilder,
2219    barrier_dismissible: Option<bool>,
2220    barrier_color: Option<Color>,
2221    barrier_label: Option<String>,
2222    use_safe_area: bool,
2223    use_root_navigator: bool,
2224    route_settings: Option<RouteSettingsRef>,
2225    traversal_edge_behavior: Option<TraversalEdgeBehavior>,
2226    request_focus: Option<bool>,
2227    animation_style: Option<AnimationStyle>,
2228}
2229
2230impl ShowAdaptiveDialog {
2231    /// Creates a builder for a platform-adaptive dialog; Dart's `showAdaptiveDialog` required
2232    /// argument is the `builder`, and every other argument is a setter.
2233    pub fn new(builder: WidgetBuilder) -> ShowAdaptiveDialog {
2234        ShowAdaptiveDialog {
2235            builder,
2236            barrier_dismissible: None,
2237            barrier_color: None,
2238            barrier_label: None,
2239            use_safe_area: true,
2240            use_root_navigator: true,
2241            route_settings: None,
2242            traversal_edge_behavior: None,
2243            request_focus: None,
2244            animation_style: None,
2245        }
2246    }
2247
2248    /// Whether tapping on the barrier will dismiss the dialog; the platform's default when
2249    /// unset.
2250    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowAdaptiveDialog {
2251        self.barrier_dismissible = Some(barrier_dismissible);
2252        self
2253    }
2254
2255    /// The color of the modal barrier that darkens everything below the dialog.
2256    pub fn barrier_color(mut self, barrier_color: Color) -> ShowAdaptiveDialog {
2257        self.barrier_color = Some(barrier_color);
2258        self
2259    }
2260
2261    /// The semantic label of the dialog's modal barrier.
2262    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowAdaptiveDialog {
2263        self.barrier_label = Some(barrier_label.into());
2264        self
2265    }
2266
2267    /// Whether the dialog should only display in the safe areas of the screen. Defaults to
2268    /// `true`.
2269    pub fn use_safe_area(mut self, use_safe_area: bool) -> ShowAdaptiveDialog {
2270        self.use_safe_area = use_safe_area;
2271        self
2272    }
2273
2274    /// Whether to push the dialog to the root navigator rather than the nearest one. Defaults
2275    /// to `true`.
2276    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowAdaptiveDialog {
2277        self.use_root_navigator = use_root_navigator;
2278        self
2279    }
2280
2281    /// The route settings passed to the dialog route.
2282    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowAdaptiveDialog {
2283        self.route_settings = Some(route_settings);
2284        self
2285    }
2286
2287    /// How focus transfers beyond the first and last items of the dialog route.
2288    pub fn traversal_edge_behavior(
2289        mut self,
2290        traversal_edge_behavior: TraversalEdgeBehavior,
2291    ) -> ShowAdaptiveDialog {
2292        self.traversal_edge_behavior = Some(traversal_edge_behavior);
2293        self
2294    }
2295
2296    /// Whether the dialog's route requests focus when it is pushed.
2297    pub fn request_focus(mut self, request_focus: bool) -> ShowAdaptiveDialog {
2298        self.request_focus = Some(request_focus);
2299        self
2300    }
2301
2302    /// An animation style that overrides the default animation duration and curves.
2303    pub fn animation_style(mut self, animation_style: AnimationStyle) -> ShowAdaptiveDialog {
2304        self.animation_style = Some(animation_style);
2305        self
2306    }
2307
2308    /// Displays the dialog and returns a future that resolves to the value passed to
2309    /// [`Navigator::pop`] when it closes.
2310    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
2311        let ShowAdaptiveDialog {
2312            builder,
2313            barrier_dismissible,
2314            barrier_color,
2315            barrier_label,
2316            use_safe_area,
2317            use_root_navigator,
2318            route_settings,
2319            traversal_edge_behavior,
2320            request_focus,
2321            animation_style,
2322        } = self;
2323        let theme = Theme::of(app, context);
2324        match theme.platform {
2325            TargetPlatform::Android
2326            | TargetPlatform::Fuchsia
2327            | TargetPlatform::Linux
2328            | TargetPlatform::Windows => {
2329                let mut show = ShowDialog::new(builder)
2330                    .barrier_dismissible(barrier_dismissible.unwrap_or(true))
2331                    .use_safe_area(use_safe_area)
2332                    .use_root_navigator(use_root_navigator);
2333                if let Some(barrier_color) = barrier_color {
2334                    show = show.barrier_color(barrier_color);
2335                }
2336                if let Some(barrier_label) = barrier_label {
2337                    show = show.barrier_label(barrier_label);
2338                }
2339                if let Some(route_settings) = route_settings {
2340                    show = show.route_settings(route_settings);
2341                }
2342                if let Some(traversal_edge_behavior) = traversal_edge_behavior {
2343                    show = show.traversal_edge_behavior(traversal_edge_behavior);
2344                }
2345                if let Some(request_focus) = request_focus {
2346                    show = show.request_focus(request_focus);
2347                }
2348                if let Some(animation_style) = animation_style {
2349                    show = show.animation_style(animation_style);
2350                }
2351                show.show(app, context)
2352            }
2353            TargetPlatform::IOS | TargetPlatform::MacOS => {
2354                let mut show = ShowCupertinoDialog::new(builder)
2355                    .use_root_navigator(use_root_navigator)
2356                    .barrier_dismissible(barrier_dismissible.unwrap_or(false));
2357                if let Some(barrier_label) = barrier_label {
2358                    show = show.barrier_label(barrier_label);
2359                }
2360                if let Some(route_settings) = route_settings {
2361                    show = show.route_settings(route_settings);
2362                }
2363                if let Some(request_focus) = request_focus {
2364                    show = show.request_focus(request_focus);
2365                }
2366                show.show(app, context)
2367            }
2368        }
2369    }
2370}
2371
2372fn debug_is_active(app: &App, context: BuildContext) -> bool {
2373    if !context.debug_is_active(app) {
2374        panic!(
2375            "This BuildContext is no longer valid.\nThe showDialog function context parameter \
2376             is a BuildContext that is no longer valid.\nThis can commonly occur when the \
2377             showDialog function is called after awaiting a Future. In this situation the \
2378             BuildContext might refer to a widget that has already been disposed during the \
2379             await. Consider using a parent context instead."
2380        );
2381    }
2382    true
2383}
2384
2385/// Dart's `pageBuilder` closure in `DialogRoute`'s constructor, over the constructor's
2386/// `builder`, `themes` and `useSafeArea`.
2387fn dialog_page_builder(
2388    builder: WidgetBuilder,
2389    themes: Option<Rc<CapturedThemes>>,
2390    use_safe_area: bool,
2391) -> RoutePageBuilder {
2392    Rc::new(
2393        move |_app, _build_context, _animation, _secondary_animation| {
2394            let builder = Rc::clone(&builder);
2395            let page_child = Builder::new(move |app, context| builder(app, context)).into_widget();
2396            let mut dialog = match &themes {
2397                Some(themes) => themes.wrap(page_child),
2398                None => page_child,
2399            };
2400            if use_safe_area {
2401                dialog = SafeArea::new(dialog).into_widget();
2402            }
2403            // Prevent clicks inside the dialog from passing through to the barrier
2404            Semantics::new()
2405                .hit_test_behavior(SemanticsHitTestBehavior::Opaque)
2406                .child(dialog)
2407                .into_widget()
2408        },
2409    )
2410}
2411
2412/// A dialog route with Material entrance and exit animations,
2413/// modal barrier color, and modal barrier behavior (dialog is dismissible
2414/// with a tap on the barrier).
2415///
2416/// It is used internally by [`ShowDialog`] or can be directly pushed
2417/// onto the [`Navigator`] stack to enable state restoration. See
2418/// [`ShowDialog`] for a state restoration app example.
2419///
2420/// This function takes a `builder` which typically builds a [`Dialog`] widget.
2421/// Content below the dialog is dimmed with a `ModalBarrier`. The widget
2422/// returned by the `builder` does not share a context with the location that
2423/// [`ShowDialog`] is originally called from. Use a `StatefulBuilder` or a
2424/// custom `StatefulWidget` if the dialog needs to update dynamically.
2425///
2426/// The `context` argument is used to look up
2427/// `MaterialLocalizations::modal_barrier_dismiss_label`, which provides the
2428/// modal with a localized accessibility label that will be used for the
2429/// modal's barrier. However, a custom `barrier_label` can be passed in as well.
2430///
2431/// The `barrier_dismissible` argument is used to indicate whether tapping on the
2432/// barrier will dismiss the dialog. It is `true` by default and can not be `null`.
2433///
2434/// The `barrier_color` argument is used to specify the color of the modal
2435/// barrier that darkens everything below the dialog. If `null`, the default
2436/// color `Colors::BLACK54` is used.
2437///
2438/// The `use_safe_area` argument is used to indicate if the dialog should only
2439/// display in 'safe' areas of the screen not used by the operating system
2440/// (see [`SafeArea`] for more details). It is `true` by default, which means
2441/// the dialog will not overlap operating system areas. If it is set to `false`
2442/// the dialog will only be constrained by the screen size. It can not be `null`.
2443///
2444/// The `settings` argument define the settings for this route. See
2445/// `RouteSettings` for details.
2446///
2447/// The `animation_style` argument is used to override the default animation
2448/// duration and curves of the dialog route.
2449///
2450/// See also:
2451///
2452///  * [`ShowDialog`], which is a way to display a [`DialogRoute`].
2453///  * `ShowGeneralDialog`, which allows for customization of the dialog popup.
2454///  * `ShowCupertinoDialog`, which displays an iOS-style dialog.
2455pub struct DialogRoute {
2456    route: RouteData,
2457    overlay_route: OverlayRouteData,
2458    transition_route: TransitionRouteData,
2459    local_history: LocalHistoryRouteData,
2460    modal_route: ModalRouteData,
2461    raw_dialog_route: RawDialogRouteData,
2462    /// The constructor's `builder`, `themes` and `useSafeArea`, which its page builder closes
2463    /// over.
2464    builder: WidgetBuilder,
2465    themes: Option<Rc<CapturedThemes>>,
2466    use_safe_area: bool,
2467    curved_animation: Option<Ref<CurvedAnimation>>,
2468    animation_style: Option<AnimationStyle>,
2469}
2470
2471impl DialogRoute {
2472    /// A dialog route with Material entrance and exit animations; Dart's optional arguments
2473    /// are the setters.
2474    ///
2475    /// Dart's defaults: `barrier_color` `Colors::BLACK54`, `barrier_dismissible` true,
2476    /// `barrier_label` the context's `MaterialLocalizations::modal_barrier_dismiss_label`,
2477    /// `use_safe_area` true, and a transition of 150 ms.
2478    pub fn new(app: &mut App, context: BuildContext, builder: WidgetBuilder) -> Ref<DialogRoute> {
2479        let barrier_label =
2480            <dyn MaterialLocalizations>::of(app, context).modal_barrier_dismiss_label();
2481        let route = RouteData::new(app, None, None);
2482        let transition_route = TransitionRouteData::new(app);
2483        let modal_route = ModalRouteData::new(app);
2484        let mut raw_dialog_route =
2485            RawDialogRouteData::new(dialog_page_builder(Rc::clone(&builder), None, true));
2486        raw_dialog_route.barrier_color = Some(Colors::BLACK54);
2487        raw_dialog_route.barrier_label = Some(barrier_label);
2488        raw_dialog_route.transition_duration = Duration::from_millis(150);
2489        raw_dialog_route.transition_builder = Some(Rc::new(build_material_dialog_transitions));
2490        app.create(DialogRoute {
2491            route,
2492            overlay_route: OverlayRouteData::new(),
2493            transition_route,
2494            local_history: LocalHistoryRouteData::new(),
2495            modal_route,
2496            raw_dialog_route,
2497            builder,
2498            themes: None,
2499            use_safe_area: true,
2500            curved_animation: None,
2501            animation_style: None,
2502        })
2503    }
2504
2505    /// Dart `DialogRoute(themes:)`.
2506    pub fn themes(self: Ref<Self>, app: &mut App, themes: Rc<CapturedThemes>) -> Ref<Self> {
2507        app.get_mut(&self).themes = Some(themes);
2508        self.build_page_builder(app);
2509        self
2510    }
2511
2512    /// Dart `DialogRoute(barrierColor:)`.
2513    pub fn barrier_color(self: Ref<Self>, app: &mut App, barrier_color: Color) -> Ref<Self> {
2514        self.raw_dialog_route_data_mut(app).barrier_color = Some(barrier_color);
2515        self
2516    }
2517
2518    /// Dart `DialogRoute(barrierDismissible:)`.
2519    pub fn barrier_dismissible(
2520        self: Ref<Self>,
2521        app: &mut App,
2522        barrier_dismissible: bool,
2523    ) -> Ref<Self> {
2524        self.raw_dialog_route_data_mut(app).barrier_dismissible = barrier_dismissible;
2525        self
2526    }
2527
2528    /// Dart `DialogRoute(barrierLabel:)`.
2529    pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
2530        self.raw_dialog_route_data_mut(app).barrier_label = Some(barrier_label);
2531        self
2532    }
2533
2534    /// Dart `DialogRoute(useSafeArea:)`.
2535    pub fn use_safe_area(self: Ref<Self>, app: &mut App, use_safe_area: bool) -> Ref<Self> {
2536        app.get_mut(&self).use_safe_area = use_safe_area;
2537        self.build_page_builder(app);
2538        self
2539    }
2540
2541    /// Dart `DialogRoute(settings:)`.
2542    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
2543        self.route_data_mut(app).set_settings(settings);
2544        self
2545    }
2546
2547    /// Dart `DialogRoute(requestFocus:)`.
2548    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
2549        self.route_data_mut(app)
2550            .set_request_focus(Some(request_focus));
2551        self
2552    }
2553
2554    /// Dart `DialogRoute(traversalEdgeBehavior:)`.
2555    pub fn traversal_edge_behavior(
2556        self: Ref<Self>,
2557        app: &mut App,
2558        behavior: TraversalEdgeBehavior,
2559    ) -> Ref<Self> {
2560        self.modal_route_data_mut(app).traversal_edge_behavior = Some(behavior);
2561        self
2562    }
2563
2564    /// Dart `DialogRoute(fullscreenDialog:)`.
2565    pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
2566        self.raw_dialog_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
2567        self
2568    }
2569
2570    /// Dart `DialogRoute(animationStyle:)`, which also sets the transition's duration.
2571    pub fn animation_style(
2572        self: Ref<Self>,
2573        app: &mut App,
2574        animation_style: AnimationStyle,
2575    ) -> Ref<Self> {
2576        self.raw_dialog_route_data_mut(app).transition_duration = animation_style
2577            .duration
2578            .unwrap_or(Duration::from_millis(150));
2579        app.get_mut(&self).animation_style = Some(animation_style);
2580        self
2581    }
2582
2583    /// Makes Dart's page builder again over the constructor arguments as they are now.
2584    fn build_page_builder(self: Handle<Self>, app: &mut App) {
2585        let route = app.get(self);
2586        let page_builder = dialog_page_builder(
2587            Rc::clone(&route.builder),
2588            route.themes.clone(),
2589            route.use_safe_area,
2590        );
2591        self.raw_dialog_route_data_mut(app).page_builder = page_builder;
2592    }
2593
2594    fn set_animation(self: Handle<Self>, app: &mut App, animation: AnimationRef<f64>) {
2595        let current = app.get(self).curved_animation.handle();
2596        if current.map(|curved| curved.parent(app)) != Some(animation.handle()) {
2597            if let Some(curved) = current {
2598                curved.dispose(app);
2599            }
2600            let style = app.get(self).animation_style.clone();
2601            let curve = style
2602                .as_ref()
2603                .and_then(|style| style.curve.clone())
2604                .unwrap_or_else(Curves::ease_out);
2605            let reverse_curve = style
2606                .as_ref()
2607                .and_then(|style| style.reverse_curve.clone())
2608                .unwrap_or_else(Curves::ease_out);
2609            let curved = CurvedAnimation::new(app, animation, curve, Some(reverse_curve));
2610            app.get_mut(self).curved_animation = Some(curved);
2611        }
2612    }
2613}
2614
2615impl Route for DialogRoute {
2616    waft_widgets::route_accessors!();
2617
2618    fn as_transition_route(self: Handle<Self>) -> Option<waft_widgets::AnyTransitionRoute> {
2619        Some(TransitionRoute::as_transition_route(self))
2620    }
2621
2622    fn as_modal_route(self: Handle<Self>) -> Option<waft_widgets::AnyModalRoute> {
2623        Some(ModalRoute::as_modal_route(self))
2624    }
2625
2626    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<waft_widgets::OverlayEntry>> {
2627        OverlayRoute::overlay_entries(self, app)
2628    }
2629
2630    fn install(self: Handle<Self>, app: &mut App) {
2631        ModalRoute::install(self, app)
2632    }
2633
2634    fn did_push(self: Handle<Self>, app: &mut App) -> waft_scheduler::TickerFuture {
2635        ModalRoute::did_push(self, app)
2636    }
2637
2638    fn did_add(self: Handle<Self>, app: &mut App) {
2639        ModalRoute::did_add(self, app)
2640    }
2641
2642    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
2643        TransitionRoute::did_replace(self, app, old_route)
2644    }
2645
2646    fn will_pop(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
2647        LocalHistoryRoute::will_pop(self, app)
2648    }
2649
2650    fn pop_disposition(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
2651        ModalRoute::pop_disposition(self, app)
2652    }
2653
2654    fn on_pop_invoked_with_result(
2655        self: Handle<Self>,
2656        app: &mut App,
2657        did_pop: bool,
2658        result: RouteResult,
2659    ) {
2660        ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
2661    }
2662
2663    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
2664        LocalHistoryRoute::will_handle_pop_internally(self, app)
2665    }
2666
2667    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
2668        LocalHistoryRoute::did_pop(self, app, result)
2669    }
2670
2671    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
2672        ModalRoute::did_pop_next(self, app, next_route)
2673    }
2674
2675    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
2676        ModalRoute::did_change_next(self, app, next_route)
2677    }
2678
2679    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
2680        ModalRoute::did_change_previous(self, app, previous_route)
2681    }
2682
2683    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
2684        ModalRoute::changed_internal_state(self, app)
2685    }
2686
2687    fn changed_external_state(self: Handle<Self>, app: &mut App) {
2688        ModalRoute::changed_external_state(self, app)
2689    }
2690
2691    fn dispose(self: Handle<Self>, app: &mut App) {
2692        if let Some(curved) = app.get(self).curved_animation.handle() {
2693            curved.dispose(app);
2694        }
2695        TransitionRoute::dispose(self, app)
2696    }
2697}
2698
2699impl OverlayRoute for DialogRoute {
2700    waft_widgets::modal_overlay_route_overrides!();
2701}
2702
2703impl PredictiveBackRoute for DialogRoute {
2704    waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
2705}
2706
2707impl TransitionRoute for DialogRoute {
2708    waft_widgets::raw_dialog_route_transition_route_overrides!();
2709}
2710
2711impl LocalHistoryRoute for DialogRoute {
2712    waft_widgets::local_history_route_accessors!();
2713}
2714
2715impl ModalRoute for DialogRoute {
2716    waft_widgets::raw_dialog_route_modal_route_overrides!();
2717}
2718
2719impl PopupRoute for DialogRoute {}
2720
2721impl RawDialogRouteLeaf for DialogRoute {
2722    waft_widgets::raw_dialog_route_accessors!();
2723
2724    fn build_transitions(
2725        self: Handle<Self>,
2726        app: &mut App,
2727        context: BuildContext,
2728        animation: AnimationRef<f64>,
2729        secondary_animation: AnimationRef<f64>,
2730        child: WidgetRef,
2731    ) -> WidgetRef {
2732        self.set_animation(app, animation.clone());
2733        let curved = app
2734            .get(self)
2735            .curved_animation
2736            .clone()
2737            .expect("set_animation made it");
2738        FadeTransition::new(curved.erase())
2739            .child(RawDialogRoute::build_transitions(
2740                self,
2741                app,
2742                context,
2743                animation,
2744                secondary_animation,
2745                child,
2746            ))
2747            .into_widget()
2748    }
2749}
2750
2751fn scale_padding(text_scale_factor: f64) -> f64 {
2752    let clamped_text_scale_factor = text_scale_factor.clamp(1.0, 2.0);
2753    // The final padding scale factor is clamped between 1/3 and 1. For example,
2754    // a non-scaled padding of 24 will produce a padding between 24 and 8.
2755    lerp_double(Some(1.0), Some(1.0 / 3.0), clamped_text_scale_factor - 1.0)
2756        .expect("both ends are given")
2757}
2758
2759/// Dart's `_DialogDefaultsM2`: hand coded defaults based on Material Design 2.
2760struct DialogDefaultsM2 {
2761    /// Dart's `super(..)` arguments.
2762    dialog_theme_data: DialogThemeData,
2763    context: DefaultsContext,
2764}
2765
2766impl DialogDefaultsM2 {
2767    fn new(context: BuildContext) -> DialogDefaultsM2 {
2768        DialogDefaultsM2 {
2769            dialog_theme_data: DialogThemeData::new()
2770                .alignment(AlignmentGeometry::CENTER)
2771                .elevation(24.0)
2772                .shape(RoundedRectangleBorder::new(
2773                    waft_painting::BorderSide::NONE,
2774                    waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(4.0)),
2775                ))
2776                .clip_behavior(Clip::None),
2777            context: DefaultsContext::new(context),
2778        }
2779    }
2780}
2781
2782impl DialogThemeDataGetters for DialogDefaultsM2 {
2783    fn dialog_theme_data(&self) -> &DialogThemeData {
2784        &self.dialog_theme_data
2785    }
2786
2787    fn icon_color(&self, app: &mut App) -> Option<Color> {
2788        self.context
2789            .theme(app)
2790            .icon_theme
2791            .color
2792            .as_ref()
2793            .map(|color| color.color())
2794    }
2795
2796    fn background_color(&self, app: &mut App) -> Option<Color> {
2797        Some(
2798            if self.context.theme(app).brightness() == Brightness::Dark {
2799                Colors::GREY.shade800()
2800            } else {
2801                Colors::WHITE
2802            },
2803        )
2804    }
2805
2806    fn shadow_color(&self, app: &mut App) -> Option<Color> {
2807        Some(self.context.theme(app).shadow_color)
2808    }
2809
2810    fn title_text_style(&self, app: &mut App) -> Option<TextStyle> {
2811        self.context.text_theme(app).title_large.clone()
2812    }
2813
2814    fn content_text_style(&self, app: &mut App) -> Option<TextStyle> {
2815        self.context.text_theme(app).title_medium.clone()
2816    }
2817
2818    fn actions_padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
2819        Some(EdgeInsetsGeometry::ZERO)
2820    }
2821}
2822
2823#[cfg(test)]
2824pub(crate) mod tests {
2825    //! Ported from `test/dialog_test.dart`; the semantics-tree cases wait for the semantics
2826    //! tree, the goldens are not ported, and the display-feature cases wait for
2827    //! `DisplayFeatureSubScreen`.
2828
2829    use std::cell::Cell;
2830    use waft_painting::ShapeBorder;
2831
2832    use waft_embedder::{Offset, Radius, Rect, Size};
2833    use waft_painting::{Border, BorderRadiusGeometry, BorderSide};
2834    use waft_rendering::RenderParagraph;
2835    use waft_widgets::{AnyElement, Center, Container, GlobalKey, MediaQueryData, SizedBox, Text};
2836
2837    use waft_widgets::testing::{
2838        WidgetTester, assert_f32_equals, expect, find, finds_one_widget, test_widgets,
2839    };
2840
2841    use super::*;
2842    use crate::elevated_button::ElevatedButton;
2843    use crate::text_button::TextButton;
2844    use crate::theme_data::ThemeData;
2845    use crate::tooltip::tests::{m2, m3, pump_app};
2846
2847    fn rounded(radius: f64) -> RoundedRectangleBorder {
2848        RoundedRectangleBorder::new(
2849            BorderSide::NONE,
2850            BorderRadiusGeometry::all(Radius::circular(radius)),
2851        )
2852    }
2853
2854    /// Dart's `_defaultM2DialogShape`.
2855    fn default_m2_dialog_shape() -> ShapeBorderRef {
2856        ShapeBorderRef::new(rounded(4.0))
2857    }
2858
2859    /// Dart's `_defaultM3DialogShape`.
2860    fn default_m3_dialog_shape() -> ShapeBorderRef {
2861        ShapeBorderRef::new(rounded(28.0))
2862    }
2863
2864    /// Dart's `material3Theme`.
2865    fn material3_theme(app: &App) -> ThemeData {
2866        ThemeData::builder().brightness(Brightness::Dark).build(app)
2867    }
2868
2869    /// Dart's `material2Theme`.
2870    fn material2_theme(app: &App) -> ThemeData {
2871        ThemeData::builder()
2872            .use_material3(false)
2873            .brightness(Brightness::Dark)
2874            .build(app)
2875    }
2876
2877    /// `showDialog`'s optional arguments with Dart's defaults.
2878    #[derive(Clone)]
2879    struct Show {
2880        barrier_dismissible: bool,
2881        barrier_color: Option<Color>,
2882        barrier_label: Option<String>,
2883        use_safe_area: bool,
2884        use_root_navigator: bool,
2885        route_settings: Option<RouteSettingsRef>,
2886        traversal_edge_behavior: Option<TraversalEdgeBehavior>,
2887        fullscreen_dialog: bool,
2888        request_focus: Option<bool>,
2889        animation_style: Option<AnimationStyle>,
2890    }
2891
2892    impl Default for Show {
2893        fn default() -> Show {
2894            Show {
2895                barrier_dismissible: true,
2896                barrier_color: None,
2897                barrier_label: None,
2898                use_safe_area: true,
2899                use_root_navigator: true,
2900                route_settings: None,
2901                traversal_edge_behavior: None,
2902                fullscreen_dialog: false,
2903                request_focus: None,
2904                animation_style: None,
2905            }
2906        }
2907    }
2908
2909    impl Show {
2910        fn show(
2911            self,
2912            app: &mut App,
2913            context: BuildContext,
2914            builder: WidgetBuilder,
2915        ) -> CompleterFuture<RouteResult> {
2916            let mut show = ShowDialog::new(builder)
2917                .barrier_dismissible(self.barrier_dismissible)
2918                .use_safe_area(self.use_safe_area)
2919                .use_root_navigator(self.use_root_navigator)
2920                .fullscreen_dialog(self.fullscreen_dialog);
2921            if let Some(barrier_color) = self.barrier_color {
2922                show = show.barrier_color(barrier_color);
2923            }
2924            if let Some(barrier_label) = self.barrier_label {
2925                show = show.barrier_label(barrier_label);
2926            }
2927            if let Some(route_settings) = self.route_settings {
2928                show = show.route_settings(route_settings);
2929            }
2930            if let Some(traversal_edge_behavior) = self.traversal_edge_behavior {
2931                show = show.traversal_edge_behavior(traversal_edge_behavior);
2932            }
2933            if let Some(request_focus) = self.request_focus {
2934                show = show.request_focus(request_focus);
2935            }
2936            if let Some(animation_style) = self.animation_style {
2937                show = show.animation_style(animation_style);
2938            }
2939            show.show(app, context)
2940        }
2941
2942        fn on(
2943            self,
2944            tester: &WidgetTester,
2945            context: BuildContext,
2946            builder: WidgetBuilder,
2947        ) -> CompleterFuture<RouteResult> {
2948            let future = self.show(&mut tester.cell.borrow_mut(), context, builder);
2949            tester.cell.checkpoint();
2950            future
2951        }
2952    }
2953
2954    /// Dart's `_buildAppWithDialog(dialog, theme:, textScaleFactor:, traversalEdgeBehavior:)`.
2955    fn app_with_dialog(
2956        tester: &mut WidgetTester,
2957        theme: impl FnOnce(&App) -> ThemeData,
2958        dialog: WidgetRef,
2959        text_scale_factor: f64,
2960        traversal_edge_behavior: Option<TraversalEdgeBehavior>,
2961    ) {
2962        pump_app(tester, theme, move |_app| {
2963            Material::new()
2964                .child(Builder::new(move |_app, context| {
2965                    let dialog = dialog.clone();
2966                    Center::new()
2967                        .child(ElevatedButton::new(
2968                            Some(waft_foundation::Listener::new(move |app| {
2969                                let dialog = dialog.clone();
2970                                let show = Show {
2971                                    traversal_edge_behavior,
2972                                    ..Show::default()
2973                                };
2974                                drop(show.show(
2975                                    app,
2976                                    context,
2977                                    Rc::new(move |_app, _context| {
2978                                        MediaQuery::with_clamped_text_scaling(
2979                                            None,
2980                                            text_scale_factor,
2981                                            text_scale_factor,
2982                                            dialog.clone(),
2983                                        )
2984                                    }),
2985                                ));
2986                            })),
2987                            Some(Text::new("X")),
2988                        ))
2989                        .into_widget()
2990                }))
2991                .into_widget()
2992        });
2993    }
2994
2995    /// [`app_with_dialog`] with Dart's defaults.
2996    fn pump_with_dialog<K>(
2997        tester: &mut WidgetTester,
2998        theme: impl FnOnce(&App) -> ThemeData,
2999        dialog: impl IntoWidget<K>,
3000    ) {
3001        app_with_dialog(tester, theme, dialog.into_widget(), 1.0, None);
3002    }
3003
3004    /// Dart's `tester.tap(find.text('X'))` then `tester.pumpAndSettle()`.
3005    pub(crate) fn open(tester: &mut WidgetTester) {
3006        tester.tap(find::text("X"));
3007        tester.pump_and_settle();
3008    }
3009
3010    /// Dart's `find.text(text)` with `findsOneWidget` or `findsNothing`.
3011    pub(crate) fn shows(tester: &WidgetTester, text: &str) -> usize {
3012        find::text(text).evaluate(tester).len()
3013    }
3014
3015    /// Dart's `tester.tapAt(at)`.
3016    pub(crate) fn tap_at(tester: &mut WidgetTester, at: Offset) {
3017        tester.tap_at(at, 1);
3018    }
3019
3020    pub(crate) fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
3021        tester.get_rect(tester.render_object(key).as_box().expect("a render box"))
3022    }
3023
3024    /// Dart's `find.descendant(of: find.byType(Dialog), matching: find.byType(Material))`, the
3025    /// first.
3026    pub(crate) fn dialog_material(tester: &WidgetTester) -> AnyElement {
3027        let dialog = find::by_type::<Dialog>().evaluate(tester)[0];
3028        tester.descendants_of_type::<Material>(dialog)[0]
3029    }
3030
3031    /// Dart's `_getMaterialFromDialog(tester)`, read through `read`.
3032    pub(crate) fn material_from_dialog<R>(
3033        tester: &WidgetTester,
3034        read: impl FnOnce(&Material) -> R,
3035    ) -> R {
3036        tester.widget::<Material, R>(dialog_material(tester), read)
3037    }
3038
3039    /// Dart's `_getTextRenderObjectFromDialog(tester, text).text.style`.
3040    pub(crate) fn text_style_in_dialog(tester: &WidgetTester, text: &str) -> Option<TextStyle> {
3041        let dialog = find::by_type::<Dialog>().evaluate(tester)[0];
3042        let element = find::text(text)
3043            .evaluate(tester)
3044            .into_iter()
3045            .find(|element| tester.ancestors(*element).contains(&dialog))
3046            .expect("the text is in the dialog");
3047        let app = tester.cell.borrow();
3048        let paragraph = element
3049            .find_render_object(&app)
3050            .and_then(|object| object.downcast::<RenderParagraph>(&app))
3051            .expect("a paragraph");
3052        paragraph.text(&app).style().cloned()
3053    }
3054
3055    /// Dart's `_findOverflowBar()`: the `Padding` the `OverflowBar` is the child of.
3056    fn overflow_bar_padding(tester: &WidgetTester) -> Rect {
3057        let bar = find::by_type::<OverflowBar>().evaluate(tester)[0];
3058        tester.get_rect(tester.ancestor_of_type::<Padding>(bar))
3059    }
3060
3061    fn green_box(height: f64, width: f64) -> WidgetRef {
3062        Container::new()
3063            .height(height)
3064            .width(width)
3065            .color(Colors::GREEN.shade500())
3066            .into_widget()
3067    }
3068
3069    /// Dart's `MaterialApp(home: Material(child: Center(child: ElevatedButton(onPressed: null,
3070    /// child: Text(text)))))`, and the context of the text.
3071    fn app_with_disabled_button(tester: &mut WidgetTester, text: &'static str) -> BuildContext {
3072        pump_app(tester, m3, move |_app| {
3073            Material::new()
3074                .child(Center::new().child(ElevatedButton::new(None, Some(Text::new(text)))))
3075                .into_widget()
3076        });
3077        find::text(text).evaluate(tester)[0]
3078    }
3079
3080    /// Records the value `future` resolves with: Dart's `await result`.
3081    fn result_of<T: Clone + 'static>(
3082        tester: &WidgetTester,
3083        future: CompleterFuture<RouteResult>,
3084    ) -> Rc<Cell<Option<Option<T>>>> {
3085        let result = Rc::new(Cell::new(None));
3086        let out = Rc::clone(&result);
3087        future.then(&mut tester.cell.borrow_mut(), move |_app, value| {
3088            out.set(Some(
3089                value
3090                    .as_ref()
3091                    .and_then(|value| value.downcast_ref::<T>().cloned()),
3092            ));
3093        });
3094        result
3095    }
3096
3097    /// Not a Dart case: what Flutter's leak tracking checks, that opening and closing a dialog
3098    /// leaves nothing in the arena.
3099    #[test]
3100    fn opening_and_closing_a_dialog_leaves_nothing_behind() {
3101        test_widgets(|tester| {
3102            pump_with_dialog(tester, m3, AlertDialog::new().content(Text::new("Body")));
3103            tester.assert_leaves_nothing_behind(|tester| {
3104                open(tester);
3105                let body = tester.element(find::text("Body"));
3106                Navigator::pop(&mut tester.cell.borrow_mut(), body, None);
3107                tester.pump_and_settle();
3108                assert_eq!(shows(tester, "Body"), 0);
3109            });
3110        });
3111    }
3112
3113    #[test]
3114    fn dialog_is_scrollable() {
3115        test_widgets(|tester| {
3116            let did_press_ok = Rc::new(Cell::new(false));
3117            let pressed = Rc::clone(&did_press_ok);
3118            let dialog = AlertDialog::new()
3119                .content(green_box(5000.0, 300.0))
3120                .actions([TextButton::new(
3121                    Some(waft_foundation::Listener::new(move |_app| {
3122                        pressed.set(true)
3123                    })),
3124                    Some(Text::new("OK")),
3125                )
3126                .into_widget()]);
3127            pump_with_dialog(tester, m3, dialog);
3128
3129            open(tester);
3130
3131            assert!(!did_press_ok.get());
3132            tester.tap(find::text("OK"));
3133            assert!(did_press_ok.get());
3134        });
3135    }
3136
3137    #[test]
3138    fn dialog_background_color_from_alert_dialog() {
3139        test_widgets(|tester| {
3140            let custom_color = Colors::PINK.primary();
3141            let dialog = AlertDialog::new()
3142                .background_color(custom_color)
3143                .actions([]);
3144            pump_with_dialog(
3145                tester,
3146                |app| ThemeData::builder().brightness(Brightness::Dark).build(app),
3147                dialog,
3148            );
3149
3150            open(tester);
3151
3152            assert_eq!(
3153                material_from_dialog(tester, |material| material.color),
3154                Some(custom_color)
3155            );
3156        });
3157    }
3158
3159    #[test]
3160    #[allow(
3161        deprecated,
3162        reason = "Dart's case sets the deprecated `background` too"
3163    )]
3164    fn dialog_background_defaults_to_color_scheme_surface_container_high() {
3165        test_widgets(|tester| {
3166            let theme = {
3167                let app = tester.cell.borrow();
3168                let color_scheme = ThemeData::new(&app)
3169                    .color_scheme
3170                    .copy_with()
3171                    .with_surface(Colors::ORANGE.primary())
3172                    .with_background(Colors::GREEN.primary())
3173                    .with_surface_container_high(Colors::RED.primary());
3174                ThemeData::builder().color_scheme(color_scheme).build(&app)
3175            };
3176            let expected = theme.color_scheme.surface_container_high();
3177            let dialog = Dialog::new().child(SizedBox::new().width(200.0).height(200.0));
3178            pump_with_dialog(tester, move |_app| theme, dialog);
3179
3180            open(tester);
3181
3182            assert_eq!(
3183                material_from_dialog(tester, |material| material.color),
3184                Some(expected)
3185            );
3186        });
3187    }
3188
3189    fn assert_shape(tester: &WidgetTester, expected: &dyn ShapeBorder) {
3190        material_from_dialog(tester, |material| {
3191            assert_eq!(material.shape.as_deref(), Some(expected));
3192        });
3193    }
3194
3195    #[test]
3196    fn material2_dialog_defaults() {
3197        test_widgets(|tester| {
3198            let dialog = AlertDialog::new()
3199                .title(Text::new("Title"))
3200                .content(Text::new("Y"))
3201                .actions([]);
3202            pump_with_dialog(tester, material2_theme, dialog);
3203
3204            open(tester);
3205
3206            assert_eq!(
3207                material_from_dialog(tester, |material| material.color),
3208                Some(Colors::GREY.shade800())
3209            );
3210            assert_shape(tester, &*default_m2_dialog_shape());
3211            assert_eq!(
3212                material_from_dialog(tester, |material| material.elevation),
3213                24.0
3214            );
3215
3216            let bottom_left = tester.get_rect(dialog_material(tester)).bottom_left();
3217            assert_eq!(bottom_left.dy(), 360.0);
3218        });
3219    }
3220
3221    #[test]
3222    fn material3_dialog_defaults() {
3223        test_widgets(|tester| {
3224            let expected = material3_theme(&tester.cell.borrow())
3225                .color_scheme
3226                .surface_container_high();
3227            let dialog = AlertDialog::new()
3228                .title(Text::new("Title"))
3229                .content(Text::new("Y"))
3230                .actions([]);
3231            pump_with_dialog(tester, material3_theme, dialog);
3232
3233            open(tester);
3234
3235            assert_eq!(
3236                material_from_dialog(tester, |material| material.color),
3237                Some(expected)
3238            );
3239            assert_shape(tester, &*default_m3_dialog_shape());
3240            assert_eq!(
3241                material_from_dialog(tester, |material| material.elevation),
3242                6.0
3243            );
3244        });
3245    }
3246
3247    fn dismiss_with_escape(tester: &mut WidgetTester) {
3248        tester.send_key_event(
3249            waft_services::PhysicalKeyboardKey::ESCAPE,
3250            waft_services::LogicalKeyboardKey::ESCAPE,
3251        );
3252        tester.pump_and_settle();
3253    }
3254
3255    #[test]
3256    fn material2_dialog_fullscreen_defaults() {
3257        test_widgets(|tester| {
3258            let dialog_text_m2 = "Fullscreen Dialog - M2";
3259            pump_with_dialog(
3260                tester,
3261                material2_theme,
3262                Dialog::fullscreen().child(Text::new(dialog_text_m2)),
3263            );
3264
3265            open(tester);
3266
3267            assert_eq!(shows(tester, dialog_text_m2), 1);
3268            assert_eq!(
3269                material_from_dialog(tester, |material| material.color),
3270                Some(Colors::GREY.shade800())
3271            );
3272
3273            // Try to dismiss the fullscreen dialog with the escape key.
3274            dismiss_with_escape(tester);
3275
3276            assert_eq!(shows(tester, dialog_text_m2), 0);
3277        });
3278    }
3279
3280    #[test]
3281    fn material3_dialog_fullscreen_defaults() {
3282        test_widgets(|tester| {
3283            let dialog_text_m3 = "Fullscreen Dialog - M3";
3284            let expected = material3_theme(&tester.cell.borrow())
3285                .color_scheme
3286                .surface();
3287            pump_with_dialog(
3288                tester,
3289                material3_theme,
3290                Dialog::fullscreen().child(Text::new(dialog_text_m3)),
3291            );
3292
3293            open(tester);
3294
3295            assert_eq!(shows(tester, dialog_text_m3), 1);
3296            assert_eq!(
3297                material_from_dialog(tester, |material| material.color),
3298                Some(expected)
3299            );
3300
3301            // Try to dismiss the fullscreen dialog with the escape key.
3302            dismiss_with_escape(tester);
3303
3304            assert_eq!(shows(tester, dialog_text_m3), 0);
3305        });
3306    }
3307
3308    #[test]
3309    fn custom_dialog_elevation() {
3310        test_widgets(|tester| {
3311            let custom_elevation = 12.0;
3312            let shadow_color = Color::new(0xFF000001);
3313            let surface_tint_color = Color::new(0xFF000002);
3314            let dialog = AlertDialog::new()
3315                .actions([])
3316                .elevation(custom_elevation)
3317                .shadow_color(shadow_color)
3318                .surface_tint_color(surface_tint_color);
3319            pump_with_dialog(tester, m3, dialog);
3320
3321            open(tester);
3322
3323            material_from_dialog(tester, |material| {
3324                assert_eq!(material.elevation, custom_elevation);
3325                assert_eq!(material.shadow_color, Some(shadow_color));
3326                assert_eq!(material.surface_tint_color, Some(surface_tint_color));
3327            });
3328        });
3329    }
3330
3331    #[test]
3332    fn custom_title_text_style() {
3333        test_widgets(|tester| {
3334            let title_text = "Title";
3335            let title_text_style = TextStyle::new().color(Colors::PINK.primary());
3336            let dialog = AlertDialog::new()
3337                .title(Text::new(title_text))
3338                .title_text_style(title_text_style.clone())
3339                .actions([]);
3340            pump_with_dialog(tester, m3, dialog);
3341
3342            open(tester);
3343
3344            assert_eq!(
3345                text_style_in_dialog(tester, title_text),
3346                Some(title_text_style)
3347            );
3348        });
3349    }
3350
3351    #[test]
3352    fn custom_content_text_style() {
3353        test_widgets(|tester| {
3354            let content_text = "Content";
3355            let content_text_style = TextStyle::new().color(Colors::PINK.primary());
3356            let dialog = AlertDialog::new()
3357                .content(Text::new(content_text))
3358                .content_text_style(content_text_style.clone())
3359                .actions([]);
3360            pump_with_dialog(tester, m3, dialog);
3361
3362            open(tester);
3363
3364            assert_eq!(
3365                text_style_in_dialog(tester, content_text),
3366                Some(content_text_style)
3367            );
3368        });
3369    }
3370
3371    #[test]
3372    fn alert_dialog_custom_clip_behavior() {
3373        test_widgets(|tester| {
3374            let dialog = AlertDialog::new()
3375                .actions([])
3376                .clip_behavior(Clip::AntiAlias);
3377            pump_with_dialog(tester, m3, dialog);
3378
3379            open(tester);
3380
3381            assert_eq!(
3382                material_from_dialog(tester, |material| material.clip_behavior),
3383                Clip::AntiAlias
3384            );
3385        });
3386    }
3387
3388    #[test]
3389    fn simple_dialog_custom_clip_behavior() {
3390        test_widgets(|tester| {
3391            let dialog = SimpleDialog::new()
3392                .clip_behavior(Clip::AntiAlias)
3393                .children([]);
3394            pump_with_dialog(tester, m3, dialog);
3395
3396            open(tester);
3397
3398            assert_eq!(
3399                material_from_dialog(tester, |material| material.clip_behavior),
3400                Clip::AntiAlias
3401            );
3402        });
3403    }
3404
3405    #[test]
3406    fn simple_dialog_custom_content_text_style() {
3407        test_widgets(|tester| {
3408            let content_text = "Content";
3409            let content_text_style = TextStyle::new().color(Colors::PINK.primary());
3410            let dialog = SimpleDialog::new()
3411                .content_text_style(content_text_style.clone())
3412                .children([Text::new(content_text).into_widget()]);
3413            pump_with_dialog(tester, m3, dialog);
3414
3415            open(tester);
3416
3417            assert_eq!(
3418                text_style_in_dialog(tester, content_text),
3419                Some(content_text_style)
3420            );
3421        });
3422    }
3423
3424    #[test]
3425    fn simple_dialog_custom_content_text_style_dialog_theme() {
3426        test_widgets(|tester| {
3427            let content_text = "Content";
3428            let content_text_style = TextStyle::new().color(Colors::ORANGE.primary());
3429            let dialog = SimpleDialog::new().children([Text::new(content_text).into_widget()]);
3430            let theme_style = content_text_style.clone();
3431            pump_with_dialog(
3432                tester,
3433                move |app| {
3434                    ThemeData::builder()
3435                        .dialog_theme(DialogThemeData::new().content_text_style(theme_style))
3436                        .build(app)
3437                },
3438                dialog,
3439            );
3440
3441            open(tester);
3442
3443            assert_eq!(
3444                text_style_in_dialog(tester, content_text),
3445                Some(content_text_style)
3446            );
3447        });
3448    }
3449
3450    #[test]
3451    fn material3_simple_dialog_custom_content_text_style_theme() {
3452        test_widgets(|tester| {
3453            let content_text = "Content";
3454            let content_text_style = TextStyle::new().color(Colors::PURPLE.primary());
3455            let dialog = SimpleDialog::new().children([Text::new(content_text).into_widget()]);
3456            let theme_style = content_text_style.clone();
3457            pump_with_dialog(
3458                tester,
3459                move |app| {
3460                    ThemeData::builder()
3461                        .text_theme(crate::text_theme::TextTheme::new().body_medium(theme_style))
3462                        .build(app)
3463                },
3464                dialog,
3465            );
3466
3467            open(tester);
3468
3469            assert_eq!(
3470                text_style_in_dialog(tester, content_text).and_then(|style| style.color),
3471                content_text_style.color
3472            );
3473        });
3474    }
3475
3476    #[test]
3477    fn material2_simple_dialog_custom_content_text_style_theme() {
3478        test_widgets(|tester| {
3479            let content_text = "Content";
3480            let content_text_style = TextStyle::new().color(Colors::TEAL.primary());
3481            let dialog = SimpleDialog::new().children([Text::new(content_text).into_widget()]);
3482            let theme_style = content_text_style.clone();
3483            pump_with_dialog(
3484                tester,
3485                move |app| {
3486                    ThemeData::builder()
3487                        .use_material3(false)
3488                        .text_theme(crate::text_theme::TextTheme::new().title_medium(theme_style))
3489                        .build(app)
3490                },
3491                dialog,
3492            );
3493
3494            open(tester);
3495
3496            assert_eq!(
3497                text_style_in_dialog(tester, content_text).and_then(|style| style.color),
3498                content_text_style.color
3499            );
3500        });
3501    }
3502
3503    #[test]
3504    fn custom_dialog_shape() {
3505        test_widgets(|tester| {
3506            let custom_border = rounded(16.0);
3507            let dialog = AlertDialog::new().actions([]).shape(custom_border);
3508            pump_with_dialog(tester, m3, dialog);
3509
3510            open(tester);
3511
3512            assert_shape(tester, &custom_border);
3513        });
3514    }
3515
3516    #[test]
3517    fn null_dialog_shape() {
3518        test_widgets(|tester| {
3519            let dialog = AlertDialog::new().actions([]);
3520            pump_with_dialog(tester, m3, dialog);
3521
3522            open(tester);
3523
3524            assert_shape(tester, &*default_m3_dialog_shape());
3525        });
3526    }
3527
3528    #[test]
3529    fn rectangular_dialog_shape() {
3530        test_widgets(|tester| {
3531            let custom_border = Border::default();
3532            let dialog = AlertDialog::new().actions([]).shape(custom_border);
3533            pump_with_dialog(tester, m3, dialog);
3534
3535            open(tester);
3536
3537            assert_shape(tester, &custom_border);
3538        });
3539    }
3540
3541    #[test]
3542    fn custom_dialog_alignment() {
3543        test_widgets(|tester| {
3544            let dialog = AlertDialog::new()
3545                .actions([])
3546                .alignment(AlignmentGeometry::BOTTOM_LEFT);
3547            pump_with_dialog(tester, m3, dialog);
3548
3549            open(tester);
3550
3551            let bottom_left = tester.get_rect(dialog_material(tester)).bottom_left();
3552            assert_eq!(bottom_left.dx(), 40.0);
3553            assert_eq!(bottom_left.dy(), 576.0);
3554        });
3555    }
3556
3557    /// Dart's `SimpleDialog(title: Text('Title'), children: [option(42), Text('Second
3558    /// option')])` whose first option pops 42.
3559    fn simple_dialog_popping_42() -> WidgetBuilder {
3560        Rc::new(|_app, context| {
3561            SimpleDialog::new()
3562                .title(Text::new("Title"))
3563                .children([
3564                    SimpleDialogOption::new()
3565                        .on_pressed(waft_foundation::Listener::new(move |app| {
3566                            Navigator::pop(app, context, Some(Rc::new(42_i32)));
3567                        }))
3568                        .child(Text::new("First option"))
3569                        .into_widget(),
3570                    SimpleDialogOption::new()
3571                        .child(Text::new("Second option"))
3572                        .into_widget(),
3573                ])
3574                .into_widget()
3575        })
3576    }
3577
3578    #[test]
3579    fn simple_dialog_control_test() {
3580        test_widgets(|tester| {
3581            let context = app_with_disabled_button(tester, "Go");
3582
3583            let result = result_of::<i32>(
3584                tester,
3585                Show::default().on(tester, context, simple_dialog_popping_42()),
3586            );
3587
3588            tester.pump_and_settle_by(Duration::from_secs(1));
3589            assert_eq!(shows(tester, "Title"), 1);
3590            tester.tap(find::text("First option"));
3591
3592            assert_eq!(result.get(), Some(Some(42)));
3593        });
3594    }
3595
3596    #[test]
3597    fn can_show_dialog_using_navigator_global_key() {
3598        test_widgets(|tester| {
3599            let navigator = GlobalKey::new();
3600            let root = {
3601                let app = tester.cell.borrow();
3602                crate::app::MaterialApp::new()
3603                    .theme(m3(&app))
3604                    .navigator_key(navigator.clone())
3605                    .home(Material::new().child(Center::new().child(Text::new("Go"))))
3606                    .into_widget()
3607            };
3608            tester.pump_widget(root);
3609
3610            let context = navigator
3611                .current_context(&tester.cell.borrow())
3612                .expect("the navigator is mounted");
3613            let result = result_of::<i32>(
3614                tester,
3615                Show::default().on(tester, context, simple_dialog_popping_42()),
3616            );
3617
3618            tester.pump_and_settle_by(Duration::from_secs(1));
3619            assert_eq!(shows(tester, "Title"), 1);
3620            tester.tap(find::text("First option"));
3621
3622            assert_eq!(result.get(), Some(Some(42)));
3623        });
3624    }
3625
3626    #[test]
3627    fn custom_padding_on_simple_dialog_option() {
3628        test_widgets(|tester| {
3629            let custom_padding = EdgeInsets::from_ltrb(4.0, 10.0, 8.0, 6.0);
3630            let dialog =
3631                SimpleDialog::new()
3632                    .title(Text::new("Title"))
3633                    .children([SimpleDialogOption::new()
3634                        .on_pressed(waft_foundation::Listener::new(|_app| {}))
3635                        .padding(custom_padding)
3636                        .child(Text::new("First option"))
3637                        .into_widget()]);
3638            pump_with_dialog(tester, m3, dialog);
3639            open(tester);
3640
3641            let dialog_rect =
3642                tester.get_rect(tester.element(find::by_type::<SimpleDialogOption>()));
3643            let text_rect = tester.get_rect(find::text("First option"));
3644
3645            assert_eq!(text_rect.left, dialog_rect.left + custom_padding.left);
3646            assert_eq!(text_rect.top, dialog_rect.top + custom_padding.top);
3647            assert_eq!(text_rect.right, dialog_rect.right - custom_padding.right);
3648            assert_eq!(text_rect.bottom, dialog_rect.bottom - custom_padding.bottom);
3649        });
3650    }
3651
3652    /// Dart's `Container(width: 100.0, height: 100.0, alignment: Alignment.center, child:
3653    /// Text(text))`.
3654    fn hundred_square(text: &'static str) -> WidgetBuilder {
3655        Rc::new(move |_app, _context| {
3656            Container::new()
3657                .width(100.0)
3658                .height(100.0)
3659                .alignment(AlignmentGeometry::CENTER)
3660                .child(Text::new(text))
3661                .into_widget()
3662        })
3663    }
3664
3665    #[test]
3666    fn barrier_dismissible() {
3667        test_widgets(|tester| {
3668            let context = app_with_disabled_button(tester, "Go");
3669
3670            drop(Show::default().on(tester, context, hundred_square("Dialog1")));
3671
3672            tester.pump_and_settle_by(Duration::from_secs(1));
3673            assert_eq!(shows(tester, "Dialog1"), 1);
3674
3675            // Tap on the barrier.
3676            tap_at(tester, Offset::new(10.0, 10.0));
3677
3678            tester.pump_and_settle_by(Duration::from_secs(1));
3679            assert_eq!(shows(tester, "Dialog1"), 0);
3680
3681            let show = Show {
3682                barrier_dismissible: false,
3683                ..Show::default()
3684            };
3685            drop(show.on(tester, context, hundred_square("Dialog2")));
3686
3687            tester.pump_and_settle_by(Duration::from_secs(1));
3688            assert_eq!(shows(tester, "Dialog2"), 1);
3689
3690            // Tap on the barrier, which shouldn't do anything this time.
3691            tap_at(tester, Offset::new(10.0, 10.0));
3692
3693            tester.pump_and_settle_by(Duration::from_secs(1));
3694            assert_eq!(shows(tester, "Dialog2"), 1);
3695        });
3696    }
3697
3698    pub(crate) fn last_barrier_color(tester: &WidgetTester) -> Option<Color> {
3699        let barriers = find::by_type::<waft_widgets::ModalBarrier>().evaluate(tester);
3700        tester.widget::<waft_widgets::ModalBarrier, _>(
3701            *barriers.last().expect("a modal barrier"),
3702            |barrier| barrier.color,
3703        )
3704    }
3705
3706    #[test]
3707    fn barrier_color() {
3708        test_widgets(|tester| {
3709            pump_app(tester, m3, |_app| {
3710                Center::new().child(Text::new("Test")).into_widget()
3711            });
3712            let context = find::text("Test").evaluate(tester)[0];
3713            let dialog: WidgetBuilder = Rc::new(|_app, _context| Text::new("Dialog").into_widget());
3714
3715            // Test default barrier color
3716            drop(Show::default().on(tester, context, Rc::clone(&dialog)));
3717            tester.pump_and_settle();
3718            assert_eq!(last_barrier_color(tester), Some(Colors::BLACK54));
3719
3720            // Dismiss it and test a custom barrier color
3721            tap_at(tester, Offset::new(10.0, 10.0));
3722            let show = Show {
3723                barrier_color: Some(Colors::PINK.primary()),
3724                ..Show::default()
3725            };
3726            drop(show.on(tester, context, dialog));
3727            tester.pump_and_settle();
3728            assert_eq!(last_barrier_color(tester), Some(Colors::PINK.primary()));
3729        });
3730    }
3731
3732    /// Dart's `ElevatedButton(key: key, onPressed: () {}, child: Text(text))`.
3733    fn button(key: Option<&GlobalKey>, text: &str) -> WidgetRef {
3734        let button = ElevatedButton::new(
3735            Some(waft_foundation::Listener::new(|_app| {})),
3736            Some(Text::new(text)),
3737        );
3738        match key {
3739            Some(key) => button.key(key.clone().into()).into_widget(),
3740            None => button.into_widget(),
3741        }
3742    }
3743
3744    /// The size of the first `Material` under the `AlertDialog`: the dialog itself.
3745    fn alert_dialog_material_size(tester: &WidgetTester) -> Size {
3746        let dialog = find::by_type::<AlertDialog>().evaluate(tester)[0];
3747        tester
3748            .get_rect(tester.descendants_of_type::<Material>(dialog)[0])
3749            .size()
3750    }
3751
3752    #[test]
3753    fn alert_dialog_actions_padding_defaults() {
3754        test_widgets(|tester| {
3755            let dialog = AlertDialog::new()
3756                .title(Text::new("title"))
3757                .content(Text::new("content"))
3758                .actions([button(None, "button")]);
3759            pump_with_dialog(tester, m3, dialog);
3760            open(tester);
3761
3762            // The [AlertDialog] is the entire screen, since it also contains the scrim.
3763            // The first [Material] child of [AlertDialog] is the actual dialog
3764            // itself.
3765            let dialog_size = alert_dialog_material_size(tester);
3766            let actions_size = overflow_bar_padding(tester).size();
3767
3768            assert_eq!(actions_size.width(), dialog_size.width());
3769        });
3770    }
3771
3772    #[test]
3773    fn alert_dialog_actions_padding_surrounds_actions_with_padding() {
3774        test_widgets(|tester| {
3775            let dialog = AlertDialog::new()
3776                .title(Text::new("title"))
3777                .content(Text::new("content"))
3778                .actions([button(None, "button")])
3779                // The OverflowBar is inset by the buttonPadding/2 + actionsPadding
3780                .button_padding(EdgeInsetsGeometry::ZERO)
3781                .actions_padding(EdgeInsetsGeometry::all(30.0));
3782            pump_with_dialog(tester, m3, dialog);
3783            open(tester);
3784
3785            let dialog_size = alert_dialog_material_size(tester);
3786            let actions_size = tester
3787                .get_rect(find::by_type::<OverflowBar>().evaluate(tester)[0])
3788                .size();
3789
3790            assert_eq!(actions_size.width(), dialog_size.width() - (30.0 * 2.0));
3791        });
3792    }
3793
3794    /// Dart's `AlertDialog.buttonPadding` cases: `spacing` between the buttons and
3795    /// `top`, `bottom` and `right` between them and the bar's padding edges.
3796    fn check_button_padding(
3797        tester: &mut WidgetTester,
3798        theme: impl FnOnce(&App) -> ThemeData,
3799        button_padding: Option<EdgeInsetsGeometry>,
3800        spacing: f64,
3801        top: f64,
3802        bottom: f64,
3803        right: f64,
3804    ) {
3805        let key1 = GlobalKey::new();
3806        let key2 = GlobalKey::new();
3807        let mut dialog = AlertDialog::new()
3808            .title(Text::new("title"))
3809            .content(Text::new("content"))
3810            .actions([
3811                button(Some(&key1), "button 1"),
3812                button(Some(&key2), "button 2"),
3813            ]);
3814        dialog.button_padding = button_padding;
3815        pump_with_dialog(tester, theme, dialog);
3816        open(tester);
3817
3818        let rect1 = rect_of_key(tester, &key1);
3819        let rect2 = rect_of_key(tester, &key2);
3820        let bar = overflow_bar_padding(tester);
3821
3822        // Padding between both buttons
3823        assert_f32_equals(
3824            rect2.bottom_left().dx(),
3825            rect1.bottom_right().dx() + spacing,
3826        );
3827
3828        // Padding between button and edges of the button bar
3829        // First button
3830        assert_f32_equals(rect1.top_right().dy(), bar.top_right().dy() + top);
3831        assert_f32_equals(rect1.bottom_right().dy(), bar.bottom_right().dy() - bottom);
3832
3833        // Second button
3834        assert_f32_equals(rect2.top_right().dy(), bar.top_right().dy() + top);
3835        assert_f32_equals(rect2.bottom_right().dy(), bar.bottom_right().dy() - bottom);
3836        assert_f32_equals(rect2.bottom_right().dx(), bar.bottom_right().dx() - right);
3837    }
3838
3839    #[test]
3840    fn material2_alert_dialog_button_padding_defaults() {
3841        test_widgets(|tester| {
3842            check_button_padding(tester, material2_theme, None, 8.0, 8.0, 8.0, 8.0);
3843        });
3844    }
3845
3846    #[test]
3847    fn material3_alert_dialog_button_padding_defaults() {
3848        test_widgets(|tester| {
3849            check_button_padding(tester, material3_theme, None, 8.0, 0.0, 24.0, 24.0);
3850        });
3851    }
3852
3853    #[test]
3854    fn alert_dialog_button_padding_custom_values() {
3855        test_widgets(|tester| {
3856            let half = (10.0 + 20.0) / 2.0;
3857            check_button_padding(
3858                tester,
3859                m2,
3860                Some(EdgeInsetsGeometry::only(10.0, 0.0, 20.0, 0.0)),
3861                half,
3862                half,
3863                half,
3864                half,
3865            );
3866        });
3867    }
3868
3869    /// Dart's `Dialog children padding is correct` group.
3870    mod children_padding {
3871        use waft_widgets::Icon;
3872
3873        use super::*;
3874        use crate::icons::Icons;
3875
3876        const TEXT_SCALE_FACTORS: [f64; 5] = [0.5, 1.0, 1.5, 2.0, 3.0];
3877
3878        fn padding_scale_factor(text_scale_factor: f64) -> f64 {
3879            match text_scale_factor {
3880                0.5 | 1.0 => 1.0,
3881                1.5 => 2.0 / 3.0,
3882                _ => 1.0 / 3.0,
3883            }
3884        }
3885
3886        /// The group's keys and widgets, made for each case.
3887        struct Parts {
3888            icon_key: GlobalKey,
3889            title_key: GlobalKey,
3890            content_key: GlobalKey,
3891            children_key: GlobalKey,
3892        }
3893
3894        impl Parts {
3895            fn new() -> Parts {
3896                Parts {
3897                    icon_key: GlobalKey::new(),
3898                    title_key: GlobalKey::new(),
3899                    content_key: GlobalKey::new(),
3900                    children_key: GlobalKey::new(),
3901                }
3902            }
3903
3904            fn icon(&self) -> WidgetRef {
3905                Icon::new(Some(Icons::ac_unit()))
3906                    .key(self.icon_key.clone().into())
3907                    .into_widget()
3908            }
3909
3910            fn title(&self) -> WidgetRef {
3911                Text::new("title")
3912                    .key(self.title_key.clone().into())
3913                    .into_widget()
3914            }
3915
3916            fn content(&self) -> WidgetRef {
3917                Text::new("content")
3918                    .key(self.content_key.clone().into())
3919                    .into_widget()
3920            }
3921
3922            fn actions(&self) -> Vec<WidgetRef> {
3923                vec![button(None, "button")]
3924            }
3925
3926            fn children(&self) -> Vec<WidgetRef> {
3927                vec![
3928                    SimpleDialogOption::new()
3929                        .key(self.children_key.clone().into())
3930                        .child(Text::new("child"))
3931                        .on_pressed(waft_foundation::Listener::new(|_app| {}))
3932                        .into_widget(),
3933                ]
3934            }
3935        }
3936
3937        /// What the group's finders find.
3938        enum Part<'a> {
3939            Key(&'a GlobalKey),
3940            Actions,
3941        }
3942
3943        fn rect(tester: &WidgetTester, part: Part<'_>) -> Rect {
3944            match part {
3945                Part::Key(key) => rect_of_key(tester, key),
3946                Part::Actions => overflow_bar_padding(tester),
3947            }
3948        }
3949
3950        fn dialog_rect(tester: &WidgetTester) -> Rect {
3951            tester.get_rect(dialog_material(tester))
3952        }
3953
3954        /// Dart's `openDialog(tester, dialog, textScaleFactor, isM3:)`.
3955        fn open_dialog<K>(
3956            tester: &mut WidgetTester,
3957            dialog: impl IntoWidget<K>,
3958            text_scale_factor: f64,
3959            is_m3: bool,
3960        ) {
3961            app_with_dialog(
3962                tester,
3963                move |app| ThemeData::builder().use_material3(is_m3).build(app),
3964                dialog.into_widget(),
3965                text_scale_factor,
3966                None,
3967            );
3968            open(tester);
3969        }
3970
3971        fn expect_left_edge_padding(
3972            tester: &WidgetTester,
3973            finder: Part<'_>,
3974            text_scale_factor: f64,
3975            unscaled_value: f64,
3976        ) {
3977            let dialog = dialog_rect(tester);
3978            let found = rect(tester, finder);
3979            let padding = unscaled_value * padding_scale_factor(text_scale_factor);
3980            assert_f32_equals(dialog.top_left().dx(), found.top_left().dx() - padding);
3981            assert_f32_equals(
3982                dialog.bottom_left().dx(),
3983                found.bottom_left().dx() - padding,
3984            );
3985        }
3986
3987        fn expect_right_edge_padding(
3988            tester: &WidgetTester,
3989            finder: Part<'_>,
3990            text_scale_factor: f64,
3991            unscaled_value: f64,
3992        ) {
3993            let dialog = dialog_rect(tester);
3994            let found = rect(tester, finder);
3995            let padding = unscaled_value * padding_scale_factor(text_scale_factor);
3996            assert_f32_equals(dialog.top_right().dx(), found.top_right().dx() + padding);
3997            assert_f32_equals(
3998                dialog.bottom_right().dx(),
3999                found.bottom_right().dx() + padding,
4000            );
4001        }
4002
4003        fn expect_top_edge_padding(
4004            tester: &WidgetTester,
4005            finder: Part<'_>,
4006            text_scale_factor: f64,
4007            unscaled_value: f64,
4008        ) {
4009            let dialog = dialog_rect(tester);
4010            let found = rect(tester, finder);
4011            let padding = unscaled_value * padding_scale_factor(text_scale_factor);
4012            assert_f32_equals(dialog.top_left().dy(), found.top_left().dy() - padding);
4013            assert_f32_equals(dialog.top_right().dy(), found.top_right().dy() - padding);
4014        }
4015
4016        fn expect_bottom_edge_padding(
4017            tester: &WidgetTester,
4018            finder: Part<'_>,
4019            text_scale_factor: f64,
4020            unscaled_value: f64,
4021        ) {
4022            let dialog = dialog_rect(tester);
4023            let found = rect(tester, finder);
4024            let padding = unscaled_value * padding_scale_factor(text_scale_factor);
4025            assert_f32_equals(
4026                dialog.bottom_left().dy(),
4027                found.bottom_right().dy() + padding,
4028            );
4029            assert_f32_equals(
4030                dialog.bottom_right().dy(),
4031                found.bottom_right().dy() + padding,
4032            );
4033        }
4034
4035        fn expect_vertical_inner_padding(
4036            tester: &WidgetTester,
4037            top: Part<'_>,
4038            bottom: Part<'_>,
4039            value: f64,
4040        ) {
4041            let top = rect(tester, top);
4042            let bottom = rect(tester, bottom);
4043            assert_f32_equals(top.bottom_left().dy(), bottom.top_left().dy() - value);
4044            assert_f32_equals(top.bottom_right().dy(), bottom.top_right().dy() - value);
4045        }
4046
4047        fn expect_actions_at_the_edges(tester: &WidgetTester, text_scale_factor: f64) {
4048            expect_left_edge_padding(tester, Part::Actions, text_scale_factor, 0.0);
4049            expect_right_edge_padding(tester, Part::Actions, text_scale_factor, 0.0);
4050            expect_bottom_edge_padding(tester, Part::Actions, text_scale_factor, 0.0);
4051        }
4052
4053        #[test]
4054        fn alert_dialog_padding_is_correct_when_only_icon_and_actions_are_specified() {
4055            for text_scale_factor in TEXT_SCALE_FACTORS {
4056                test_widgets(|tester| {
4057                    let parts = Parts::new();
4058                    let dialog = AlertDialog::new()
4059                        .icon(parts.icon())
4060                        .actions(parts.actions());
4061                    open_dialog(tester, dialog, text_scale_factor, false);
4062                    let icon = || Part::Key(&parts.icon_key);
4063
4064                    expect_top_edge_padding(tester, icon(), text_scale_factor, 24.0);
4065                    expect_left_edge_padding(tester, icon(), text_scale_factor, 24.0);
4066                    expect_right_edge_padding(tester, icon(), text_scale_factor, 24.0);
4067                    expect_vertical_inner_padding(tester, icon(), Part::Actions, 24.0);
4068                    expect_actions_at_the_edges(tester, text_scale_factor);
4069                });
4070            }
4071        }
4072
4073        #[test]
4074        fn alert_dialog_padding_is_correct_when_only_icon_title_and_actions_are_specified() {
4075            for text_scale_factor in TEXT_SCALE_FACTORS {
4076                test_widgets(|tester| {
4077                    let parts = Parts::new();
4078                    let dialog = AlertDialog::new()
4079                        .icon(parts.icon())
4080                        .title(parts.title())
4081                        .actions(parts.actions());
4082                    open_dialog(tester, dialog, text_scale_factor, false);
4083                    let icon = || Part::Key(&parts.icon_key);
4084                    let title = || Part::Key(&parts.title_key);
4085
4086                    expect_top_edge_padding(tester, icon(), text_scale_factor, 24.0);
4087                    expect_left_edge_padding(tester, icon(), text_scale_factor, 24.0);
4088                    expect_right_edge_padding(tester, icon(), text_scale_factor, 24.0);
4089                    expect_vertical_inner_padding(tester, icon(), title(), 16.0);
4090                    expect_left_edge_padding(tester, title(), text_scale_factor, 24.0);
4091                    expect_right_edge_padding(tester, title(), text_scale_factor, 24.0);
4092                    expect_vertical_inner_padding(tester, title(), Part::Actions, 20.0);
4093                    expect_actions_at_the_edges(tester, text_scale_factor);
4094                });
4095            }
4096        }
4097
4098        #[test]
4099        fn alert_dialog_padding_is_correct_when_only_icon_content_and_actions_are_specified() {
4100            for text_scale_factor in TEXT_SCALE_FACTORS {
4101                for is_m3 in [true, false] {
4102                    test_widgets(|tester| {
4103                        let parts = Parts::new();
4104                        let dialog = AlertDialog::new()
4105                            .icon(parts.icon())
4106                            .content(parts.content())
4107                            .actions(parts.actions());
4108                        open_dialog(tester, dialog, text_scale_factor, is_m3);
4109                        let icon = || Part::Key(&parts.icon_key);
4110                        let content = || Part::Key(&parts.content_key);
4111
4112                        expect_top_edge_padding(tester, icon(), text_scale_factor, 24.0);
4113                        expect_left_edge_padding(tester, icon(), text_scale_factor, 24.0);
4114                        expect_right_edge_padding(tester, icon(), text_scale_factor, 24.0);
4115                        expect_vertical_inner_padding(
4116                            tester,
4117                            icon(),
4118                            content(),
4119                            if is_m3 { 16.0 } else { 20.0 },
4120                        );
4121                        expect_left_edge_padding(tester, content(), text_scale_factor, 24.0);
4122                        expect_right_edge_padding(tester, content(), text_scale_factor, 24.0);
4123                        expect_vertical_inner_padding(tester, content(), Part::Actions, 24.0);
4124                        expect_actions_at_the_edges(tester, text_scale_factor);
4125                    });
4126                }
4127            }
4128        }
4129
4130        #[test]
4131        fn alert_dialog_padding_is_correct_when_only_title_and_actions_are_specified() {
4132            for text_scale_factor in TEXT_SCALE_FACTORS {
4133                test_widgets(|tester| {
4134                    let parts = Parts::new();
4135                    let dialog = AlertDialog::new()
4136                        .title(parts.title())
4137                        .actions(parts.actions());
4138                    open_dialog(tester, dialog, text_scale_factor, false);
4139                    let title = || Part::Key(&parts.title_key);
4140
4141                    expect_top_edge_padding(tester, title(), text_scale_factor, 24.0);
4142                    expect_left_edge_padding(tester, title(), text_scale_factor, 24.0);
4143                    expect_right_edge_padding(tester, title(), text_scale_factor, 24.0);
4144                    expect_vertical_inner_padding(tester, title(), Part::Actions, 20.0);
4145                    expect_actions_at_the_edges(tester, text_scale_factor);
4146                });
4147            }
4148        }
4149
4150        #[test]
4151        fn alert_dialog_padding_is_correct_when_only_content_and_actions_are_specified() {
4152            for text_scale_factor in TEXT_SCALE_FACTORS {
4153                test_widgets(|tester| {
4154                    let parts = Parts::new();
4155                    let dialog = AlertDialog::new()
4156                        .content(parts.content())
4157                        .actions(parts.actions());
4158                    open_dialog(tester, dialog, text_scale_factor, false);
4159                    let content = || Part::Key(&parts.content_key);
4160
4161                    expect_top_edge_padding(tester, content(), text_scale_factor, 20.0);
4162                    expect_left_edge_padding(tester, content(), text_scale_factor, 24.0);
4163                    expect_right_edge_padding(tester, content(), text_scale_factor, 24.0);
4164                    expect_vertical_inner_padding(tester, content(), Part::Actions, 24.0);
4165                    expect_actions_at_the_edges(tester, text_scale_factor);
4166                });
4167            }
4168        }
4169
4170        #[test]
4171        fn alert_dialog_padding_is_correct_when_title_content_and_actions_are_specified() {
4172            for text_scale_factor in TEXT_SCALE_FACTORS {
4173                test_widgets(|tester| {
4174                    let parts = Parts::new();
4175                    let dialog = AlertDialog::new()
4176                        .title(parts.title())
4177                        .content(parts.content())
4178                        .actions(parts.actions());
4179                    open_dialog(tester, dialog, text_scale_factor, false);
4180                    let title = || Part::Key(&parts.title_key);
4181                    let content = || Part::Key(&parts.content_key);
4182
4183                    expect_top_edge_padding(tester, title(), text_scale_factor, 24.0);
4184                    expect_left_edge_padding(tester, title(), text_scale_factor, 24.0);
4185                    expect_right_edge_padding(tester, title(), text_scale_factor, 24.0);
4186                    expect_vertical_inner_padding(tester, title(), content(), 20.0);
4187                    expect_left_edge_padding(tester, content(), text_scale_factor, 24.0);
4188                    expect_right_edge_padding(tester, content(), text_scale_factor, 24.0);
4189                    expect_vertical_inner_padding(tester, content(), Part::Actions, 24.0);
4190                    expect_actions_at_the_edges(tester, text_scale_factor);
4191                });
4192            }
4193        }
4194
4195        #[test]
4196        fn simple_dialog_padding_is_correct_when_only_children_are_specified() {
4197            for text_scale_factor in TEXT_SCALE_FACTORS {
4198                test_widgets(|tester| {
4199                    let parts = Parts::new();
4200                    let dialog = SimpleDialog::new().children(parts.children());
4201                    open_dialog(tester, dialog, text_scale_factor, false);
4202                    let children = || Part::Key(&parts.children_key);
4203
4204                    expect_top_edge_padding(tester, children(), text_scale_factor, 12.0);
4205                    expect_left_edge_padding(tester, children(), text_scale_factor, 0.0);
4206                    expect_right_edge_padding(tester, children(), text_scale_factor, 0.0);
4207                    expect_bottom_edge_padding(tester, children(), text_scale_factor, 16.0);
4208                });
4209            }
4210        }
4211
4212        #[test]
4213        fn simple_dialog_padding_is_correct_when_title_and_children_are_specified() {
4214            for text_scale_factor in TEXT_SCALE_FACTORS {
4215                test_widgets(|tester| {
4216                    let parts = Parts::new();
4217                    let dialog = SimpleDialog::new()
4218                        .title(parts.title())
4219                        .children(parts.children());
4220                    open_dialog(tester, dialog, text_scale_factor, false);
4221                    let title = || Part::Key(&parts.title_key);
4222                    let children = || Part::Key(&parts.children_key);
4223
4224                    expect_top_edge_padding(tester, title(), text_scale_factor, 24.0);
4225                    expect_left_edge_padding(tester, title(), text_scale_factor, 24.0);
4226                    expect_right_edge_padding(tester, title(), text_scale_factor, 24.0);
4227                    expect_vertical_inner_padding(tester, title(), children(), 12.0);
4228                    expect_left_edge_padding(tester, children(), text_scale_factor, 0.0);
4229                    expect_right_edge_padding(tester, children(), text_scale_factor, 0.0);
4230                    expect_bottom_edge_padding(tester, children(), text_scale_factor, 16.0);
4231                });
4232            }
4233        }
4234    }
4235
4236    /// Dart's two actions with long labels, keyed.
4237    fn long_buttons(
4238        key1: &GlobalKey,
4239        key2: &GlobalKey,
4240        label1: &str,
4241        label2: &str,
4242    ) -> [WidgetRef; 2] {
4243        [button(Some(key1), label1), button(Some(key2), label2)]
4244    }
4245
4246    fn overflowing_dialog(key1: &GlobalKey, key2: &GlobalKey) -> AlertDialog {
4247        AlertDialog::new()
4248            .title(Text::new("title"))
4249            .content(Text::new("content"))
4250            .actions(long_buttons(
4251                key1,
4252                key2,
4253                "Looooooooooooooong button 1",
4254                "Looooooooooooooong button 2",
4255            ))
4256    }
4257
4258    #[test]
4259    fn dialogs_can_set_the_vertical_direction_of_overflowing_actions() {
4260        test_widgets(|tester| {
4261            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
4262            let dialog =
4263                overflowing_dialog(&key1, &key2).actions_overflow_direction(VerticalDirection::Up);
4264            pump_with_dialog(tester, m3, dialog);
4265            open(tester);
4266
4267            let button_one_rect = rect_of_key(tester, &key1);
4268            let button_two_rect = rect_of_key(tester, &key2);
4269            // Second [ElevatedButton] should appear above the first.
4270            assert!(button_two_rect.bottom <= button_one_rect.top);
4271        });
4272    }
4273
4274    #[test]
4275    fn dialogs_have_no_spacing_by_default_for_overflowing_actions() {
4276        test_widgets(|tester| {
4277            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
4278            pump_with_dialog(tester, m3, overflowing_dialog(&key1, &key2));
4279            open(tester);
4280
4281            let button_one_rect = rect_of_key(tester, &key1);
4282            let button_two_rect = rect_of_key(tester, &key2);
4283            assert_f32_equals(button_one_rect.bottom, button_two_rect.top);
4284        });
4285    }
4286
4287    #[test]
4288    fn dialogs_can_set_the_button_spacing_of_overflowing_actions() {
4289        test_widgets(|tester| {
4290            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
4291            let dialog = overflowing_dialog(&key1, &key2).actions_overflow_button_spacing(10.0);
4292            pump_with_dialog(tester, m3, dialog);
4293            open(tester);
4294
4295            let button_one_rect = rect_of_key(tester, &key1);
4296            let button_two_rect = rect_of_key(tester, &key2);
4297            assert_f32_equals(button_one_rect.bottom, button_two_rect.top - 10.0);
4298        });
4299    }
4300
4301    #[test]
4302    fn dialogs_can_set_the_alignment_of_the_overflow_bar() {
4303        test_widgets(|tester| {
4304            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
4305            let dialog = AlertDialog::new()
4306                .title(Text::new("title"))
4307                .content(Text::new("content"))
4308                .actions(long_buttons(
4309                    &key1,
4310                    &key2,
4311                    "Loooooooooong button 1",
4312                    "Loooooooooooooonger button 2",
4313                ))
4314                .actions_overflow_alignment(OverflowBarAlignment::Center);
4315            pump_with_dialog(tester, m3, dialog);
4316            open(tester);
4317
4318            let button_one_rect = rect_of_key(tester, &key1);
4319            let button_two_rect = rect_of_key(tester, &key2);
4320            assert_f32_equals(button_one_rect.center().dx(), button_two_rect.center().dx());
4321        });
4322    }
4323
4324    /// Dart's `Localizations(locale: Locale('en', 'US'), delegates: [widgets, material],
4325    /// child: child)`.
4326    fn localized(child: WidgetRef) -> WidgetRef {
4327        waft_widgets::Localizations::new(
4328            waft_embedder::Locale::new("en").country_code("US"),
4329            vec![
4330                waft_widgets::DefaultWidgetsLocalizations::delegate(),
4331                crate::material_localizations::DefaultMaterialLocalizations::delegate(),
4332            ],
4333        )
4334        .child(child)
4335        .into_widget()
4336    }
4337
4338    /// A navigator whose first route is a `PageRouteBuilder` building `page`.
4339    fn navigator_of_page(page: WidgetBuilder) -> Navigator {
4340        Navigator::new().on_generate_route(move |app, _settings| {
4341            let page = Rc::clone(&page);
4342            let page_builder: RoutePageBuilder =
4343                Rc::new(move |app, context, _animation, _secondary_animation| page(app, context));
4344            Some(PageRouteBuilder::new(app, page_builder).into_erased())
4345        })
4346    }
4347
4348    /// A context `builder` saw: Dart's `late BuildContext`.
4349    fn context_cell() -> Rc<Cell<Option<BuildContext>>> {
4350        Rc::new(Cell::new(None))
4351    }
4352
4353    fn seen(context: &Cell<Option<BuildContext>>) -> BuildContext {
4354        context.get().expect("the builder ran")
4355    }
4356
4357    /// Dart's `Placeholder()` where its constraints are bounded: a box filling them, keyed so a
4358    /// case can find it (Waft has no `Placeholder`).
4359    pub(crate) fn placeholder(key: &GlobalKey) -> WidgetRef {
4360        SizedBox::expand().key(key.clone().into()).into_widget()
4361    }
4362
4363    #[test]
4364    fn dialogs_removes_media_query_padding_and_view_insets() {
4365        test_widgets(|tester| {
4366            let outer_context = context_cell();
4367            let route_context = context_cell();
4368            let dialog_context = context_cell();
4369            let outer = Rc::clone(&outer_context);
4370            tester.pump_widget(localized(
4371                MediaQuery::new(
4372                    MediaQueryData::new()
4373                        .padding(EdgeInsets::all(50.0))
4374                        .view_insets(EdgeInsets::only(25.0, 0.0, 0.0, 75.0)),
4375                    navigator_of_page(Rc::new(move |_app, context| {
4376                        outer.set(Some(context));
4377                        Container::new().into_widget()
4378                    })),
4379                )
4380                .into_widget(),
4381            ));
4382
4383            let route = Rc::clone(&route_context);
4384            let dialog = Rc::clone(&dialog_context);
4385            let show = Show {
4386                barrier_dismissible: false,
4387                ..Show::default()
4388            };
4389            drop(show.on(
4390                tester,
4391                seen(&outer_context),
4392                Rc::new(move |_app, context| {
4393                    route.set(Some(context));
4394                    let dialog = Rc::clone(&dialog);
4395                    Dialog::new()
4396                        .child(Builder::new(move |_app, context| {
4397                            dialog.set(Some(context));
4398                            SizedBox::expand().into_widget()
4399                        }))
4400                        .into_widget()
4401                }),
4402            ));
4403
4404            tester.pump();
4405
4406            let mut app = tester.cell.borrow_mut();
4407            let padding = |app: &mut App, context: &Cell<Option<BuildContext>>| {
4408                MediaQuery::of(app, seen(context)).padding
4409            };
4410            let view_insets = |app: &mut App, context: &Cell<Option<BuildContext>>| {
4411                MediaQuery::of(app, seen(context)).view_insets
4412            };
4413            assert_eq!(padding(&mut app, &outer_context), EdgeInsets::all(50.0));
4414            assert_eq!(padding(&mut app, &route_context), EdgeInsets::ZERO);
4415            assert_eq!(padding(&mut app, &dialog_context), EdgeInsets::ZERO);
4416            assert_eq!(
4417                view_insets(&mut app, &outer_context),
4418                EdgeInsets::only(25.0, 0.0, 0.0, 75.0)
4419            );
4420            assert_eq!(
4421                view_insets(&mut app, &route_context),
4422                EdgeInsets::only(25.0, 0.0, 0.0, 75.0)
4423            );
4424            assert_eq!(view_insets(&mut app, &dialog_context), EdgeInsets::ZERO);
4425        });
4426    }
4427
4428    #[test]
4429    fn dialog_widget_insets_by_view_insets() {
4430        test_widgets(|tester| {
4431            let key = GlobalKey::new();
4432            tester.pump_widget(
4433                MediaQuery::new(
4434                    MediaQueryData::new()
4435                        .view_insets(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)),
4436                    Dialog::new().child(placeholder(&key)),
4437                )
4438                .into_widget(),
4439            );
4440            let inset = Rect::from_ltrb(
4441                10.0 + 40.0,
4442                20.0 + 24.0,
4443                800.0 - (40.0 + 30.0),
4444                600.0 - (24.0 + 40.0),
4445            );
4446            assert_eq!(rect_of_key(tester, &key), inset);
4447            tester.pump_widget(
4448                MediaQuery::new(
4449                    MediaQueryData::new(),
4450                    Dialog::new().child(placeholder(&key)),
4451                )
4452                .into_widget(),
4453            );
4454            // no change because this is an animation
4455            assert_eq!(rect_of_key(tester, &key), inset);
4456            tester.pump_by(Duration::from_secs(1));
4457            // animation finished
4458            assert_eq!(
4459                rect_of_key(tester, &key),
4460                Rect::from_ltrb(40.0, 24.0, 800.0 - 40.0, 600.0 - 24.0)
4461            );
4462        });
4463    }
4464
4465    #[test]
4466    fn dialog_inset_padding_added_to_outside_of_dialog() {
4467        test_widgets(|tester| {
4468            let key = GlobalKey::new();
4469            // The default testing screen (800, 600)
4470            let screen_rect = Rect::from_ltrb(0.0, 0.0, 800.0, 600.0);
4471
4472            // Test with no padding.
4473            tester.pump_widget(
4474                MediaQuery::new(
4475                    MediaQueryData::new(),
4476                    Dialog::new()
4477                        .inset_padding(EdgeInsets::ZERO)
4478                        .child(placeholder(&key)),
4479                )
4480                .into_widget(),
4481            );
4482            tester.pump_and_settle();
4483            assert_eq!(rect_of_key(tester, &key), screen_rect);
4484
4485            // Test with an insetPadding.
4486            tester.pump_widget(
4487                MediaQuery::new(
4488                    MediaQueryData::new(),
4489                    Dialog::new()
4490                        .inset_padding(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0))
4491                        .child(placeholder(&key)),
4492                )
4493                .into_widget(),
4494            );
4495            tester.pump_and_settle();
4496            assert_eq!(
4497                rect_of_key(tester, &key),
4498                Rect::from_ltrb(
4499                    screen_rect.left + 10.0,
4500                    screen_rect.top + 20.0,
4501                    screen_rect.right - 30.0,
4502                    screen_rect.bottom - 40.0,
4503                )
4504            );
4505        });
4506    }
4507
4508    #[test]
4509    fn dialog_fullscreen_material_extends_behind_the_keyboard_child_stays_above_it() {
4510        test_widgets(|tester| {
4511            let key = GlobalKey::new();
4512            let child_context = context_cell();
4513            let dialog = |key: &GlobalKey, child_context: &Rc<Cell<Option<BuildContext>>>| {
4514                let key = key.clone();
4515                let child_context = Rc::clone(child_context);
4516                Dialog::fullscreen().child(Builder::new(move |_app, context| {
4517                    child_context.set(Some(context));
4518                    placeholder(&key)
4519                }))
4520            };
4521            let material_rect = |tester: &WidgetTester| tester.get_rect(dialog_material(tester));
4522
4523            tester.pump_widget(
4524                MediaQuery::new(
4525                    MediaQueryData::new().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, 200.0)),
4526                    dialog(&key, &child_context),
4527                )
4528                .into_widget(),
4529            );
4530            tester.pump_and_settle();
4531            // The child is kept above the keyboard and does not see the inset.
4532            assert_eq!(
4533                rect_of_key(tester, &key),
4534                Rect::from_ltrb(0.0, 0.0, 800.0, 400.0)
4535            );
4536            assert_eq!(
4537                MediaQuery::view_insets_of(&mut tester.cell.borrow_mut(), seen(&child_context)),
4538                EdgeInsets::ZERO
4539            );
4540            // The dialog's surface keeps covering the whole screen, including the
4541            // area behind the keyboard.
4542            assert_eq!(
4543                material_rect(tester),
4544                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0)
4545            );
4546
4547            // Hiding the keyboard gives the child the whole screen back.
4548            tester.pump_widget(
4549                MediaQuery::new(MediaQueryData::new(), dialog(&key, &child_context)).into_widget(),
4550            );
4551            tester.pump_and_settle();
4552            assert_eq!(
4553                rect_of_key(tester, &key),
4554                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0)
4555            );
4556            assert_eq!(
4557                material_rect(tester),
4558                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0)
4559            );
4560        });
4561    }
4562
4563    /// Dart's `AlertDialog.scrollable` cases: drags `drag` by `dy` and expects every one of
4564    /// `moved` to have moved by `dy` from where it was.
4565    fn drag_key(tester: &mut WidgetTester, key: &GlobalKey, dy: f64) {
4566        let start = tester.get_center(key);
4567        tester.drag_from(start, Offset::new(0.0, dy), 1);
4568    }
4569
4570    fn origin_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
4571        rect_of_key(tester, key).top_left()
4572    }
4573
4574    fn keyed_box(key: &GlobalKey, color: Color, height: f64) -> WidgetRef {
4575        Container::new()
4576            .key(key.clone().into())
4577            .color(color)
4578            .height(height)
4579            .into_widget()
4580    }
4581
4582    mod alert_dialog_scrollable {
4583        use super::*;
4584
4585        #[test]
4586        fn title_is_scrollable() {
4587            test_widgets(|tester| {
4588                let title_key = GlobalKey::new();
4589                let dialog = AlertDialog::new()
4590                    .title(keyed_box(&title_key, Colors::GREEN.primary(), 1000.0))
4591                    .scrollable(true);
4592                pump_with_dialog(tester, m3, dialog);
4593                open(tester);
4594
4595                let original_offset = origin_of(tester, &title_key);
4596                drag_key(tester, &title_key, -200.0);
4597                assert_eq!(
4598                    origin_of(tester, &title_key),
4599                    original_offset.translate(0.0, -200.0)
4600                );
4601            });
4602        }
4603
4604        #[test]
4605        fn content_is_scrollable() {
4606            test_widgets(|tester| {
4607                let content_key = GlobalKey::new();
4608                let dialog = AlertDialog::new()
4609                    .content(keyed_box(&content_key, Colors::ORANGE.primary(), 1000.0))
4610                    .scrollable(true);
4611                pump_with_dialog(tester, m3, dialog);
4612                open(tester);
4613
4614                let original_offset = origin_of(tester, &content_key);
4615                drag_key(tester, &content_key, -200.0);
4616                assert_eq!(
4617                    origin_of(tester, &content_key),
4618                    original_offset.translate(0.0, -200.0)
4619                );
4620            });
4621        }
4622
4623        #[test]
4624        fn title_and_content_are_scrollable() {
4625            test_widgets(|tester| {
4626                let title_key = GlobalKey::new();
4627                let content_key = GlobalKey::new();
4628                let dialog = AlertDialog::new()
4629                    .title(keyed_box(&title_key, Colors::GREEN.primary(), 400.0))
4630                    .content(keyed_box(&content_key, Colors::ORANGE.primary(), 400.0))
4631                    .scrollable(true);
4632                pump_with_dialog(tester, m3, dialog);
4633                open(tester);
4634
4635                let title_original_offset = origin_of(tester, &title_key);
4636                let content_original_offset = origin_of(tester, &content_key);
4637
4638                // Dragging the title widget should scroll both the title
4639                // and the content widgets.
4640                drag_key(tester, &title_key, -200.0);
4641                assert_eq!(
4642                    origin_of(tester, &title_key),
4643                    title_original_offset.translate(0.0, -200.0)
4644                );
4645                assert_eq!(
4646                    origin_of(tester, &content_key),
4647                    content_original_offset.translate(0.0, -200.0)
4648                );
4649
4650                // Dragging the content widget should scroll both the title
4651                // and the content widgets.
4652                drag_key(tester, &content_key, 200.0);
4653                assert_eq!(origin_of(tester, &title_key), title_original_offset);
4654                assert_eq!(origin_of(tester, &content_key), content_original_offset);
4655            });
4656        }
4657    }
4658
4659    /// Dart's `_ClosureNavigatorObserver.onDidChange`.
4660    type OnDidChange = Rc<dyn Fn(&mut App, AnyRoute)>;
4661
4662    /// Dart's `_ClosureNavigatorObserver`.
4663    struct ClosureNavigatorObserver {
4664        navigator_observer: waft_widgets::NavigatorObserverData,
4665        on_did_change: OnDidChange,
4666    }
4667
4668    impl waft_widgets::NavigatorObserver for ClosureNavigatorObserver {
4669        waft_widgets::navigator_observer_accessors!();
4670
4671        fn did_push(
4672            self: Handle<Self>,
4673            app: &mut App,
4674            route: AnyRoute,
4675            _previous: Option<AnyRoute>,
4676        ) {
4677            let on_did_change = Rc::clone(&app.get(self).on_did_change);
4678            on_did_change(app, route);
4679        }
4680
4681        fn did_pop(
4682            self: Handle<Self>,
4683            app: &mut App,
4684            _route: AnyRoute,
4685            previous: Option<AnyRoute>,
4686        ) {
4687            let on_did_change = Rc::clone(&app.get(self).on_did_change);
4688            on_did_change(app, previous.expect("a previous route"));
4689        }
4690
4691        fn did_remove(
4692            self: Handle<Self>,
4693            app: &mut App,
4694            _route: AnyRoute,
4695            previous: Option<AnyRoute>,
4696        ) {
4697            let on_did_change = Rc::clone(&app.get(self).on_did_change);
4698            on_did_change(app, previous.expect("a previous route"));
4699        }
4700
4701        fn did_replace(
4702            self: Handle<Self>,
4703            app: &mut App,
4704            new_route: Option<AnyRoute>,
4705            _old_route: Option<AnyRoute>,
4706        ) {
4707            let on_did_change = Rc::clone(&app.get(self).on_did_change);
4708            on_did_change(app, new_route.expect("a new route"));
4709        }
4710    }
4711
4712    #[test]
4713    fn dialog_with_route_settings() {
4714        test_widgets(|tester| {
4715            let current_route_setting: Rc<std::cell::RefCell<Option<RouteSettingsRef>>> =
4716                Rc::default();
4717            let current = Rc::clone(&current_route_setting);
4718            let root = {
4719                let mut app = tester.cell.borrow_mut();
4720                let observer = app.create(ClosureNavigatorObserver {
4721                    navigator_observer: waft_widgets::NavigatorObserverData::new(),
4722                    on_did_change: Rc::new(move |app, new_route| {
4723                        *current.borrow_mut() = Some(new_route.settings(app));
4724                    }),
4725                });
4726                crate::app::MaterialApp::new()
4727                    .theme(m3(&app))
4728                    .navigator_observers([observer.erase::<waft_widgets::AnyNavigatorObserver>()])
4729                    .home(Material::new().child(
4730                        Center::new().child(ElevatedButton::new(None, Some(Text::new("Go")))),
4731                    ))
4732                    .into_widget()
4733            };
4734            tester.pump_widget(root);
4735
4736            let context = find::text("Go").evaluate(tester)[0];
4737            let example_setting =
4738                RouteSettingsRef::Settings(waft_widgets::RouteSettings::default().name("simple"));
4739
4740            let show = Show {
4741                route_settings: Some(example_setting.clone()),
4742                ..Show::default()
4743            };
4744            let result = result_of::<i32>(
4745                tester,
4746                show.on(
4747                    tester,
4748                    context,
4749                    Rc::new(|_app, context| {
4750                        SimpleDialog::new()
4751                            .title(Text::new("Title"))
4752                            .children([SimpleDialogOption::new()
4753                                .child(Text::new("X"))
4754                                .on_pressed(waft_foundation::Listener::new(move |app| {
4755                                    Navigator::of(app, context, false).pop(app, None);
4756                                }))
4757                                .into_widget()])
4758                            .into_widget()
4759                    }),
4760                ),
4761            );
4762
4763            tester.pump_and_settle();
4764            assert_eq!(shows(tester, "Title"), 1);
4765            assert_eq!(
4766                current_route_setting.borrow().clone(),
4767                Some(example_setting)
4768            );
4769
4770            tester.tap(find::text("X"));
4771            tester.pump_and_settle();
4772
4773            assert_eq!(result.get(), Some(None));
4774            tester.pump_and_settle();
4775            assert_eq!(
4776                current_route_setting
4777                    .borrow()
4778                    .as_ref()
4779                    .and_then(|settings| settings.name().map(str::to_owned)),
4780                Some("/".to_owned())
4781            );
4782        });
4783    }
4784
4785    #[test]
4786    fn alert_dialog_actions_alignment() {
4787        test_widgets(|tester| {
4788            let action_key = GlobalKey::new();
4789            let build_frame = |tester: &mut WidgetTester, alignment: Option<MainAxisAlignment>| {
4790                let action_key = action_key.clone();
4791                pump_app(tester, m2, move |_app| {
4792                    let mut dialog = AlertDialog::new()
4793                        .content(SizedBox::new().width(800.0))
4794                        .actions([SizedBox::new()
4795                            .key(action_key.into())
4796                            .width(20.0)
4797                            .height(20.0)
4798                            .into_widget()])
4799                        .button_padding(EdgeInsetsGeometry::ZERO)
4800                        .inset_padding(EdgeInsets::ZERO);
4801                    dialog.actions_alignment = alignment;
4802                    crate::scaffold::Scaffold::new().body(dialog).into_widget()
4803                });
4804            };
4805            let alert_dialog = |tester: &WidgetTester| {
4806                tester.get_rect(find::by_type::<AlertDialog>().evaluate(tester)[0])
4807            };
4808            let action = |tester: &WidgetTester| rect_of_key(tester, &action_key);
4809
4810            // Default configuration
4811            build_frame(tester, None);
4812            assert_eq!(alert_dialog(tester).top_left().dx(), 0.0);
4813            assert_eq!(alert_dialog(tester).top_right().dx(), 800.0);
4814            assert_eq!(
4815                tester
4816                    .get_rect(find::by_type::<OverflowBar>().evaluate(tester)[0])
4817                    .width(),
4818                800.0
4819            );
4820            assert_eq!(action(tester).top_left().dx(), 800.0 - 20.0);
4821            assert_eq!(action(tester).top_right().dx(), 800.0);
4822
4823            // All possible alignment values
4824            let centered = ((800.0 - 20.0) / 2.0, (800.0 - 20.0) / 2.0 + 20.0);
4825            for (alignment, (left, right)) in [
4826                (MainAxisAlignment::Start, (0.0, 20.0)),
4827                (MainAxisAlignment::Center, centered),
4828                (MainAxisAlignment::End, (800.0 - 20.0, 800.0)),
4829                (MainAxisAlignment::SpaceBetween, (0.0, 20.0)),
4830                (MainAxisAlignment::SpaceAround, centered),
4831                (MainAxisAlignment::SpaceEvenly, centered),
4832            ] {
4833                build_frame(tester, Some(alignment));
4834                assert_eq!(action(tester).top_left().dx(), left, "{alignment:?}");
4835                assert_eq!(action(tester).top_right().dx(), right, "{alignment:?}");
4836            }
4837        });
4838    }
4839
4840    /// Dart's `Actions.invoke(primaryFocus!.context!, intent)! as bool` then `tester.pump()`.
4841    fn move_focus(tester: &mut WidgetTester, intent: &dyn waft_widgets::Intent) -> bool {
4842        let result = {
4843            let mut app = tester.cell.borrow_mut();
4844            let context = waft_widgets::primary_focus(&mut app)
4845                .and_then(|focus| focus.context(&app))
4846                .expect("a focused node with a context");
4847            waft_widgets::Actions::invoke(&mut app, context, intent)
4848        };
4849        tester.pump();
4850        result
4851            .and_then(|result| result.downcast_ref::<bool>().copied())
4852            .expect("the focus actions answer whether focus moved")
4853    }
4854
4855    /// The traversal cases' dialog: two buttons, OK and Cancel, with focus nodes of their own.
4856    fn ok_cancel_dialog(
4857        tester: &WidgetTester,
4858    ) -> (
4859        AlertDialog,
4860        waft_widgets::AnyFocusNode,
4861        waft_widgets::AnyFocusNode,
4862    ) {
4863        let (ok_node, cancel_node) = {
4864            let mut app = tester.cell.borrow_mut();
4865            (
4866                waft_widgets::FocusNode::new(&mut app).into_erased::<waft_widgets::AnyFocusNode>(),
4867                waft_widgets::FocusNode::new(&mut app).into_erased::<waft_widgets::AnyFocusNode>(),
4868            )
4869        };
4870        let pressed = || Some(waft_foundation::Listener::new(|_app| {}));
4871        let dialog = AlertDialog::new()
4872            .content(Text::new("Test dialog"))
4873            .actions([
4874                TextButton::new(pressed(), Some(Text::new("OK")))
4875                    .focus_node(ok_node.clone())
4876                    .into_widget(),
4877                TextButton::new(pressed(), Some(Text::new("Cancel")))
4878                    .focus_node(cancel_node.clone())
4879                    .into_widget(),
4880            ]);
4881        (dialog, ok_node.handle(), cancel_node.handle())
4882    }
4883
4884    fn focus_of(tester: &WidgetTester, node: waft_widgets::AnyFocusNode) -> bool {
4885        node.has_focus(&tester.cell.borrow_mut())
4886    }
4887
4888    #[test]
4889    fn uses_closed_loop_focus_traversal() {
4890        test_widgets(|tester| {
4891            let (dialog, ok_node, cancel_node) = ok_cancel_dialog(tester);
4892            pump_with_dialog(tester, m3, dialog);
4893            open(tester);
4894
4895            // Start at OK
4896            ok_node.request_focus(&mut tester.cell.borrow_mut(), None);
4897            tester.pump();
4898            assert!(focus_of(tester, ok_node));
4899            assert!(!focus_of(tester, cancel_node));
4900
4901            for (intent, ok_focused) in [
4902                // OK -> Cancel
4903                (
4904                    &waft_widgets::NextFocusIntent as &dyn waft_widgets::Intent,
4905                    false,
4906                ),
4907                // Cancel -> OK
4908                (&waft_widgets::NextFocusIntent, true),
4909                // Cancel <- OK
4910                (&waft_widgets::PreviousFocusIntent, false),
4911                // OK <- Cancel
4912                (&waft_widgets::PreviousFocusIntent, true),
4913            ] {
4914                assert!(move_focus(tester, intent));
4915                assert_eq!(focus_of(tester, ok_node), ok_focused);
4916                assert_eq!(focus_of(tester, cancel_node), !ok_focused);
4917            }
4918        });
4919    }
4920
4921    #[test]
4922    fn uses_open_focus_traversal_when_overridden() {
4923        test_widgets(|tester| {
4924            let (dialog, ok_node, cancel_node) = ok_cancel_dialog(tester);
4925            app_with_dialog(
4926                tester,
4927                m3,
4928                dialog.into_widget(),
4929                1.0,
4930                Some(TraversalEdgeBehavior::LeaveFlutterView),
4931            );
4932            open(tester);
4933
4934            // Start at OK
4935            ok_node.request_focus(&mut tester.cell.borrow_mut(), None);
4936            tester.pump();
4937            assert!(focus_of(tester, ok_node));
4938            assert!(!focus_of(tester, cancel_node));
4939
4940            // OK -> Cancel
4941            assert!(move_focus(tester, &waft_widgets::NextFocusIntent));
4942            assert!(!focus_of(tester, ok_node));
4943            assert!(focus_of(tester, cancel_node));
4944
4945            // Cancel -> nothing
4946            assert!(!move_focus(tester, &waft_widgets::NextFocusIntent));
4947            assert!(!focus_of(tester, ok_node));
4948            assert!(!focus_of(tester, cancel_node));
4949        });
4950    }
4951
4952    #[test]
4953    fn adaptive_alert_dialog_shows_correct_widget_on_each_platform() {
4954        test_widgets(|tester| {
4955            let dialog = AlertDialog::adaptive()
4956                .content(green_box(5000.0, 300.0))
4957                .actions([TextButton::new(
4958                    Some(waft_foundation::Listener::new(|_app| {})),
4959                    Some(Text::new("OK")),
4960                )
4961                .into_widget()])
4962                .into_widget();
4963
4964            for (platform, cupertino) in [
4965                (TargetPlatform::IOS, 1),
4966                (TargetPlatform::MacOS, 1),
4967                (TargetPlatform::Android, 0),
4968                (TargetPlatform::Fuchsia, 0),
4969                (TargetPlatform::Linux, 0),
4970                (TargetPlatform::Windows, 0),
4971            ] {
4972                app_with_dialog(
4973                    tester,
4974                    move |app| ThemeData::builder().platform(platform).build(app),
4975                    dialog.clone(),
4976                    1.0,
4977                    None,
4978                );
4979                tester.pump_and_settle();
4980
4981                open(tester);
4982
4983                assert_eq!(
4984                    find::by_type::<CupertinoAlertDialog>()
4985                        .evaluate(tester)
4986                        .len(),
4987                    cupertino,
4988                    "on {platform:?}"
4989                );
4990
4991                tap_at(tester, Offset::new(10.0, 10.0));
4992                tester.pump_and_settle();
4993            }
4994        });
4995    }
4996
4997    /// Dart's `showAdaptiveDialog`'s optional arguments with Dart's defaults.
4998    fn show_adaptive(
4999        tester: &WidgetTester,
5000        context: BuildContext,
5001        builder: WidgetBuilder,
5002        animation_style: Option<AnimationStyle>,
5003    ) {
5004        let mut show = ShowAdaptiveDialog::new(builder);
5005        if let Some(animation_style) = animation_style {
5006            show = show.animation_style(animation_style);
5007        }
5008        let future = show.show(&mut tester.cell.borrow_mut(), context);
5009        drop(future);
5010        tester.cell.checkpoint();
5011    }
5012
5013    #[test]
5014    fn show_adaptive_dialog_should_not_allow_dismiss_on_barrier_on_ios_by_default() {
5015        test_widgets(|tester| {
5016            pump_app(
5017                tester,
5018                |app| {
5019                    ThemeData::builder()
5020                        .platform(TargetPlatform::IOS)
5021                        .build(app)
5022                },
5023                |_app| {
5024                    Material::new()
5025                        .child(
5026                            Center::new().child(ElevatedButton::new(None, Some(Text::new("Go")))),
5027                        )
5028                        .into_widget()
5029                },
5030            );
5031            let context = find::text("Go").evaluate(tester)[0];
5032
5033            drop(Show::default().on(tester, context, hundred_square("Dialog1")));
5034
5035            tester.pump_and_settle_by(Duration::from_secs(1));
5036            assert_eq!(shows(tester, "Dialog1"), 1);
5037
5038            // Tap on the barrier.
5039            tap_at(tester, Offset::new(10.0, 10.0));
5040
5041            tester.pump_and_settle_by(Duration::from_secs(1));
5042            assert_eq!(shows(tester, "Dialog1"), 0);
5043
5044            show_adaptive(tester, context, hundred_square("Dialog2"), None);
5045
5046            tester.pump_and_settle_by(Duration::from_secs(1));
5047            assert_eq!(shows(tester, "Dialog2"), 1);
5048
5049            // Tap on the barrier, which shouldn't do anything this time.
5050            tap_at(tester, Offset::new(10.0, 10.0));
5051
5052            tester.pump_and_settle_by(Duration::from_secs(1));
5053            assert_eq!(shows(tester, "Dialog2"), 1);
5054        });
5055    }
5056
5057    #[test]
5058    fn applies_animation_style_to_show_adaptive_dialog() {
5059        test_widgets(|tester| {
5060            let animation_style = AnimationStyle::new(
5061                Some(Curves::ease_in_out()),
5062                Some(Duration::from_secs(1)),
5063                None,
5064                None,
5065            );
5066            let context = app_with_disabled_button(tester, "Go");
5067            show_adaptive(
5068                tester,
5069                context,
5070                hundred_square("Dialog1"),
5071                Some(animation_style),
5072            );
5073
5074            tester.pump_and_settle_by(Duration::from_secs(1));
5075            assert_eq!(shows(tester, "Dialog1"), 1);
5076
5077            tap_at(tester, Offset::new(10.0, 10.0));
5078            tester.pump_and_settle_by(Duration::from_secs(1));
5079            assert_eq!(shows(tester, "Dialog1"), 0);
5080        });
5081    }
5082
5083    #[test]
5084    fn dialog_inset_padding_is_nullable() {
5085        let dialog = Dialog::new();
5086        assert_eq!(dialog.inset_padding, None);
5087    }
5088
5089    #[test]
5090    fn alert_dialog_inset_padding_is_nullable() {
5091        let alert_dialog = AlertDialog::new();
5092        assert_eq!(alert_dialog.inset_padding, None);
5093    }
5094
5095    #[test]
5096    fn simple_dialog_inset_padding_is_nullable() {
5097        let simple_dialog = SimpleDialog::new();
5098        assert_eq!(simple_dialog.inset_padding, None);
5099    }
5100
5101    #[test]
5102    fn can_pass_a_null_value_to_alert_dialog_adaptive_clip_behavior() {
5103        for clip_behavior in [
5104            None,
5105            Some(Clip::None),
5106            Some(Clip::HardEdge),
5107            Some(Clip::AntiAlias),
5108            Some(Clip::AntiAliasWithSaveLayer),
5109        ] {
5110            let mut dialog = AlertDialog::adaptive();
5111            dialog.clip_behavior = clip_behavior;
5112            assert_eq!(dialog.clip_behavior, clip_behavior);
5113        }
5114    }
5115
5116    fn has_focus_of(tester: &WidgetTester, node: Handle<waft_widgets::FocusNode>) -> bool {
5117        use waft_widgets::FocusNodeLeaf;
5118        node.as_node().has_focus(&tester.cell.borrow_mut())
5119    }
5120
5121    fn request_focus_of(tester: &mut WidgetTester, node: Handle<waft_widgets::FocusNode>) {
5122        use waft_widgets::FocusNodeLeaf;
5123        node.as_node()
5124            .request_focus(&mut tester.cell.borrow_mut(), None);
5125        tester.pump();
5126    }
5127
5128    #[test]
5129    fn setting_dialog_route_request_focus_to_false_does_not_request_focus_on_the_dialog() {
5130        test_widgets(|tester| {
5131            let saved_context = context_cell();
5132            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut());
5133            let dialog_text = "Dialog Text";
5134            let saved = Rc::clone(&saved_context);
5135            pump_app(tester, m3, {
5136                let focus_node = focus_node.clone();
5137                move |_app| {
5138                    Material::new()
5139                        .child(Builder::new(move |_app, context| {
5140                            saved.set(Some(context));
5141                            crate::text_field::TextField::new()
5142                                .focus_node(focus_node.erase())
5143                                .into_widget()
5144                        }))
5145                        .into_widget()
5146                }
5147            });
5148            tester.pump();
5149
5150            // Initially, there is no dialog and the text field has no focus.
5151            assert_eq!(shows(tester, dialog_text), 0);
5152            assert!(!has_focus_of(tester, focus_node.handle()));
5153
5154            // Request focus on the text field.
5155            request_focus_of(tester, focus_node.handle());
5156            assert!(has_focus_of(tester, focus_node.handle()));
5157
5158            // Bring up dialog.
5159            let navigator =
5160                Navigator::of(&mut tester.cell.borrow_mut(), seen(&saved_context), false);
5161            {
5162                let mut app = tester.cell.borrow_mut();
5163                let route = DialogRoute::new(
5164                    &mut app,
5165                    seen(&saved_context),
5166                    Rc::new(move |_app, _context| Text::new(dialog_text).into_widget()),
5167                );
5168                drop(navigator.push(&mut app, route.erase()));
5169            }
5170            tester.pump();
5171
5172            // The dialog is showing and the text field has lost focus.
5173            assert_eq!(shows(tester, dialog_text), 1);
5174            assert!(!has_focus_of(tester, focus_node.handle()));
5175
5176            // Dismiss the dialog.
5177            navigator.pop(&mut tester.cell.borrow_mut(), None);
5178            tester.pump();
5179
5180            // The dialog is dismissed and the focus is shifted back to the text field.
5181            assert_eq!(shows(tester, dialog_text), 0);
5182            assert!(has_focus_of(tester, focus_node.handle()));
5183
5184            // Bring up dialog again with requestFocus to false.
5185            {
5186                let mut app = tester.cell.borrow_mut();
5187                let route = crate::bottom_sheet::ModalBottomSheetRoute::new(
5188                    &mut app,
5189                    Rc::new(move |_app, _context| Text::new(dialog_text).into_widget()),
5190                    false,
5191                );
5192                route.clone().request_focus(&mut app, false);
5193                drop(navigator.push(&mut app, route.erase()));
5194            }
5195            tester.pump();
5196
5197            // The dialog is showing and the text field still has focus.
5198            assert_eq!(shows(tester, dialog_text), 1);
5199            assert!(has_focus_of(tester, focus_node.handle()));
5200        });
5201    }
5202
5203    #[test]
5204    fn request_focus_works_correctly_in_show_dialog() {
5205        test_widgets(|tester| {
5206            let navigator_key = GlobalKey::new();
5207            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut());
5208            let root =
5209                {
5210                    let app = tester.cell.borrow();
5211                    crate::app::MaterialApp::new()
5212                        .theme(m3(&app))
5213                        .navigator_key(navigator_key.clone())
5214                        .home(crate::scaffold::Scaffold::new().body(
5215                            crate::text_field::TextField::new().focus_node(focus_node.erase()),
5216                        ))
5217                        .into_widget()
5218                };
5219            tester.pump_widget(root);
5220            request_focus_of(tester, focus_node.handle());
5221            assert!(has_focus_of(tester, focus_node.handle()));
5222
5223            let dialog_scope_has_focus = |tester: &WidgetTester| {
5224                use waft_widgets::FocusNodeLeaf;
5225                let element = find::text("dialog").evaluate(tester)[0];
5226                let mut app = tester.cell.borrow_mut();
5227                let scope = waft_widgets::FocusScope::of(&mut app, element, true);
5228                scope.as_node().has_focus(&app)
5229            };
5230            let navigator_context = |tester: &WidgetTester| {
5231                navigator_key
5232                    .current_context(&tester.cell.borrow())
5233                    .expect("the navigator is mounted")
5234            };
5235            let dialog: WidgetBuilder = Rc::new(|_app, _context| Text::new("dialog").into_widget());
5236
5237            let show = Show {
5238                request_focus: Some(true),
5239                ..Show::default()
5240            };
5241            drop(show.on(tester, navigator_context(tester), Rc::clone(&dialog)));
5242            tester.pump_and_settle();
5243            assert!(dialog_scope_has_focus(tester));
5244            assert!(!has_focus_of(tester, focus_node.handle()));
5245
5246            {
5247                let mut app = tester.cell.borrow_mut();
5248                navigator_key
5249                    .current_state::<waft_widgets::NavigatorState>(&app)
5250                    .expect("the navigator is mounted")
5251                    .pop(&mut app, None);
5252            }
5253            tester.pump_and_settle();
5254            assert!(has_focus_of(tester, focus_node.handle()));
5255
5256            let show = Show {
5257                request_focus: Some(false),
5258                ..Show::default()
5259            };
5260            drop(show.on(tester, navigator_context(tester), dialog));
5261            tester.pump_and_settle();
5262            assert!(!dialog_scope_has_focus(tester));
5263            assert!(has_focus_of(tester, focus_node.handle()));
5264        });
5265    }
5266
5267    /// The width of the only `SizedBox` in the dialog: Dart's
5268    /// `tester.getSize(find.byType(SizedBox)).width`.
5269    fn sized_box_width(tester: &WidgetTester, key: &GlobalKey) -> f64 {
5270        rect_of_key(tester, key).width()
5271    }
5272
5273    #[test]
5274    fn dialog_respects_the_given_constraints() {
5275        test_widgets(|tester| {
5276            let key = GlobalKey::new();
5277            pump_with_dialog(
5278                tester,
5279                m3,
5280                Dialog::new()
5281                    .constraints(BoxConstraints::new().max_width(560.0))
5282                    .child(
5283                        SizedBox::new()
5284                            .key(key.clone().into())
5285                            .width(1000.0)
5286                            .height(100.0),
5287                    ),
5288            );
5289            open(tester);
5290
5291            assert_eq!(sized_box_width(tester, &key), 560.0);
5292        });
5293    }
5294
5295    #[test]
5296    fn alert_dialog_respects_the_default_constraints() {
5297        test_widgets(|tester| {
5298            let key = GlobalKey::new();
5299            pump_with_dialog(
5300                tester,
5301                m3,
5302                AlertDialog::new()
5303                    .content(SizedBox::new().key(key.clone().into()))
5304                    .content_padding(EdgeInsetsGeometry::ZERO),
5305            );
5306            open(tester);
5307
5308            assert_eq!(sized_box_width(tester, &key), 280.0);
5309        });
5310    }
5311
5312    #[test]
5313    fn alert_dialog_respects_the_given_constraints() {
5314        test_widgets(|tester| {
5315            let key = GlobalKey::new();
5316            pump_with_dialog(
5317                tester,
5318                m3,
5319                AlertDialog::new()
5320                    .constraints(BoxConstraints::new().max_width(560.0))
5321                    .content(
5322                        SizedBox::new()
5323                            .key(key.clone().into())
5324                            .width(1000.0)
5325                            .height(100.0),
5326                    )
5327                    .content_padding(EdgeInsetsGeometry::ZERO),
5328            );
5329            open(tester);
5330
5331            assert_eq!(sized_box_width(tester, &key), 560.0);
5332        });
5333    }
5334
5335    #[test]
5336    fn simple_dialog_respects_the_default_constraints() {
5337        test_widgets(|tester| {
5338            let key = GlobalKey::new();
5339            pump_with_dialog(
5340                tester,
5341                m3,
5342                SimpleDialog::new()
5343                    .content_padding(EdgeInsetsGeometry::ZERO)
5344                    .children([SizedBox::new().key(key.clone().into()).into_widget()]),
5345            );
5346            open(tester);
5347
5348            assert_eq!(sized_box_width(tester, &key), 280.0);
5349        });
5350    }
5351
5352    #[test]
5353    fn simple_dialog_respects_the_given_constraints() {
5354        test_widgets(|tester| {
5355            let key = GlobalKey::new();
5356            pump_with_dialog(
5357                tester,
5358                m3,
5359                SimpleDialog::new()
5360                    .constraints(BoxConstraints::new().max_width(560.0))
5361                    .content_padding(EdgeInsetsGeometry::ZERO)
5362                    .children([SizedBox::new()
5363                        .key(key.clone().into())
5364                        .width(1000.0)
5365                        .height(100.0)
5366                        .into_widget()]),
5367            );
5368            open(tester);
5369
5370            assert_eq!(sized_box_width(tester, &key), 560.0);
5371        });
5372    }
5373
5374    #[test]
5375    fn test_no_back_gesture_on_fullscreen_dialogs() {
5376        test_widgets(|tester| {
5377            // no back button in app bar for RawDialogRoute with full screen dialog set to true
5378            pump_app(tester, m3, |_app| {
5379                crate::scaffold::Scaffold::new()
5380                    .body(Builder::new(|_app, context| {
5381                        TextButton::new(
5382                            Some(waft_foundation::Listener::new(move |app| {
5383                                let page_builder: RoutePageBuilder =
5384                                    Rc::new(|_app, _context, _animation, _secondary| {
5385                                        crate::scaffold::Scaffold::new()
5386                                            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5387                                                crate::app_bar::AppBar::new()
5388                                                    .title(Text::new("title")),
5389                                            ))
5390                                            .body(Text::new("body"))
5391                                            .into_widget()
5392                                    });
5393                                let route = RawDialogRoute::new(app, page_builder)
5394                                    .fullscreen_dialog(app, true);
5395                                drop(Navigator::of(app, context, false).push(app, route.erase()));
5396                            })),
5397                            Some(Text::new("X")),
5398                        )
5399                        .into_widget()
5400                    }))
5401                    .into_widget()
5402            });
5403
5404            open(tester);
5405
5406            assert_eq!(
5407                find::by_type::<crate::action_buttons::BackButton>()
5408                    .evaluate(tester)
5409                    .len(),
5410                0
5411            );
5412            assert_eq!(
5413                find::by_type::<crate::action_buttons::CloseButton>()
5414                    .evaluate(tester)
5415                    .len(),
5416                1
5417            );
5418        });
5419    }
5420
5421    fn size_of_only<W: 'static>(tester: &WidgetTester) -> Size {
5422        tester.get_rect(tester.element(find::by_type::<W>())).size()
5423    }
5424
5425    #[test]
5426    fn simple_dialog_does_not_crash_at_zero_area() {
5427        test_widgets(|tester| {
5428            pump_app(tester, m3, |_app| {
5429                Center::new()
5430                    .child(SizedBox::shrink().child(SimpleDialog::new().title(Text::new("X"))))
5431                    .into_widget()
5432            });
5433            assert_eq!(size_of_only::<SimpleDialog>(tester), Size::ZERO);
5434        });
5435    }
5436
5437    #[test]
5438    fn simple_dialog_option_does_not_crash_at_zero_area() {
5439        test_widgets(|tester| {
5440            pump_app(tester, m3, |_app| {
5441                Material::new()
5442                    .child(Center::new().child(
5443                        SizedBox::shrink().child(SimpleDialogOption::new().child(Text::new("X"))),
5444                    ))
5445                    .into_widget()
5446            });
5447            assert_eq!(size_of_only::<SimpleDialogOption>(tester), Size::ZERO);
5448        });
5449    }
5450
5451    #[test]
5452    fn dialog_does_not_crash_at_zero_area() {
5453        test_widgets(|tester| {
5454            pump_app(tester, m3, |_app| {
5455                Center::new()
5456                    .child(SizedBox::shrink().child(Dialog::new().child(Text::new("X"))))
5457                    .into_widget()
5458            });
5459            assert!(size_of_only::<Dialog>(tester).is_empty());
5460        });
5461    }
5462
5463    #[test]
5464    fn alert_dialog_does_not_crash_at_zero_area() {
5465        test_widgets(|tester| {
5466            pump_app(tester, m3, |_app| {
5467                Center::new()
5468                    .child(SizedBox::shrink().child(AlertDialog::new().content(Text::new("X"))))
5469                    .into_widget()
5470            });
5471            assert!(size_of_only::<AlertDialog>(tester).is_empty());
5472        });
5473    }
5474
5475    /// Dart's `tester.widget<Semantics>(find.ancestor(of: find.byType(Dialog), matching:
5476    /// find.byType(Semantics)).first).properties.hitTestBehavior`.
5477    fn route_semantics_hit_test_behavior(
5478        tester: &WidgetTester,
5479    ) -> Option<SemanticsHitTestBehavior> {
5480        let dialog = tester.element(find::by_type::<Dialog>());
5481        let semantics = tester.ancestor_of_type::<Semantics>(dialog);
5482        tester.widget::<Semantics, _>(semantics, |semantics| {
5483            semantics.properties.hit_test_behavior
5484        })
5485    }
5486
5487    /// Dart's `MaterialApp(home: Material(child: Builder(builder: (context) =>
5488    /// ElevatedButton(onPressed: () => showDialog(context:, builder:), child: Text('Show
5489    /// Dialog')))))`.
5490    fn app_showing_on_press(tester: &mut WidgetTester, builder: WidgetBuilder) {
5491        pump_app(tester, m3, move |_app| {
5492            Material::new()
5493                .child(Builder::new(move |_app, context| {
5494                    let builder = Rc::clone(&builder);
5495                    ElevatedButton::new(
5496                        Some(waft_foundation::Listener::new(move |app| {
5497                            drop(Show::default().show(app, context, Rc::clone(&builder)));
5498                        })),
5499                        Some(Text::new("Show Dialog")),
5500                    )
5501                    .into_widget()
5502                }))
5503                .into_widget()
5504        });
5505    }
5506
5507    #[test]
5508    fn dialog_has_hit_test_behavior_opaque_to_prevent_dismissal_on_empty_areas() {
5509        test_widgets(|tester| {
5510            app_showing_on_press(
5511                tester,
5512                Rc::new(|_app, _context| {
5513                    Dialog::new()
5514                        .child(SizedBox::new().width(200.0).height(200.0))
5515                        .into_widget()
5516                }),
5517            );
5518
5519            tester.tap(find::text("Show Dialog"));
5520            tester.pump_and_settle();
5521
5522            expect(tester, &find::by_type::<Dialog>(), finds_one_widget());
5523            assert_eq!(
5524                route_semantics_hit_test_behavior(tester),
5525                Some(SemanticsHitTestBehavior::Opaque)
5526            );
5527        });
5528    }
5529
5530    #[test]
5531    fn alert_dialog_has_hit_test_behavior_opaque_via_dialog() {
5532        test_widgets(|tester| {
5533            app_showing_on_press(
5534                tester,
5535                Rc::new(|_app, context| {
5536                    AlertDialog::new()
5537                        .title(Text::new("Test Dialog"))
5538                        .content(SizedBox::new().width(200.0).height(100.0))
5539                        .actions([TextButton::new(
5540                            Some(waft_foundation::Listener::new(move |app| {
5541                                Navigator::pop(app, context, None);
5542                            })),
5543                            Some(Text::new("OK")),
5544                        )
5545                        .into_widget()])
5546                        .into_widget()
5547                }),
5548            );
5549
5550            tester.tap(find::text("Show Dialog"));
5551            tester.pump_and_settle();
5552
5553            expect(tester, &find::by_type::<AlertDialog>(), finds_one_widget());
5554            expect(tester, &find::by_type::<Dialog>(), finds_one_widget());
5555            // Find the route-level Semantics with hitTestBehavior.opaque
5556            // (wraps the entire dialog content, above the Dialog widget)
5557            assert_eq!(
5558                route_semantics_hit_test_behavior(tester),
5559                Some(SemanticsHitTestBehavior::Opaque)
5560            );
5561        });
5562    }
5563
5564    #[test]
5565    fn dismissible_confirm_dismiss_defers_to_an_alert_dialog() {
5566        use std::cell::RefCell;
5567        use waft_widgets::{DismissDirection, Dismissible, ListView, StateSetter, StatefulBuilder};
5568
5569        test_widgets(|tester| {
5570            let scaffold_key = GlobalKey::new();
5571            let dismissed_items: Rc<RefCell<Vec<i32>>> = Rc::default();
5572
5573            // Dismiss is confirmed IFF confirmDismiss() returns true.
5574            let confirm_key = scaffold_key.clone();
5575            let confirm_dismiss = Rc::new(move |app: &mut App, _direction: DismissDirection| {
5576                let context = confirm_key
5577                    .current_context(app)
5578                    .expect("the scaffold is mounted");
5579                let popped = Show::default().show(
5580                    app,
5581                    context,
5582                    Rc::new(|_app, context| {
5583                        let pop_with = move |value: bool| {
5584                            Some(waft_foundation::Listener::new(move |app| {
5585                                // showDialog() returns `value`
5586                                Navigator::pop(app, context, Some(Rc::new(value)));
5587                            }))
5588                        };
5589                        AlertDialog::new()
5590                            .actions([
5591                                TextButton::new(pop_with(true), Some(Text::new("TRUE")))
5592                                    .into_widget(),
5593                                TextButton::new(pop_with(false), Some(Text::new("FALSE")))
5594                                    .into_widget(),
5595                            ])
5596                            .into_widget()
5597                    }),
5598                );
5599                app.spawn(async move |_cx| {
5600                    popped
5601                        .await
5602                        .and_then(|value| value.downcast_ref::<bool>().copied())
5603                })
5604            });
5605
5606            let build_dismissible_item = {
5607                let dismissed_items = Rc::clone(&dismissed_items);
5608                move |item: i32, set_state: StateSetter| {
5609                    let dismissed_items = Rc::clone(&dismissed_items);
5610                    let confirm_dismiss = Rc::clone(&confirm_dismiss);
5611                    Dismissible::new(
5612                        waft_foundation::ValueKey::new(item).into(),
5613                        SizedBox::new()
5614                            .height(100.0)
5615                            .child(Text::new(item.to_string())),
5616                    )
5617                    .confirm_dismiss(move |app, direction| confirm_dismiss(app, direction))
5618                    .on_dismissed(move |app, _direction| {
5619                        let dismissed_items = Rc::clone(&dismissed_items);
5620                        set_state(app, &mut |_app| {
5621                            assert!(!dismissed_items.borrow().contains(&item));
5622                            dismissed_items.borrow_mut().push(item);
5623                        });
5624                    })
5625                    .into_widget()
5626                }
5627            };
5628            let build_dismissible_item = Rc::new(build_dismissible_item);
5629
5630            let build_frame = |tester: &mut WidgetTester| {
5631                let scaffold_key = scaffold_key.clone();
5632                let dismissed_items = Rc::clone(&dismissed_items);
5633                let build_dismissible_item = Rc::clone(&build_dismissible_item);
5634                pump_app(tester, m3, move |_app| {
5635                    StatefulBuilder::new(move |_app, _context, set_state| {
5636                        let items: Vec<WidgetRef> = [0, 1, 2, 3, 4]
5637                            .into_iter()
5638                            .filter(|i| !dismissed_items.borrow().contains(i))
5639                            .map(|item| build_dismissible_item(item, Rc::clone(&set_state)))
5640                            .collect();
5641                        crate::scaffold::Scaffold::new()
5642                            .key(scaffold_key.clone().into())
5643                            .body(
5644                                Padding::new(EdgeInsetsGeometry::all(16.0))
5645                                    .child(ListView::new().item_extent(100.0).children(items)),
5646                            )
5647                            .into_widget()
5648                    })
5649                    .into_widget()
5650                });
5651            };
5652
5653            let dismiss_item = |tester: &mut WidgetTester, item: i32| {
5654                let start = tester.get_rect(find::text(&item.to_string())).center();
5655                tester.fling_from(start, Offset::new(300.0, 0.0), 1000.0, 1); // fling to the right
5656                tester.pump(); // start the slide
5657                tester.pump_by(Duration::from_secs(1)); // finish the slide and start shrinking...
5658                tester.pump(); // first frame of shrinking animation
5659                tester.pump_by(Duration::from_secs(1)); // finish the shrinking and call the callback...
5660                tester.pump(); // rebuild after the callback removes the entry
5661            };
5662            let dismissed = || dismissed_items.borrow().clone();
5663
5664            // Dismiss item 0 is confirmed via the AlertDialog
5665            build_frame(tester);
5666            assert!(dismissed().is_empty());
5667            dismiss_item(tester, 0); // Causes the AlertDialog to appear per confirmDismiss
5668            tester.pump_and_settle();
5669            tester.tap(find::text("TRUE")); // AlertDialog action
5670            tester.pump_and_settle();
5671            assert_eq!(shows(tester, "TRUE"), 0); // Dialog was dismissed
5672            assert_eq!(shows(tester, "FALSE"), 0);
5673            assert_eq!(dismissed(), vec![0]);
5674            assert_eq!(shows(tester, "0"), 0);
5675
5676            // Dismiss item 1 is not confirmed via the AlertDialog
5677            build_frame(tester);
5678            assert_eq!(dismissed(), vec![0]);
5679            dismiss_item(tester, 1); // Causes the AlertDialog to appear per confirmDismiss
5680            tester.pump_and_settle();
5681            tester.tap(find::text("FALSE")); // AlertDialog action
5682            tester.pump_and_settle();
5683            assert_eq!(shows(tester, "TRUE"), 0); // Dialog was dismissed
5684            assert_eq!(shows(tester, "FALSE"), 0);
5685            assert_eq!(dismissed(), vec![0]);
5686            assert_eq!(shows(tester, "0"), 0);
5687            assert_eq!(shows(tester, "1"), 1);
5688
5689            // Dismiss item 1 is not confirmed via the AlertDialog
5690            build_frame(tester);
5691            assert_eq!(dismissed(), vec![0]);
5692            dismiss_item(tester, 1); // Causes the AlertDialog to appear per confirmDismiss
5693            tester.pump_and_settle();
5694            assert_eq!(shows(tester, "FALSE"), 1);
5695            assert_eq!(shows(tester, "TRUE"), 1);
5696            tap_at(tester, Offset::ZERO); // Tap outside of the AlertDialog
5697            tester.pump_and_settle();
5698            assert_eq!(dismissed(), vec![0]);
5699            assert_eq!(shows(tester, "0"), 0);
5700            assert_eq!(shows(tester, "1"), 1);
5701            assert_eq!(shows(tester, "TRUE"), 0); // Dialog was dismissed
5702            assert_eq!(shows(tester, "FALSE"), 0);
5703
5704            // Dismiss item 1 is confirmed via the AlertDialog
5705            build_frame(tester);
5706            assert_eq!(dismissed(), vec![0]);
5707            dismiss_item(tester, 1); // Causes the AlertDialog to appear per confirmDismiss
5708            tester.pump_and_settle();
5709            tester.tap(find::text("TRUE")); // AlertDialog action
5710            tester.pump_and_settle();
5711            assert_eq!(shows(tester, "TRUE"), 0); // Dialog was dismissed
5712            assert_eq!(shows(tester, "FALSE"), 0);
5713            assert_eq!(dismissed(), vec![0, 1]);
5714            assert_eq!(shows(tester, "0"), 0);
5715            assert_eq!(shows(tester, "1"), 0);
5716        });
5717    }
5718
5719    // Regression test for https://github.com/flutter/flutter/issues/28505.
5720    #[test]
5721    fn show_dialog_only_gets_theme_from_context_on_the_first_call() {
5722        test_widgets(|tester| {
5723            let build_frame = |tester: &mut WidgetTester, builder_key: KeyRef| {
5724                pump_app(tester, m3, move |_app| {
5725                    Center::new()
5726                        .child(
5727                            Builder::new(|_app, outer_context| {
5728                                ElevatedButton::new(
5729                                    Some(waft_foundation::Listener::new(move |app| {
5730                                        drop(Show::default().show(
5731                                            app,
5732                                            outer_context,
5733                                            Rc::new(|_app, _inner_context| {
5734                                                AlertDialog::new()
5735                                                    .title(Text::new("Title"))
5736                                                    .into_widget()
5737                                            }),
5738                                        ));
5739                                    })),
5740                                    Some(Text::new("Show Dialog")),
5741                                )
5742                                .into_widget()
5743                            })
5744                            .key(builder_key),
5745                        )
5746                        .into_widget()
5747                });
5748            };
5749
5750            build_frame(tester, waft_foundation::UniqueKey::new().into());
5751
5752            // Open the dialog.
5753            let button = tester.element(find::by_type::<ElevatedButton>());
5754            let center = tester.get_rect(button).center();
5755            tester.tap_at(center, 1);
5756            tester.pump_and_settle();
5757
5758            // Force the Builder to be recreated (new key) which causes outerContext to
5759            // be deactivated. If showDialog()'s implementation were to refer to
5760            // outerContext again, it would crash.
5761            build_frame(tester, waft_foundation::UniqueKey::new().into());
5762            tester.pump();
5763        });
5764    }
5765
5766    #[test]
5767    fn show_dialog_safe_area() {
5768        test_widgets(|tester| {
5769            let root = {
5770                let app = tester.cell.borrow();
5771                crate::app::MaterialApp::new()
5772                    .theme(m3(&app))
5773                    .builder(|_app, _context, child| {
5774                        MediaQuery::new(
5775                            // Set up the safe area to be 20 pixels in from each side
5776                            MediaQueryData::new().padding(EdgeInsets::all(20.0)),
5777                            child.expect("the navigator").clone(),
5778                        )
5779                        .into_widget()
5780                    })
5781                    .home(Center::new().child(Text::new("Test")))
5782                    .into_widget()
5783            };
5784            tester.pump_widget(root);
5785            let context = find::text("Test").evaluate(tester)[0];
5786            let key = GlobalKey::new();
5787            let page = {
5788                let key = key.clone();
5789                move || -> WidgetBuilder {
5790                    let key = key.clone();
5791                    Rc::new(move |_app, _context| placeholder(&key))
5792                }
5793            };
5794
5795            // By default it should honor the safe area
5796            drop(Show::default().on(tester, context, page()));
5797            tester.pump_and_settle();
5798            assert_eq!(
5799                rect_of_key(tester, &key).top_left(),
5800                Offset::new(20.0, 20.0)
5801            );
5802            assert_eq!(
5803                rect_of_key(tester, &key).bottom_right(),
5804                Offset::new(780.0, 580.0)
5805            );
5806
5807            // Dismiss it and test with useSafeArea off
5808            tap_at(tester, Offset::new(10.0, 10.0));
5809            let show = Show {
5810                use_safe_area: false,
5811                ..Show::default()
5812            };
5813            drop(show.on(tester, context, page()));
5814            tester.pump_and_settle();
5815            // Should take up the whole screen
5816            assert_eq!(rect_of_key(tester, &key).top_left(), Offset::ZERO);
5817            assert_eq!(
5818                rect_of_key(tester, &key).bottom_right(),
5819                Offset::new(800.0, 600.0)
5820            );
5821        });
5822    }
5823
5824    /// Dart's `DialogObserver`: counts the `DialogRoute`s pushed.
5825    #[derive(Default)]
5826    struct DialogObserver {
5827        navigator_observer: waft_widgets::NavigatorObserverData,
5828        dialog_count: Cell<u32>,
5829    }
5830
5831    impl waft_widgets::NavigatorObserver for DialogObserver {
5832        waft_widgets::navigator_observer_accessors!();
5833
5834        fn did_push(
5835            self: Handle<Self>,
5836            app: &mut App,
5837            route: AnyRoute,
5838            _previous: Option<AnyRoute>,
5839        ) {
5840            if route.downcast::<DialogRoute>(app).is_some() {
5841                let count = &app.get(self).dialog_count;
5842                count.set(count.get() + 1);
5843            }
5844        }
5845    }
5846
5847    /// Dart's `showDialog uses root navigator by default` and `... nested navigator if
5848    /// useRootNavigator is false`: the dialogs the root and the nested observer saw.
5849    fn dialogs_seen_by_root_and_nested(
5850        tester: &mut WidgetTester,
5851        use_root_navigator: bool,
5852    ) -> (u32, u32) {
5853        let (root_observer, nested_observer) = {
5854            let mut app = tester.cell.borrow_mut();
5855            (
5856                app.create(DialogObserver::default()),
5857                app.create(DialogObserver::default()),
5858            )
5859        };
5860        let root = {
5861            let app = tester.cell.borrow();
5862            crate::app::MaterialApp::new()
5863                .theme(m3(&app))
5864                .navigator_observers([root_observer.erase::<waft_widgets::AnyNavigatorObserver>()])
5865                .home(
5866                    Navigator::new()
5867                        .observers([nested_observer.erase::<waft_widgets::AnyNavigatorObserver>()])
5868                        .on_generate_route(move |app, _settings| {
5869                            let route = crate::page::MaterialPageRoute::new(
5870                                app,
5871                                Rc::new(move |_app, context| {
5872                                    ElevatedButton::new(
5873                                        Some(waft_foundation::Listener::new(move |app| {
5874                                            let show = Show {
5875                                                use_root_navigator,
5876                                                ..Show::default()
5877                                            };
5878                                            drop(show.show(
5879                                                app,
5880                                                context,
5881                                                Rc::new(|_app, _inner_context| {
5882                                                    AlertDialog::new()
5883                                                        .title(Text::new("Title"))
5884                                                        .into_widget()
5885                                                }),
5886                                            ));
5887                                        })),
5888                                        Some(Text::new("Show Dialog")),
5889                                    )
5890                                    .into_widget()
5891                                }),
5892                            );
5893                            Some(route.erase())
5894                        }),
5895                )
5896                .into_widget()
5897        };
5898        tester.pump_widget(root);
5899
5900        // Open the dialog.
5901        let button = tester.element(find::by_type::<ElevatedButton>());
5902        let center = tester.get_rect(button).center();
5903        tester.tap_at(center, 1);
5904
5905        let app = tester.cell.borrow();
5906        (
5907            app.get(&root_observer).dialog_count.get(),
5908            app.get(&nested_observer).dialog_count.get(),
5909        )
5910    }
5911
5912    #[test]
5913    fn show_dialog_uses_root_navigator_by_default() {
5914        test_widgets(|tester| {
5915            assert_eq!(dialogs_seen_by_root_and_nested(tester, true), (1, 0));
5916        });
5917    }
5918
5919    #[test]
5920    fn show_dialog_uses_nested_navigator_if_use_root_navigator_is_false() {
5921        test_widgets(|tester| {
5922            assert_eq!(dialogs_seen_by_root_and_nested(tester, false), (0, 1));
5923        });
5924    }
5925
5926    #[test]
5927    fn show_dialog_throws_a_friendly_user_message_when_context_is_not_active() {
5928        // Regression test for https://github.com/flutter/flutter/issues/12467
5929        test_widgets(|tester| {
5930            pump_app(tester, m3, |_app| {
5931                Center::new().child(Text::new("Test")).into_widget()
5932            });
5933            let context = find::text("Test").evaluate(tester)[0];
5934
5935            pump_app(tester, m3, |_app| Center::new().into_widget());
5936
5937            let error = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5938                drop(Show::default().on(
5939                    tester,
5940                    context,
5941                    Rc::new(|_app, _inner_context| {
5942                        AlertDialog::new().title(Text::new("Title")).into_widget()
5943                    }),
5944                ));
5945            }))
5946            .expect_err("showDialog throws");
5947
5948            let message = error
5949                .downcast_ref::<String>()
5950                .cloned()
5951                .or_else(|| error.downcast_ref::<&str>().map(|text| (*text).to_owned()))
5952                .expect("a message");
5953            assert_eq!(
5954                message.lines().next(),
5955                Some("This BuildContext is no longer valid.")
5956            );
5957        });
5958    }
5959
5960    /// Not a Dart case: what Dart's collector does with the `CurvedAnimation` a `DialogRoute`
5961    /// makes for its fade, freed once the route is gone.
5962    #[test]
5963    fn a_disposed_dialog_route_frees_its_fade() {
5964        test_widgets(|tester| {
5965            let saved_context = context_cell();
5966            let saved = Rc::clone(&saved_context);
5967            pump_app(tester, m3, move |_app| {
5968                Material::new()
5969                    .child(Builder::new(move |_app, context| {
5970                        saved.set(Some(context));
5971                        SizedBox::new().into_widget()
5972                    }))
5973                    .into_widget()
5974            });
5975            let navigator =
5976                Navigator::of(&mut tester.cell.borrow_mut(), seen(&saved_context), false);
5977            let route = {
5978                let mut app = tester.cell.borrow_mut();
5979                let route = DialogRoute::new(
5980                    &mut app,
5981                    seen(&saved_context),
5982                    Rc::new(move |_app, _context| Text::new("Dialog").into_widget()),
5983                );
5984                drop(navigator.push(&mut app, route.erase()));
5985                route
5986            };
5987            tester.pump_and_settle();
5988            let fade = tester
5989                .cell
5990                .borrow()
5991                .get(&route)
5992                .curved_animation
5993                .as_ref()
5994                .expect("the route built its transitions")
5995                .handle();
5996
5997            navigator.pop(&mut tester.cell.borrow_mut(), None);
5998            tester.pump_and_settle();
5999            drop(route);
6000            tester.cell.checkpoint();
6001            assert!(!tester.cell.borrow().contains(fade));
6002        });
6003    }
6004}