Skip to main content

waft_material/
bottom_sheet.rs

1//! Flutter counterpart: material_ui's `bottom_sheet.dart`.
2
3use std::any::TypeId;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{
9    Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
10    AnimationStyle, AnyAnimation, ColorTween, Curve, CurveTween, CurvedAnimation, Curves, Drive,
11    ProxyAnimation, Split, k_always_dismissed_animation,
12};
13use waft_embedder::{
14    Clip, Color, Offset, SemanticsHitTestBehavior, Size, TargetPlatform, TextBaseline,
15};
16use waft_foundation::{
17    App, CompleterFuture, Handle, Listenable, OptionRetained, PRECISION_ERROR_TOLERANCE, Ref,
18    ValueChanged, ValueNotifier, VoidCallback,
19};
20use waft_gestures::{
21    DragEndDetails, DragGestureRecognizer, DragStartDetails, DragUpdateDetails,
22    GestureDragEndCallback, GestureDragStartCallback, GestureDragUpdateCallback, PointerEnterEvent,
23    PointerExitEvent, VerticalDragGestureRecognizer,
24};
25use waft_painting::{
26    AlignmentGeometry, AnyColor, BorderRadius, BoxDecoration, EdgeInsets, EdgeInsetsGeometry,
27    ShapeBorderRef,
28};
29use waft_rendering::{
30    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData, Constraints,
31    PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
32    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderShiftedBox,
33};
34use waft_widgets::{
35    Align, AnimatedModalBarrier, BuildContext, Builder, CapturedThemes, Center, ClipRect,
36    ConstrainedBox, Container, DraggableScrollableNotification, GestureRecognizerFactory,
37    GestureRecognizerFactoryWithHandlers, GlobalKey, InheritedTheme, IntoWidget, KeyRef,
38    ListenableBuilder, LocalHistoryRoute, LocalHistoryRouteData, MediaQuery, ModalBarrier,
39    ModalRoute, ModalRouteData, MouseRegion, Navigator, NotificationListener, OverlayRoute,
40    OverlayRouteData, Padding, PopupRoute, PredictiveBackRoute, RawGestureDetector,
41    RenderObjectWidget, Route, RouteData, RouteResult, RouteSettingsRef, SafeArea, Semantics,
42    SingleChildRenderObjectWidget, SizedBox, Stack, State, StateData, StatefulWidget,
43    StatelessWidget, TransitionRoute, TransitionRouteData, WidgetBuilder, WidgetRef, WidgetState,
44    WidgetStateProperty, WidgetStates, debug_check_has_media_query,
45};
46
47use crate::bottom_sheet_theme::{BottomSheetThemeData, BottomSheetThemeDataGetters};
48use crate::colors::Colors;
49use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
50use crate::debug::{debug_check_has_material_localizations, debug_check_has_scaffold};
51use crate::generated::bottom_sheet_defaults_m3::BottomSheetDefaultsM3;
52use crate::material::Material;
53use crate::material_localizations::MaterialLocalizations;
54use crate::motion::Easing;
55use crate::scaffold::{PersistentBottomSheetController, Scaffold};
56use crate::theme::Theme;
57
58const K_BOTTOM_SHEET_ENTER_DURATION: Duration = Duration::from_millis(250);
59const K_BOTTOM_SHEET_EXIT_DURATION: Duration = Duration::from_millis(200);
60const K_MIN_FLING_VELOCITY: f64 = 700.0;
61const K_CLOSE_PROGRESS_THRESHOLD: f64 = 0.5;
62const K_DEFAULT_SCROLL_CONTROL_DISABLED_MAX_HEIGHT_RATIO: f64 = 9.0 / 16.0;
63
64/// Dart's `_kModalBottomSheetCurve`.
65fn k_modal_bottom_sheet_curve() -> Rc<dyn Curve> {
66    Easing::legacy_decelerate()
67}
68
69/// A callback for when the user begins dragging the bottom sheet.
70///
71/// Used by [`BottomSheet::on_drag_start`].
72pub type BottomSheetDragStartHandler = Rc<dyn Fn(&mut App, DragStartDetails)>;
73
74/// A callback for when the user stops dragging the bottom sheet.
75///
76/// The `bool` is Dart's named `isClosing`.
77///
78/// Used by [`BottomSheet::on_drag_end`].
79pub type BottomSheetDragEndHandler = Rc<dyn Fn(&mut App, DragEndDetails, bool)>;
80
81/// A Material Design bottom sheet.
82///
83/// There are two kinds of bottom sheets in Material Design:
84///
85///  * _Persistent_. A persistent bottom sheet shows information that
86///    supplements the primary content of the app. A persistent bottom sheet
87///    remains visible even when the user interacts with other parts of the app.
88///    Persistent bottom sheets can be created and displayed with the
89///    `ScaffoldState::show_bottom_sheet` function or by specifying the
90///    `Scaffold::bottom_sheet` constructor parameter.
91///
92///  * _Modal_. A modal bottom sheet is an alternative to a menu or a dialog and
93///    prevents the user from interacting with the rest of the app. Modal bottom
94///    sheets can be created and displayed with the [`ShowModalBottomSheet`]
95///    function.
96///
97/// The [`BottomSheet`] widget itself is rarely used directly. Instead, prefer to
98/// create a persistent bottom sheet with `ScaffoldState::show_bottom_sheet` or
99/// `Scaffold::bottom_sheet`, and a modal bottom sheet with [`ShowModalBottomSheet`].
100///
101/// See also:
102///
103///  * [`show_bottom_sheet`] and `ScaffoldState::show_bottom_sheet`, for showing
104///    non-modal "persistent" bottom sheets.
105///  * [`ShowModalBottomSheet`], which can be used to display a modal bottom
106///    sheet.
107///  * [`BottomSheetThemeData`], which can be used to customize the default
108///    bottom sheet property values.
109///  * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
110///  * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
111pub struct BottomSheet {
112    pub key: Option<KeyRef>,
113
114    /// The animation controller that controls the bottom sheet's entrance and
115    /// exit animations.
116    ///
117    /// The BottomSheet widget will manipulate the position of this animation, it
118    /// is not just a passive observer.
119    pub animation_controller: Option<Ref<AnimationController>>,
120
121    /// Called when the bottom sheet begins to close.
122    ///
123    /// A bottom sheet might be prevented from closing (e.g., by user
124    /// interaction) even after this callback is called. For this reason, this
125    /// callback might be call multiple times for a given bottom sheet.
126    pub on_closing: VoidCallback,
127
128    /// A builder for the contents of the sheet.
129    ///
130    /// The bottom sheet will wrap the widget produced by this builder in a
131    /// [`Material`] widget.
132    pub builder: WidgetBuilder,
133
134    /// If true, the bottom sheet can be dragged up and down and dismissed by
135    /// swiping downwards.
136    ///
137    /// If [`show_drag_handle`](Self::show_drag_handle) is true, this only applies to the
138    /// content below the drag handle, because the drag handle is always draggable.
139    ///
140    /// Default is true.
141    ///
142    /// If this is true, the [`animation_controller`](Self::animation_controller) must not be
143    /// null. Use [`BottomSheet::create_animation_controller`] to create one, or provide
144    /// another AnimationController.
145    pub enable_drag: bool,
146
147    /// Specifies whether a drag handle is shown.
148    ///
149    /// The drag handle appears at the top of the bottom sheet. The default color is
150    /// `ColorScheme.onSurfaceVariant` with an opacity of 0.4 and can be customized
151    /// using [`drag_handle_color`](Self::drag_handle_color). The default size is
152    /// `Size(32,4)` and can be customized with [`drag_handle_size`](Self::drag_handle_size).
153    ///
154    /// If null, then the value of [`BottomSheetThemeData::show_drag_handle`] is used. If
155    /// that is also null, defaults to false.
156    ///
157    /// If this is true, the [`animation_controller`](Self::animation_controller) must not be
158    /// null. Use [`BottomSheet::create_animation_controller`] to create one, or provide
159    /// another AnimationController.
160    pub show_drag_handle: Option<bool>,
161
162    /// The bottom sheet drag handle's color.
163    ///
164    /// Defaults to [`BottomSheetThemeData::drag_handle_color`].
165    /// If that is also null, defaults to `ColorScheme.onSurfaceVariant`.
166    pub drag_handle_color: Option<AnyColor>,
167
168    /// Defaults to [`BottomSheetThemeData::drag_handle_size`].
169    /// If that is also null, defaults to Size(32, 4).
170    pub drag_handle_size: Option<Size>,
171
172    /// Called when the user begins dragging the bottom sheet vertically, if
173    /// [`enable_drag`](Self::enable_drag) is true.
174    ///
175    /// Would typically be used to change the bottom sheet animation curve so
176    /// that it tracks the user's finger accurately.
177    pub on_drag_start: Option<BottomSheetDragStartHandler>,
178
179    /// Called when the user stops dragging the bottom sheet, if
180    /// [`enable_drag`](Self::enable_drag) is true.
181    ///
182    /// Would typically be used to reset the bottom sheet animation curve, so
183    /// that it animates non-linearly. Called before [`on_closing`](Self::on_closing) if the
184    /// bottom sheet is closing.
185    pub on_drag_end: Option<BottomSheetDragEndHandler>,
186
187    /// The bottom sheet's background color.
188    ///
189    /// Defines the bottom sheet's `Material.color`.
190    ///
191    /// Defaults to null and falls back to [`Material`]'s default.
192    pub background_color: Option<Color>,
193
194    /// The color of the shadow below the sheet.
195    ///
196    /// If this property is null, then [`BottomSheetThemeData::shadow_color`] of
197    /// `ThemeData.bottomSheetTheme` is used. If that is also null, the default value
198    /// is transparent.
199    ///
200    /// See also:
201    ///
202    ///  * [`elevation`](Self::elevation), which defines the size of the shadow below the
203    ///    sheet.
204    ///  * [`shape`](Self::shape), which defines the shape of the sheet and its shadow.
205    pub shadow_color: Option<Color>,
206
207    /// The z-coordinate at which to place this material relative to its parent.
208    ///
209    /// This controls the size of the shadow below the material.
210    ///
211    /// Defaults to 0. The value is non-negative.
212    pub elevation: Option<f64>,
213
214    /// The shape of the bottom sheet.
215    ///
216    /// Defines the bottom sheet's `Material.shape`.
217    ///
218    /// Defaults to null and falls back to [`Material`]'s default.
219    pub shape: Option<ShapeBorderRef>,
220
221    /// The content will be clipped (or not) according to this option.
222    ///
223    /// Defines the bottom sheet's `Material.clipBehavior`.
224    ///
225    /// Use this property to enable clipping of content when the bottom sheet has
226    /// a custom [`shape`](Self::shape) and the content can extend past this shape. For
227    /// example, a bottom sheet with rounded corners and an edge-to-edge `Image` at the
228    /// top.
229    ///
230    /// If this property is null then [`BottomSheetThemeData::clip_behavior`] of
231    /// `ThemeData.bottomSheetTheme` is used. If that's null then the behavior
232    /// will be [`Clip::None`].
233    pub clip_behavior: Option<Clip>,
234
235    /// Defines minimum and maximum sizes for a [`BottomSheet`].
236    ///
237    /// If null, then the ambient `ThemeData.bottomSheetTheme`'s
238    /// [`BottomSheetThemeData::constraints`] will be used. If that
239    /// is null and `ThemeData.useMaterial3` is true, then the bottom sheet
240    /// will have a max width of 640dp. If `ThemeData.useMaterial3` is false, then
241    /// the bottom sheet's size will be constrained by its parent
242    /// (usually a `Scaffold`). In this case, consider limiting the width by
243    /// setting smaller constraints for large screens.
244    ///
245    /// If constraints are specified (either in this property or in the
246    /// theme), the bottom sheet will be aligned to the bottom-center of
247    /// the available space. Otherwise, no alignment is applied.
248    pub constraints: Option<BoxConstraints>,
249}
250
251impl BottomSheet {
252    /// Creates a bottom sheet.
253    ///
254    /// Typically, bottom sheets are created implicitly by
255    /// `ScaffoldState::show_bottom_sheet`, for persistent bottom sheets, or by
256    /// [`ShowModalBottomSheet`], for modal bottom sheets.
257    pub fn new(on_closing: VoidCallback, builder: WidgetBuilder) -> BottomSheet {
258        BottomSheet {
259            key: None,
260            animation_controller: None,
261            on_closing,
262            builder,
263            enable_drag: true,
264            show_drag_handle: None,
265            drag_handle_color: None,
266            drag_handle_size: None,
267            on_drag_start: None,
268            on_drag_end: None,
269            background_color: None,
270            shadow_color: None,
271            elevation: None,
272            shape: None,
273            clip_behavior: None,
274            constraints: None,
275        }
276    }
277
278    /// Dart `BottomSheet(key:)`.
279    pub fn key(mut self, key: KeyRef) -> BottomSheet {
280        self.key = Some(key);
281        self
282    }
283
284    /// Dart `BottomSheet(animationController:)`.
285    pub fn animation_controller(
286        mut self,
287        animation_controller: Ref<AnimationController>,
288    ) -> BottomSheet {
289        self.animation_controller = Some(animation_controller);
290        self
291    }
292
293    /// Dart `BottomSheet(enableDrag:)`.
294    pub fn enable_drag(mut self, enable_drag: bool) -> BottomSheet {
295        self.enable_drag = enable_drag;
296        self
297    }
298
299    /// Dart `BottomSheet(showDragHandle:)`.
300    pub fn show_drag_handle(mut self, show_drag_handle: bool) -> BottomSheet {
301        self.show_drag_handle = Some(show_drag_handle);
302        self
303    }
304
305    /// Dart `BottomSheet(dragHandleColor:)`.
306    pub fn drag_handle_color(mut self, drag_handle_color: impl Into<AnyColor>) -> BottomSheet {
307        self.drag_handle_color = Some(drag_handle_color.into());
308        self
309    }
310
311    /// Dart `BottomSheet(dragHandleSize:)`.
312    pub fn drag_handle_size(mut self, drag_handle_size: Size) -> BottomSheet {
313        self.drag_handle_size = Some(drag_handle_size);
314        self
315    }
316
317    /// Dart `BottomSheet(onDragStart:)`.
318    pub fn on_drag_start(
319        mut self,
320        on_drag_start: impl Fn(&mut App, DragStartDetails) + 'static,
321    ) -> BottomSheet {
322        self.on_drag_start = Some(Rc::new(on_drag_start));
323        self
324    }
325
326    /// Dart `BottomSheet(onDragEnd:)`.
327    pub fn on_drag_end(
328        mut self,
329        on_drag_end: impl Fn(&mut App, DragEndDetails, bool) + 'static,
330    ) -> BottomSheet {
331        self.on_drag_end = Some(Rc::new(on_drag_end));
332        self
333    }
334
335    /// Dart `BottomSheet(backgroundColor:)`.
336    pub fn background_color(mut self, background_color: Color) -> BottomSheet {
337        self.background_color = Some(background_color);
338        self
339    }
340
341    /// Dart `BottomSheet(shadowColor:)`.
342    pub fn shadow_color(mut self, shadow_color: Color) -> BottomSheet {
343        self.shadow_color = Some(shadow_color);
344        self
345    }
346
347    /// Dart `BottomSheet(elevation:)`.
348    pub fn elevation(mut self, elevation: f64) -> BottomSheet {
349        debug_assert!(elevation >= 0.0);
350        self.elevation = Some(elevation);
351        self
352    }
353
354    /// Dart `BottomSheet(shape:)`.
355    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> BottomSheet {
356        self.shape = Some(shape.into());
357        self
358    }
359
360    /// Dart `BottomSheet(clipBehavior:)`.
361    pub fn clip_behavior(mut self, clip_behavior: Clip) -> BottomSheet {
362        self.clip_behavior = Some(clip_behavior);
363        self
364    }
365
366    /// Dart `BottomSheet(constraints:)`.
367    pub fn constraints(mut self, constraints: BoxConstraints) -> BottomSheet {
368        self.constraints = Some(constraints);
369        self
370    }
371
372    /// Creates an [`AnimationController`] suitable for a
373    /// [`BottomSheet::animation_controller`].
374    ///
375    /// This API is available as a convenience for a Material compliant bottom sheet
376    /// animation. If alternative animation durations are required, a different
377    /// animation controller could be provided.
378    pub fn create_animation_controller(
379        app: &mut App,
380        vsync: impl waft_scheduler::TickerProvider,
381        sheet_animation_style: Option<&AnimationStyle>,
382    ) -> Ref<AnimationController> {
383        AnimationController::new(
384            app,
385            None,
386            Some(
387                sheet_animation_style
388                    .and_then(|style| style.duration)
389                    .unwrap_or(K_BOTTOM_SHEET_ENTER_DURATION),
390            ),
391            Some(
392                sheet_animation_style
393                    .and_then(|style| style.reverse_duration)
394                    .unwrap_or(K_BOTTOM_SHEET_EXIT_DURATION),
395            ),
396            0.0,
397            1.0,
398            AnimationBehavior::Normal,
399            vsync,
400        )
401    }
402}
403
404impl Debug for BottomSheet {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        f.debug_struct("BottomSheet")
407            .field("key", &self.key)
408            .field("animationController", &self.animation_controller)
409            .field("enableDrag", &self.enable_drag)
410            .field("showDragHandle", &self.show_drag_handle)
411            .field("dragHandleColor", &self.drag_handle_color)
412            .field("dragHandleSize", &self.drag_handle_size)
413            .field("backgroundColor", &self.background_color)
414            .field("shadowColor", &self.shadow_color)
415            .field("elevation", &self.elevation)
416            .field("shape", &self.shape)
417            .field("clipBehavior", &self.clip_behavior)
418            .field("constraints", &self.constraints)
419            .finish_non_exhaustive()
420    }
421}
422
423impl StatefulWidget for BottomSheet {
424    type State = BottomSheetState;
425
426    fn key(&self) -> Option<&KeyRef> {
427        self.key.as_ref()
428    }
429
430    fn create_state(&self) -> BottomSheetState {
431        BottomSheetState {
432            state: StateData::new(),
433            child_key: GlobalKey::new(),
434            drag_handle_states: WidgetStates::new(),
435        }
436    }
437}
438
439/// Dart's `_BottomSheetState`.
440pub struct BottomSheetState {
441    state: StateData<BottomSheet>,
442    /// Dart's `GlobalKey(debugLabel: 'BottomSheet child')`.
443    child_key: GlobalKey,
444    drag_handle_states: WidgetStates,
445}
446
447impl BottomSheetState {
448    fn child_height(self: Handle<Self>, app: &mut App) -> f64 {
449        let child_key = app.get(self).child_key.clone();
450        let render_box = child_key
451            .current_context(app)
452            .expect("the sheet's Material is mounted")
453            .find_render_object(app)
454            .and_then(|render_object| render_object.as_box())
455            .expect("a Material renders a box");
456        render_box.size(app).height()
457    }
458
459    fn dismiss_underway(self: Handle<Self>, app: &App) -> bool {
460        self.animation_controller(app).status(app) == AnimationStatus::Reverse
461    }
462
463    /// Dart's `widget.animationController!`.
464    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
465        self.widget(app)
466            .animation_controller
467            .handle()
468            .expect("the sheet has an animation controller")
469    }
470
471    fn handle_drag_start(self: Handle<Self>, app: &mut App, details: DragStartDetails) {
472        self.set_state(app, |state| {
473            state.drag_handle_states.insert(WidgetState::Dragged);
474        });
475        if let Some(on_drag_start) = self.widget(app).on_drag_start.clone() {
476            on_drag_start(app, details);
477        }
478    }
479
480    fn debug_assert_has_controller(self: Handle<Self>, app: &App) {
481        let widget = self.widget(app);
482        debug_assert!(
483            (widget.enable_drag || widget.show_drag_handle.unwrap_or(false))
484                && widget.animation_controller.is_some(),
485            "'BottomSheet.animationController' cannot be null when 'BottomSheet.enableDrag' or \
486             'BottomSheet.showDragHandle' is true. Use 'BottomSheet.createAnimationController' to \
487             create one, or provide another AnimationController."
488        );
489    }
490
491    fn handle_drag_update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
492        self.debug_assert_has_controller(app);
493        if self.dismiss_underway(app) {
494            return;
495        }
496        let controller = self.animation_controller(app);
497        let child_height = self.child_height(app);
498        let primary_delta = details
499            .primary_delta
500            .expect("a vertical drag has a primary delta");
501        let value = controller.value(app) - primary_delta / child_height;
502        controller.set_value(app, value);
503    }
504
505    fn handle_drag_end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
506        self.debug_assert_has_controller(app);
507        if self.dismiss_underway(app) {
508            return;
509        }
510        self.set_state(app, |state| {
511            state.drag_handle_states.remove(&WidgetState::Dragged);
512        });
513        let controller = self.animation_controller(app);
514        let mut is_closing = false;
515        if details.velocity.pixels_per_second.dy() > K_MIN_FLING_VELOCITY {
516            let fling_velocity = -details.velocity.pixels_per_second.dy() / self.child_height(app);
517            if controller.value(app) > 0.0 {
518                controller.fling(app, fling_velocity, None, None);
519            }
520            if fling_velocity < 0.0 {
521                is_closing = true;
522            }
523        } else if controller.value(app) < K_CLOSE_PROGRESS_THRESHOLD {
524            if controller.value(app) > 0.0 {
525                controller.fling(app, -1.0, None, None);
526            }
527            is_closing = true;
528        } else {
529            controller.forward(app, None);
530        }
531
532        if let Some(on_drag_end) = self.widget(app).on_drag_end.clone() {
533            on_drag_end(app, details, is_closing);
534        }
535
536        if is_closing {
537            let on_closing = self.widget(app).on_closing.clone();
538            on_closing(app);
539        }
540    }
541
542    /// Dart's `extentChanged`.
543    pub fn extent_changed(
544        self: Handle<Self>,
545        app: &mut App,
546        notification: &DraggableScrollableNotification,
547    ) -> bool {
548        if (notification.extent - notification.min_extent).abs() < PRECISION_ERROR_TOLERANCE
549            && notification.should_close_on_min_extent
550        {
551            let on_closing = self.widget(app).on_closing.clone();
552            on_closing(app);
553        }
554        false
555    }
556
557    fn handle_drag_handle_hover(self: Handle<Self>, app: &mut App, hovering: bool) {
558        if hovering
559            != app
560                .get(self)
561                .drag_handle_states
562                .contains(&WidgetState::Hovered)
563        {
564            self.set_state(app, |state| {
565                if hovering {
566                    state.drag_handle_states.insert(WidgetState::Hovered);
567                } else {
568                    state.drag_handle_states.remove(&WidgetState::Hovered);
569                }
570            });
571        }
572    }
573}
574
575impl State for BottomSheetState {
576    type Widget = BottomSheet;
577    waft_widgets::state_accessors!();
578
579    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
580        let theme = Theme::of(app, context);
581        let bottom_sheet_theme = theme.bottom_sheet_theme.clone();
582        let use_material3 = theme.use_material3;
583        let defaults: Box<dyn BottomSheetThemeDataGetters> = if use_material3 {
584            Box::new(BottomSheetDefaultsM3::new(context))
585        } else {
586            Box::new(BottomSheetThemeData::new())
587        };
588        let widget_ref = context.widget(app).clone();
589        let widget = waft_widgets::downcast_widget::<BottomSheet>(&*widget_ref)
590            .expect("a BottomSheetState builds its BottomSheet");
591        let constraints = widget
592            .constraints
593            .or(bottom_sheet_theme.constraints)
594            .or_else(|| defaults.constraints(app));
595        let color = widget
596            .background_color
597            .or(bottom_sheet_theme.background_color)
598            .or_else(|| defaults.background_color(app));
599        let surface_tint_color = bottom_sheet_theme
600            .surface_tint_color
601            .or_else(|| defaults.surface_tint_color(app));
602        let shadow_color = widget
603            .shadow_color
604            .or(bottom_sheet_theme.shadow_color)
605            .or_else(|| defaults.shadow_color(app));
606        let elevation = widget
607            .elevation
608            .or(bottom_sheet_theme.elevation)
609            .or_else(|| defaults.elevation(app))
610            .unwrap_or(0.0);
611        let shape = widget
612            .shape
613            .clone()
614            .or_else(|| bottom_sheet_theme.shape.clone())
615            .or_else(|| defaults.shape(app));
616        let clip_behavior = widget
617            .clip_behavior
618            .or(bottom_sheet_theme.clip_behavior)
619            .unwrap_or(Clip::None);
620        let show_drag_handle = widget
621            .show_drag_handle
622            .unwrap_or(widget.enable_drag && bottom_sheet_theme.show_drag_handle.unwrap_or(false));
623        let enable_drag = widget.enable_drag;
624        let builder = Rc::clone(&widget.builder);
625        let drag_handle_color = widget.drag_handle_color.clone();
626        let drag_handle_size = widget.drag_handle_size;
627        let on_closing = Rc::clone(&widget.on_closing);
628
629        let mut drag_handle: Option<WidgetRef> = None;
630        if show_drag_handle {
631            let handle = DragHandle {
632                on_semantics_tap: Some(on_closing),
633                handle_hover: Rc::new(move |app, hovering| {
634                    self.handle_drag_handle_hover(app, hovering)
635                }),
636                states: app.get(self).drag_handle_states.clone(),
637                drag_handle_color,
638                drag_handle_size,
639            }
640            .into_widget();
641            // Only add [_BottomSheetGestureDetector] to the drag handle when the rest of the
642            // bottom sheet is not draggable. If the whole bottom sheet is draggable,
643            // no need to add it.
644            drag_handle = Some(if !enable_drag {
645                self.gesture_detector(handle)
646            } else {
647                handle
648            });
649        }
650
651        let child_key = app.get(self).child_key.clone();
652        let content = if !show_drag_handle {
653            builder(app, context)
654        } else {
655            Stack::new()
656                .alignment(AlignmentGeometry::TOP_CENTER)
657                .children([
658                    drag_handle.expect("built when the drag handle shows"),
659                    Padding::new(EdgeInsetsGeometry::only(
660                        0.0,
661                        K_MIN_INTERACTIVE_DIMENSION,
662                        0.0,
663                        0.0,
664                    ))
665                    .child(builder(app, context))
666                    .into_widget(),
667                ])
668                .into_widget()
669        };
670        let mut material = Material::new()
671            .key(child_key.into())
672            .elevation(elevation)
673            .clip_behavior(clip_behavior)
674            .child(
675                NotificationListener::<DraggableScrollableNotification>::new(content)
676                    .on_notification(move |app, notification| {
677                        self.extent_changed(app, notification)
678                    })
679                    .into_widget(),
680            );
681        material.color = color;
682        material.surface_tint_color = surface_tint_color;
683        material.shadow_color = shadow_color;
684        material.shape = shape;
685        let mut bottom_sheet = material.into_widget();
686
687        if let Some(constraints) = constraints {
688            bottom_sheet = Align::new()
689                .alignment(AlignmentGeometry::BOTTOM_CENTER)
690                .height_factor(1.0)
691                .child(ConstrainedBox::new(constraints).child(bottom_sheet))
692                .into_widget();
693        }
694
695        if !enable_drag {
696            bottom_sheet
697        } else {
698            self.gesture_detector(bottom_sheet)
699        }
700    }
701}
702
703impl BottomSheetState {
704    /// Dart's `_BottomSheetGestureDetector` around `child`, with this state's drag handlers.
705    fn gesture_detector(self: Handle<Self>, child: WidgetRef) -> WidgetRef {
706        BottomSheetGestureDetector {
707            child,
708            on_vertical_drag_start: Rc::new(move |app, details| {
709                self.handle_drag_start(app, details)
710            }),
711            on_vertical_drag_update: Rc::new(move |app, details| {
712                self.handle_drag_update(app, details)
713            }),
714            on_vertical_drag_end: Rc::new(move |app, details| self.handle_drag_end(app, details)),
715        }
716        .into_widget()
717    }
718}
719
720// PERSISTENT BOTTOM SHEETS
721
722// See scaffold.rs
723
724/// Dart's `_DragHandle`.
725struct DragHandle {
726    on_semantics_tap: Option<VoidCallback>,
727    handle_hover: ValueChanged<bool>,
728    states: WidgetStates,
729    drag_handle_color: Option<AnyColor>,
730    drag_handle_size: Option<Size>,
731}
732
733impl Debug for DragHandle {
734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735        f.debug_struct("DragHandle")
736            .field("states", &self.states)
737            .field("dragHandleColor", &self.drag_handle_color)
738            .field("dragHandleSize", &self.drag_handle_size)
739            .finish_non_exhaustive()
740    }
741}
742
743impl StatelessWidget for DragHandle {
744    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
745        let bottom_sheet_theme = Theme::of(app, context).bottom_sheet_theme.clone();
746        let m3_defaults = BottomSheetDefaultsM3::new(context);
747        let handle_size = self
748            .drag_handle_size
749            .or(bottom_sheet_theme.drag_handle_size)
750            .or_else(|| m3_defaults.drag_handle_size(app))
751            .expect("the Material 3 defaults have a drag handle size");
752        let color =
753            <dyn WidgetStateProperty<Color>>::resolve_as(&self.drag_handle_color, &self.states)
754                .or_else(|| {
755                    <dyn WidgetStateProperty<Color>>::resolve_as(
756                        &bottom_sheet_theme.drag_handle_color,
757                        &self.states,
758                    )
759                })
760                .or_else(|| m3_defaults.drag_handle_color(app))
761                .map(|color| color.color());
762        let mut decoration =
763            BoxDecoration::new().border_radius(BorderRadius::circular(handle_size.height() / 2.0));
764        decoration.color = color.map(Into::into);
765
766        let enter_hover = Rc::clone(&self.handle_hover);
767        let exit_hover = Rc::clone(&self.handle_hover);
768        let mut semantics = Semantics::new()
769            .label(<dyn MaterialLocalizations>::of(app, context).modal_barrier_dismiss_label())
770            .container(true)
771            .button(true);
772        if let Some(on_semantics_tap) = self.on_semantics_tap.clone() {
773            semantics = semantics.on_tap(on_semantics_tap);
774        }
775        MouseRegion::new()
776            .on_enter(Rc::new(move |app: &mut App, _event: PointerEnterEvent| {
777                enter_hover(app, true)
778            }))
779            .on_exit(Rc::new(move |app: &mut App, _event: PointerExitEvent| {
780                exit_hover(app, false)
781            }))
782            .child(
783                semantics.child(
784                    SizedBox::new()
785                        .width(handle_size.width().max(K_MIN_INTERACTIVE_DIMENSION))
786                        .height(handle_size.height().max(K_MIN_INTERACTIVE_DIMENSION))
787                        .child(
788                            Center::new().child(
789                                Container::new()
790                                    .height(handle_size.height())
791                                    .width(handle_size.width())
792                                    .decoration(decoration),
793                            ),
794                        ),
795                ),
796            )
797            .into_widget()
798    }
799}
800
801/// Dart's `_BottomSheetLayoutWithSizeListener`.
802struct BottomSheetLayoutWithSizeListener {
803    on_child_size_changed: ValueChanged<Size>,
804    animation_value: f64,
805    is_scroll_controlled: bool,
806    scroll_control_disabled_max_height_ratio: f64,
807    child: Option<WidgetRef>,
808}
809
810impl Debug for BottomSheetLayoutWithSizeListener {
811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812        f.debug_struct("BottomSheetLayoutWithSizeListener")
813            .field("animationValue", &self.animation_value)
814            .field("isScrollControlled", &self.is_scroll_controlled)
815            .field(
816                "scrollControlDisabledMaxHeightRatio",
817                &self.scroll_control_disabled_max_height_ratio,
818            )
819            .finish_non_exhaustive()
820    }
821}
822
823impl RenderObjectWidget for BottomSheetLayoutWithSizeListener {
824    type RenderObject = RenderBottomSheetLayoutWithSizeListener;
825
826    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
827        RenderBottomSheetLayoutWithSizeListener::new(
828            app,
829            None,
830            Rc::clone(&self.on_child_size_changed),
831            self.animation_value,
832            self.is_scroll_controlled,
833            self.scroll_control_disabled_max_height_ratio,
834        )
835        .as_object()
836    }
837
838    fn update_render_object(
839        &self,
840        app: &mut App,
841        _context: BuildContext,
842        render_object: RenderHandle<RenderBottomSheetLayoutWithSizeListener>,
843    ) {
844        render_object.set_on_child_size_changed(app, Rc::clone(&self.on_child_size_changed));
845        render_object.set_animation_value(app, self.animation_value);
846        render_object.set_is_scroll_controlled(app, self.is_scroll_controlled);
847        render_object.set_scroll_control_disabled_max_height_ratio(
848            app,
849            self.scroll_control_disabled_max_height_ratio,
850        );
851    }
852}
853
854impl SingleChildRenderObjectWidget for BottomSheetLayoutWithSizeListener {
855    fn child(&self) -> Option<&WidgetRef> {
856        self.child.as_ref()
857    }
858}
859
860/// Dart's `_RenderBottomSheetLayoutWithSizeListener`.
861struct RenderBottomSheetLayoutWithSizeListener {
862    render_object: RenderObjectData,
863    render_box: RenderBoxData,
864    child: RenderObjectWithChildData<AnyRenderBox>,
865    last_size: Size,
866    on_child_size_changed: ValueChanged<Size>,
867    animation_value: f64,
868    is_scroll_controlled: bool,
869    scroll_control_disabled_max_height_ratio: f64,
870}
871
872impl RenderBottomSheetLayoutWithSizeListener {
873    fn new(
874        app: &mut App,
875        child: Option<AnyRenderBox>,
876        on_child_size_changed: ValueChanged<Size>,
877        animation_value: f64,
878        is_scroll_controlled: bool,
879        scroll_control_disabled_max_height_ratio: f64,
880    ) -> RenderHandle<RenderBottomSheetLayoutWithSizeListener> {
881        let this = RenderHandle::new_box(
882            app,
883            RenderBottomSheetLayoutWithSizeListener {
884                render_object: RenderObjectData::new(),
885                render_box: RenderBoxData::new(),
886                child: RenderObjectWithChildData::new(),
887                last_size: Size::ZERO,
888                on_child_size_changed,
889                animation_value,
890                is_scroll_controlled,
891                scroll_control_disabled_max_height_ratio,
892            },
893        );
894        this.set_child(app, child);
895        this
896    }
897
898    fn set_on_child_size_changed(
899        self: RenderHandle<Self>,
900        app: &mut App,
901        new_callback: ValueChanged<Size>,
902    ) {
903        if Rc::ptr_eq(&self.get(app).on_child_size_changed, &new_callback) {
904            return;
905        }
906
907        self.get_mut(app).on_child_size_changed = new_callback;
908        self.mark_needs_layout(app);
909    }
910
911    fn animation_value(self: RenderHandle<Self>, app: &App) -> f64 {
912        self.get(app).animation_value
913    }
914
915    fn set_animation_value(self: RenderHandle<Self>, app: &mut App, new_value: f64) {
916        if self.get(app).animation_value == new_value {
917            return;
918        }
919
920        self.get_mut(app).animation_value = new_value;
921        self.mark_needs_layout(app);
922    }
923
924    fn is_scroll_controlled(self: RenderHandle<Self>, app: &App) -> bool {
925        self.get(app).is_scroll_controlled
926    }
927
928    fn set_is_scroll_controlled(self: RenderHandle<Self>, app: &mut App, new_value: bool) {
929        if self.get(app).is_scroll_controlled == new_value {
930            return;
931        }
932
933        self.get_mut(app).is_scroll_controlled = new_value;
934        self.mark_needs_layout(app);
935    }
936
937    fn scroll_control_disabled_max_height_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
938        self.get(app).scroll_control_disabled_max_height_ratio
939    }
940
941    fn set_scroll_control_disabled_max_height_ratio(
942        self: RenderHandle<Self>,
943        app: &mut App,
944        new_value: f64,
945    ) {
946        if self.get(app).scroll_control_disabled_max_height_ratio == new_value {
947            return;
948        }
949
950        self.get_mut(app).scroll_control_disabled_max_height_ratio = new_value;
951        self.mark_needs_layout(app);
952    }
953
954    fn get_constraints_for_child(
955        self: RenderHandle<Self>,
956        app: &App,
957        constraints: BoxConstraints,
958    ) -> BoxConstraints {
959        BoxConstraints::new()
960            .min_width(constraints.max_width)
961            .max_width(constraints.max_width)
962            .max_height(if self.is_scroll_controlled(app) {
963                constraints.max_height
964            } else {
965                constraints.max_height * self.scroll_control_disabled_max_height_ratio(app)
966            })
967    }
968
969    fn get_position_for_child(
970        self: RenderHandle<Self>,
971        app: &App,
972        size: Size,
973        child_size: Size,
974    ) -> Offset {
975        Offset::new(
976            0.0,
977            size.height() - child_size.height() * self.animation_value(app),
978        )
979    }
980}
981
982impl RenderObjectWithChildMixin for RenderBottomSheetLayoutWithSizeListener {
983    type ChildType = AnyRenderBox;
984
985    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
986        &self.get(app).child
987    }
988
989    fn child_data_mut(
990        self: RenderHandle<Self>,
991        app: &mut App,
992    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
993        &mut self.get_mut(app).child
994    }
995}
996
997impl RenderShiftedBox for RenderBottomSheetLayoutWithSizeListener {}
998
999impl RenderObject for RenderBottomSheetLayoutWithSizeListener {
1000    waft_rendering::render_object_accessors!();
1001
1002    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1003        let constraints = self.constraints(app);
1004        let size = constraints.biggest();
1005        self.set_size(app, size);
1006        let Some(child) = self.child(app) else {
1007            return;
1008        };
1009
1010        let child_constraints = self.get_constraints_for_child(app, constraints);
1011        debug_assert!(child_constraints.debug_assert_is_valid(true));
1012        child.layout(app, child_constraints, !child_constraints.is_tight());
1013        let child_size = if child_constraints.is_tight() {
1014            child_constraints.smallest()
1015        } else {
1016            child.size(app)
1017        };
1018        child.parent_data_of_mut::<BoxParentData>(app).offset =
1019            self.get_position_for_child(app, size, child_size);
1020
1021        if self.get(app).last_size != child_size {
1022            self.get_mut(app).last_size = child_size;
1023            let on_child_size_changed = Rc::clone(&self.get(app).on_child_size_changed);
1024            on_child_size_changed(app, child_size);
1025        }
1026    }
1027
1028    fn paint(
1029        self: RenderHandle<Self>,
1030        app: &mut App,
1031        context: &mut PaintingContext,
1032        offset: Offset,
1033    ) {
1034        RenderShiftedBox::paint(self, app, context, offset);
1035    }
1036
1037    fn visit_children(
1038        self: RenderHandle<Self>,
1039        app: &App,
1040        visitor: &mut dyn FnMut(AnyRenderObject),
1041    ) {
1042        if let Some(child) = self.child(app) {
1043            visitor(child.as_object());
1044        }
1045    }
1046}
1047
1048impl RenderBox for RenderBottomSheetLayoutWithSizeListener {
1049    waft_rendering::render_box_accessors!();
1050
1051    fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
1052        0.0
1053    }
1054
1055    fn compute_max_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
1056        0.0
1057    }
1058
1059    fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
1060        0.0
1061    }
1062
1063    fn compute_max_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
1064        0.0
1065    }
1066
1067    fn compute_dry_layout(
1068        self: RenderHandle<Self>,
1069        _app: &mut App,
1070        constraints: BoxConstraints,
1071    ) -> Size {
1072        constraints.biggest()
1073    }
1074
1075    fn compute_dry_baseline(
1076        self: RenderHandle<Self>,
1077        app: &mut App,
1078        constraints: BoxConstraints,
1079        baseline: TextBaseline,
1080    ) -> Option<f64> {
1081        let child = self.child(app)?;
1082        let child_constraints = self.get_constraints_for_child(app, constraints);
1083        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
1084        let child_size = if child_constraints.is_tight() {
1085            child_constraints.smallest()
1086        } else {
1087            child.get_dry_layout(app, child_constraints)
1088        };
1089        Some(
1090            result
1091                + self
1092                    .get_position_for_child(app, constraints.biggest(), child_size)
1093                    .dy(),
1094        )
1095    }
1096
1097    fn compute_distance_to_actual_baseline(
1098        self: RenderHandle<Self>,
1099        app: &mut App,
1100        baseline: TextBaseline,
1101    ) -> Option<f64> {
1102        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1103    }
1104
1105    fn hit_test_children(
1106        self: RenderHandle<Self>,
1107        app: &mut App,
1108        result: &mut BoxHitTestResult<'_>,
1109        position: Offset,
1110    ) -> bool {
1111        RenderShiftedBox::hit_test_children(self, app, result, position)
1112    }
1113}
1114
1115/// Dart's `_ModalBottomSheet<T>`.
1116struct ModalBottomSheet {
1117    route: Handle<ModalBottomSheetRoute>,
1118    is_scroll_controlled: bool,
1119    scroll_control_disabled_max_height_ratio: f64,
1120    background_color: Option<Color>,
1121    elevation: Option<f64>,
1122    shape: Option<ShapeBorderRef>,
1123    clip_behavior: Option<Clip>,
1124    constraints: Option<BoxConstraints>,
1125    enable_drag: bool,
1126    show_drag_handle: bool,
1127    animation_style: Option<AnimationStyle>,
1128}
1129
1130impl ModalBottomSheet {
1131    fn new(route: Handle<ModalBottomSheetRoute>) -> ModalBottomSheet {
1132        ModalBottomSheet {
1133            route,
1134            is_scroll_controlled: false,
1135            scroll_control_disabled_max_height_ratio:
1136                K_DEFAULT_SCROLL_CONTROL_DISABLED_MAX_HEIGHT_RATIO,
1137            background_color: None,
1138            elevation: None,
1139            shape: None,
1140            clip_behavior: None,
1141            constraints: None,
1142            enable_drag: true,
1143            show_drag_handle: false,
1144            animation_style: None,
1145        }
1146    }
1147}
1148
1149impl Debug for ModalBottomSheet {
1150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1151        f.debug_struct("ModalBottomSheet")
1152            .field("route", &self.route)
1153            .field("isScrollControlled", &self.is_scroll_controlled)
1154            .field(
1155                "scrollControlDisabledMaxHeightRatio",
1156                &self.scroll_control_disabled_max_height_ratio,
1157            )
1158            .field("backgroundColor", &self.background_color)
1159            .field("elevation", &self.elevation)
1160            .field("shape", &self.shape)
1161            .field("clipBehavior", &self.clip_behavior)
1162            .field("constraints", &self.constraints)
1163            .field("enableDrag", &self.enable_drag)
1164            .field("showDragHandle", &self.show_drag_handle)
1165            .finish_non_exhaustive()
1166    }
1167}
1168
1169impl StatefulWidget for ModalBottomSheet {
1170    type State = ModalBottomSheetState;
1171
1172    fn create_state(&self) -> ModalBottomSheetState {
1173        ModalBottomSheetState {
1174            state: StateData::new(),
1175            sheet_animation: None,
1176            curved_sheet_animation: None,
1177            drag_end_curved_animation: None,
1178        }
1179    }
1180}
1181
1182/// Dart's `_ModalBottomSheetState<T>`.
1183struct ModalBottomSheetState {
1184    state: StateData<ModalBottomSheet>,
1185    /// Dart's `late final _sheetAnimation`, set in `init_state`.
1186    sheet_animation: Option<Ref<ProxyAnimation>>,
1187    /// Dart's `late final _curvedSheetAnimation`, set in `init_state`.
1188    curved_sheet_animation: Option<Ref<CurvedAnimation>>,
1189    // The CurvedAnimation created for the most recent drag end, tracked so it can
1190    // be disposed when it is replaced or the state is disposed.
1191    drag_end_curved_animation: Option<Ref<CurvedAnimation>>,
1192}
1193
1194impl ModalBottomSheetState {
1195    fn sheet_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
1196        app.get(self)
1197            .sheet_animation
1198            .handle()
1199            .expect("set in init_state")
1200    }
1201
1202    fn curved_sheet_animation(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
1203        app.get(self)
1204            .curved_sheet_animation
1205            .handle()
1206            .expect("set in init_state")
1207    }
1208
1209    /// Dart's `widget.route.animation!`.
1210    fn route_animation(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
1211        ModalRoute::animation(self.widget(app).route, app)
1212            .expect("an installed route")
1213            .keep(app)
1214    }
1215
1216    fn get_route_label(app: &App, localizations: &dyn MaterialLocalizations) -> String {
1217        match app.platform().target_platform() {
1218            TargetPlatform::IOS | TargetPlatform::MacOS => String::new(),
1219            TargetPlatform::Android
1220            | TargetPlatform::Fuchsia
1221            | TargetPlatform::Linux
1222            | TargetPlatform::Windows => localizations.dialog_label(),
1223        }
1224    }
1225
1226    fn get_new_clip_details(top_layer_size: Size) -> EdgeInsets {
1227        EdgeInsets::from_ltrb(0.0, 0.0, 0.0, top_layer_size.height())
1228    }
1229
1230    fn handle_drag_start(self: Handle<Self>, app: &mut App, _details: DragStartDetails) {
1231        // Allow the bottom sheet to track the user's finger accurately.
1232        let route_animation = self.route_animation(app);
1233        self.sheet_animation(app)
1234            .set_parent(app, Some(route_animation));
1235        // The CurvedAnimation from the previous drag end is no longer the parent of
1236        // [_sheetAnimation], so dispose it to avoid leaking its listeners on the
1237        // route animation.
1238        if let Some(drag_end_curved_animation) = app.get_mut(self).drag_end_curved_animation.take()
1239        {
1240            drag_end_curved_animation.dispose(app);
1241        }
1242    }
1243
1244    fn handle_drag_end(
1245        self: Handle<Self>,
1246        app: &mut App,
1247        _details: DragEndDetails,
1248        _is_closing: bool,
1249    ) {
1250        let route_animation = self.route_animation(app);
1251        let current_progress = route_animation.value(app);
1252
1253        // Rebind the animation using CurvedAnimation and Split so the
1254        // remaining transition continues smoothly from the exact point
1255        // where the drag gesture ended.
1256        let old_drag_end_curved_animation = app.get(self).drag_end_curved_animation.handle();
1257        let animation_style = self.widget(app).animation_style.clone();
1258        let curve = animation_style
1259            .as_ref()
1260            .and_then(|style| style.curve.clone())
1261            .unwrap_or_else(k_modal_bottom_sheet_curve);
1262        let reverse_curve = animation_style
1263            .as_ref()
1264            .and_then(|style| style.reverse_curve.clone())
1265            .unwrap_or_else(k_modal_bottom_sheet_curve);
1266        let drag_end_curved_animation = CurvedAnimation::new(
1267            app,
1268            route_animation,
1269            Rc::new(Split::new(current_progress, Curves::linear(), curve)),
1270            Some(Rc::new(Split::new(
1271                current_progress,
1272                Curves::linear(),
1273                reverse_curve,
1274            ))),
1275        );
1276        app.get_mut(self).drag_end_curved_animation = Some(drag_end_curved_animation.clone());
1277        self.sheet_animation(app)
1278            .set_parent(app, Some(drag_end_curved_animation.erase()));
1279        // Dispose the previous drag-end CurvedAnimation only after detaching it
1280        // from [_sheetAnimation], so it is never disposed while still in use.
1281        if let Some(old_drag_end_curved_animation) = old_drag_end_curved_animation {
1282            old_drag_end_curved_animation.dispose(app);
1283        }
1284    }
1285}
1286
1287impl State for ModalBottomSheetState {
1288    type Widget = ModalBottomSheet;
1289    waft_widgets::state_accessors!();
1290
1291    fn init_state(self: Handle<Self>, app: &mut App) {
1292        let route_animation = self.route_animation(app);
1293        let animation_style = self.widget(app).animation_style.clone();
1294        let curved_sheet_animation = CurvedAnimation::new(
1295            app,
1296            route_animation,
1297            animation_style
1298                .as_ref()
1299                .and_then(|style| style.curve.clone())
1300                .unwrap_or_else(k_modal_bottom_sheet_curve),
1301            Some(
1302                animation_style
1303                    .as_ref()
1304                    .and_then(|style| style.reverse_curve.clone())
1305                    .unwrap_or_else(k_modal_bottom_sheet_curve),
1306            ),
1307        );
1308        let sheet_animation = ProxyAnimation::new(app, Some(curved_sheet_animation.erase()));
1309        let this = app.get_mut(self);
1310        this.curved_sheet_animation = Some(curved_sheet_animation);
1311        this.sheet_animation = Some(sheet_animation);
1312    }
1313
1314    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ModalBottomSheet) {
1315        if cfg!(debug_assertions) {
1316            let widget = self.widget(app);
1317            assert!(old_widget.route == widget.route);
1318            let curved_sheet_animation = app.get(self.curved_sheet_animation(app));
1319            let curve = widget
1320                .animation_style
1321                .as_ref()
1322                .and_then(|style| style.curve.clone())
1323                .unwrap_or_else(k_modal_bottom_sheet_curve);
1324            assert!(Rc::ptr_eq(&curved_sheet_animation.curve, &curve));
1325            let reverse_curve = widget
1326                .animation_style
1327                .as_ref()
1328                .and_then(|style| style.reverse_curve.clone())
1329                .unwrap_or_else(k_modal_bottom_sheet_curve);
1330            assert!(
1331                curved_sheet_animation
1332                    .reverse_curve
1333                    .as_ref()
1334                    .is_some_and(|curve| Rc::ptr_eq(curve, &reverse_curve))
1335            );
1336        }
1337    }
1338
1339    fn dispose(self: Handle<Self>, app: &mut App) {
1340        // Detach to avoid leaking listeners on the route animation.
1341        let always_dismissed = k_always_dismissed_animation(app);
1342        self.sheet_animation(app)
1343            .set_parent(app, Some(always_dismissed));
1344        let curved_sheet_animation = self.curved_sheet_animation(app);
1345        curved_sheet_animation.dispose(app);
1346        if let Some(drag_end_curved_animation) = app.get(self).drag_end_curved_animation.handle() {
1347            drag_end_curved_animation.dispose(app);
1348        }
1349    }
1350
1351    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1352        debug_assert!(debug_check_has_media_query(app, context));
1353        debug_assert!(debug_check_has_material_localizations(app, context));
1354        let localizations = <dyn MaterialLocalizations>::of(app, context);
1355        let route_label = Self::get_route_label(app, &*localizations);
1356
1357        let widget = self.widget(app);
1358        let route = widget.route;
1359        let mut bottom_sheet = BottomSheet::new(
1360            Rc::new(move |app: &mut App| {
1361                if Route::is_current(route, app) {
1362                    Navigator::pop(app, context, None);
1363                }
1364            }),
1365            Rc::clone(&app.get(route).builder),
1366        )
1367        .enable_drag(widget.enable_drag)
1368        .show_drag_handle(widget.show_drag_handle)
1369        .on_drag_start(move |app, details| self.handle_drag_start(app, details))
1370        .on_drag_end(move |app, details, is_closing| {
1371            self.handle_drag_end(app, details, is_closing)
1372        });
1373        bottom_sheet.animation_controller = app.get(route).animation_controller.clone();
1374        bottom_sheet.background_color = widget.background_color;
1375        bottom_sheet.elevation = widget.elevation;
1376        bottom_sheet.shape = widget.shape.clone();
1377        bottom_sheet.clip_behavior = widget.clip_behavior;
1378        bottom_sheet.constraints = widget.constraints;
1379        let is_scroll_controlled = widget.is_scroll_controlled;
1380        let scroll_control_disabled_max_height_ratio =
1381            widget.scroll_control_disabled_max_height_ratio;
1382
1383        let sheet_animation = self.sheet_animation(app);
1384        let listenable: Rc<dyn Listenable> = Rc::new(
1385            app.get(self)
1386                .sheet_animation
1387                .as_ref()
1388                .expect("set in init_state")
1389                .erase::<AnyAnimation<f64>>(),
1390        );
1391        ListenableBuilder::new(listenable, move |app, _context, child| {
1392            let animation_value = sheet_animation.value(app);
1393            Semantics::new()
1394                .scopes_route(true)
1395                .names_route(true)
1396                .label(route_label.clone())
1397                .explicit_child_nodes(true)
1398                .child(ClipRect::new().child(BottomSheetLayoutWithSizeListener {
1399                    on_child_size_changed: Rc::new(move |app, size| {
1400                        route.did_change_barrier_semantics_clip(
1401                            app,
1402                            ModalBottomSheetState::get_new_clip_details(size),
1403                        );
1404                    }),
1405                    animation_value,
1406                    is_scroll_controlled,
1407                    scroll_control_disabled_max_height_ratio,
1408                    child: child.cloned(),
1409                }))
1410                .into_widget()
1411        })
1412        .child(bottom_sheet)
1413        .into_widget()
1414    }
1415}
1416
1417/// A route that represents a Material Design modal bottom sheet.
1418///
1419/// A modal bottom sheet is an alternative to a menu or a dialog and prevents
1420/// the user from interacting with the rest of the app.
1421///
1422/// A closely related widget is a persistent bottom sheet, which shows
1423/// information that supplements the primary content of the app without
1424/// preventing the user from interacting with the app. Persistent bottom sheets
1425/// can be created and displayed with the [`ShowBottomSheet`] builder or the
1426/// `ScaffoldState::show_bottom_sheet` method.
1427///
1428/// The [`is_scroll_controlled`](Self::is_scroll_controlled) parameter specifies whether this
1429/// is a route for a bottom sheet that will utilize `DraggableScrollableSheet`. Consider
1430/// setting this parameter to true if this bottom sheet has
1431/// a scrollable child, such as a `ListView` or a `GridView`,
1432/// to have the bottom sheet be draggable.
1433///
1434/// The [`is_dismissible`](Self::is_dismissible) parameter specifies whether the bottom sheet
1435/// will be dismissed when user taps on the scrim.
1436///
1437/// The [`enable_drag`](Self::enable_drag) parameter specifies whether the bottom sheet can be
1438/// dragged up and down and dismissed by swiping downwards.
1439///
1440/// The [`use_safe_area`](Self::use_safe_area) parameter specifies whether the sheet will
1441/// avoid system intrusions on the top, left, and right. If false, no [`SafeArea`] is added;
1442/// and [`MediaQuery::remove_padding`] is applied to the top,
1443/// so that system intrusions at the top will not be avoided by a [`SafeArea`]
1444/// inside the bottom sheet either.
1445/// Defaults to false.
1446///
1447/// The optional [`background_color`](Self::background_color), [`elevation`](Self::elevation),
1448/// [`shape`](Self::shape), [`clip_behavior`](Self::clip_behavior),
1449/// [`constraints`](Self::constraints) and
1450/// [`transition_animation_controller`](Self::transition_animation_controller)
1451/// parameters can be passed in to customize the appearance and behavior of
1452/// modal bottom sheets (see the documentation for these on [`BottomSheet`]
1453/// for more details).
1454///
1455/// The [`transition_animation_controller`](Self::transition_animation_controller) controls
1456/// the bottom sheet's entrance and exit animations. It's up to the owner of the controller to
1457/// call [`AnimationController::dispose`] when the controller is no longer needed.
1458///
1459/// The optional `settings` parameter sets the `RouteSettings` of the modal bottom sheet
1460/// sheet. This is particularly useful in the case that a user wants to observe
1461/// [`PopupRoute`]s within a `NavigatorObserver`.
1462///
1463/// See also:
1464///
1465///  * [`ShowModalBottomSheet`], which is a way to display a ModalBottomSheetRoute.
1466///  * [`BottomSheet`], which becomes the parent of the widget returned by the
1467///    function passed as the `builder` argument to [`ShowModalBottomSheet`].
1468///  * [`show_bottom_sheet`] and `ScaffoldState::show_bottom_sheet`, for showing
1469///    non-modal bottom sheets.
1470///  * `DraggableScrollableSheet`, creates a bottom sheet that grows
1471///    and then becomes scrollable once it reaches its maximum size.
1472///  * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
1473///  * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
1474pub struct ModalBottomSheetRoute {
1475    route: RouteData,
1476    overlay_route: OverlayRouteData,
1477    transition_route: TransitionRouteData,
1478    local_history: LocalHistoryRouteData,
1479    modal_route: ModalRouteData,
1480
1481    /// A builder for the contents of the sheet.
1482    ///
1483    /// The bottom sheet will wrap the widget produced by this builder in a
1484    /// [`Material`] widget.
1485    pub builder: WidgetBuilder,
1486
1487    /// Stores a list of captured [`InheritedTheme`]s that are wrapped around the
1488    /// bottom sheet.
1489    ///
1490    /// Consider setting this attribute when the [`ModalBottomSheetRoute`]
1491    /// is created through `Navigator::push` and its friends.
1492    pub captured_themes: Option<CapturedThemes>,
1493
1494    /// Specifies whether this is a route for a bottom sheet that will utilize
1495    /// `DraggableScrollableSheet`.
1496    ///
1497    /// Consider setting this parameter to true if this bottom sheet has
1498    /// a scrollable child, such as a `ListView` or a `GridView`,
1499    /// to have the bottom sheet be draggable.
1500    pub is_scroll_controlled: bool,
1501
1502    /// The max height constraint ratio for the bottom sheet
1503    /// when [`is_scroll_controlled`](Self::is_scroll_controlled) is set to false,
1504    /// no ratio will be applied when [`is_scroll_controlled`](Self::is_scroll_controlled) is
1505    /// set to true.
1506    ///
1507    /// Defaults to 9 / 16.
1508    pub scroll_control_disabled_max_height_ratio: f64,
1509
1510    /// The bottom sheet's background color.
1511    ///
1512    /// Defines the bottom sheet's `Material.color`.
1513    ///
1514    /// If this property is not provided, it falls back to [`Material`]'s default.
1515    pub background_color: Option<Color>,
1516
1517    /// The z-coordinate at which to place this material relative to its parent.
1518    ///
1519    /// This controls the size of the shadow below the material.
1520    ///
1521    /// Defaults to 0, must not be negative.
1522    pub elevation: Option<f64>,
1523
1524    /// The shape of the bottom sheet.
1525    ///
1526    /// Defines the bottom sheet's `Material.shape`.
1527    ///
1528    /// If this property is not provided, it falls back to [`Material`]'s default.
1529    pub shape: Option<ShapeBorderRef>,
1530
1531    /// The content will be clipped (or not) according to this option.
1532    ///
1533    /// Defines the bottom sheet's `Material.clipBehavior`.
1534    ///
1535    /// Use this property to enable clipping of content when the bottom sheet has
1536    /// a custom [`shape`](Self::shape) and the content can extend past this shape. For
1537    /// example, a bottom sheet with rounded corners and an edge-to-edge `Image` at the
1538    /// top.
1539    ///
1540    /// If this property is null, the [`BottomSheetThemeData::clip_behavior`] of
1541    /// `ThemeData.bottomSheetTheme` is used. If that's null, the behavior defaults to
1542    /// [`Clip::None`] will be [`Clip::None`].
1543    pub clip_behavior: Option<Clip>,
1544
1545    /// Defines minimum and maximum sizes for a [`BottomSheet`].
1546    ///
1547    /// If null, the ambient `ThemeData.bottomSheetTheme`'s
1548    /// [`BottomSheetThemeData::constraints`] will be used. If that
1549    /// is null and `ThemeData.useMaterial3` is true, then the bottom sheet
1550    /// will have a max width of 640dp. If `ThemeData.useMaterial3` is false, then
1551    /// the bottom sheet's size will be constrained by its parent
1552    /// (usually a `Scaffold`). In this case, consider limiting the width by
1553    /// setting smaller constraints for large screens.
1554    ///
1555    /// If constraints are specified (either in this property or in the
1556    /// theme), the bottom sheet will be aligned to the bottom-center of
1557    /// the available space. Otherwise, no alignment is applied.
1558    pub constraints: Option<BoxConstraints>,
1559
1560    /// Specifies the color of the modal barrier that darkens everything below the
1561    /// bottom sheet.
1562    ///
1563    /// Defaults to `Colors.black54` if not provided.
1564    pub modal_barrier_color: Option<Color>,
1565
1566    /// Specifies whether the bottom sheet will be dismissed
1567    /// when user taps on the scrim.
1568    ///
1569    /// If true, the bottom sheet will be dismissed when user taps on the scrim.
1570    ///
1571    /// Defaults to true.
1572    pub is_dismissible: bool,
1573
1574    /// Specifies whether the bottom sheet can be dragged up and down
1575    /// and dismissed by swiping downwards.
1576    ///
1577    /// If true, the bottom sheet can be dragged up and down and dismissed by
1578    /// swiping downwards.
1579    ///
1580    /// This applies to the content below the drag handle, if showDragHandle is true.
1581    ///
1582    /// Defaults is true.
1583    pub enable_drag: bool,
1584
1585    /// Specifies whether a drag handle is shown.
1586    ///
1587    /// The drag handle appears at the top of the bottom sheet. The default color is
1588    /// `ColorScheme.onSurfaceVariant` with an opacity of 0.4 and can be customized
1589    /// using dragHandleColor. The default size is `Size(32,4)` and can be customized
1590    /// with dragHandleSize.
1591    ///
1592    /// If null, then the value of [`BottomSheetThemeData::show_drag_handle`] is used. If
1593    /// that is also null, defaults to false.
1594    pub show_drag_handle: Option<bool>,
1595
1596    /// The animation controller that controls the bottom sheet's entrance and
1597    /// exit animations.
1598    ///
1599    /// The BottomSheet widget will manipulate the position of this animation, it
1600    /// is not just a passive observer.
1601    pub transition_animation_controller: Option<Ref<AnimationController>>,
1602
1603    /// Whether to avoid system intrusions on the top, left, and right.
1604    ///
1605    /// If true, a [`SafeArea`] is inserted to keep the bottom sheet away from
1606    /// system intrusions at the top, left, and right sides of the screen.
1607    ///
1608    /// If false, the bottom sheet will extend through any system intrusions
1609    /// at the top, left, and right.
1610    ///
1611    /// If false, then moreover [`MediaQuery::remove_padding`] will be used
1612    /// to remove top padding, so that a [`SafeArea`] widget inside the bottom
1613    /// sheet will have no effect at the top edge. If this is undesired, consider
1614    /// setting [`use_safe_area`](Self::use_safe_area) to true. Alternatively, wrap the
1615    /// [`SafeArea`] in a [`MediaQuery`] that restates an ambient `MediaQueryData` from outside
1616    /// [`builder`](Self::builder).
1617    ///
1618    /// In either case, the bottom sheet extends all the way to the bottom of
1619    /// the screen, including any system intrusions.
1620    ///
1621    /// The default is false.
1622    pub use_safe_area: bool,
1623
1624    /// Used to override the modal bottom sheet animation duration and reverse
1625    /// animation duration.
1626    ///
1627    /// If `AnimationStyle.duration` is provided, it will be used to override
1628    /// the modal bottom sheet animation duration in the underlying
1629    /// [`BottomSheet::create_animation_controller`].
1630    ///
1631    /// If `AnimationStyle.reverseDuration` is provided, it will be used to
1632    /// override the modal bottom sheet reverse animation duration in the
1633    /// underlying [`BottomSheet::create_animation_controller`].
1634    ///
1635    /// To disable the modal bottom sheet animation, use `AnimationStyle.noAnimation`.
1636    pub sheet_animation_style: Option<AnimationStyle>,
1637
1638    /// The semantic hint text that informs users what will happen if they
1639    /// tap on the widget. Announced in the format of 'Double tap to ...'.
1640    ///
1641    /// If the field is null, the default hint will be used, which results in
1642    /// announcement of 'Double tap to activate'.
1643    ///
1644    /// See also:
1645    ///
1646    ///  * [`ModalRoute::barrier_dismissible`], which controls the behavior of the barrier
1647    ///    when tapped.
1648    ///  * [`ModalBarrier`], which uses this field as onTapHint when it has an onTap action.
1649    pub barrier_on_tap_hint: Option<String>,
1650
1651    clip_details_notifier: Ref<ValueNotifier<EdgeInsets>>,
1652
1653    barrier_label: Option<String>,
1654
1655    animation_controller: Option<Ref<AnimationController>>,
1656}
1657
1658impl ModalBottomSheetRoute {
1659    /// A modal bottom sheet route; Dart's optional arguments are the setters.
1660    pub fn new(
1661        app: &mut App,
1662        builder: WidgetBuilder,
1663        is_scroll_controlled: bool,
1664    ) -> Ref<ModalBottomSheetRoute> {
1665        let route = RouteData::new(app, None, None);
1666        let transition_route = TransitionRouteData::new(app);
1667        let modal_route = ModalRouteData::new(app);
1668        let clip_details_notifier = app.create(ValueNotifier::new(EdgeInsets::ZERO));
1669        app.create(ModalBottomSheetRoute {
1670            route,
1671            overlay_route: OverlayRouteData::new(),
1672            transition_route,
1673            local_history: LocalHistoryRouteData::new(),
1674            modal_route,
1675            builder,
1676            captured_themes: None,
1677            is_scroll_controlled,
1678            scroll_control_disabled_max_height_ratio:
1679                K_DEFAULT_SCROLL_CONTROL_DISABLED_MAX_HEIGHT_RATIO,
1680            background_color: None,
1681            elevation: None,
1682            shape: None,
1683            clip_behavior: None,
1684            constraints: None,
1685            modal_barrier_color: None,
1686            is_dismissible: true,
1687            enable_drag: true,
1688            show_drag_handle: None,
1689            transition_animation_controller: None,
1690            use_safe_area: false,
1691            sheet_animation_style: None,
1692            barrier_on_tap_hint: None,
1693            clip_details_notifier,
1694            barrier_label: None,
1695            animation_controller: None,
1696        })
1697    }
1698
1699    /// Dart `ModalBottomSheetRoute(capturedThemes:)`.
1700    pub fn captured_themes(
1701        self: Ref<Self>,
1702        app: &mut App,
1703        captured_themes: CapturedThemes,
1704    ) -> Ref<Self> {
1705        app.get_mut(&self).captured_themes = Some(captured_themes);
1706        self
1707    }
1708
1709    /// Dart `ModalBottomSheetRoute(barrierLabel:)`.
1710    pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
1711        app.get_mut(&self).barrier_label = Some(barrier_label);
1712        self
1713    }
1714
1715    /// Dart `ModalBottomSheetRoute(barrierOnTapHint:)`.
1716    pub fn barrier_on_tap_hint(
1717        self: Ref<Self>,
1718        app: &mut App,
1719        barrier_on_tap_hint: String,
1720    ) -> Ref<Self> {
1721        app.get_mut(&self).barrier_on_tap_hint = Some(barrier_on_tap_hint);
1722        self
1723    }
1724
1725    /// Dart `ModalBottomSheetRoute(backgroundColor:)`.
1726    pub fn background_color(self: Ref<Self>, app: &mut App, background_color: Color) -> Ref<Self> {
1727        app.get_mut(&self).background_color = Some(background_color);
1728        self
1729    }
1730
1731    /// Dart `ModalBottomSheetRoute(elevation:)`.
1732    pub fn elevation(self: Ref<Self>, app: &mut App, elevation: f64) -> Ref<Self> {
1733        app.get_mut(&self).elevation = Some(elevation);
1734        self
1735    }
1736
1737    /// Dart `ModalBottomSheetRoute(shape:)`.
1738    pub fn shape(self: Ref<Self>, app: &mut App, shape: impl Into<ShapeBorderRef>) -> Ref<Self> {
1739        app.get_mut(&self).shape = Some(shape.into());
1740        self
1741    }
1742
1743    /// Dart `ModalBottomSheetRoute(clipBehavior:)`.
1744    pub fn clip_behavior(self: Ref<Self>, app: &mut App, clip_behavior: Clip) -> Ref<Self> {
1745        app.get_mut(&self).clip_behavior = Some(clip_behavior);
1746        self
1747    }
1748
1749    /// Dart `ModalBottomSheetRoute(constraints:)`.
1750    pub fn constraints(self: Ref<Self>, app: &mut App, constraints: BoxConstraints) -> Ref<Self> {
1751        app.get_mut(&self).constraints = Some(constraints);
1752        self
1753    }
1754
1755    /// Dart `ModalBottomSheetRoute(modalBarrierColor:)`.
1756    pub fn modal_barrier_color(
1757        self: Ref<Self>,
1758        app: &mut App,
1759        modal_barrier_color: Color,
1760    ) -> Ref<Self> {
1761        app.get_mut(&self).modal_barrier_color = Some(modal_barrier_color);
1762        self
1763    }
1764
1765    /// Dart `ModalBottomSheetRoute(isDismissible:)`.
1766    pub fn is_dismissible(self: Ref<Self>, app: &mut App, is_dismissible: bool) -> Ref<Self> {
1767        app.get_mut(&self).is_dismissible = is_dismissible;
1768        self
1769    }
1770
1771    /// Dart `ModalBottomSheetRoute(enableDrag:)`.
1772    pub fn enable_drag(self: Ref<Self>, app: &mut App, enable_drag: bool) -> Ref<Self> {
1773        app.get_mut(&self).enable_drag = enable_drag;
1774        self
1775    }
1776
1777    /// Dart `ModalBottomSheetRoute(showDragHandle:)`.
1778    pub fn show_drag_handle(self: Ref<Self>, app: &mut App, show_drag_handle: bool) -> Ref<Self> {
1779        app.get_mut(&self).show_drag_handle = Some(show_drag_handle);
1780        self
1781    }
1782
1783    /// Dart `ModalBottomSheetRoute(scrollControlDisabledMaxHeightRatio:)`.
1784    pub fn scroll_control_disabled_max_height_ratio(
1785        self: Ref<Self>,
1786        app: &mut App,
1787        scroll_control_disabled_max_height_ratio: f64,
1788    ) -> Ref<Self> {
1789        app.get_mut(&self).scroll_control_disabled_max_height_ratio =
1790            scroll_control_disabled_max_height_ratio;
1791        self
1792    }
1793
1794    /// Dart `ModalBottomSheetRoute(settings:)`.
1795    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
1796        self.route_data_mut(app).set_settings(settings);
1797        self
1798    }
1799
1800    /// Dart `ModalBottomSheetRoute(requestFocus:)`.
1801    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
1802        self.route_data_mut(app)
1803            .set_request_focus(Some(request_focus));
1804        self
1805    }
1806
1807    /// Dart `ModalBottomSheetRoute(transitionAnimationController:)`.
1808    pub fn transition_animation_controller(
1809        self: Ref<Self>,
1810        app: &mut App,
1811        transition_animation_controller: Ref<AnimationController>,
1812    ) -> Ref<Self> {
1813        app.get_mut(&self).transition_animation_controller = Some(transition_animation_controller);
1814        self
1815    }
1816
1817    /// Dart `ModalBottomSheetRoute(useSafeArea:)`.
1818    pub fn use_safe_area(self: Ref<Self>, app: &mut App, use_safe_area: bool) -> Ref<Self> {
1819        app.get_mut(&self).use_safe_area = use_safe_area;
1820        self
1821    }
1822
1823    /// Dart `ModalBottomSheetRoute(sheetAnimationStyle:)`.
1824    pub fn sheet_animation_style(
1825        self: Ref<Self>,
1826        app: &mut App,
1827        sheet_animation_style: AnimationStyle,
1828    ) -> Ref<Self> {
1829        app.get_mut(&self).sheet_animation_style = Some(sheet_animation_style);
1830        self
1831    }
1832
1833    /// Updates the details regarding how the `SemanticsNode.rect` (focus) of
1834    /// the barrier for this [`ModalBottomSheetRoute`] should be clipped.
1835    ///
1836    /// Returns true if the clipDetails did change and false otherwise.
1837    fn did_change_barrier_semantics_clip(
1838        self: Handle<Self>,
1839        app: &mut App,
1840        new_clip_details: EdgeInsets,
1841    ) -> bool {
1842        let clip_details_notifier = app.get(self).clip_details_notifier.clone();
1843        if *app.get(&clip_details_notifier).value() == new_clip_details {
1844            return false;
1845        }
1846        clip_details_notifier.set_value(app, new_clip_details);
1847        true
1848    }
1849}
1850
1851// Dart's `ModalBottomSheetRoute.dispose` disposes the clip notifier and runs `super.dispose()`,
1852// so this impl writes out `modal_route_overrides!` with that `dispose`.
1853impl Route for ModalBottomSheetRoute {
1854    waft_widgets::route_accessors!();
1855
1856    fn as_transition_route(self: Handle<Self>) -> Option<waft_widgets::AnyTransitionRoute> {
1857        Some(TransitionRoute::as_transition_route(self))
1858    }
1859
1860    fn as_modal_route(self: Handle<Self>) -> Option<waft_widgets::AnyModalRoute> {
1861        Some(ModalRoute::as_modal_route(self))
1862    }
1863
1864    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<waft_widgets::OverlayEntry>> {
1865        OverlayRoute::overlay_entries(self, app)
1866    }
1867
1868    fn install(self: Handle<Self>, app: &mut App) {
1869        ModalRoute::install(self, app)
1870    }
1871
1872    fn did_push(self: Handle<Self>, app: &mut App) -> waft_scheduler::TickerFuture {
1873        ModalRoute::did_push(self, app)
1874    }
1875
1876    fn did_add(self: Handle<Self>, app: &mut App) {
1877        ModalRoute::did_add(self, app)
1878    }
1879
1880    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<waft_widgets::AnyRoute>) {
1881        TransitionRoute::did_replace(self, app, old_route)
1882    }
1883
1884    fn will_pop(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1885        LocalHistoryRoute::will_pop(self, app)
1886    }
1887
1888    fn pop_disposition(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1889        ModalRoute::pop_disposition(self, app)
1890    }
1891
1892    fn on_pop_invoked_with_result(
1893        self: Handle<Self>,
1894        app: &mut App,
1895        did_pop: bool,
1896        result: RouteResult,
1897    ) {
1898        ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
1899    }
1900
1901    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
1902        LocalHistoryRoute::will_handle_pop_internally(self, app)
1903    }
1904
1905    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
1906        LocalHistoryRoute::did_pop(self, app, result)
1907    }
1908
1909    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: waft_widgets::AnyRoute) {
1910        ModalRoute::did_pop_next(self, app, next_route)
1911    }
1912
1913    fn did_change_next(
1914        self: Handle<Self>,
1915        app: &mut App,
1916        next_route: Option<waft_widgets::AnyRoute>,
1917    ) {
1918        ModalRoute::did_change_next(self, app, next_route)
1919    }
1920
1921    fn did_change_previous(
1922        self: Handle<Self>,
1923        app: &mut App,
1924        previous_route: Option<waft_widgets::AnyRoute>,
1925    ) {
1926        ModalRoute::did_change_previous(self, app, previous_route)
1927    }
1928
1929    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
1930        ModalRoute::changed_internal_state(self, app)
1931    }
1932
1933    fn changed_external_state(self: Handle<Self>, app: &mut App) {
1934        ModalRoute::changed_external_state(self, app)
1935    }
1936
1937    fn dispose(self: Handle<Self>, app: &mut App) {
1938        let clip_details_notifier = app.get(self).clip_details_notifier.clone();
1939        clip_details_notifier.dispose(app);
1940        TransitionRoute::dispose(self, app)
1941    }
1942}
1943
1944impl OverlayRoute for ModalBottomSheetRoute {
1945    waft_widgets::modal_overlay_route_overrides!();
1946}
1947
1948impl PredictiveBackRoute for ModalBottomSheetRoute {
1949    waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
1950}
1951
1952impl TransitionRoute for ModalBottomSheetRoute {
1953    waft_widgets::modal_transition_route_overrides!();
1954
1955    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
1956        let route = app.get(self);
1957        route
1958            .transition_animation_controller
1959            .as_ref()
1960            .and_then(|controller| app.get(controller).duration)
1961            .or(route
1962                .sheet_animation_style
1963                .as_ref()
1964                .and_then(|style| style.duration))
1965            .unwrap_or(K_BOTTOM_SHEET_ENTER_DURATION)
1966    }
1967
1968    fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
1969        let route = app.get(self);
1970        route
1971            .transition_animation_controller
1972            .as_ref()
1973            .and_then(|controller| app.get(controller).reverse_duration)
1974            .or(route
1975                .transition_animation_controller
1976                .as_ref()
1977                .and_then(|controller| app.get(controller).duration))
1978            .or(route
1979                .sheet_animation_style
1980                .as_ref()
1981                .and_then(|style| style.reverse_duration))
1982            .unwrap_or(K_BOTTOM_SHEET_EXIT_DURATION)
1983    }
1984
1985    fn opaque(self: Handle<Self>, app: &App) -> bool {
1986        PopupRoute::opaque(self, app)
1987    }
1988
1989    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
1990        PopupRoute::allow_snapshotting(self, app)
1991    }
1992
1993    fn create_animation_controller(self: Handle<Self>, app: &mut App) -> Ref<AnimationController> {
1994        debug_assert!(app.get(self).animation_controller.is_none());
1995        let animation_controller = if let Some(transition_animation_controller) =
1996            app.get(self).transition_animation_controller.clone()
1997        {
1998            self.transition_route_data_mut(app)
1999                .will_dispose_animation_controller = false;
2000            transition_animation_controller
2001        } else {
2002            let navigator = self
2003                .as_route()
2004                .navigator(app)
2005                .expect("an installed route has a navigator");
2006            let sheet_animation_style = app.get(self).sheet_animation_style.clone();
2007            BottomSheet::create_animation_controller(app, navigator, sheet_animation_style.as_ref())
2008        };
2009        app.get_mut(self).animation_controller = Some(animation_controller.clone());
2010        animation_controller
2011    }
2012}
2013
2014impl LocalHistoryRoute for ModalBottomSheetRoute {
2015    waft_widgets::local_history_route_accessors!();
2016}
2017
2018impl ModalRoute for ModalBottomSheetRoute {
2019    waft_widgets::modal_route_accessors!();
2020
2021    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
2022        app.get(self).is_dismissible
2023    }
2024
2025    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
2026        app.get(self).barrier_label.clone()
2027    }
2028
2029    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
2030        Some(app.get(self).modal_barrier_color.unwrap_or(Colors::BLACK54))
2031    }
2032
2033    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
2034        PopupRoute::maintain_state(self, app)
2035    }
2036
2037    fn build_page(
2038        self: Handle<Self>,
2039        app: &mut App,
2040        context: BuildContext,
2041        animation: AnimationRef<f64>,
2042        secondary_animation: AnimationRef<f64>,
2043    ) -> WidgetRef {
2044        let _ = (animation, secondary_animation);
2045        let content = Builder::new(move |app, context| {
2046            let theme = Theme::of(app, context);
2047            let sheet_theme = theme.bottom_sheet_theme.clone();
2048            let defaults: Box<dyn BottomSheetThemeDataGetters> = if theme.use_material3 {
2049                Box::new(BottomSheetDefaultsM3::new(context))
2050            } else {
2051                Box::new(BottomSheetThemeData::new())
2052            };
2053            let route = app.get(self);
2054            let mut modal_bottom_sheet = ModalBottomSheet::new(self);
2055            modal_bottom_sheet.animation_style = route.sheet_animation_style.clone();
2056            let (background_color, elevation) = (route.background_color, route.elevation);
2057            modal_bottom_sheet.background_color = background_color
2058                .or(sheet_theme.modal_background_color)
2059                .or(sheet_theme.background_color)
2060                .or_else(|| defaults.background_color(app));
2061            modal_bottom_sheet.elevation = elevation
2062                .or(sheet_theme.modal_elevation)
2063                .or(sheet_theme.elevation)
2064                .or_else(|| defaults.modal_elevation(app));
2065            let route = app.get(self);
2066            modal_bottom_sheet.shape = route.shape.clone();
2067            modal_bottom_sheet.clip_behavior = route.clip_behavior;
2068            modal_bottom_sheet.constraints = route.constraints;
2069            modal_bottom_sheet.is_scroll_controlled = route.is_scroll_controlled;
2070            modal_bottom_sheet.scroll_control_disabled_max_height_ratio =
2071                route.scroll_control_disabled_max_height_ratio;
2072            modal_bottom_sheet.enable_drag = route.enable_drag;
2073            modal_bottom_sheet.show_drag_handle = route
2074                .show_drag_handle
2075                .unwrap_or(route.enable_drag && sheet_theme.show_drag_handle.unwrap_or(false));
2076            modal_bottom_sheet.into_widget()
2077        })
2078        .into_widget();
2079
2080        let bottom_sheet = if app.get(self).use_safe_area {
2081            SafeArea::new(content).bottom(false).into_widget()
2082        } else {
2083            MediaQuery::remove_padding(app, context, false, true, false, false, content)
2084                .into_widget()
2085        };
2086
2087        // Prevent clicks inside the bottom sheet from passing through to the barrier
2088        let bottom_sheet = Semantics::new()
2089            .hit_test_behavior(SemanticsHitTestBehavior::Opaque)
2090            .child(bottom_sheet)
2091            .into_widget();
2092
2093        match &app.get(self).captured_themes {
2094            Some(captured_themes) => captured_themes.wrap(bottom_sheet),
2095            None => bottom_sheet,
2096        }
2097    }
2098
2099    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2100        let _ = context;
2101        let barrier_color = ModalRoute::barrier_color(self, app).expect("always has a color");
2102        let dismissible = ModalRoute::barrier_dismissible(self, app);
2103        let semantics_label = ModalRoute::barrier_label(self, app);
2104        let semantics_dismissible = ModalRoute::semantics_dismissible(self, app);
2105        let clip_details_notifier = app.get(self).clip_details_notifier.clone();
2106        let barrier_on_tap_hint = app.get(self).barrier_on_tap_hint.clone();
2107        if barrier_color.a != 0.0 && !ModalRoute::offstage(self, app) {
2108            // changedInternalState is called if barrierColor or offstage updates
2109            let transparent = barrier_color.with_values(Some(0.0), None, None, None, None);
2110            debug_assert!(barrier_color != transparent);
2111            let animation = TransitionRoute::animation(self, app)
2112                .expect("an installed route")
2113                .keep(app);
2114            // changedInternalState is called if barrierColor updates
2115            let color_tween = ColorTween::new(app, Some(transparent), Some(barrier_color));
2116            // changedInternalState is called if barrierCurve updates
2117            let curve = ModalRoute::barrier_curve(self, app);
2118            let curve_tween = CurveTween::new(app, curve);
2119            let color = animation.drive(app, color_tween.chain(curve_tween));
2120            let mut barrier = AnimatedModalBarrier::new(color)
2121                // changedInternalState is called if barrierDismissible updates
2122                .dismissible(dismissible)
2123                // changedInternalState is called if barrierLabel updates
2124                .maybe_semantics_label(semantics_label)
2125                .barrier_semantics_dismissible(semantics_dismissible)
2126                .clip_details_notifier(clip_details_notifier);
2127            barrier.semantics_on_tap_hint = barrier_on_tap_hint;
2128            barrier.into_widget()
2129        } else {
2130            let mut barrier = ModalBarrier::new()
2131                // changedInternalState is called if barrierDismissible updates
2132                .dismissible(dismissible)
2133                // changedInternalState is called if barrierLabel updates
2134                .maybe_semantics_label(semantics_label)
2135                .barrier_semantics_dismissible(semantics_dismissible)
2136                .clip_details_notifier(clip_details_notifier);
2137            barrier.semantics_on_tap_hint = barrier_on_tap_hint;
2138            barrier.into_widget()
2139        }
2140    }
2141}
2142
2143impl PopupRoute for ModalBottomSheetRoute {}
2144
2145/// Shows a modal Material Design bottom sheet.
2146///
2147/// A modal bottom sheet is an alternative to a menu or a dialog and prevents
2148/// the user from interacting with the rest of the app.
2149///
2150/// A closely related widget is a persistent bottom sheet, which shows
2151/// information that supplements the primary content of the app without
2152/// preventing the user from interacting with the app. Persistent bottom sheets
2153/// can be created and displayed with the [`ShowBottomSheet`] builder or the
2154/// `ScaffoldState::show_bottom_sheet` method.
2155///
2156/// The `is_scroll_controlled` parameter specifies whether this is a route for
2157/// a bottom sheet that will utilize `DraggableScrollableSheet`. Consider
2158/// setting this parameter to true if this bottom sheet has
2159/// a scrollable child, such as a `ListView` or a `GridView`,
2160/// to have the bottom sheet be draggable.
2161///
2162/// The `is_dismissible` parameter specifies whether the bottom sheet will be
2163/// dismissed when user taps on the scrim.
2164///
2165/// The `enable_drag` parameter specifies whether the bottom sheet can be
2166/// dragged up and down and dismissed by swiping downwards.
2167///
2168/// The `use_safe_area` parameter specifies whether the sheet will avoid system
2169/// intrusions on the top, left, and right. If false, no [`SafeArea`] is added;
2170/// and [`MediaQuery::remove_padding`] is applied to the top,
2171/// so that system intrusions at the top will not be avoided by a [`SafeArea`]
2172/// inside the bottom sheet either.
2173/// Defaults to false.
2174///
2175/// The optional `background_color`, `elevation`, `shape`, `clip_behavior`,
2176/// `constraints` and `transition_animation_controller`
2177/// parameters can be passed in to customize the appearance and behavior of
2178/// modal bottom sheets (see the documentation for these on [`BottomSheet`]
2179/// for more details).
2180///
2181/// The `transition_animation_controller` controls the bottom sheet's entrance and
2182/// exit animations. It's up to the owner of the controller to call
2183/// [`AnimationController::dispose`] when the controller is no longer needed.
2184///
2185/// The optional `route_settings` parameter sets the `RouteSettings` of the modal bottom
2186/// sheet sheet. This is particularly useful in the case that a user wants to observe
2187/// [`PopupRoute`]s within a `NavigatorObserver`.
2188///
2189/// The `context` argument is used to look up the [`Navigator`] and [`Theme`] for
2190/// the bottom sheet. It is only used when the method is called. Its
2191/// corresponding widget can be safely removed from the tree before the bottom
2192/// sheet is closed.
2193///
2194/// The `use_root_navigator` parameter ensures that the root navigator is used to
2195/// display the [`BottomSheet`] when set to `true`. This is useful in the case
2196/// that a modal [`BottomSheet`] needs to be displayed above all other content
2197/// but the caller is inside another [`Navigator`].
2198///
2199/// Returns a `Future` that resolves to the value (if any) that was passed to
2200/// [`Navigator::pop`] when the modal bottom sheet was closed.
2201///
2202/// The 'barrier_label' parameter can be used to set a custom barrier label.
2203/// Will default to `MaterialLocalizations::modal_barrier_dismiss_label` of context
2204/// if not set.
2205///
2206/// The `sheet_animation_style` parameter is used to override the modal bottom sheet
2207/// animation duration and reverse animation duration.
2208///
2209/// The `request_focus` parameter is used to specify whether the bottom sheet should
2210/// request focus when shown.
2211///
2212/// If `AnimationStyle.duration` is provided, it will be used to override
2213/// the modal bottom sheet animation duration in the underlying
2214/// [`BottomSheet::create_animation_controller`].
2215///
2216/// If `AnimationStyle.reverseDuration` is provided, it will be used to
2217/// override the modal bottom sheet reverse animation duration in the
2218/// underlying [`BottomSheet::create_animation_controller`].
2219///
2220/// To disable the bottom sheet animation, use `AnimationStyle.noAnimation`.
2221///
2222/// See also:
2223///
2224///  * [`BottomSheet`], which becomes the parent of the widget returned by the
2225///    function passed as the `builder` argument to [`ShowModalBottomSheet`].
2226///  * [`show_bottom_sheet`] and `ScaffoldState::show_bottom_sheet`, for showing
2227///    non-modal bottom sheets.
2228///  * `DraggableScrollableSheet`, creates a bottom sheet that grows
2229///    and then becomes scrollable once it reaches its maximum size.
2230///  * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
2231///  * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
2232///  * [`AnimationStyle`], which is used to override the modal bottom sheet
2233///    animation duration and reverse animation duration.
2234pub struct ShowModalBottomSheet {
2235    builder: WidgetBuilder,
2236    background_color: Option<Color>,
2237    barrier_label: Option<String>,
2238    elevation: Option<f64>,
2239    shape: Option<ShapeBorderRef>,
2240    clip_behavior: Option<Clip>,
2241    constraints: Option<BoxConstraints>,
2242    barrier_color: Option<Color>,
2243    is_scroll_controlled: bool,
2244    scroll_control_disabled_max_height_ratio: f64,
2245    use_root_navigator: bool,
2246    is_dismissible: bool,
2247    enable_drag: bool,
2248    show_drag_handle: Option<bool>,
2249    use_safe_area: bool,
2250    route_settings: Option<RouteSettingsRef>,
2251    transition_animation_controller: Option<Ref<AnimationController>>,
2252    sheet_animation_style: Option<AnimationStyle>,
2253    request_focus: Option<bool>,
2254}
2255
2256impl ShowModalBottomSheet {
2257    /// Creates a builder for a modal bottom sheet; Dart's `showModalBottomSheet` required
2258    /// argument is the `builder`, and every other argument is a setter.
2259    pub fn new(builder: WidgetBuilder) -> ShowModalBottomSheet {
2260        ShowModalBottomSheet {
2261            builder,
2262            background_color: None,
2263            barrier_label: None,
2264            elevation: None,
2265            shape: None,
2266            clip_behavior: None,
2267            constraints: None,
2268            barrier_color: None,
2269            is_scroll_controlled: false,
2270            scroll_control_disabled_max_height_ratio:
2271                K_DEFAULT_SCROLL_CONTROL_DISABLED_MAX_HEIGHT_RATIO,
2272            use_root_navigator: false,
2273            is_dismissible: true,
2274            enable_drag: true,
2275            show_drag_handle: None,
2276            use_safe_area: false,
2277            route_settings: None,
2278            transition_animation_controller: None,
2279            sheet_animation_style: None,
2280            request_focus: None,
2281        }
2282    }
2283
2284    /// The background color of the sheet.
2285    pub fn background_color(mut self, background_color: Color) -> ShowModalBottomSheet {
2286        self.background_color = Some(background_color);
2287        self
2288    }
2289
2290    /// The semantic label of the sheet's modal barrier.
2291    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowModalBottomSheet {
2292        self.barrier_label = Some(barrier_label.into());
2293        self
2294    }
2295
2296    /// The z-coordinate of the sheet.
2297    pub fn elevation(mut self, elevation: f64) -> ShowModalBottomSheet {
2298        self.elevation = Some(elevation);
2299        self
2300    }
2301
2302    /// The shape of the sheet's material.
2303    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ShowModalBottomSheet {
2304        self.shape = Some(shape.into());
2305        self
2306    }
2307
2308    /// The clip behavior of the sheet.
2309    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ShowModalBottomSheet {
2310        self.clip_behavior = Some(clip_behavior);
2311        self
2312    }
2313
2314    /// The size constraints on the sheet.
2315    pub fn constraints(mut self, constraints: BoxConstraints) -> ShowModalBottomSheet {
2316        self.constraints = Some(constraints);
2317        self
2318    }
2319
2320    /// The color of the modal barrier below the sheet.
2321    pub fn barrier_color(mut self, barrier_color: Color) -> ShowModalBottomSheet {
2322        self.barrier_color = Some(barrier_color);
2323        self
2324    }
2325
2326    /// Whether the sheet may take the full height when a scroll view is inside it. Defaults to
2327    /// `false`.
2328    pub fn is_scroll_controlled(mut self, is_scroll_controlled: bool) -> ShowModalBottomSheet {
2329        self.is_scroll_controlled = is_scroll_controlled;
2330        self
2331    }
2332
2333    /// The maximum height of a non-scroll-controlled sheet, as a ratio of the available height.
2334    pub fn scroll_control_disabled_max_height_ratio(
2335        mut self,
2336        scroll_control_disabled_max_height_ratio: f64,
2337    ) -> ShowModalBottomSheet {
2338        self.scroll_control_disabled_max_height_ratio = scroll_control_disabled_max_height_ratio;
2339        self
2340    }
2341
2342    /// Whether to push the sheet to the root navigator. Defaults to `false`.
2343    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowModalBottomSheet {
2344        self.use_root_navigator = use_root_navigator;
2345        self
2346    }
2347
2348    /// Whether tapping the barrier dismisses the sheet. Defaults to `true`.
2349    pub fn is_dismissible(mut self, is_dismissible: bool) -> ShowModalBottomSheet {
2350        self.is_dismissible = is_dismissible;
2351        self
2352    }
2353
2354    /// Whether the sheet can be dragged up and down. Defaults to `true`.
2355    pub fn enable_drag(mut self, enable_drag: bool) -> ShowModalBottomSheet {
2356        self.enable_drag = enable_drag;
2357        self
2358    }
2359
2360    /// Whether the sheet shows a drag handle.
2361    pub fn show_drag_handle(mut self, show_drag_handle: bool) -> ShowModalBottomSheet {
2362        self.show_drag_handle = Some(show_drag_handle);
2363        self
2364    }
2365
2366    /// Whether the sheet avoids the operating system's safe areas. Defaults to `false`.
2367    pub fn use_safe_area(mut self, use_safe_area: bool) -> ShowModalBottomSheet {
2368        self.use_safe_area = use_safe_area;
2369        self
2370    }
2371
2372    /// The route settings passed to the sheet's route.
2373    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowModalBottomSheet {
2374        self.route_settings = Some(route_settings);
2375        self
2376    }
2377
2378    /// An animation controller the sheet uses instead of creating one.
2379    pub fn transition_animation_controller(
2380        mut self,
2381        transition_animation_controller: Ref<AnimationController>,
2382    ) -> ShowModalBottomSheet {
2383        self.transition_animation_controller = Some(transition_animation_controller);
2384        self
2385    }
2386
2387    /// An animation style that overrides the sheet's animation durations.
2388    pub fn sheet_animation_style(
2389        mut self,
2390        sheet_animation_style: AnimationStyle,
2391    ) -> ShowModalBottomSheet {
2392        self.sheet_animation_style = Some(sheet_animation_style);
2393        self
2394    }
2395
2396    /// Whether the sheet's route requests focus when it is pushed.
2397    pub fn request_focus(mut self, request_focus: bool) -> ShowModalBottomSheet {
2398        self.request_focus = Some(request_focus);
2399        self
2400    }
2401
2402    /// Shows the sheet and returns a future that resolves to the value passed to
2403    /// [`Navigator::pop`] when it closes.
2404    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
2405        let ShowModalBottomSheet {
2406            builder,
2407            background_color,
2408            barrier_label,
2409            elevation,
2410            shape,
2411            clip_behavior,
2412            constraints,
2413            barrier_color,
2414            is_scroll_controlled,
2415            scroll_control_disabled_max_height_ratio,
2416            use_root_navigator,
2417            is_dismissible,
2418            enable_drag,
2419            show_drag_handle,
2420            use_safe_area,
2421            route_settings,
2422            transition_animation_controller,
2423            sheet_animation_style,
2424            request_focus,
2425        } = self;
2426
2427        debug_assert!(debug_check_has_media_query(app, context));
2428        debug_assert!(debug_check_has_material_localizations(app, context));
2429
2430        let navigator = Navigator::of(app, context, use_root_navigator);
2431        let localizations = <dyn MaterialLocalizations>::of(app, context);
2432        let navigator_context = navigator.context(app);
2433        let captured_themes = <dyn InheritedTheme>::capture(app, context, Some(navigator_context));
2434        let modal_barrier_color = barrier_color.or(Theme::of(app, context)
2435            .bottom_sheet_theme
2436            .modal_barrier_color);
2437        let route = ModalBottomSheetRoute::new(app, builder, is_scroll_controlled)
2438            .captured_themes(app, captured_themes)
2439            .scroll_control_disabled_max_height_ratio(app, scroll_control_disabled_max_height_ratio)
2440            .barrier_label(
2441                app,
2442                barrier_label.unwrap_or_else(|| localizations.scrim_label()),
2443            )
2444            .barrier_on_tap_hint(
2445                app,
2446                localizations.scrim_on_tap_hint(&localizations.bottom_sheet_label()),
2447            )
2448            .is_dismissible(app, is_dismissible)
2449            .enable_drag(app, enable_drag)
2450            .use_safe_area(app, use_safe_area);
2451        let mut route = route;
2452        let this = app.get_mut(&route);
2453        this.background_color = background_color;
2454        this.elevation = elevation;
2455        this.shape = shape;
2456        this.clip_behavior = clip_behavior;
2457        this.constraints = constraints;
2458        this.modal_barrier_color = modal_barrier_color;
2459        this.show_drag_handle = show_drag_handle;
2460        this.transition_animation_controller = transition_animation_controller;
2461        this.sheet_animation_style = sheet_animation_style;
2462        if let Some(route_settings) = route_settings {
2463            route = route.settings(app, route_settings);
2464        }
2465        if let Some(request_focus) = request_focus {
2466            route = route.request_focus(app, request_focus);
2467        }
2468        navigator.push(app, route.into_erased())
2469    }
2470}
2471
2472/// Shows a Material Design bottom sheet in the nearest [`Scaffold`] ancestor. To
2473/// show a persistent bottom sheet, use the `Scaffold::bottom_sheet`.
2474///
2475/// Returns a controller that can be used to close and otherwise manipulate the
2476/// bottom sheet.
2477///
2478/// The optional `background_color`, `elevation`, `shape`, `clip_behavior`,
2479/// `constraints` and `transition_animation_controller`
2480/// parameters can be passed in to customize the appearance and behavior of
2481/// persistent bottom sheets (see the documentation for these on [`BottomSheet`]
2482/// for more details).
2483///
2484/// The `enable_drag` parameter specifies whether the bottom sheet can be
2485/// dragged up and down and dismissed by swiping downwards.
2486///
2487/// The `sheet_animation_style` parameter is used to override the bottom sheet
2488/// animation duration and reverse animation duration.
2489///
2490/// If `AnimationStyle.duration` is provided, it will be used to override
2491/// the bottom sheet animation duration in the underlying
2492/// [`BottomSheet::create_animation_controller`].
2493///
2494/// If `AnimationStyle.reverseDuration` is provided, it will be used to
2495/// override the bottom sheet reverse animation duration in the underlying
2496/// [`BottomSheet::create_animation_controller`].
2497///
2498/// To disable the bottom sheet animation, use `AnimationStyle.noAnimation`.
2499///
2500/// To rebuild the bottom sheet (e.g. if it is stateful), call
2501/// `PersistentBottomSheetController::set_state` on the controller returned by
2502/// this method.
2503///
2504/// The new bottom sheet becomes a `LocalHistoryEntry` for the enclosing
2505/// [`ModalRoute`] and a back button is added to the app bar of the [`Scaffold`]
2506/// that closes the bottom sheet.
2507///
2508/// To create a persistent bottom sheet that is not a `LocalHistoryEntry` and
2509/// does not add a back button to the enclosing Scaffold's app bar, use the
2510/// `Scaffold::bottom_sheet` constructor parameter.
2511///
2512/// A closely related widget is a modal bottom sheet, which is an alternative
2513/// to a menu or a dialog and prevents the user from interacting with the rest
2514/// of the app. Modal bottom sheets can be created and displayed with the
2515/// [`ShowModalBottomSheet`] function.
2516///
2517/// The `context` argument is used to look up the [`Scaffold`] for the bottom
2518/// sheet. It is only used when the method is called. Its corresponding widget
2519/// can be safely removed from the tree before the bottom sheet is closed.
2520///
2521/// See also:
2522///
2523///  * [`BottomSheet`], which becomes the parent of the widget returned by the
2524///    `builder`.
2525///  * [`ShowModalBottomSheet`], which can be used to display a modal bottom
2526///    sheet.
2527///  * [`Scaffold::of`], for information about how to obtain the [`BuildContext`].
2528///  * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
2529///  * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
2530///  * [`AnimationStyle`], which is used to override the bottom sheet animation
2531///    duration and reverse animation duration.
2532pub struct ShowBottomSheet {
2533    builder: WidgetBuilder,
2534    background_color: Option<Color>,
2535    elevation: Option<f64>,
2536    shape: Option<ShapeBorderRef>,
2537    clip_behavior: Option<Clip>,
2538    constraints: Option<BoxConstraints>,
2539    enable_drag: Option<bool>,
2540    show_drag_handle: Option<bool>,
2541    transition_animation_controller: Option<Ref<AnimationController>>,
2542    sheet_animation_style: Option<AnimationStyle>,
2543}
2544
2545impl ShowBottomSheet {
2546    /// Creates a builder for a persistent bottom sheet; Dart's `showBottomSheet` required
2547    /// argument is the `builder`, and every other argument is a setter.
2548    pub fn new(builder: WidgetBuilder) -> ShowBottomSheet {
2549        ShowBottomSheet {
2550            builder,
2551            background_color: None,
2552            elevation: None,
2553            shape: None,
2554            clip_behavior: None,
2555            constraints: None,
2556            enable_drag: None,
2557            show_drag_handle: None,
2558            transition_animation_controller: None,
2559            sheet_animation_style: None,
2560        }
2561    }
2562
2563    /// The background color of the sheet.
2564    pub fn background_color(mut self, background_color: Color) -> ShowBottomSheet {
2565        self.background_color = Some(background_color);
2566        self
2567    }
2568
2569    /// The z-coordinate of the sheet.
2570    pub fn elevation(mut self, elevation: f64) -> ShowBottomSheet {
2571        self.elevation = Some(elevation);
2572        self
2573    }
2574
2575    /// The shape of the sheet's material.
2576    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ShowBottomSheet {
2577        self.shape = Some(shape.into());
2578        self
2579    }
2580
2581    /// The clip behavior of the sheet.
2582    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ShowBottomSheet {
2583        self.clip_behavior = Some(clip_behavior);
2584        self
2585    }
2586
2587    /// The size constraints on the sheet.
2588    pub fn constraints(mut self, constraints: BoxConstraints) -> ShowBottomSheet {
2589        self.constraints = Some(constraints);
2590        self
2591    }
2592
2593    /// Whether the sheet can be dragged up and down.
2594    pub fn enable_drag(mut self, enable_drag: bool) -> ShowBottomSheet {
2595        self.enable_drag = Some(enable_drag);
2596        self
2597    }
2598
2599    /// Whether the sheet shows a drag handle.
2600    pub fn show_drag_handle(mut self, show_drag_handle: bool) -> ShowBottomSheet {
2601        self.show_drag_handle = Some(show_drag_handle);
2602        self
2603    }
2604
2605    /// An animation controller the sheet uses instead of creating one.
2606    pub fn transition_animation_controller(
2607        mut self,
2608        transition_animation_controller: Ref<AnimationController>,
2609    ) -> ShowBottomSheet {
2610        self.transition_animation_controller = Some(transition_animation_controller);
2611        self
2612    }
2613
2614    /// An animation style that overrides the sheet's animation durations.
2615    pub fn sheet_animation_style(
2616        mut self,
2617        sheet_animation_style: AnimationStyle,
2618    ) -> ShowBottomSheet {
2619        self.sheet_animation_style = Some(sheet_animation_style);
2620        self
2621    }
2622
2623    /// Shows the sheet and returns its controller.
2624    pub fn show(self, app: &mut App, context: BuildContext) -> Rc<PersistentBottomSheetController> {
2625        let ShowBottomSheet {
2626            builder,
2627            background_color,
2628            elevation,
2629            shape,
2630            clip_behavior,
2631            constraints,
2632            enable_drag,
2633            show_drag_handle,
2634            transition_animation_controller,
2635            sheet_animation_style,
2636        } = self;
2637
2638        debug_assert!(debug_check_has_scaffold(app, context));
2639
2640        Scaffold::of(app, context).show_bottom_sheet(
2641            app,
2642            builder,
2643            background_color,
2644            elevation,
2645            shape,
2646            clip_behavior,
2647            constraints,
2648            enable_drag,
2649            show_drag_handle,
2650            transition_animation_controller,
2651            sheet_animation_style,
2652        )
2653    }
2654}
2655
2656/// Dart's `_BottomSheetGestureDetector`.
2657struct BottomSheetGestureDetector {
2658    child: WidgetRef,
2659    on_vertical_drag_start: GestureDragStartCallback,
2660    on_vertical_drag_update: GestureDragUpdateCallback,
2661    on_vertical_drag_end: GestureDragEndCallback,
2662}
2663
2664impl Debug for BottomSheetGestureDetector {
2665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2666        f.debug_struct("BottomSheetGestureDetector")
2667            .field("child", &self.child)
2668            .finish_non_exhaustive()
2669    }
2670}
2671
2672impl StatelessWidget for BottomSheetGestureDetector {
2673    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
2674        let on_vertical_drag_start = Rc::clone(&self.on_vertical_drag_start);
2675        let on_vertical_drag_update = Rc::clone(&self.on_vertical_drag_update);
2676        let on_vertical_drag_end = Rc::clone(&self.on_vertical_drag_end);
2677        RawGestureDetector::new()
2678            .gestures(vec![(
2679                TypeId::of::<VerticalDragGestureRecognizer>(),
2680                GestureRecognizerFactoryWithHandlers::<VerticalDragGestureRecognizer>::new(
2681                    VerticalDragGestureRecognizer::new,
2682                    move |app, instance| {
2683                        instance.set_on_start(app, Some(Rc::clone(&on_vertical_drag_start)));
2684                        instance.set_on_update(app, Some(Rc::clone(&on_vertical_drag_update)));
2685                        instance.set_on_end(app, Some(Rc::clone(&on_vertical_drag_end)));
2686                        instance.set_only_accept_drag_on_threshold(app, true);
2687                    },
2688                )
2689                .into_factory(),
2690            )])
2691            .child(self.child.clone())
2692            .into_widget()
2693    }
2694}
2695
2696#[cfg(test)]
2697mod tests {
2698    use std::cell::{Cell, RefCell};
2699    use waft_painting::ShapeBorder;
2700    use waft_widgets::Text;
2701
2702    use waft_embedder::Rect;
2703    use waft_widgets::{AnyElement, Notification, RouteSettings};
2704
2705    use waft_widgets::testing::{
2706        TestPointer, WidgetTester, assert_f32_equals, assert_more_or_less_equals_within, expect,
2707        find, finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
2708    };
2709
2710    use super::*;
2711    use crate::scaffold::ScaffoldState;
2712    use crate::test_support::material_app;
2713    use crate::theme_data::ThemeData;
2714    use waft_test::{assert_no_new_objects, object_snapshot};
2715
2716    fn m3(tester: &WidgetTester) -> ThemeData {
2717        ThemeData::new(&tester.cell.borrow())
2718    }
2719
2720    fn m2(tester: &WidgetTester) -> ThemeData {
2721        ThemeData::builder()
2722            .use_material3(false)
2723            .build(&tester.cell.borrow())
2724    }
2725
2726    /// Dart's `const Text('BottomSheet')` as the tests lay it out.
2727    fn text(text: &'static str) -> WidgetRef {
2728        Text::new(text).into_widget()
2729    }
2730
2731    fn sheet_builder(content: &'static str) -> WidgetBuilder {
2732        Rc::new(move |_app, _context| text(content))
2733    }
2734
2735    /// A slot a builder writes its context into: Dart's `late BuildContext savedContext`.
2736    #[derive(Clone, Default)]
2737    struct Saved(Rc<Cell<Option<BuildContext>>>);
2738
2739    impl Saved {
2740        fn get(&self) -> BuildContext {
2741            self.0.get().expect("the builder ran")
2742        }
2743
2744        /// Dart's `Builder(builder: (context) { saved = context; return child; })`.
2745        fn builder(&self, child: impl Fn() -> WidgetRef + 'static) -> WidgetRef {
2746            let slot = Rc::clone(&self.0);
2747            Builder::new(move |_app, context| {
2748                slot.set(Some(context));
2749                child()
2750            })
2751            .into_widget()
2752        }
2753    }
2754
2755    /// `MaterialApp(home: Builder(builder: (context) { savedContext = context; return Container(); }))`.
2756    fn app_saving_context(tester: &WidgetTester, saved: &Saved) -> WidgetRef {
2757        material_app(m3(tester), saved.builder(|| Container::new().into_widget()))
2758    }
2759
2760    /// `MaterialApp(home: Scaffold(key: scaffoldKey, body: const Center(child: Text('body'))))`.
2761    fn app_with_scaffold(theme: ThemeData, scaffold_key: &GlobalKey) -> WidgetRef {
2762        material_app(
2763            theme,
2764            Scaffold::new()
2765                .key(scaffold_key.clone().into())
2766                .body(Center::new().child(text("body")))
2767                .into_widget(),
2768        )
2769    }
2770
2771    /// `showModalBottomSheet`'s arguments with Dart's defaults.
2772    struct Modal {
2773        background_color: Option<Color>,
2774        barrier_label: Option<String>,
2775        elevation: Option<f64>,
2776        shape: Option<ShapeBorderRef>,
2777        clip_behavior: Option<Clip>,
2778        constraints: Option<BoxConstraints>,
2779        barrier_color: Option<Color>,
2780        is_scroll_controlled: bool,
2781        scroll_control_disabled_max_height_ratio: f64,
2782        use_root_navigator: bool,
2783        is_dismissible: bool,
2784        enable_drag: bool,
2785        show_drag_handle: Option<bool>,
2786        use_safe_area: bool,
2787        route_settings: Option<RouteSettingsRef>,
2788        transition_animation_controller: Option<Ref<AnimationController>>,
2789        sheet_animation_style: Option<AnimationStyle>,
2790        request_focus: Option<bool>,
2791    }
2792
2793    impl Default for Modal {
2794        fn default() -> Modal {
2795            Modal {
2796                background_color: None,
2797                barrier_label: None,
2798                elevation: None,
2799                shape: None,
2800                clip_behavior: None,
2801                constraints: None,
2802                barrier_color: None,
2803                is_scroll_controlled: false,
2804                scroll_control_disabled_max_height_ratio:
2805                    K_DEFAULT_SCROLL_CONTROL_DISABLED_MAX_HEIGHT_RATIO,
2806                use_root_navigator: false,
2807                is_dismissible: true,
2808                enable_drag: true,
2809                show_drag_handle: None,
2810                use_safe_area: false,
2811                route_settings: None,
2812                transition_animation_controller: None,
2813                sheet_animation_style: None,
2814                request_focus: None,
2815            }
2816        }
2817    }
2818
2819    impl Modal {
2820        fn show(
2821            self,
2822            tester: &WidgetTester,
2823            context: BuildContext,
2824            builder: WidgetBuilder,
2825        ) -> CompleterFuture<RouteResult> {
2826            self.show_in(&mut tester.cell.borrow_mut(), context, builder)
2827        }
2828
2829        fn show_in(
2830            self,
2831            app: &mut App,
2832            context: BuildContext,
2833            builder: WidgetBuilder,
2834        ) -> CompleterFuture<RouteResult> {
2835            let mut show = ShowModalBottomSheet::new(builder)
2836                .is_scroll_controlled(self.is_scroll_controlled)
2837                .scroll_control_disabled_max_height_ratio(
2838                    self.scroll_control_disabled_max_height_ratio,
2839                )
2840                .use_root_navigator(self.use_root_navigator)
2841                .is_dismissible(self.is_dismissible)
2842                .enable_drag(self.enable_drag)
2843                .use_safe_area(self.use_safe_area);
2844            if let Some(background_color) = self.background_color {
2845                show = show.background_color(background_color);
2846            }
2847            if let Some(barrier_label) = self.barrier_label {
2848                show = show.barrier_label(barrier_label);
2849            }
2850            if let Some(elevation) = self.elevation {
2851                show = show.elevation(elevation);
2852            }
2853            if let Some(shape) = self.shape {
2854                show = show.shape(shape);
2855            }
2856            if let Some(clip_behavior) = self.clip_behavior {
2857                show = show.clip_behavior(clip_behavior);
2858            }
2859            if let Some(constraints) = self.constraints {
2860                show = show.constraints(constraints);
2861            }
2862            if let Some(barrier_color) = self.barrier_color {
2863                show = show.barrier_color(barrier_color);
2864            }
2865            if let Some(show_drag_handle) = self.show_drag_handle {
2866                show = show.show_drag_handle(show_drag_handle);
2867            }
2868            if let Some(route_settings) = self.route_settings {
2869                show = show.route_settings(route_settings);
2870            }
2871            if let Some(transition_animation_controller) = self.transition_animation_controller {
2872                show = show.transition_animation_controller(transition_animation_controller);
2873            }
2874            if let Some(sheet_animation_style) = self.sheet_animation_style {
2875                show = show.sheet_animation_style(sheet_animation_style);
2876            }
2877            if let Some(request_focus) = self.request_focus {
2878                show = show.request_focus(request_focus);
2879            }
2880            show.show(app, context)
2881        }
2882    }
2883
2884    /// `ScaffoldState.showBottomSheet`'s optional arguments with Dart's defaults.
2885    #[derive(Default)]
2886    struct Persistent {
2887        constraints: Option<BoxConstraints>,
2888        enable_drag: Option<bool>,
2889        show_drag_handle: Option<bool>,
2890        transition_animation_controller: Option<Ref<AnimationController>>,
2891        sheet_animation_style: Option<AnimationStyle>,
2892    }
2893
2894    impl Persistent {
2895        fn show(
2896            self,
2897            tester: &WidgetTester,
2898            scaffold: Handle<ScaffoldState>,
2899            builder: WidgetBuilder,
2900        ) -> Rc<PersistentBottomSheetController> {
2901            let mut app = tester.cell.borrow_mut();
2902            scaffold.show_bottom_sheet(
2903                &mut app,
2904                builder,
2905                None,
2906                None,
2907                None,
2908                None,
2909                self.constraints,
2910                self.enable_drag,
2911                self.show_drag_handle,
2912                self.transition_animation_controller,
2913                self.sheet_animation_style,
2914            )
2915        }
2916    }
2917
2918    fn scaffold_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<ScaffoldState> {
2919        key.current_state::<ScaffoldState>(&tester.cell.borrow_mut())
2920            .expect("the scaffold is mounted")
2921    }
2922
2923    /// Sets the flag when `future` completes: Dart's `.then((_) { called = true; })`.
2924    fn flag_when_complete<T: Clone + 'static>(
2925        tester: &WidgetTester,
2926        future: CompleterFuture<T>,
2927    ) -> Rc<Cell<bool>> {
2928        let called = Rc::new(Cell::new(false));
2929        let flag = Rc::clone(&called);
2930        future.then(&mut tester.cell.borrow_mut(), move |_app, _| flag.set(true));
2931        called
2932    }
2933
2934    fn found(tester: &WidgetTester, content: &str) -> usize {
2935        find::text(content).evaluate(tester).len()
2936    }
2937
2938    fn only(found: Vec<AnyElement>) -> AnyElement {
2939        assert_eq!(found.len(), 1, "one widget found");
2940        found[0]
2941    }
2942
2943    fn rect_of_text(tester: &WidgetTester, content: &str) -> Rect {
2944        tester.get_rect(only(find::text(content).evaluate(tester)))
2945    }
2946
2947    fn center_of_text(tester: &WidgetTester, content: &str) -> Offset {
2948        rect_of_text(tester, content).center()
2949    }
2950
2951    /// Dart's `tester.drag(find.text(content), offset)`.
2952    fn drag_text(tester: &mut WidgetTester, content: &str, offset: Offset) {
2953        let start = center_of_text(tester, content);
2954        tester.drag_from(start, offset, 1);
2955    }
2956
2957    /// Dart's `tester.fling(find.text(content), offset, speed)`.
2958    fn fling_text(tester: &mut WidgetTester, content: &str, offset: Offset, speed: f64) {
2959        let start = center_of_text(tester, content);
2960        tester.fling_from(start, offset, speed, 1);
2961    }
2962
2963    /// Pumps and ensures that the BottomSheet animates non-linearly; Dart's
2964    /// `checkNonLinearAnimation`.
2965    fn check_non_linear_animation(tester: &mut WidgetTester) {
2966        let first_position = center_of_text(tester, "BottomSheet");
2967        tester.pump_by(Duration::from_millis(30));
2968        let second_position = center_of_text(tester, "BottomSheet");
2969        tester.pump_by(Duration::from_millis(30));
2970        let third_position = center_of_text(tester, "BottomSheet");
2971
2972        let dy_delta1 = second_position.dy() - first_position.dy();
2973        let dy_delta2 = third_position.dy() - second_position.dy();
2974
2975        // If the animation were linear, these two values would be the same.
2976        assert!((dy_delta1 - dy_delta2).abs() > 0.1);
2977    }
2978
2979    /// Dart's 'Swiping down a BottomSheet should dismiss it by default', 'when enableDrag is
2980    /// false' and 'when enableDrag is true'.
2981    fn swipe_persistent(tester: &mut WidgetTester, enable_drag: Option<bool>, dismissed: bool) {
2982        let scaffold_key = GlobalKey::new();
2983        tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
2984        tester.pump();
2985        assert_eq!(found(tester, "BottomSheet"), 0);
2986
2987        let scaffold = scaffold_state(tester, &scaffold_key);
2988        let controller = Persistent {
2989            enable_drag,
2990            ..Persistent::default()
2991        }
2992        .show(
2993            tester,
2994            scaffold,
2995            Rc::new(|_app, _context| {
2996                SizedBox::new()
2997                    .height(200.0)
2998                    .child(text("BottomSheet"))
2999                    .into_widget()
3000            }),
3001        );
3002        let then_called = flag_when_complete(tester, controller.closed());
3003
3004        tester.pump_and_settle();
3005        assert!(!then_called.get());
3006        assert_eq!(found(tester, "BottomSheet"), 1);
3007
3008        // Swipe the bottom sheet to dismiss it.
3009        drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
3010        tester.pump_and_settle(); // Bottom sheet dismiss animation.
3011        assert_eq!(then_called.get(), dismissed);
3012        assert_eq!(found(tester, "BottomSheet"), if dismissed { 0 } else { 1 });
3013    }
3014
3015    #[test]
3016    fn swiping_down_a_bottom_sheet_dismisses_it_by_default() {
3017        test_widgets(|tester| swipe_persistent(tester, None, true));
3018    }
3019
3020    #[test]
3021    fn swiping_down_a_bottom_sheet_does_not_dismiss_it_when_enable_drag_is_false() {
3022        test_widgets(|tester| swipe_persistent(tester, Some(false), false));
3023    }
3024
3025    #[test]
3026    fn swiping_down_a_bottom_sheet_dismisses_it_when_enable_drag_is_true() {
3027        test_widgets(|tester| swipe_persistent(tester, Some(true), true));
3028    }
3029
3030    /// Dart's 'Tapping on a BottomSheet should not trigger a rebuild when enableDrag is true'.
3031    #[test]
3032    fn tapping_a_draggable_bottom_sheet_does_not_rebuild_it() {
3033        test_widgets(|tester| {
3034            let scaffold_key = GlobalKey::new();
3035            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3036            tester.pump();
3037            let build_count = Rc::new(Cell::new(0));
3038            assert_eq!(build_count.get(), 0);
3039            assert_eq!(found(tester, "BottomSheet"), 0);
3040
3041            let scaffold = scaffold_state(tester, &scaffold_key);
3042            let count = Rc::clone(&build_count);
3043            Persistent {
3044                enable_drag: Some(true),
3045                ..Persistent::default()
3046            }
3047            .show(
3048                tester,
3049                scaffold,
3050                Rc::new(move |_app, _context| {
3051                    count.set(count.get() + 1);
3052                    SizedBox::new()
3053                        .height(200.0)
3054                        .child(text("BottomSheet"))
3055                        .into_widget()
3056                }),
3057            );
3058
3059            tester.pump_and_settle();
3060            assert_eq!(build_count.get(), 1);
3061            assert_eq!(found(tester, "BottomSheet"), 1);
3062
3063            // Tap on bottom sheet should not trigger a rebuild.
3064            let center = center_of_text(tester, "BottomSheet");
3065            tester.tap_at(center, 1);
3066            tester.pump_and_settle();
3067            assert_eq!(build_count.get(), 1);
3068            assert_eq!(found(tester, "BottomSheet"), 1);
3069        });
3070    }
3071
3072    /// Dart's first 'Modal BottomSheet builder should only be called once'.
3073    #[test]
3074    fn a_modal_bottom_sheet_builder_is_called_once() {
3075        test_widgets(|tester| {
3076            let saved = Saved::default();
3077            tester.pump_widget(app_saving_context(tester, &saved));
3078
3079            let num_builder_calls = Rc::new(Cell::new(0));
3080            let calls = Rc::clone(&num_builder_calls);
3081            Modal {
3082                is_dismissible: false,
3083                ..Modal::default()
3084            }
3085            .show(
3086                tester,
3087                saved.get(),
3088                Rc::new(move |_app, _context| {
3089                    calls.set(calls.get() + 1);
3090                    text("BottomSheet")
3091                }),
3092            );
3093
3094            tester.pump_and_settle();
3095            assert_eq!(num_builder_calls.get(), 1);
3096
3097            // Swipe the bottom sheet to dismiss it.
3098            drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
3099            tester.pump_and_settle(); // Bottom sheet dismiss animation.
3100            assert_eq!(num_builder_calls.get(), 1);
3101        });
3102    }
3103
3104    /// Dart's 'Tapping on a modal BottomSheet should not dismiss it'.
3105    #[test]
3106    fn tapping_on_a_modal_bottom_sheet_does_not_dismiss_it() {
3107        test_widgets(|tester| {
3108            let saved = Saved::default();
3109            tester.pump_widget(app_saving_context(tester, &saved));
3110            tester.pump();
3111            assert_eq!(found(tester, "BottomSheet"), 0);
3112
3113            let future = Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet"));
3114            let then_called = flag_when_complete(tester, future);
3115
3116            tester.pump_and_settle();
3117            assert_eq!(found(tester, "BottomSheet"), 1);
3118            assert!(!then_called.get());
3119
3120            // Tap on the bottom sheet itself, it should not be dismissed
3121            let center = center_of_text(tester, "BottomSheet");
3122            tester.tap_at(center, 1);
3123            tester.pump_and_settle();
3124            assert_eq!(found(tester, "BottomSheet"), 1);
3125            assert!(!then_called.get());
3126        });
3127    }
3128
3129    /// Dart's 'Tapping outside a modal BottomSheet should dismiss it by default', 'when
3130    /// isDismissible=true' and 'should not dismiss it when isDismissible=false'.
3131    fn tap_outside_modal(tester: &mut WidgetTester, is_dismissible: bool) {
3132        let saved = Saved::default();
3133        tester.pump_widget(app_saving_context(tester, &saved));
3134        tester.pump();
3135        assert_eq!(found(tester, "BottomSheet"), 0);
3136
3137        let future = Modal {
3138            is_dismissible,
3139            ..Modal::default()
3140        }
3141        .show(tester, saved.get(), sheet_builder("BottomSheet"));
3142        let then_called = flag_when_complete(tester, future);
3143
3144        tester.pump_and_settle();
3145        assert_eq!(found(tester, "BottomSheet"), 1);
3146        assert!(!then_called.get());
3147
3148        // Tap above the bottom sheet to dismiss it.
3149        tester.tap_at(Offset::new(20.0, 20.0), 1);
3150        tester.pump_and_settle(); // Bottom sheet dismiss animation.
3151        assert_eq!(then_called.get(), is_dismissible);
3152        assert_eq!(
3153            found(tester, "BottomSheet"),
3154            if is_dismissible { 0 } else { 1 }
3155        );
3156    }
3157
3158    #[test]
3159    fn tapping_outside_a_modal_bottom_sheet_dismisses_it_by_default() {
3160        test_widgets(|tester| tap_outside_modal(tester, Modal::default().is_dismissible));
3161    }
3162
3163    #[test]
3164    fn tapping_outside_a_modal_bottom_sheet_dismisses_it_when_is_dismissible_is_true() {
3165        test_widgets(|tester| tap_outside_modal(tester, true));
3166    }
3167
3168    #[test]
3169    fn tapping_outside_a_modal_bottom_sheet_does_not_dismiss_it_when_is_dismissible_is_false() {
3170        test_widgets(|tester| tap_outside_modal(tester, false));
3171    }
3172
3173    /// Dart's 'Verify that the BottomSheet animates non-linearly'.
3174    #[test]
3175    fn the_bottom_sheet_animates_non_linearly() {
3176        test_widgets(|tester| {
3177            let saved = Saved::default();
3178            tester.pump_widget(app_saving_context(tester, &saved));
3179            tester.pump();
3180            assert_eq!(found(tester, "BottomSheet"), 0);
3181
3182            Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet"));
3183            tester.pump();
3184
3185            check_non_linear_animation(tester);
3186            tester.pump_and_settle();
3187
3188            // Tap above the bottom sheet to dismiss it.
3189            tester.tap_at(Offset::new(20.0, 20.0), 1);
3190            tester.pump();
3191            check_non_linear_animation(tester);
3192            tester.pump_and_settle(); // Bottom sheet dismiss animation.
3193            assert_eq!(found(tester, "BottomSheet"), 0);
3194        });
3195    }
3196
3197    /// Dart's 'Swiping down a modal BottomSheet should dismiss it by default', 'should not
3198    /// dismiss it when enableDrag is false' and 'should dismiss it when enableDrag is true'.
3199    fn swipe_modal(tester: &mut WidgetTester, enable_drag: bool, dismissed: bool) {
3200        let saved = Saved::default();
3201        tester.pump_widget(app_saving_context(tester, &saved));
3202        tester.pump();
3203        assert_eq!(found(tester, "BottomSheet"), 0);
3204
3205        let future = Modal {
3206            is_dismissible: false,
3207            enable_drag,
3208            ..Modal::default()
3209        }
3210        .show(tester, saved.get(), sheet_builder("BottomSheet"));
3211        let then_called = flag_when_complete(tester, future);
3212
3213        tester.pump_and_settle();
3214        assert_eq!(found(tester, "BottomSheet"), 1);
3215        assert!(!then_called.get());
3216
3217        // Swipe the bottom sheet to dismiss it.
3218        drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
3219        tester.pump_and_settle(); // Bottom sheet dismiss animation.
3220        assert_eq!(then_called.get(), dismissed);
3221        assert_eq!(found(tester, "BottomSheet"), if dismissed { 0 } else { 1 });
3222    }
3223
3224    #[test]
3225    fn swiping_down_a_modal_bottom_sheet_dismisses_it_by_default() {
3226        test_widgets(|tester| swipe_modal(tester, Modal::default().enable_drag, true));
3227    }
3228
3229    #[test]
3230    fn swiping_down_a_modal_bottom_sheet_does_not_dismiss_it_when_enable_drag_is_false() {
3231        test_widgets(|tester| swipe_modal(tester, false, false));
3232    }
3233
3234    #[test]
3235    fn swiping_down_a_modal_bottom_sheet_dismisses_it_when_enable_drag_is_true() {
3236        test_widgets(|tester| swipe_modal(tester, true, true));
3237    }
3238
3239    /// Dart's 'Verify that a downwards fling dismisses a persistent BottomSheet'.
3240    #[test]
3241    fn a_downwards_fling_dismisses_a_persistent_bottom_sheet() {
3242        test_widgets(|tester| {
3243            let scaffold_key = GlobalKey::new();
3244            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3245            assert_eq!(found(tester, "BottomSheet"), 0);
3246
3247            let scaffold = scaffold_state(tester, &scaffold_key);
3248            let controller = Persistent::default().show(
3249                tester,
3250                scaffold,
3251                Rc::new(|_app, _context| {
3252                    Container::new()
3253                        .margin(EdgeInsetsGeometry::all(40.0))
3254                        .child(text("BottomSheet"))
3255                        .into_widget()
3256                }),
3257            );
3258            let then_called = flag_when_complete(tester, controller.closed());
3259
3260            assert!(!then_called.get());
3261            assert_eq!(found(tester, "BottomSheet"), 0);
3262
3263            tester.pump(); // bottom sheet show animation starts
3264
3265            assert!(!then_called.get());
3266            assert_eq!(found(tester, "BottomSheet"), 1);
3267
3268            tester.pump_by(Duration::from_secs(1)); // animation done
3269
3270            assert!(!then_called.get());
3271            assert_eq!(found(tester, "BottomSheet"), 1);
3272
3273            // The fling below must be such that the velocity estimation examines an
3274            // offset greater than the kTouchSlop. Too slow or too short a distance, and
3275            // it won't trigger. Also, it must not be so much that it drags the bottom
3276            // sheet off the screen, or we won't see it after we pump!
3277            fling_text(tester, "BottomSheet", Offset::new(0.0, 50.0), 2000.0);
3278            tester.pump(); // drain the microtask queue (Future completion callback)
3279
3280            assert!(then_called.get());
3281            assert_eq!(found(tester, "BottomSheet"), 1);
3282
3283            tester.pump(); // bottom sheet dismiss animation starts
3284
3285            assert!(then_called.get());
3286            assert_eq!(found(tester, "BottomSheet"), 1);
3287
3288            tester.pump_by(Duration::from_secs(1)); // animation done
3289
3290            assert!(then_called.get());
3291            assert_eq!(found(tester, "BottomSheet"), 0);
3292        });
3293    }
3294
3295    /// Dart's 'Verify that dragging past the bottom dismisses a persistent BottomSheet'.
3296    #[test]
3297    fn dragging_past_the_bottom_dismisses_a_persistent_bottom_sheet() {
3298        test_widgets(|tester| {
3299            // This is a regression test for https://github.com/flutter/flutter/issues/5528
3300            let scaffold_key = GlobalKey::new();
3301            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3302
3303            let scaffold = scaffold_state(tester, &scaffold_key);
3304            Persistent::default().show(
3305                tester,
3306                scaffold,
3307                Rc::new(|_app, _context| {
3308                    Container::new()
3309                        .margin(EdgeInsetsGeometry::all(40.0))
3310                        .child(text("BottomSheet"))
3311                        .into_widget()
3312                }),
3313            );
3314
3315            tester.pump(); // bottom sheet show animation starts
3316            tester.pump_by(Duration::from_secs(1)); // animation done
3317            assert_eq!(found(tester, "BottomSheet"), 1);
3318
3319            fling_text(tester, "BottomSheet", Offset::new(0.0, 400.0), 1000.0);
3320            tester.pump(); // drain the microtask queue (Future completion callback)
3321            tester.pump(); // bottom sheet dismiss animation starts
3322            tester.pump_by(Duration::from_secs(1)); // animation done
3323
3324            assert_eq!(found(tester, "BottomSheet"), 0);
3325        });
3326    }
3327
3328    /// Dispatches Dart's `DraggableScrollableNotification(extent: 0.20000000001, minExtent:
3329    /// 0.2, maxExtent: 1.0, initialExtent: 0.5, context: notificationContext)` from `context`.
3330    fn dispatch_nearly_minimum_extent(tester: &WidgetTester, context: BuildContext) {
3331        let mut app = tester.cell.borrow_mut();
3332        DraggableScrollableNotification::new(0.20000000001, 0.2, 1.0, 0.5, context)
3333            .dispatch(&mut app, Some(context));
3334    }
3335
3336    /// Dart's 'Standard BottomSheet closes when its extent is nearly its minimum'.
3337    #[test]
3338    fn a_standard_bottom_sheet_closes_when_its_extent_is_nearly_its_minimum() {
3339        test_widgets(|tester| {
3340            let scaffold_key = GlobalKey::new();
3341            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3342
3343            let notification_context = Saved::default();
3344            let saving = notification_context.clone();
3345            let scaffold = scaffold_state(tester, &scaffold_key);
3346            Persistent::default().show(
3347                tester,
3348                scaffold,
3349                Rc::new(move |_app, _context| saving.builder(|| text("BottomSheet"))),
3350            );
3351            tester.pump_and_settle();
3352
3353            dispatch_nearly_minimum_extent(tester, notification_context.get());
3354            tester.pump_and_settle();
3355
3356            assert_eq!(found(tester, "BottomSheet"), 0);
3357        });
3358    }
3359
3360    /// Dart's 'Modal BottomSheet closes when its extent is nearly its minimum'.
3361    #[test]
3362    fn a_modal_bottom_sheet_closes_when_its_extent_is_nearly_its_minimum() {
3363        test_widgets(|tester| {
3364            let scaffold_key = GlobalKey::new();
3365            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3366
3367            let notification_context = Saved::default();
3368            let saving = notification_context.clone();
3369            let context = scaffold_key
3370                .current_context(&tester.cell.borrow_mut())
3371                .expect("the scaffold is mounted");
3372            Modal::default().show(
3373                tester,
3374                context,
3375                Rc::new(move |_app, _context| saving.builder(|| text("BottomSheet"))),
3376            );
3377            tester.pump_and_settle();
3378
3379            dispatch_nearly_minimum_extent(tester, notification_context.get());
3380            tester.pump_and_settle();
3381
3382            assert_eq!(found(tester, "BottomSheet"), 0);
3383        });
3384    }
3385
3386    /// flutter_test's `TestVSync`: vends ordinary tickers, in no view.
3387    use waft_widgets::testing::TestVSync;
3388
3389    /// `AnimationController(vsync: const TestVSync(), duration: 2s, reverseDuration: 2s)`.
3390    fn two_second_controller(tester: &WidgetTester) -> Ref<AnimationController> {
3391        AnimationController::new(
3392            &mut tester.cell.borrow_mut(),
3393            None,
3394            Some(Duration::from_secs(2)),
3395            Some(Duration::from_secs(2)),
3396            0.0,
3397            1.0,
3398            AnimationBehavior::Normal,
3399            TestVSync,
3400        )
3401    }
3402
3403    fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
3404        let render = tester.render_object(key).as_box().expect("a render box");
3405        tester.get_rect(render)
3406    }
3407
3408    fn mounted(tester: &WidgetTester, key: &GlobalKey) -> bool {
3409        key.current_context(&tester.cell.borrow_mut()).is_some()
3410    }
3411
3412    fn pop(tester: &WidgetTester, context: BuildContext) {
3413        Navigator::pop(&mut tester.cell.borrow_mut(), context, None);
3414    }
3415
3416    /// `MaterialApp(home: Scaffold(key:, body: Center(child: Text('body'))))`'s context.
3417    fn scaffold_context(tester: &WidgetTester, key: &GlobalKey) -> BuildContext {
3418        key.current_context(&tester.cell.borrow_mut())
3419            .expect("the scaffold is mounted")
3420    }
3421
3422    /// Dart's 'Disposing app while bottom sheet is disappearing does not crash'.
3423    #[test]
3424    fn disposing_the_app_while_a_bottom_sheet_is_disappearing_does_not_crash() {
3425        test_widgets(|tester| {
3426            let saved = Saved::default();
3427            tester.pump_widget(app_saving_context(tester, &saved));
3428
3429            tester.pump();
3430            assert_eq!(found(tester, "BottomSheet"), 0);
3431
3432            // Bring up bottom sheet.
3433            let future = Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet"));
3434            let then_called = flag_when_complete(tester, future);
3435            tester.pump_and_settle();
3436            assert_eq!(found(tester, "BottomSheet"), 1);
3437            assert!(!then_called.get());
3438
3439            // Start closing animation of Bottom sheet.
3440            pop(tester, saved.get());
3441            tester.pump();
3442
3443            // Dispose app by replacing it with a container. This shouldn't crash.
3444            tester.pump_widget(Container::new().into_widget());
3445        });
3446    }
3447
3448    /// Dart's 'Verify that accessibleNavigation has no impact on the BottomSheet animation'.
3449    #[test]
3450    fn accessible_navigation_has_no_impact_on_the_bottom_sheet_animation() {
3451        test_widgets(|tester| {
3452            // Regression test for https://github.com/flutter/flutter/issues/121098
3453            let saved = Saved::default();
3454            let home = saved.builder(|| Center::new().child(text("Test")).into_widget());
3455            let app = material_app(m3(tester), home);
3456            // Dart's `MaterialApp(builder:)` wraps the navigator; a `MediaQuery` around the
3457            // home is what that builder's descendants see.
3458            let _ = app;
3459            let home = Builder::new({
3460                let saved = saved.clone();
3461                move |app, context| {
3462                    let data = MediaQuery::of(app, context)
3463                        .copy_with()
3464                        .accessible_navigation(true);
3465                    MediaQuery::new(
3466                        data,
3467                        saved.builder(|| Center::new().child(text("Test")).into_widget()),
3468                    )
3469                    .into_widget()
3470                }
3471            })
3472            .into_widget();
3473            tester.pump_widget(material_app(m3(tester), home));
3474
3475            tester.pump();
3476            assert_eq!(found(tester, "BottomSheet"), 0);
3477
3478            Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet"));
3479            tester.pump();
3480
3481            check_non_linear_animation(tester);
3482            tester.pump_and_settle();
3483        });
3484    }
3485
3486    /// Dart's tree for 'modal BottomSheet has no top MediaQuery' and 'can insert a SafeArea':
3487    /// a navigator under a `MediaQuery` with 50 pixels of padding all round, its page saving
3488    /// its context.
3489    fn padded_navigator(outer: &Saved) -> WidgetRef {
3490        let outer = outer.clone();
3491        waft_widgets::Localizations::new(
3492            waft_embedder::Locale::new("en").country_code("US"),
3493            vec![
3494                waft_widgets::DefaultWidgetsLocalizations::delegate(),
3495                crate::material_localizations::DefaultMaterialLocalizations::delegate(),
3496            ],
3497        )
3498        .child(waft_widgets::Directionality::new(
3499            waft_embedder::TextDirection::Ltr,
3500            MediaQuery::new(
3501                waft_widgets::MediaQueryData::new()
3502                    .padding(EdgeInsets::all(50.0))
3503                    .size(Size::new(400.0, 600.0)),
3504                Navigator::new().on_generate_route(move |app, _settings| {
3505                    let outer = outer.clone();
3506                    let page_builder: waft_widgets::RoutePageBuilder =
3507                        Rc::new(move |_app, context, _animation, _secondary_animation| {
3508                            outer.0.set(Some(context));
3509                            Container::new().into_widget()
3510                        });
3511                    Some((waft_widgets::PageRouteBuilder::new(app, page_builder)).into_erased())
3512                }),
3513            )
3514            .into_widget(),
3515        ))
3516        .into_widget()
3517    }
3518
3519    fn padding_of(tester: &WidgetTester, context: BuildContext) -> EdgeInsets {
3520        MediaQuery::of(&mut tester.cell.borrow_mut(), context).padding
3521    }
3522
3523    /// Dart's 'modal BottomSheet has no top MediaQuery'.
3524    #[test]
3525    fn a_modal_bottom_sheet_has_no_top_media_query_padding() {
3526        test_widgets(|tester| {
3527            let outer = Saved::default();
3528            let inner = Saved::default();
3529            tester.pump_widget(padded_navigator(&outer));
3530
3531            let saving = inner.clone();
3532            Modal::default().show(
3533                tester,
3534                outer.get(),
3535                Rc::new(move |_app, context| {
3536                    saving.0.set(Some(context));
3537                    Container::new().into_widget()
3538                }),
3539            );
3540            tester.pump();
3541            tester.pump_by(Duration::from_secs(1));
3542
3543            assert_eq!(padding_of(tester, outer.get()), EdgeInsets::all(50.0));
3544            assert_eq!(
3545                padding_of(tester, inner.get()),
3546                EdgeInsets::only(50.0, 0.0, 50.0, 50.0)
3547            );
3548        });
3549    }
3550
3551    /// Dart's 'modal BottomSheet can insert a SafeArea'.
3552    #[test]
3553    fn a_modal_bottom_sheet_can_insert_a_safe_area() {
3554        test_widgets(|tester| {
3555            let outer = Saved::default();
3556            let inner = Saved::default();
3557            tester.pump_widget(padded_navigator(&outer));
3558
3559            let inner_builder = |inner: &Saved| -> WidgetBuilder {
3560                let saving = inner.clone();
3561                Rc::new(move |_app, context| {
3562                    saving.0.set(Some(context));
3563                    Container::new().into_widget()
3564                })
3565            };
3566
3567            // Without a SafeArea (useSafeArea is false by default)
3568            Modal::default().show(tester, outer.get(), inner_builder(&inner));
3569            tester.pump();
3570            tester.pump_by(Duration::from_secs(1));
3571
3572            // Top padding is consumed and there is no SafeArea
3573            assert_eq!(padding_of(tester, inner.get()).top, 0.0);
3574            expect(tester, &find::by_type::<SafeArea>(), finds_nothing());
3575
3576            // With a SafeArea
3577            Modal {
3578                use_safe_area: true,
3579                ..Modal::default()
3580            }
3581            .show(tester, outer.get(), inner_builder(&inner));
3582            tester.pump();
3583            tester.pump_by(Duration::from_secs(1));
3584
3585            // A SafeArea is inserted, with left / top / right true but bottom false.
3586            let safe_area = only(find::by_type::<SafeArea>().evaluate(tester));
3587            tester.widget(safe_area, |safe_area: &SafeArea| {
3588                assert!(safe_area.left);
3589                assert!(safe_area.top);
3590                assert!(safe_area.right);
3591                assert!(!safe_area.bottom);
3592            });
3593
3594            // Because that SafeArea is inserted, no left / top / right padding remains
3595            // for `builder` to consume. Bottom padding does remain.
3596            assert_eq!(
3597                padding_of(tester, inner.get()),
3598                EdgeInsets::from_ltrb(0.0, 0.0, 0.0, 50.0)
3599            );
3600        });
3601    }
3602
3603    /// Dart's 'Verify that visual properties are passed through'.
3604    #[test]
3605    fn visual_properties_are_passed_through_to_the_modal_bottom_sheet() {
3606        test_widgets(|tester| {
3607            let scaffold_key = GlobalKey::new();
3608            let color = Colors::PINK.primary();
3609            let elevation = 9.0;
3610            let shape: ShapeBorderRef =
3611                ShapeBorderRef::new(waft_painting::BeveledRectangleBorder::new(
3612                    waft_painting::BorderSide::NONE,
3613                    waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(12.0)),
3614                ));
3615            let clip_behavior = Clip::AntiAlias;
3616            let barrier_color = Colors::RED.primary();
3617
3618            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3619
3620            Modal {
3621                background_color: Some(color),
3622                barrier_color: Some(barrier_color),
3623                elevation: Some(elevation),
3624                shape: Some(shape.clone()),
3625                clip_behavior: Some(clip_behavior),
3626                ..Modal::default()
3627            }
3628            .show(
3629                tester,
3630                scaffold_context(tester, &scaffold_key),
3631                sheet_builder("BottomSheet"),
3632            );
3633
3634            tester.pump();
3635            tester.pump_by(Duration::from_secs(1));
3636
3637            let bottom_sheet = only(find::by_type::<BottomSheet>().evaluate(tester));
3638            tester.widget(bottom_sheet, |bottom_sheet: &BottomSheet| {
3639                assert_eq!(bottom_sheet.background_color, Some(color));
3640                assert_eq!(bottom_sheet.elevation, Some(elevation));
3641                assert!(**bottom_sheet.shape.as_ref().expect("a shape") == *shape);
3642                assert_eq!(bottom_sheet.clip_behavior, Some(clip_behavior));
3643            });
3644
3645            let modal_barrier = *find::by_type::<ModalBarrier>()
3646                .evaluate(tester)
3647                .last()
3648                .expect("a modal barrier");
3649            tester.widget(modal_barrier, |modal_barrier: &ModalBarrier| {
3650                assert_eq!(modal_barrier.color, Some(barrier_color));
3651            });
3652        });
3653    }
3654
3655    /// The `Material` under the only `BottomSheet`: Dart's `find.descendant(of:
3656    /// find.byType(BottomSheet), matching: find.byType(Material))`.
3657    fn sheet_material(tester: &WidgetTester) -> AnyElement {
3658        let sheet = only(find::by_type::<BottomSheet>().evaluate(tester));
3659        only(
3660            find::by_type::<Material>()
3661                .evaluate(tester)
3662                .into_iter()
3663                .filter(|material| tester.ancestors(*material).contains(&sheet))
3664                .collect(),
3665        )
3666    }
3667
3668    /// Dart's 'Material3 - BottomSheet uses fallback values'.
3669    #[test]
3670    fn material3_bottom_sheet_uses_fallback_values() {
3671        test_widgets(|tester| {
3672            let surface_color = Colors::PINK.primary();
3673            let surface_tint_color = Colors::BLUE.primary();
3674            let default_shape: ShapeBorderRef =
3675                ShapeBorderRef::new(waft_painting::RoundedRectangleBorder::new(
3676                    waft_painting::BorderSide::NONE,
3677                    waft_painting::BorderRadiusGeometry::vertical(
3678                        waft_embedder::Radius::circular(28.0),
3679                        waft_embedder::Radius::ZERO,
3680                    ),
3681                ));
3682
3683            let theme = ThemeData::builder()
3684                .color_scheme(
3685                    crate::color_scheme::ColorScheme::light()
3686                        .with_surface(surface_color)
3687                        .with_surface_tint(surface_tint_color),
3688                )
3689                .build(&tester.cell.borrow());
3690            tester.pump_widget(material_app(
3691                theme,
3692                Scaffold::new()
3693                    .body(BottomSheet::new(
3694                        Rc::new(|_app| {}),
3695                        Rc::new(|_app, _context| Container::new().into_widget()),
3696                    ))
3697                    .into_widget(),
3698            ));
3699
3700            let material = sheet_material(tester);
3701            tester.widget(material, |material: &Material| {
3702                assert_eq!(material.color, Some(surface_color));
3703                // Surface tint is no longer used by default.
3704                assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
3705                assert_eq!(material.elevation, 1.0);
3706                assert!(**material.shape.as_ref().expect("a shape") == *default_shape);
3707            });
3708            assert_eq!(tester.get_rect(material).width(), 640.0);
3709        });
3710    }
3711
3712    /// Dart's 'Material3 - BottomSheet has transparent shadow'.
3713    #[test]
3714    fn material3_bottom_sheet_has_a_transparent_shadow() {
3715        test_widgets(|tester| {
3716            tester.pump_widget(material_app(
3717                m3(tester),
3718                Scaffold::new()
3719                    .body(BottomSheet::new(
3720                        Rc::new(|_app| {}),
3721                        Rc::new(|_app, _context| Container::new().into_widget()),
3722                    ))
3723                    .into_widget(),
3724            ));
3725
3726            let material = sheet_material(tester);
3727            tester.widget(material, |material: &Material| {
3728                assert_eq!(material.shadow_color, Some(Colors::TRANSPARENT));
3729            });
3730        });
3731    }
3732
3733    /// The box the only `_DragHandle` lays out: Dart's `find.bySemanticsLabel('Dismiss')`,
3734    /// whose `Semantics` wraps the handle's `SizedBox`.
3735    fn drag_handle_rect(tester: &WidgetTester) -> Rect {
3736        tester.get_rect(only(find::by_type::<DragHandle>().evaluate(tester)))
3737    }
3738
3739    /// Dart's 'Drag handle interactive area size at minimum possible size' and 'at given
3740    /// dragHandleSize'.
3741    fn drag_handle_size(tester: &mut WidgetTester, drag_handle_size: Size, expected: Size) {
3742        let scaffold_key = GlobalKey::new();
3743        let theme = ThemeData::builder()
3744            .bottom_sheet_theme(BottomSheetThemeData::new().drag_handle_size(drag_handle_size))
3745            .build(&tester.cell.borrow());
3746        tester.pump_widget(material_app(
3747            theme,
3748            Scaffold::new()
3749                .key(scaffold_key.clone().into())
3750                .into_widget(),
3751        ));
3752
3753        Modal {
3754            show_drag_handle: Some(true),
3755            ..Modal::default()
3756        }
3757        .show(
3758            tester,
3759            scaffold_context(tester, &scaffold_key),
3760            sheet_builder("BottomSheet"),
3761        );
3762
3763        tester.pump(); // Bottom sheet show animation starts.
3764        tester.pump_by(Duration::from_secs(1)); // Animation done.
3765
3766        assert_eq!(drag_handle_rect(tester).size(), expected);
3767    }
3768
3769    #[test]
3770    fn the_drag_handle_interactive_area_is_at_least_the_minimum_interactive_size() {
3771        test_widgets(|tester| {
3772            drag_handle_size(
3773                tester,
3774                Size::new(20.0, 20.0),
3775                Size::new(K_MIN_INTERACTIVE_DIMENSION, K_MIN_INTERACTIVE_DIMENSION),
3776            )
3777        });
3778    }
3779
3780    #[test]
3781    fn the_drag_handle_interactive_area_is_the_given_drag_handle_size() {
3782        test_widgets(|tester| {
3783            drag_handle_size(tester, Size::new(100.0, 50.0), Size::new(100.0, 50.0))
3784        });
3785    }
3786
3787    /// The colour of the decorated `Container` under the only `_DragHandle`.
3788    fn drag_handle_color(tester: &WidgetTester) -> Option<Color> {
3789        let handle = only(find::by_type::<DragHandle>().evaluate(tester));
3790        let decorated = only(
3791            find::by_type::<Container>()
3792                .evaluate(tester)
3793                .into_iter()
3794                .filter(|container| tester.ancestors(*container).contains(&handle))
3795                .filter(|container| {
3796                    tester.widget(*container, |container: &Container| {
3797                        container.decoration.is_some()
3798                    })
3799                })
3800                .collect(),
3801        );
3802        tester.widget(decorated, |container: &Container| {
3803            container
3804                .decoration
3805                .as_ref()
3806                .expect("the container has a decoration")
3807                .as_any()
3808                .downcast_ref::<BoxDecoration>()
3809                .expect("a BoxDecoration")
3810                .color
3811                .as_ref()
3812                .map(|color| color.color())
3813        })
3814    }
3815
3816    /// Dart's `checkDragHandleAndColors` of 'Drag handle color can take WidgetStateProperty'.
3817    fn check_drag_handle_and_colors(
3818        tester: &mut WidgetTester,
3819        default_color: Color,
3820        hovering_color: Color,
3821    ) {
3822        tester.pump(); // bottom sheet show animation starts
3823        tester.pump_by(Duration::from_secs(1)); // animation done
3824
3825        let drag_handle = drag_handle_rect(tester);
3826        assert_eq!(drag_handle.size(), Size::new(48.0, 48.0));
3827        let center = drag_handle.center();
3828        let edge = drag_handle.top_left() - Offset::new(1.0, 1.0);
3829
3830        // Shows default drag handle color
3831        let mut gesture = TestPointer::mouse(1, 0);
3832        tester.add_pointer(&mut gesture, edge);
3833        tester.pump();
3834        assert_eq!(drag_handle_color(tester), Some(default_color));
3835
3836        // Shows hovering drag handle color
3837        tester.move_to(&mut gesture, center, false);
3838        tester.pump();
3839        assert_eq!(drag_handle_color(tester), Some(hovering_color));
3840        tester.send(&gesture, waft_embedder::PointerChange::Remove);
3841    }
3842
3843    /// Dart's 'Drag handle color can take WidgetStateProperty'.
3844    #[test]
3845    fn the_theme_drag_handle_color_can_take_a_widget_state_property() {
3846        test_widgets(|tester| {
3847            let default_color = Colors::BLUE.primary();
3848            let hovering_color = Colors::GREEN.primary();
3849            let build_scaffold = |tester: &WidgetTester, scaffold_key: &GlobalKey| {
3850                let theme = ThemeData::builder()
3851                    .bottom_sheet_theme(
3852                        BottomSheetThemeData::new().drag_handle_color(
3853                            waft_widgets::WidgetStateColor::resolve_with(move |states| {
3854                                if states.contains(&WidgetState::Hovered) {
3855                                    return hovering_color;
3856                                }
3857                                default_color
3858                            })
3859                            .into_any(),
3860                        ),
3861                    )
3862                    .build(&tester.cell.borrow());
3863                app_with_scaffold(theme, scaffold_key)
3864            };
3865
3866            let scaffold_key = GlobalKey::new();
3867            let app = build_scaffold(tester, &scaffold_key);
3868            tester.pump_widget(app);
3869
3870            Modal {
3871                show_drag_handle: Some(true),
3872                ..Modal::default()
3873            }
3874            .show(
3875                tester,
3876                scaffold_context(tester, &scaffold_key),
3877                sheet_builder("BottomSheet"),
3878            );
3879
3880            check_drag_handle_and_colors(tester, default_color, hovering_color);
3881
3882            tester.pump_widget(Container::new().into_widget()); // Reset
3883            let scaffold_key = GlobalKey::new();
3884            let app = build_scaffold(tester, &scaffold_key);
3885            tester.pump_widget(app);
3886
3887            Persistent {
3888                show_drag_handle: Some(true),
3889                ..Persistent::default()
3890            }
3891            .show(
3892                tester,
3893                scaffold_state(tester, &scaffold_key),
3894                Rc::new(|_app, _context| {
3895                    Builder::new(|_app, _context| {
3896                        SizedBox::new()
3897                            .height(200.0)
3898                            .child(text("Bottom Sheet"))
3899                            .into_widget()
3900                    })
3901                    .into_widget()
3902                }),
3903            );
3904
3905            check_drag_handle_and_colors(tester, default_color, hovering_color);
3906        });
3907    }
3908
3909    /// Not a Dart case: what Dart's collector does with the tweens and the colour animation
3910    /// each build of the sheet's barrier replaces; each is freed once the next build replaces
3911    /// it.
3912    #[test]
3913    fn rebuilding_a_modal_bottom_sheet_barrier_leaves_no_new_arena_objects() {
3914        test_widgets(|tester| {
3915            let scaffold_key = GlobalKey::new();
3916            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3917            let sheet_route: Rc<Cell<Option<waft_widgets::AnyModalRoute>>> = Rc::default();
3918            let route = Rc::clone(&sheet_route);
3919            Modal::default().show(
3920                tester,
3921                scaffold_context(tester, &scaffold_key),
3922                Rc::new(move |app, context| {
3923                    route.set(waft_widgets::AnyModalRoute::of(app, context));
3924                    text("BottomSheet")
3925                }),
3926            );
3927            tester.pump();
3928            tester.pump_by(Duration::from_secs(1));
3929            let sheet_route = sheet_route.get().expect("the sheet built");
3930            let rebuild_barrier = |tester: &mut WidgetTester| {
3931                sheet_route
3932                    .as_route()
3933                    .changed_internal_state(&mut tester.cell.borrow_mut());
3934                tester.pump_by(Duration::from_millis(16));
3935            };
3936            rebuild_barrier(tester);
3937
3938            let snapshot = object_snapshot(&tester.cell.borrow());
3939            rebuild_barrier(tester);
3940            tester.cell.checkpoint();
3941            assert_no_new_objects(&tester.cell.borrow(), &snapshot);
3942        });
3943    }
3944
3945    /// Dart's 'Verify that route settings can be set in the showModalBottomSheet'.
3946    #[test]
3947    fn route_settings_can_be_set_in_show_modal_bottom_sheet() {
3948        test_widgets(|tester| {
3949            let scaffold_key = GlobalKey::new();
3950            let route_settings = RouteSettings::new()
3951                .name("route_name".to_string())
3952                .arguments(Rc::new("route_argument".to_string()));
3953
3954            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
3955
3956            let retrieved_route_settings: Rc<RefCell<Option<RouteSettingsRef>>> =
3957                Rc::new(RefCell::new(None));
3958            let retrieved = Rc::clone(&retrieved_route_settings);
3959            Modal {
3960                route_settings: Some(RouteSettingsRef::Settings(route_settings.clone())),
3961                ..Modal::default()
3962            }
3963            .show(
3964                tester,
3965                scaffold_context(tester, &scaffold_key),
3966                Rc::new(move |app, context| {
3967                    *retrieved.borrow_mut() =
3968                        waft_widgets::AnyModalRoute::settings_of(app, context);
3969                    text("BottomSheet")
3970                }),
3971            );
3972
3973            tester.pump();
3974            tester.pump_by(Duration::from_secs(1));
3975
3976            match retrieved_route_settings.borrow().as_ref() {
3977                Some(RouteSettingsRef::Settings(settings)) => {
3978                    assert_eq!(settings.name, route_settings.name);
3979                    assert_eq!(
3980                        settings
3981                            .arguments
3982                            .as_ref()
3983                            .and_then(|arguments| arguments.downcast_ref::<String>())
3984                            .map(String::as_str),
3985                        Some("route_argument")
3986                    );
3987                }
3988                _ => panic!("the sheet's route has the given settings"),
3989            }
3990        });
3991    }
3992
3993    /// Dart's 'Verify showModalBottomSheet use AnimationController if provided.' and 'the
3994    /// framework do not dispose the transitionAnimationController provided by user.'. Dart
3995    /// taps a `GestureDetector` that calls `showModalBottomSheet`; the case calls it.
3996    fn modal_with_controller(tester: &mut WidgetTester, dispose_after: bool) {
3997        let saved = Saved::default();
3998        let controller = two_second_controller(tester);
3999        tester.pump_widget(material_app(
4000            m3(tester),
4001            Scaffold::new()
4002                .body(saved.builder(|| SizedBox::new().height(100.0).width(100.0).into_widget()))
4003                .into_widget(),
4004        ));
4005
4006        assert_eq!(found(tester, "BottomSheet"), 0);
4007
4008        // Opening animation will start after tapping
4009        Modal {
4010            // The default duration and reverseDuration is 1 second
4011            transition_animation_controller: Some(controller.clone()),
4012            ..Modal::default()
4013        }
4014        .show(tester, saved.get(), sheet_builder("BottomSheet"));
4015        tester.pump();
4016
4017        assert_eq!(found(tester, "BottomSheet"), 1);
4018        tester.pump_by(Duration::from_millis(2000));
4019        assert_eq!(found(tester, "BottomSheet"), 1);
4020
4021        // Tapping above the bottom sheet to dismiss it.
4022        tester.tap_at(Offset::new(20.0, 20.0), 1); // Closing animation will start after tapping
4023        tester.pump();
4024
4025        assert_eq!(found(tester, "BottomSheet"), 1);
4026        tester.pump_by(Duration::from_millis(2000));
4027        // The bottom sheet should still be present at the very end of the animation.
4028        assert_eq!(found(tester, "BottomSheet"), 1);
4029
4030        tester.pump_by(Duration::from_millis(1));
4031        // The bottom sheet should not be showing any longer.
4032        assert_eq!(found(tester, "BottomSheet"), 0);
4033
4034        if dispose_after {
4035            // Double disposal panics.
4036            controller.dispose(&mut tester.cell.borrow_mut());
4037        }
4038    }
4039
4040    #[test]
4041    fn show_modal_bottom_sheet_uses_the_animation_controller_it_is_given() {
4042        test_widgets(|tester| modal_with_controller(tester, false));
4043    }
4044
4045    #[test]
4046    fn the_framework_does_not_dispose_the_transition_animation_controller_a_caller_gives() {
4047        test_widgets(|tester| modal_with_controller(tester, true));
4048    }
4049
4050    /// Dart's `_StatusTestAnimationController.isListening`: whether any value or status
4051    /// listener is registered, which its `AnimationLazyListenerMixin` counts.
4052    fn is_listening(tester: &WidgetTester, controller: Handle<AnimationController>) -> bool {
4053        use waft_animation::{AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin};
4054        let app = tester.cell.borrow();
4055        !controller.local_listeners_data(&app).is_empty()
4056            || !controller.local_status_listeners_data(&app).is_empty()
4057    }
4058
4059    /// Dart's 'The framework removes all animation listeners from foreign controllers when
4060    /// disposing.'.
4061    #[test]
4062    fn a_dismissed_persistent_sheet_leaves_no_listener_on_a_callers_controller() {
4063        test_widgets(|tester| {
4064            let scaffold_key = GlobalKey::new();
4065            let controller = two_second_controller(tester);
4066
4067            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
4068
4069            tester.pump();
4070            assert!(!is_listening(tester, controller.handle()));
4071
4072            Persistent {
4073                transition_animation_controller: Some(controller.clone()),
4074                ..Persistent::default()
4075            }
4076            .show(
4077                tester,
4078                scaffold_state(tester, &scaffold_key),
4079                Rc::new(|_app, _context| {
4080                    SizedBox::new()
4081                        .height(200.0)
4082                        .child(text("BottomSheet"))
4083                        .into_widget()
4084                }),
4085            );
4086
4087            tester.pump_and_settle();
4088            assert!(is_listening(tester, controller.handle()));
4089            assert_eq!(found(tester, "BottomSheet"), 1);
4090
4091            // Swipe the bottom sheet to dismiss it.
4092            drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
4093            tester.pump_and_settle(); // Bottom sheet dismiss animation.
4094            assert!(!is_listening(tester, controller.handle()));
4095            assert_eq!(found(tester, "BottomSheet"), 0);
4096
4097            controller.dispose(&mut tester.cell.borrow_mut());
4098        });
4099    }
4100
4101    /// Dart's 'Verify persistence BottomSheet use AnimationController if provided.' and 'The
4102    /// framework does not dispose of the transitionAnimationController provided by user.'.
4103    /// Dart's sheet is an `ElevatedButton` whose `onPressed` pops; the case pops from the
4104    /// sheet's context.
4105    #[test]
4106    fn a_persistent_bottom_sheet_uses_the_animation_controller_it_is_given() {
4107        test_widgets(|tester| {
4108            let saved = Saved::default();
4109            let sheet = Saved::default();
4110            let controller = two_second_controller(tester);
4111            tester.pump_widget(material_app(
4112                m3(tester),
4113                Scaffold::new()
4114                    .body(
4115                        saved.builder(|| SizedBox::new().height(100.0).width(100.0).into_widget()),
4116                    )
4117                    .into_widget(),
4118            ));
4119
4120            assert_eq!(found(tester, "BottomSheet"), 0);
4121
4122            let saving = sheet.clone();
4123            {
4124                let mut show = ShowBottomSheet::new(Rc::new(move |_app, _context| {
4125                    saving.builder(|| text("BottomSheet"))
4126                }));
4127                // The default duration and reverseDuration is 1 second.
4128                show = show.transition_animation_controller(controller.clone());
4129                show.show(&mut tester.cell.borrow_mut(), saved.get())
4130            };
4131            tester.pump();
4132
4133            assert_eq!(found(tester, "BottomSheet"), 1);
4134            tester.pump_by(Duration::from_millis(2000));
4135            assert_eq!(found(tester, "BottomSheet"), 1);
4136
4137            // Dismiss it as the sheet's button would.
4138            pop(tester, sheet.get()); // Closing animation will start after tapping
4139            tester.pump();
4140
4141            assert_eq!(found(tester, "BottomSheet"), 1);
4142            tester.pump_by(Duration::from_millis(2000));
4143            // The bottom sheet should still be present at the very end of the animation.
4144            assert_eq!(found(tester, "BottomSheet"), 1);
4145
4146            tester.pump_by(Duration::from_millis(1));
4147            // The bottom sheet should not be showing any longer.
4148            assert_eq!(found(tester, "BottomSheet"), 0);
4149
4150            tester.pump_widget(SizedBox::shrink().into_widget());
4151            // Double dispose panics.
4152            controller.dispose(&mut tester.cell.borrow_mut());
4153        });
4154    }
4155
4156    /// Dart's 'Each of the internal animation controllers should be disposed by the framework.'.
4157    #[test]
4158    fn each_internal_animation_controller_is_disposed_by_the_framework() {
4159        test_widgets(|tester| {
4160            let scaffold_key = GlobalKey::new();
4161            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
4162
4163            let sheet = || -> WidgetBuilder {
4164                Rc::new(|_app, _context| {
4165                    Builder::new(|_app, _context| Container::new().height(200.0).into_widget())
4166                        .into_widget()
4167                })
4168            };
4169            let scaffold = scaffold_state(tester, &scaffold_key);
4170            Persistent::default().show(tester, scaffold, sheet());
4171
4172            tester.pump();
4173            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4174
4175            // The first sheet's animation is still running.
4176
4177            // Trigger the second sheet will remove the first sheet from tree.
4178            Persistent::default().show(tester, scaffold, sheet());
4179            tester.pump();
4180            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4181
4182            // Remove the Scaffold from the tree. A ticker still running when its provider is
4183            // disposed panics.
4184            tester.pump_widget(SizedBox::shrink().into_widget());
4185        });
4186    }
4187
4188    /// Dart's 'The old route entry should be removed when a new sheet popup'.
4189    #[test]
4190    fn the_old_route_entry_is_removed_when_a_new_sheet_pops_up() {
4191        test_widgets(|tester| {
4192            // Regression test for https://github.com/flutter/flutter/issues/99627
4193            let scaffold_key = GlobalKey::new();
4194            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
4195
4196            let context = scaffold_context(tester, &scaffold_key);
4197            let route = waft_widgets::AnyModalRoute::of(&mut tester.cell.borrow_mut(), context)
4198                .expect("the scaffold is in a route");
4199            let can_pop = |tester: &WidgetTester| route.can_pop(&mut tester.cell.borrow_mut());
4200            assert!(!can_pop(tester));
4201
4202            let sheet = || -> WidgetBuilder {
4203                Rc::new(|_app, _context| {
4204                    Builder::new(|_app, _context| Container::new().height(200.0).into_widget())
4205                        .into_widget()
4206                })
4207            };
4208            let scaffold = scaffold_state(tester, &scaffold_key);
4209            Persistent::default().show(tester, scaffold, sheet());
4210
4211            tester.pump();
4212            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4213            assert!(can_pop(tester));
4214
4215            // Trigger the second sheet will remove the first sheet from tree.
4216            let sheet_controller = Persistent::default().show(tester, scaffold, sheet());
4217            tester.pump();
4218            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4219            assert!(can_pop(tester));
4220
4221            sheet_controller.close(&mut tester.cell.borrow_mut());
4222
4223            assert!(!can_pop(tester));
4224        });
4225    }
4226
4227    /// Dart's 'Calling PersistentBottomSheetController.close does not crash when it is not the
4228    /// current bottom sheet'. Dart's buttons call `showBottomSheet` and `close`; the case
4229    /// calls them.
4230    #[test]
4231    fn closing_a_persistent_bottom_sheet_that_is_not_the_current_one_does_not_crash() {
4232        test_widgets(|tester| {
4233            // Regression test for https://github.com/flutter/flutter/issues/93717
4234            let scaffold_key = GlobalKey::new();
4235            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
4236            let scaffold = scaffold_state(tester, &scaffold_key);
4237
4238            let sheet_controller1 =
4239                Persistent::default().show(tester, scaffold, sheet_builder("BottomSheet 1"));
4240            tester.pump_and_settle();
4241            assert_eq!(found(tester, "BottomSheet 1"), 1);
4242
4243            Persistent::default().show(tester, scaffold, sheet_builder("BottomSheet 2"));
4244            tester.pump_and_settle();
4245            assert_eq!(found(tester, "BottomSheet 2"), 1);
4246
4247            // This will throw an assertion if regressed
4248            sheet_controller1.close(&mut tester.cell.borrow_mut());
4249            tester.pump_and_settle();
4250            assert_eq!(found(tester, "BottomSheet 2"), 1);
4251        });
4252    }
4253
4254    /// Dart's 'ModalBottomSheetRoute shows BottomSheet correctly'.
4255    #[test]
4256    fn a_pushed_modal_bottom_sheet_route_shows_a_bottom_sheet() {
4257        test_widgets(|tester| {
4258            let saved = Saved::default();
4259            tester.pump_widget(app_saving_context(tester, &saved));
4260
4261            tester.pump();
4262            expect(tester, &find::by_type::<BottomSheet>(), finds_nothing());
4263
4264            // Bring up bottom sheet.
4265            {
4266                let mut app = tester.cell.borrow_mut();
4267                let navigator = Navigator::of(&mut app, saved.get(), false);
4268                let route = ModalBottomSheetRoute::new(
4269                    &mut app,
4270                    Rc::new(|_app, _context| Container::new().into_widget()),
4271                    false,
4272                );
4273                navigator.push(&mut app, route.erase());
4274            }
4275            tester.pump_and_settle();
4276            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4277        });
4278    }
4279
4280    /// Dart's `TextField(focusNode: focusNode)` for what the focus cases read of it: a `Focus`
4281    /// on `focus_node`, which is the node Dart's `getTextFieldFocusNode` finds.
4282    fn focusable(focus_node: waft_widgets::FocusNodeRef) -> WidgetRef {
4283        waft_widgets::Focus::new(SizedBox::new().height(48.0))
4284            .focus_node(focus_node.clone())
4285            .into_widget()
4286    }
4287
4288    use waft_widgets::FocusNodeLeaf;
4289
4290    fn has_focus(tester: &WidgetTester, focus_node: waft_widgets::AnyFocusNode) -> bool {
4291        focus_node.has_focus(&tester.cell.borrow_mut())
4292    }
4293
4294    /// Dart's `navigator.push(ModalBottomSheetRoute(requestFocus:, isScrollControlled: false,
4295    /// builder: (context) => Container()))`.
4296    fn push_container_sheet(
4297        tester: &WidgetTester,
4298        context: BuildContext,
4299        request_focus: Option<bool>,
4300    ) {
4301        let mut app = tester.cell.borrow_mut();
4302        let navigator = Navigator::of(&mut app, context, false);
4303        let mut route = ModalBottomSheetRoute::new(
4304            &mut app,
4305            Rc::new(|_app, _context| Container::new().into_widget()),
4306            false,
4307        );
4308        if let Some(request_focus) = request_focus {
4309            route = route.request_focus(&mut app, request_focus);
4310        }
4311        drop(navigator.push(&mut app, route.erase()));
4312    }
4313
4314    /// The height of the stand-in for Dart's two-item `BottomNavigationBar`.
4315    const BOTTOM_NAVIGATION_BAR_HEIGHT: f64 = 56.0;
4316
4317    /// Dart's `MaterialApp(home: Scaffold(body: Navigator(onGenerateRoute: (settings) =>
4318    /// MaterialPageRoute(builder: (_) => _TestPage(useRootNavigator:))), bottomNavigationBar:
4319    /// BottomNavigationBar(..)))`. A `PageRouteBuilder` stands in for `MaterialPageRoute`, and a
4320    /// 56-tall box for the bar, which are not ported; `_TestPage`'s button is a `TextButton`.
4321    fn nested_navigator_app(tester: &WidgetTester, use_root_navigator: Option<bool>) -> WidgetRef {
4322        let inner_navigator = Navigator::new().on_generate_route(move |app, _settings| {
4323            let page_builder: waft_widgets::RoutePageBuilder =
4324                Rc::new(move |_app, context, _animation, _secondary_animation| {
4325                    Center::new()
4326                        .child(crate::text_button::TextButton::new(
4327                            Some(waft_foundation::Listener::new(move |app| {
4328                                drop(
4329                                    Modal {
4330                                        use_root_navigator: use_root_navigator.unwrap_or(false),
4331                                        ..Modal::default()
4332                                    }
4333                                    .show_in(
4334                                        app,
4335                                        context,
4336                                        sheet_builder("Modal bottom sheet"),
4337                                    ),
4338                                );
4339                            })),
4340                            Some(text("Show bottom sheet")),
4341                        ))
4342                        .into_widget()
4343                });
4344            Some((waft_widgets::PageRouteBuilder::new(app, page_builder)).into_erased())
4345        });
4346        material_app(
4347            m3(tester),
4348            Scaffold::new()
4349                .body(inner_navigator)
4350                .bottom_navigation_bar(SizedBox::new().height(BOTTOM_NAVIGATION_BAR_HEIGHT))
4351                .into_widget(),
4352        )
4353    }
4354
4355    /// Dart's `tester.getBottomLeft(find.byType(BottomSheet)).dy`.
4356    fn bottom_sheet_bottom(tester: &WidgetTester) -> f64 {
4357        let sheet = only(find::by_type::<BottomSheet>().evaluate(tester));
4358        tester.get_rect(sheet).bottom
4359    }
4360
4361    /// Dart's 'showModalBottomSheet does not use root Navigator by default'.
4362    #[test]
4363    fn show_modal_bottom_sheet_uses_the_nearest_navigator_by_default() {
4364        test_widgets(|tester| {
4365            tester.pump_widget(nested_navigator_app(tester, None));
4366
4367            let button = center_of_text(tester, "Show bottom sheet");
4368            tester.tap_at(button, 1);
4369            tester.pump_and_settle();
4370
4371            // Bottom sheet is displayed in correct position within the inner navigator
4372            // and above the BottomNavigationBar.
4373            assert_eq!(
4374                bottom_sheet_bottom(tester),
4375                600.0 - BOTTOM_NAVIGATION_BAR_HEIGHT
4376            );
4377        });
4378    }
4379
4380    /// Dart's 'showModalBottomSheet uses root Navigator when specified'.
4381    #[test]
4382    fn show_modal_bottom_sheet_uses_the_root_navigator_when_asked() {
4383        test_widgets(|tester| {
4384            tester.pump_widget(nested_navigator_app(tester, Some(true)));
4385
4386            let button = center_of_text(tester, "Show bottom sheet");
4387            tester.tap_at(button, 1);
4388            tester.pump_and_settle();
4389
4390            // Bottom sheet is displayed in correct position above all content including
4391            // the BottomNavigationBar.
4392            assert_eq!(bottom_sheet_bottom(tester), 600.0);
4393        });
4394    }
4395
4396    /// Dart's 'Setting ModalBottomSheetRoute.requestFocus to false does not request focus on
4397    /// the bottom sheet'.
4398    #[test]
4399    fn a_modal_bottom_sheet_route_that_does_not_request_focus_leaves_it_where_it_is() {
4400        test_widgets(|tester| {
4401            let saved = Saved::default();
4402            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut())
4403                .into_erased::<waft_widgets::AnyFocusNode>();
4404            tester.pump_widget(material_app(
4405                m3(tester),
4406                Material::new()
4407                    .child(saved.builder({
4408                        let focus_node = focus_node.clone();
4409                        move || focusable(focus_node.clone())
4410                    }))
4411                    .into_widget(),
4412            ));
4413            tester.pump();
4414
4415            // Initially, there is no bottom sheet and the text field has no focus.
4416            expect(tester, &find::by_type::<BottomSheet>(), finds_nothing());
4417            assert!(!has_focus(tester, focus_node.handle()));
4418
4419            // Request focus on the text field.
4420            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
4421            tester.pump();
4422            assert!(has_focus(tester, focus_node.handle()));
4423
4424            // Bring up bottom sheet.
4425            push_container_sheet(tester, saved.get(), None);
4426            tester.pump();
4427
4428            // The bottom sheet is showing and the text field has lost focus.
4429            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4430            assert!(!has_focus(tester, focus_node.handle()));
4431
4432            // Dismiss the bottom sheet.
4433            pop(tester, saved.get());
4434            tester.pump();
4435
4436            // The bottom sheet is dismissed and the focus is shifted back to the text field.
4437            expect(tester, &find::by_type::<BottomSheet>(), finds_nothing());
4438            assert!(has_focus(tester, focus_node.handle()));
4439
4440            // Bring up bottom sheet again with requestFocus to false.
4441            push_container_sheet(tester, saved.get(), Some(false));
4442            tester.pump();
4443
4444            // The bottom sheet is showing and the text field still has focus.
4445            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
4446            assert!(has_focus(tester, focus_node.handle()));
4447        });
4448    }
4449
4450    /// Dart's 'requestFocus works correctly in showModalBottomSheet.'. Dart shows the sheet
4451    /// from the navigator's own context; a context under it reaches the same navigator.
4452    #[test]
4453    fn show_modal_bottom_sheet_requests_focus_only_when_asked() {
4454        test_widgets(|tester| {
4455            let saved = Saved::default();
4456            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut())
4457                .into_erased::<waft_widgets::AnyFocusNode>();
4458            tester.pump_widget(material_app(
4459                m3(tester),
4460                Scaffold::new()
4461                    .body(saved.builder({
4462                        let focus_node = focus_node.clone();
4463                        move || focusable(focus_node.clone())
4464                    }))
4465                    .into_widget(),
4466            ));
4467            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
4468            tester.pump();
4469            assert!(has_focus(tester, focus_node.handle()));
4470
4471            let sheet_scope_has_focus = |tester: &WidgetTester| {
4472                let sheet_text = only(find::text("BottomSheet").evaluate(tester));
4473                let mut app = tester.cell.borrow_mut();
4474                waft_widgets::FocusScope::of(&mut app, sheet_text, true)
4475                    .as_node()
4476                    .has_focus(&app)
4477            };
4478
4479            drop(
4480                Modal {
4481                    request_focus: Some(true),
4482                    ..Modal::default()
4483                }
4484                .show(tester, saved.get(), sheet_builder("BottomSheet")),
4485            );
4486            tester.pump_and_settle();
4487            assert!(sheet_scope_has_focus(tester));
4488            assert!(!has_focus(tester, focus_node.handle()));
4489
4490            pop(tester, saved.get());
4491            tester.pump_and_settle();
4492            assert!(has_focus(tester, focus_node.handle()));
4493
4494            drop(
4495                Modal {
4496                    request_focus: Some(false),
4497                    ..Modal::default()
4498                }
4499                .show(tester, saved.get(), sheet_builder("BottomSheet")),
4500            );
4501            tester.pump_and_settle();
4502            assert!(!sheet_scope_has_focus(tester));
4503            assert!(has_focus(tester, focus_node.handle()));
4504        });
4505    }
4506
4507    /// `MaterialApp(theme:, home: Scaffold(body: Builder(saving its context)))`.
4508    fn app_with_scaffold_body(theme: ThemeData, saved: &Saved) -> WidgetRef {
4509        material_app(
4510            theme,
4511            Scaffold::new()
4512                .body(saved.builder(|| Center::new().child(text("Press me")).into_widget()))
4513                .into_widget(),
4514        )
4515    }
4516
4517    /// A `Placeholder(fallbackWidth: 800)` as it sizes: its fallback limits, filled.
4518    fn placeholder(fallback_width: f64) -> WidgetRef {
4519        waft_widgets::LimitedBox::new()
4520            .max_width(fallback_width)
4521            .max_height(400.0)
4522            .child(SizedBox::expand())
4523            .into_widget()
4524    }
4525
4526    /// Dart's 'Material3 - Default constraints are max width 640'. Placeholder is not ported;
4527    /// the box stands in with its fallback sizing.
4528    #[test]
4529    fn material3_default_constraints_are_a_max_width_of_640() {
4530        test_widgets(|tester| {
4531            let key = GlobalKey::new();
4532            tester.pump_widget(material_app(
4533                m3(tester),
4534                MediaQuery::new(
4535                    waft_widgets::MediaQueryData::new().size(Size::new(1000.0, 1000.0)),
4536                    Scaffold::new()
4537                        .body(Center::new().child(text("body")))
4538                        .bottom_sheet(
4539                            waft_widgets::KeyedSubtree::new(placeholder(800.0))
4540                                .key(key.clone().into()),
4541                        ),
4542                )
4543                .into_widget(),
4544            ));
4545            assert_eq!(rect_of_key(tester, &key).width(), 640.0);
4546        });
4547    }
4548
4549    /// Dart's 'Material2 - No constraints by default for bottomSheet property'.
4550    #[test]
4551    fn material2_has_no_constraints_by_default_for_the_bottom_sheet_property() {
4552        test_widgets(|tester| {
4553            tester.pump_widget(material_app(
4554                m2(tester),
4555                Scaffold::new()
4556                    .body(Center::new().child(text("body")))
4557                    .bottom_sheet(text("BottomSheet"))
4558                    .into_widget(),
4559            ));
4560            assert_eq!(found(tester, "BottomSheet"), 1);
4561            assert_eq!(
4562                rect_of_text(tester, "BottomSheet"),
4563                Rect::from_ltrb(0.0, 586.0, 154.0, 600.0)
4564            );
4565        });
4566    }
4567
4568    /// Dart's 'No constraints by default for showBottomSheet'. Dart's `ElevatedButton` calls
4569    /// `showBottomSheet`; the case calls it.
4570    #[test]
4571    fn there_are_no_constraints_by_default_for_show_bottom_sheet() {
4572        test_widgets(|tester| {
4573            let saved = Saved::default();
4574            tester.pump_widget(app_with_scaffold_body(m2(tester), &saved));
4575            assert_eq!(found(tester, "BottomSheet"), 0);
4576            let scaffold = Scaffold::of(&mut tester.cell.borrow_mut(), saved.get());
4577            Persistent::default().show(tester, scaffold, sheet_builder("BottomSheet"));
4578            tester.pump_and_settle();
4579            assert_eq!(found(tester, "BottomSheet"), 1);
4580            assert_eq!(
4581                rect_of_text(tester, "BottomSheet"),
4582                Rect::from_ltrb(0.0, 586.0, 154.0, 600.0)
4583            );
4584        });
4585    }
4586
4587    /// Dart's 'No constraints by default for showModalBottomSheet'.
4588    #[test]
4589    fn there_are_no_constraints_by_default_for_show_modal_bottom_sheet() {
4590        test_widgets(|tester| {
4591            let saved = Saved::default();
4592            tester.pump_widget(app_with_scaffold_body(m2(tester), &saved));
4593            assert_eq!(found(tester, "BottomSheet"), 0);
4594            Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet"));
4595            tester.pump_and_settle();
4596            assert_eq!(found(tester, "BottomSheet"), 1);
4597            assert_eq!(
4598                rect_of_text(tester, "BottomSheet"),
4599                Rect::from_ltrb(0.0, 586.0, 800.0, 600.0)
4600            );
4601        });
4602    }
4603
4604    fn max_width_theme(tester: &WidgetTester, max_width: f64) -> ThemeData {
4605        ThemeData::builder()
4606            .bottom_sheet_theme(
4607                BottomSheetThemeData::new().constraints(BoxConstraints::new().max_width(max_width)),
4608            )
4609            .build(&tester.cell.borrow())
4610    }
4611
4612    /// Dart's 'Theme constraints used for showBottomSheet' and 'constraints param overrides
4613    /// theme for showBottomSheet'.
4614    fn persistent_constraints(
4615        tester: &mut WidgetTester,
4616        constraints: Option<BoxConstraints>,
4617        sheet_max_width: f64,
4618    ) {
4619        let saved = Saved::default();
4620        tester.pump_widget(app_with_scaffold_body(
4621            max_width_theme(tester, 80.0),
4622            &saved,
4623        ));
4624        assert_eq!(found(tester, "BottomSheet"), 0);
4625        let scaffold = Scaffold::of(&mut tester.cell.borrow_mut(), saved.get());
4626        Persistent {
4627            constraints,
4628            ..Persistent::default()
4629        }
4630        .show(tester, scaffold, sheet_builder("BottomSheet"));
4631        tester.pump_and_settle();
4632        assert_eq!(found(tester, "BottomSheet"), 1);
4633
4634        // Should be centered and only 80dp wide.
4635        let bottom_sheet_rect = rect_of_text(tester, "BottomSheet");
4636        assert_eq!(bottom_sheet_rect.left, 800.0 / 2.0 - sheet_max_width / 2.0);
4637        assert_eq!(bottom_sheet_rect.width(), sheet_max_width);
4638    }
4639
4640    #[test]
4641    fn theme_constraints_are_used_for_show_bottom_sheet() {
4642        test_widgets(|tester| persistent_constraints(tester, None, 80.0));
4643    }
4644
4645    #[test]
4646    fn the_constraints_argument_overrides_the_theme_for_show_bottom_sheet() {
4647        test_widgets(|tester| {
4648            persistent_constraints(tester, Some(BoxConstraints::new().max_width(100.0)), 100.0)
4649        });
4650    }
4651
4652    /// Dart's 'Theme constraints used for showModalBottomSheet' and 'constraints param
4653    /// overrides theme for showModalBottomSheet'.
4654    fn modal_constraints(
4655        tester: &mut WidgetTester,
4656        constraints: Option<BoxConstraints>,
4657        sheet_max_width: f64,
4658    ) {
4659        let saved = Saved::default();
4660        tester.pump_widget(app_with_scaffold_body(
4661            max_width_theme(tester, 80.0),
4662            &saved,
4663        ));
4664        assert_eq!(found(tester, "BottomSheet"), 0);
4665        Modal {
4666            constraints,
4667            ..Modal::default()
4668        }
4669        .show(tester, saved.get(), sheet_builder("BottomSheet"));
4670        tester.pump_and_settle();
4671        assert_eq!(found(tester, "BottomSheet"), 1);
4672
4673        // Should be centered and only 80dp wide.
4674        let bottom_sheet_rect = rect_of_text(tester, "BottomSheet");
4675        assert_eq!(bottom_sheet_rect.left, 800.0 / 2.0 - sheet_max_width / 2.0);
4676        assert_eq!(bottom_sheet_rect.width(), sheet_max_width);
4677    }
4678
4679    #[test]
4680    fn theme_constraints_are_used_for_show_modal_bottom_sheet() {
4681        test_widgets(|tester| modal_constraints(tester, None, 80.0));
4682    }
4683
4684    #[test]
4685    fn the_constraints_argument_overrides_the_theme_for_show_modal_bottom_sheet() {
4686        test_widgets(|tester| {
4687            modal_constraints(tester, Some(BoxConstraints::new().max_width(100.0)), 100.0)
4688        });
4689    }
4690
4691    /// Dart's 'scrollControlDisabledMaxHeightRatio' group.
4692    fn scroll_control_disabled_max_height_ratio(
4693        tester: &mut WidgetTester,
4694        is_scroll_controlled: bool,
4695        scroll_control_disabled_max_height_ratio: f64,
4696    ) {
4697        let saved = Saved::default();
4698        tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4699        Modal {
4700            is_scroll_controlled,
4701            scroll_control_disabled_max_height_ratio,
4702            ..Modal::default()
4703        }
4704        .show(
4705            tester,
4706            saved.get(),
4707            Rc::new(|_app, _context| SizedBox::expand().child(text("BottomSheet")).into_widget()),
4708        );
4709        tester.pump_and_settle();
4710        assert_eq!(
4711            rect_of_text(tester, "BottomSheet"),
4712            Rect::from_ltrb(
4713                80.0,
4714                600.0
4715                    * (if is_scroll_controlled {
4716                        0.0
4717                    } else {
4718                        1.0 - scroll_control_disabled_max_height_ratio
4719                    }),
4720                720.0,
4721                600.0,
4722            )
4723        );
4724    }
4725
4726    #[test]
4727    fn the_scroll_control_disabled_max_height_ratio_works_at_9_16() {
4728        test_widgets(|tester| scroll_control_disabled_max_height_ratio(tester, false, 9.0 / 16.0));
4729    }
4730
4731    #[test]
4732    fn the_scroll_control_disabled_max_height_ratio_works_at_8_16() {
4733        test_widgets(|tester| scroll_control_disabled_max_height_ratio(tester, false, 8.0 / 16.0));
4734    }
4735
4736    #[test]
4737    fn the_scroll_control_disabled_max_height_ratio_works_when_scroll_controlled() {
4738        test_widgets(|tester| scroll_control_disabled_max_height_ratio(tester, true, 8.0 / 16.0));
4739    }
4740
4741    /// Dart's 'Verify that modalBarrierDismissLabel is used if provided' and 'from context is
4742    /// used if barrierLabel is not provided'.
4743    fn barrier_label(tester: &mut WidgetTester, barrier_label: Option<&str>) {
4744        let scaffold_key = GlobalKey::new();
4745        tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
4746        let context = scaffold_context(tester, &scaffold_key);
4747        Modal {
4748            barrier_label: barrier_label.map(str::to_string),
4749            ..Modal::default()
4750        }
4751        .show(tester, context, sheet_builder("BottomSheet"));
4752        tester.pump();
4753        tester.pump_by(Duration::from_secs(1));
4754
4755        let expected = barrier_label.map(str::to_string).unwrap_or_else(|| {
4756            <dyn MaterialLocalizations>::of(&mut tester.cell.borrow_mut(), context).scrim_label()
4757        });
4758        let modal_barrier = *find::by_type::<ModalBarrier>()
4759            .evaluate(tester)
4760            .last()
4761            .expect("a modal barrier");
4762        tester.widget(modal_barrier, |modal_barrier: &ModalBarrier| {
4763            assert_eq!(
4764                modal_barrier.semantics_label.as_deref(),
4765                Some(expected.as_str())
4766            );
4767        });
4768    }
4769
4770    #[test]
4771    fn the_given_barrier_label_is_used() {
4772        test_widgets(|tester| barrier_label(tester, Some("custom label")));
4773    }
4774
4775    #[test]
4776    fn the_scrim_label_is_used_when_no_barrier_label_is_given() {
4777        test_widgets(|tester| barrier_label(tester, None));
4778    }
4779
4780    /// The sheet of Dart's animation cases: `SizedBox.expand(child: ColoredBox(key: sheetKey,
4781    /// color: primary, child: FilledButton(onPressed: () => Navigator.pop(context))))`. The
4782    /// cases pop from the saved context instead of tapping the button.
4783    fn expanded_sheet(sheet_key: &GlobalKey, sheet: &Saved) -> WidgetBuilder {
4784        let sheet_key = sheet_key.clone();
4785        let sheet = sheet.clone();
4786        Rc::new(move |app, context| {
4787            sheet.0.set(Some(context));
4788            let primary = Theme::of(app, context).color_scheme.primary();
4789            SizedBox::expand()
4790                .child(
4791                    waft_widgets::ColoredBox::new(primary)
4792                        .key(sheet_key.clone().into())
4793                        .child(text("Close")),
4794                )
4795                .into_widget()
4796        })
4797    }
4798
4799    fn top_of(tester: &WidgetTester, key: &GlobalKey) -> f64 {
4800        rect_of_key(tester, key).top
4801    }
4802
4803    /// Dart's 'Bottom sheet animation can be customized'.
4804    #[test]
4805    fn the_bottom_sheet_animation_can_be_customized() {
4806        test_widgets(|tester| {
4807            let saved = Saved::default();
4808            let sheet = Saved::default();
4809            let sheet_key = GlobalKey::new();
4810
4811            // Test custom animation style.
4812            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4813            let scaffold = Scaffold::of(&mut tester.cell.borrow_mut(), saved.get());
4814            Persistent {
4815                sheet_animation_style: Some(AnimationStyle::new(
4816                    None,
4817                    Some(Duration::from_millis(800)),
4818                    None,
4819                    Some(Duration::from_millis(400)),
4820                )),
4821                ..Persistent::default()
4822            }
4823            .show(tester, scaffold, expanded_sheet(&sheet_key, &sheet));
4824            tester.pump();
4825            // Advance the animation by 1/2 of the custom forward duration.
4826            tester.pump_by(Duration::from_millis(400));
4827
4828            // The bottom sheet is partially visible.
4829            assert_more_or_less_equals_within(top_of(tester, &sheet_key), 134.6, 0.1);
4830
4831            // Advance the animation by 1/2 of the custom forward duration.
4832            tester.pump_by(Duration::from_millis(400));
4833
4834            // The bottom sheet is fully visible.
4835            assert_eq!(top_of(tester, &sheet_key), 0.0);
4836
4837            // Dismiss the bottom sheet.
4838            pop(tester, sheet.get());
4839            tester.pump();
4840            // Advance the animation by 1/2 of the custom reverse duration.
4841            tester.pump_by(Duration::from_millis(200));
4842
4843            // The bottom sheet is partially visible.
4844            assert_more_or_less_equals_within(top_of(tester, &sheet_key), 134.6, 0.1);
4845
4846            // Advance the animation by 1/2 of the custom reverse duration.
4847            tester.pump_by(Duration::from_millis(200));
4848
4849            // The bottom sheet is dismissed.
4850            assert_eq!(top_of(tester, &sheet_key), 600.0);
4851
4852            // Test no animation style.
4853            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4854            tester.pump_and_settle();
4855            let scaffold = Scaffold::of(&mut tester.cell.borrow_mut(), saved.get());
4856            Persistent {
4857                sheet_animation_style: Some(AnimationStyle::NO_ANIMATION),
4858                ..Persistent::default()
4859            }
4860            .show(tester, scaffold, expanded_sheet(&sheet_key, &sheet));
4861            tester.pump();
4862
4863            // The bottom sheet is fully visible.
4864            assert_eq!(top_of(tester, &sheet_key), 0.0);
4865
4866            // Dismiss the bottom sheet.
4867            pop(tester, sheet.get());
4868            tester.pump();
4869
4870            // The bottom sheet is dismissed.
4871            assert!(!mounted(tester, &sheet_key));
4872        });
4873    }
4874
4875    /// Dart's 'Modal bottom sheet default animation' and 'Modal bottom sheet animation can be
4876    /// customized': `forward`/`reverse` are half of each duration.
4877    fn modal_animation(
4878        tester: &mut WidgetTester,
4879        style: Option<AnimationStyle>,
4880        half_forward: u64,
4881        half_reverse: u64,
4882    ) {
4883        let saved = Saved::default();
4884        let sheet = Saved::default();
4885        let sheet_key = GlobalKey::new();
4886        tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4887
4888        // Tap the 'X' to show the bottom sheet.
4889        Modal {
4890            sheet_animation_style: style,
4891            ..Modal::default()
4892        }
4893        .show(tester, saved.get(), expanded_sheet(&sheet_key, &sheet));
4894        tester.pump();
4895        // Advance the animation by 1/2 of the forward duration.
4896        tester.pump_by(Duration::from_millis(half_forward));
4897
4898        // The modal bottom sheet is partially visible.
4899        assert_more_or_less_equals_within(top_of(tester, &sheet_key), 316.7, 0.1);
4900
4901        // Advance the animation by 1/2 of the forward duration.
4902        tester.pump_by(Duration::from_millis(half_forward));
4903
4904        // The modal bottom sheet is fully visible.
4905        assert_eq!(top_of(tester, &sheet_key), 262.5);
4906
4907        // Dismiss the bottom sheet.
4908        pop(tester, sheet.get());
4909        tester.pump();
4910        // Advance the animation by 1/2 of the reverse duration.
4911        tester.pump_by(Duration::from_millis(half_reverse));
4912
4913        // The modal bottom sheet is partially visible.
4914        assert_more_or_less_equals_within(top_of(tester, &sheet_key), 316.7, 0.1);
4915
4916        // Advance the animation by 1/2 of the reverse duration.
4917        tester.pump_by(Duration::from_millis(half_reverse));
4918
4919        // The modal bottom sheet is dismissed.
4920        assert_eq!(top_of(tester, &sheet_key), 600.0);
4921    }
4922
4923    #[test]
4924    fn the_modal_bottom_sheet_default_animation() {
4925        test_widgets(|tester| modal_animation(tester, None, 125, 100));
4926    }
4927
4928    #[test]
4929    fn the_modal_bottom_sheet_animation_can_be_customized() {
4930        test_widgets(|tester| {
4931            modal_animation(
4932                tester,
4933                Some(AnimationStyle::new(
4934                    None,
4935                    Some(Duration::from_millis(800)),
4936                    None,
4937                    Some(Duration::from_millis(400)),
4938                )),
4939                400,
4940                200,
4941            );
4942
4943            // Test no animation style.
4944            let saved = Saved::default();
4945            let sheet = Saved::default();
4946            let sheet_key = GlobalKey::new();
4947            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4948            tester.pump_and_settle();
4949            Modal {
4950                sheet_animation_style: Some(AnimationStyle::NO_ANIMATION),
4951                ..Modal::default()
4952            }
4953            .show(tester, saved.get(), expanded_sheet(&sheet_key, &sheet));
4954            tester.pump();
4955
4956            // The bottom sheet is fully visible.
4957            assert_eq!(top_of(tester, &sheet_key), 262.5);
4958
4959            // Dismiss the bottom sheet.
4960            pop(tester, sheet.get());
4961            tester.pump();
4962
4963            // The bottom sheet is dismissed.
4964            assert!(!mounted(tester, &sheet_key));
4965        });
4966    }
4967
4968    /// Dart's 'BottomSheet does not crash at zero area'.
4969    #[test]
4970    fn a_bottom_sheet_does_not_crash_at_zero_area() {
4971        test_widgets(|tester| {
4972            tester.pump_widget(material_app(
4973                m3(tester),
4974                Scaffold::new()
4975                    .body(
4976                        Center::new().child(SizedBox::shrink().child(BottomSheet::new(
4977                            Rc::new(|_app| {}),
4978                            Rc::new(|_app, _context| text("X")),
4979                        ))),
4980                    )
4981                    .into_widget(),
4982            ));
4983            let sheet = only(find::by_type::<BottomSheet>().evaluate(tester));
4984            assert_eq!(tester.get_rect(sheet).size(), Size::ZERO);
4985        });
4986    }
4987
4988    /// Dart's 'ModalBottomSheet uses AnimationStyle curve' and 'reverseCurve'.
4989    #[test]
4990    fn a_modal_bottom_sheet_uses_the_animation_style_curve() {
4991        test_widgets(|tester| {
4992            let saved = Saved::default();
4993            let sheet = Saved::default();
4994            let sheet_key = GlobalKey::new();
4995            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
4996            Modal {
4997                sheet_animation_style: Some(AnimationStyle::new(
4998                    Some(Curves::linear()),
4999                    None,
5000                    None,
5001                    None,
5002                )),
5003                ..Modal::default()
5004            }
5005            .show(tester, saved.get(), expanded_sheet(&sheet_key, &sheet));
5006            tester.pump();
5007
5008            // Advance the animation by 50ms.
5009            tester.pump_by(Duration::from_millis(50));
5010            let open_extent1 = top_of(tester, &sheet_key);
5011
5012            // Advance the animation by an additional 50ms.
5013            tester.pump_by(Duration::from_millis(50));
5014            let open_extent2 = top_of(tester, &sheet_key);
5015
5016            // Advance the animation by an additional 50ms.
5017            tester.pump_by(Duration::from_millis(50));
5018            let open_extent3 = top_of(tester, &sheet_key);
5019
5020            // For the linear curve, the distance covered in each time interval should
5021            // be the same.
5022            assert_more_or_less_equals_within(
5023                open_extent1 - open_extent2,
5024                open_extent2 - open_extent3,
5025                0.1,
5026            );
5027            tester.pump_and_settle();
5028
5029            // Dismiss the bottom sheet.
5030            pop(tester, sheet.get());
5031            tester.pump_and_settle();
5032        });
5033    }
5034
5035    #[test]
5036    fn a_modal_bottom_sheet_uses_the_animation_style_reverse_curve() {
5037        test_widgets(|tester| {
5038            let saved = Saved::default();
5039            let sheet = Saved::default();
5040            let sheet_key = GlobalKey::new();
5041            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
5042            Modal {
5043                sheet_animation_style: Some(AnimationStyle::new(
5044                    None,
5045                    None,
5046                    Some(Curves::linear()),
5047                    None,
5048                )),
5049                ..Modal::default()
5050            }
5051            .show(tester, saved.get(), expanded_sheet(&sheet_key, &sheet));
5052            tester.pump_and_settle();
5053
5054            // Start the dismissal.
5055            pop(tester, sheet.get());
5056            tester.pump();
5057
5058            // Advance the animation by 50ms during the close transition.
5059            tester.pump_by(Duration::from_millis(50));
5060            let close_extent1 = top_of(tester, &sheet_key);
5061
5062            // Advance the animation by an additional 50ms.
5063            tester.pump_by(Duration::from_millis(50));
5064            let close_extent2 = top_of(tester, &sheet_key);
5065
5066            // Advance the animation by an additional 50ms.
5067            tester.pump_by(Duration::from_millis(50));
5068            let close_extent3 = top_of(tester, &sheet_key);
5069
5070            // For the linear curve, the distance covered in each time interval should
5071            // be the same.
5072            assert_more_or_less_equals_within(
5073                close_extent2 - close_extent1,
5074                close_extent3 - close_extent2,
5075                0.1,
5076            );
5077
5078            tester.pump_and_settle();
5079        });
5080    }
5081
5082    /// Dart's 'ModalBottomSheet with AnimationStyle.noAnimation opens and closes immediately'.
5083    #[test]
5084    fn a_modal_bottom_sheet_without_animation_opens_and_closes_immediately() {
5085        test_widgets(|tester| {
5086            let saved = Saved::default();
5087            let sheet = Saved::default();
5088            let sheet_key = GlobalKey::new();
5089            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
5090            let saving = sheet.clone();
5091            let key = sheet_key.clone();
5092            Modal {
5093                sheet_animation_style: Some(AnimationStyle::NO_ANIMATION),
5094                ..Modal::default()
5095            }
5096            .show(
5097                tester,
5098                saved.get(),
5099                Rc::new(move |_app, context| {
5100                    saving.0.set(Some(context));
5101                    SizedBox::new()
5102                        .key(key.clone().into())
5103                        .child(text("Close"))
5104                        .into_widget()
5105                }),
5106            );
5107            tester.pump();
5108
5109            assert!(mounted(tester, &sheet_key));
5110
5111            pop(tester, sheet.get());
5112            tester.pump();
5113
5114            assert!(!mounted(tester, &sheet_key));
5115        });
5116    }
5117
5118    /// Dart's 'ModalBottomSheet does not jump when drag gesture ends'.
5119    #[test]
5120    fn a_modal_bottom_sheet_does_not_jump_when_the_drag_gesture_ends() {
5121        test_widgets(|tester| {
5122            // Regression test for https://github.com/flutter/flutter/issues/183299.
5123            let saved = Saved::default();
5124            let sheet_key = GlobalKey::new();
5125            tester.pump_widget(app_with_scaffold_body(m3(tester), &saved));
5126            let key = sheet_key.clone();
5127            Modal {
5128                show_drag_handle: Some(true),
5129                ..Modal::default()
5130            }
5131            .show(
5132                tester,
5133                saved.get(),
5134                Rc::new(move |_app, _context| {
5135                    SizedBox::expand()
5136                        .key(key.clone().into())
5137                        .child(SizedBox::new())
5138                        .into_widget()
5139                }),
5140            );
5141            tester.pump_and_settle();
5142
5143            let mut gesture = TestPointer::touch(1);
5144            let center = drag_handle_rect(tester).center();
5145            tester.down(&mut gesture, center);
5146
5147            let by = |tester: &mut WidgetTester, gesture: &mut TestPointer, dy: f64| {
5148                let at = gesture.position + Offset::new(0.0, dy);
5149                tester.move_to(gesture, at, true);
5150            };
5151            by(tester, &mut gesture, 50.0);
5152            tester.pump();
5153
5154            by(tester, &mut gesture, 50.0);
5155            tester.pump();
5156
5157            by(tester, &mut gesture, 100.0);
5158            tester.pump();
5159
5160            let y_before_up = top_of(tester, &sheet_key);
5161
5162            tester.up(&gesture);
5163            tester.pump();
5164
5165            let y_after_up = top_of(tester, &sheet_key);
5166
5167            // The bottom sheet should not jump when the drag gesture ends.
5168            // Its position immediately after releasing the gesture should remain
5169            // approximately the same as the last dragged position, ensuring the
5170            // animation continues from the current visual offset.
5171            assert_more_or_less_equals_within(y_after_up, y_before_up, 0.1);
5172        });
5173    }
5174
5175    // persistent_bottom_sheet_test.dart
5176
5177    /// `ListView(children: [SizedBox(height: 100.0, child: Text(t)) for t in texts])` with
5178    /// the given setters.
5179    fn texts_list(texts: &[&'static str]) -> waft_widgets::ListView {
5180        waft_widgets::ListView::new().children(
5181            texts
5182                .iter()
5183                .map(|&content| {
5184                    SizedBox::new()
5185                        .height(100.0)
5186                        .child(text(content))
5187                        .into_widget()
5188                })
5189                .collect::<Vec<_>>(),
5190        )
5191    }
5192
5193    /// `DraggableScrollableSheet(expand: false, builder: (_, controller) => ListView(controller:
5194    /// controller, shrinkWrap: true, children: One, Two, Three))`.
5195    fn draggable_texts(should_close_on_min_extent: Option<bool>) -> WidgetRef {
5196        let mut sheet =
5197            waft_widgets::DraggableScrollableSheet::new(Rc::new(|_app, _context, controller| {
5198                texts_list(&["One", "Two", "Three"])
5199                    .controller(controller)
5200                    .shrink_wrap(true)
5201                    .into_widget()
5202            }))
5203            .expand(false);
5204        if let Some(should_close_on_min_extent) = should_close_on_min_extent {
5205            sheet = sheet.should_close_on_min_extent(should_close_on_min_extent);
5206        }
5207        sheet.into_widget()
5208    }
5209
5210    /// Whether a hit test at the centre of `element` reaches its render box: Dart's
5211    /// `hitTestable()` finder.
5212    fn hit_testable(tester: &WidgetTester, element: AnyElement) -> bool {
5213        let render = tester.render_box_of(element);
5214        let center = tester.get_rect(render).center();
5215        let mut app = tester.cell.borrow_mut();
5216        let view_id = app.platform().views()[0].id();
5217        let mut result = waft_gestures::HitTestResult::new();
5218        waft_gestures::GestureBinding::instance(&mut app).hit_test_in_view(
5219            &mut app,
5220            &mut result,
5221            center,
5222            view_id,
5223        );
5224        result.path().iter().any(|entry| {
5225            (entry.target() as &dyn std::any::Any)
5226                .downcast_ref::<waft_rendering::BoxHitTestEntry>()
5227                .is_some_and(|entry| entry.target() == render)
5228        })
5229    }
5230
5231    /// Dart's 'Scaffold.bottomSheet update test'.
5232    #[test]
5233    fn the_scaffold_bottom_sheet_can_come_back_while_it_is_disappearing() {
5234        test_widgets(|tester| {
5235            // Regression test for https://github.com/flutter/flutter/issues/83668
5236            let build_frame = |tester: &WidgetTester, bottom_sheet: Option<WidgetRef>| {
5237                let mut scaffold = Scaffold::new().body(placeholder(800.0));
5238                if let Some(bottom_sheet) = bottom_sheet {
5239                    scaffold = scaffold.bottom_sheet(bottom_sheet);
5240                }
5241                material_app(m3(tester), scaffold.into_widget())
5242            };
5243
5244            tester.pump_widget(build_frame(tester, Some(text("I love Flutter!"))));
5245            tester.pump_widget(build_frame(tester, None));
5246
5247            // The disappearing animation has not yet been completed.
5248            tester.pump_widget(build_frame(tester, Some(text("I love Flutter!"))));
5249        });
5250    }
5251
5252    /// Dart's 'Verify that a BottomSheet can be rebuilt with ScaffoldFeatureController.setState()'.
5253    #[test]
5254    fn a_bottom_sheet_can_be_rebuilt_with_its_controller_set_state() {
5255        test_widgets(|tester| {
5256            let scaffold_key = GlobalKey::new();
5257            let build_count = Rc::new(Cell::new(0));
5258            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5259
5260            let scaffold = scaffold_state(tester, &scaffold_key);
5261            let count = Rc::clone(&build_count);
5262            let bottom_sheet = Persistent::default().show(
5263                tester,
5264                scaffold,
5265                Rc::new(move |_app, _context| {
5266                    let count = Rc::clone(&count);
5267                    Builder::new(move |_app, _context| {
5268                        count.set(count.get() + 1);
5269                        Container::new().height(200.0).into_widget()
5270                    })
5271                    .into_widget()
5272                }),
5273            );
5274
5275            tester.pump();
5276            assert_eq!(build_count.get(), 1);
5277            bottom_sheet.set_state(&mut tester.cell.borrow_mut(), &mut |_app| {});
5278            tester.pump();
5279            assert_eq!(build_count.get(), 2);
5280        });
5281    }
5282
5283    /// Dart's 'Verify that a persistent BottomSheet cannot be dismissed'.
5284    #[test]
5285    fn a_persistent_bottom_sheet_cannot_be_dismissed() {
5286        test_widgets(|tester| {
5287            tester.pump_widget(material_app(
5288                m3(tester),
5289                Scaffold::new()
5290                    .body(Center::new().child(text("body")))
5291                    .bottom_sheet(draggable_texts(None))
5292                    .into_widget(),
5293            ));
5294
5295            tester.pump_and_settle();
5296
5297            assert_eq!(found(tester, "Two"), 1);
5298
5299            drag_text(tester, "Two", Offset::new(0.0, 400.0));
5300            tester.pump_and_settle();
5301
5302            assert_eq!(found(tester, "Two"), 1);
5303        });
5304    }
5305
5306    /// Dart's 'Verify that a scrollable BottomSheet can be dismissed'.
5307    #[test]
5308    fn a_scrollable_bottom_sheet_can_be_dismissed() {
5309        test_widgets(|tester| {
5310            let scaffold_key = GlobalKey::new();
5311            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5312
5313            let scaffold = scaffold_state(tester, &scaffold_key);
5314            Persistent::default().show(
5315                tester,
5316                scaffold,
5317                Rc::new(|_app, _context| {
5318                    texts_list(&["One", "Two", "Three"])
5319                        .shrink_wrap(true)
5320                        .primary(false)
5321                        .into_widget()
5322                }),
5323            );
5324
5325            tester.pump_and_settle();
5326
5327            assert_eq!(found(tester, "Two"), 1);
5328
5329            drag_text(tester, "Two", Offset::new(0.0, 400.0));
5330            tester.pump_and_settle();
5331
5332            assert_eq!(found(tester, "Two"), 0);
5333        });
5334    }
5335
5336    /// Dart's 'Verify DraggableScrollableSheet.shouldCloseOnMinExtent == false prevents
5337    /// dismissal' and 'Verify that a scrollControlled BottomSheet can be dismissed'.
5338    fn draggable_persistent(
5339        tester: &mut WidgetTester,
5340        should_close_on_min_extent: Option<bool>,
5341        dismissed: bool,
5342    ) {
5343        let scaffold_key = GlobalKey::new();
5344        tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5345
5346        let scaffold = scaffold_state(tester, &scaffold_key);
5347        Persistent::default().show(
5348            tester,
5349            scaffold,
5350            Rc::new(move |_app, _context| draggable_texts(should_close_on_min_extent)),
5351        );
5352
5353        tester.pump_and_settle();
5354
5355        assert_eq!(found(tester, "Two"), 1);
5356
5357        drag_text(tester, "Two", Offset::new(0.0, 400.0));
5358        tester.pump_and_settle();
5359
5360        assert_eq!(found(tester, "Two"), if dismissed { 0 } else { 1 });
5361    }
5362
5363    #[test]
5364    fn should_close_on_min_extent_false_prevents_dismissing_a_draggable_sheet() {
5365        test_widgets(|tester| draggable_persistent(tester, Some(false), false));
5366    }
5367
5368    #[test]
5369    fn a_scroll_controlled_bottom_sheet_can_be_dismissed() {
5370        test_widgets(|tester| draggable_persistent(tester, None, true));
5371    }
5372
5373    /// Dart's 'Verify that a BottomSheet animates non-linearly' (persistent).
5374    #[test]
5375    fn a_persistent_bottom_sheet_animates_non_linearly() {
5376        test_widgets(|tester| {
5377            let scaffold_key = GlobalKey::new();
5378            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5379
5380            let check = |tester: &mut WidgetTester| {
5381                let first_position = center_of_text(tester, "One");
5382                tester.pump_by(Duration::from_millis(30));
5383                let second_position = center_of_text(tester, "One");
5384                tester.pump_by(Duration::from_millis(30));
5385                let third_position = center_of_text(tester, "One");
5386
5387                let dy_delta1 = second_position.dy() - first_position.dy();
5388                let dy_delta2 = third_position.dy() - second_position.dy();
5389
5390                // If the animation were linear, these two values would be the same.
5391                assert!((dy_delta1 - dy_delta2).abs() > 0.1);
5392            };
5393
5394            let scaffold = scaffold_state(tester, &scaffold_key);
5395            Persistent::default().show(
5396                tester,
5397                scaffold,
5398                Rc::new(|_app, _context| {
5399                    texts_list(&["One", "Two", "Three"])
5400                        .shrink_wrap(true)
5401                        .primary(false)
5402                        .into_widget()
5403                }),
5404            );
5405            tester.pump();
5406            check(tester);
5407
5408            tester.pump_and_settle();
5409
5410            assert_eq!(found(tester, "Two"), 1);
5411
5412            drag_text(tester, "Two", Offset::new(0.0, 200.0));
5413            check(tester);
5414            tester.pump_and_settle();
5415
5416            assert_eq!(found(tester, "Two"), 0);
5417        });
5418    }
5419
5420    /// `DraggableScrollableSheet(expand: false, builder: (_, controller) => ListView.builder(
5421    /// itemExtent: 50.0, itemCount: 50, itemBuilder: (_, index) => Text('Item $index'),
5422    /// controller: controller))`.
5423    fn draggable_items() -> waft_widgets::DraggableScrollableSheet {
5424        waft_widgets::DraggableScrollableSheet::new(Rc::new(|_app, _context, controller| {
5425            waft_widgets::ListView::builder(|_app, _context, index| {
5426                Some(Text::new(format!("Item {index}")).into_widget())
5427            })
5428            .item_count(50)
5429            .build()
5430            .item_extent(50.0)
5431            .controller(controller)
5432            .into_widget()
5433        }))
5434        .expand(false)
5435    }
5436
5437    /// `MaterialApp(home: Scaffold(appBar: AppBar(), body: Center(child: Text('body')),
5438    /// bottomSheet: bottomSheet, floatingActionButton: FloatingActionButton(onPressed: null,
5439    /// child: Text('fab'))))`.
5440    fn app_bar_scaffold(tester: &WidgetTester, bottom_sheet: Option<WidgetRef>) -> WidgetRef {
5441        let mut scaffold = Scaffold::new()
5442            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5443                crate::app_bar::AppBar::new(),
5444            ))
5445            .body(Center::new().child(text("body")))
5446            .floating_action_button(
5447                crate::floating_action_button::FloatingActionButton::new(None).child(text("fab")),
5448            );
5449        if let Some(bottom_sheet) = bottom_sheet {
5450            scaffold = scaffold.bottom_sheet(bottom_sheet);
5451        }
5452        material_app(m3(tester), scaffold.into_widget())
5453    }
5454
5455    /// Dart's `find.byType(T).hitTestable()`: how many `T`s a hit test at their centre reaches.
5456    fn hit_testable_count<T: 'static>(tester: &WidgetTester) -> usize {
5457        find::by_type::<T>()
5458            .evaluate(tester)
5459            .into_iter()
5460            .filter(|element| hit_testable(tester, *element))
5461            .count()
5462    }
5463
5464    fn back_buttons(tester: &WidgetTester) -> usize {
5465        hit_testable_count::<crate::action_buttons::BackButton>(tester)
5466    }
5467
5468    /// Dart's `tester.tap(find.byType(BackButton))`.
5469    fn tap_back_button(tester: &mut WidgetTester, pointer: i64) {
5470        let button = only(find::by_type::<crate::action_buttons::BackButton>().evaluate(tester));
5471        let center = tester.get_rect(button).center();
5472        tester.tap_at(center, pointer);
5473    }
5474
5475    /// Dart's 'Persistent draggableScrollableSheet localHistoryEntries test'.
5476    #[test]
5477    fn a_persistent_draggable_sheet_adds_and_removes_its_local_history_entry() {
5478        test_widgets(|tester| {
5479            // Regression test for https://github.com/flutter/flutter/issues/110123
5480            let draggable_scrollable_sheet = || {
5481                draggable_items()
5482                    .snap(true)
5483                    .initial_child_size(0.3)
5484                    .min_child_size(0.3)
5485                    .into_widget()
5486            };
5487
5488            let frame = app_bar_scaffold(tester, Some(draggable_scrollable_sheet()));
5489            tester.pump_widget(frame);
5490            tester.pump_and_settle();
5491
5492            assert_eq!(back_buttons(tester), 0);
5493
5494            drag_text(tester, "Item 2", Offset::new(0.0, -200.0));
5495            tester.pump_and_settle();
5496            // We've started to drag up, we should have a back button now for a11y
5497            assert_eq!(back_buttons(tester), 1);
5498
5499            fling_text(tester, "Item 2", Offset::new(0.0, 200.0), 2000.0);
5500            tester.pump_and_settle();
5501            // BackButton should be hidden
5502            assert_eq!(back_buttons(tester), 0);
5503
5504            // Show the back button again
5505            drag_text(tester, "Item 2", Offset::new(0.0, -200.0));
5506            tester.pump_and_settle();
5507            assert_eq!(back_buttons(tester), 1);
5508
5509            // Remove the draggableScrollableSheet should hide the back button
5510            let frame = app_bar_scaffold(tester, None);
5511            tester.pump_widget(frame);
5512            assert_eq!(back_buttons(tester), 0);
5513        });
5514    }
5515
5516    /// Dart's 'Verify that a persistent BottomSheet can fling up and hide the fab'.
5517    #[test]
5518    fn a_persistent_bottom_sheet_can_fling_up_and_hide_the_fab() {
5519        test_widgets(|tester| {
5520            let frame = app_bar_scaffold(tester, Some(draggable_items().into_widget()));
5521            tester.pump_widget(frame);
5522            tester.pump_and_settle();
5523            let fabs = |tester: &WidgetTester| {
5524                find::by_type::<crate::floating_action_button::FloatingActionButton>()
5525                    .evaluate(tester)
5526                    .len()
5527            };
5528            let hit_testable_fabs = |tester: &WidgetTester| {
5529                hit_testable_count::<crate::floating_action_button::FloatingActionButton>(tester)
5530            };
5531
5532            assert_eq!(found(tester, "Item 2"), 1);
5533            assert_eq!(found(tester, "Item 22"), 0);
5534            assert_eq!(fabs(tester), 1);
5535            assert_eq!(hit_testable_fabs(tester), 1);
5536            assert_eq!(back_buttons(tester), 0);
5537
5538            drag_text(tester, "Item 2", Offset::new(0.0, -20.0));
5539            tester.pump_and_settle();
5540
5541            assert_eq!(found(tester, "Item 2"), 1);
5542            assert_eq!(found(tester, "Item 22"), 0);
5543            assert_eq!(fabs(tester), 1);
5544            assert_eq!(hit_testable_fabs(tester), 1);
5545
5546            fling_text(tester, "Item 2", Offset::new(0.0, -600.0), 2000.0);
5547            tester.pump_and_settle();
5548
5549            assert_eq!(found(tester, "Item 2"), 0);
5550            assert_eq!(found(tester, "Item 22"), 1);
5551            assert_eq!(fabs(tester), 1);
5552            assert_eq!(hit_testable_fabs(tester), 0);
5553        });
5554    }
5555
5556    /// Dart's 'Verify that a back button resets a persistent BottomSheet'.
5557    #[test]
5558    fn a_back_button_resets_a_persistent_bottom_sheet() {
5559        test_widgets(|tester| {
5560            let frame = app_bar_scaffold(tester, Some(draggable_items().into_widget()));
5561            tester.pump_widget(frame);
5562            tester.pump_and_settle();
5563
5564            assert_eq!(found(tester, "Item 2"), 1);
5565            assert_eq!(found(tester, "Item 22"), 0);
5566            assert_eq!(back_buttons(tester), 0);
5567
5568            drag_text(tester, "Item 2", Offset::new(0.0, -20.0));
5569            tester.pump_and_settle();
5570
5571            assert_eq!(found(tester, "Item 2"), 1);
5572            assert_eq!(found(tester, "Item 22"), 0);
5573            // We've started to drag up, we should have a back button now for a11y
5574            assert_eq!(back_buttons(tester), 1);
5575
5576            tap_back_button(tester, 2);
5577            tester.pump_and_settle();
5578
5579            assert_eq!(back_buttons(tester), 0);
5580            assert_eq!(found(tester, "Item 2"), 1);
5581            assert_eq!(found(tester, "Item 22"), 0);
5582
5583            fling_text(tester, "Item 2", Offset::new(0.0, -600.0), 2000.0);
5584            tester.pump_and_settle();
5585
5586            assert_eq!(found(tester, "Item 2"), 0);
5587            assert_eq!(found(tester, "Item 22"), 1);
5588            assert_eq!(back_buttons(tester), 1);
5589
5590            tap_back_button(tester, 3);
5591            tester.pump_and_settle();
5592
5593            assert_eq!(back_buttons(tester), 0);
5594            assert_eq!(found(tester, "Item 2"), 1);
5595            assert_eq!(found(tester, "Item 22"), 0);
5596        });
5597    }
5598
5599    /// Dart's 'Verify that a scrollable BottomSheet hides the fab when scrolled up'.
5600    #[test]
5601    fn a_scrollable_bottom_sheet_hides_the_fab_when_scrolled_up() {
5602        test_widgets(|tester| {
5603            let scaffold_key = GlobalKey::new();
5604            tester.pump_widget(material_app(
5605                m3(tester),
5606                Scaffold::new()
5607                    .key(scaffold_key.clone().into())
5608                    .body(Center::new().child(text("body")))
5609                    .floating_action_button(
5610                        crate::floating_action_button::FloatingActionButton::new(None)
5611                            .child(text("fab")),
5612                    )
5613                    .into_widget(),
5614            ));
5615            let fab = |tester: &WidgetTester| {
5616                only(
5617                    find::by_type::<crate::floating_action_button::FloatingActionButton>()
5618                        .evaluate(tester),
5619                )
5620            };
5621
5622            let scaffold = scaffold_state(tester, &scaffold_key);
5623            Persistent::default().show(
5624                tester,
5625                scaffold,
5626                Rc::new(|_app, _context| {
5627                    waft_widgets::DraggableScrollableSheet::new(Rc::new(
5628                        |_app, _context, controller| {
5629                            texts_list(&[
5630                                "One", "Two", "Three", "Three", "Three", "Three", "Three", "Three",
5631                                "Three", "Three", "Three",
5632                            ])
5633                            .controller(controller)
5634                            .shrink_wrap(true)
5635                            .into_widget()
5636                        },
5637                    ))
5638                    .expand(false)
5639                    .into_widget()
5640                }),
5641            );
5642
5643            tester.pump_and_settle();
5644
5645            assert_eq!(found(tester, "Two"), 1);
5646            assert!(hit_testable(tester, fab(tester)));
5647
5648            drag_text(tester, "Two", Offset::new(0.0, -600.0));
5649            tester.pump_and_settle();
5650
5651            assert_eq!(found(tester, "Two"), 1);
5652            assert_eq!(
5653                find::by_type::<crate::floating_action_button::FloatingActionButton>()
5654                    .evaluate(tester)
5655                    .len(),
5656                1
5657            );
5658            assert!(!hit_testable(tester, fab(tester)));
5659        });
5660    }
5661
5662    /// Dart's 'showBottomSheet()'.
5663    #[test]
5664    fn show_bottom_sheet_builds_the_sheet_once() {
5665        test_widgets(|tester| {
5666            let key = GlobalKey::new();
5667            tester.pump_widget(material_app(
5668                m3(tester),
5669                Scaffold::new()
5670                    .body(
5671                        waft_widgets::KeyedSubtree::new(placeholder(800.0)).key(key.clone().into()),
5672                    )
5673                    .into_widget(),
5674            ));
5675
5676            let build_count = Rc::new(Cell::new(0));
5677            let count = Rc::clone(&build_count);
5678            let context = key
5679                .current_context(&tester.cell.borrow_mut())
5680                .expect("mounted");
5681            {
5682                let show = ShowBottomSheet::new(Rc::new(move |_app, _context| {
5683                    let count = Rc::clone(&count);
5684                    Builder::new(move |_app, _context| {
5685                        count.set(count.get() + 1);
5686                        Container::new().height(200.0).into_widget()
5687                    })
5688                    .into_widget()
5689                }));
5690                show.show(&mut tester.cell.borrow_mut(), context)
5691            };
5692            tester.pump();
5693            assert_eq!(build_count.get(), 1);
5694        });
5695    }
5696
5697    /// Dart's 'Scaffold removes top MediaQuery padding'.
5698    #[test]
5699    fn the_scaffold_removes_top_media_query_padding_from_a_bottom_sheet() {
5700        test_widgets(|tester| {
5701            let scaffold_context = Saved::default();
5702            let bottom_sheet_context = Saved::default();
5703            let saving = scaffold_context.clone();
5704            tester.pump_widget(material_app(
5705                m3(tester),
5706                Builder::new(move |app, context| {
5707                    let data = MediaQuery::of(app, context)
5708                        .copy_with()
5709                        .padding(EdgeInsets::all(50.0));
5710                    let saving = saving.clone();
5711                    MediaQuery::new(
5712                        data,
5713                        Scaffold::new()
5714                            .resize_to_avoid_bottom_inset(false)
5715                            .body(saving.builder(|| Container::new().into_widget())),
5716                    )
5717                    .into_widget()
5718                })
5719                .into_widget(),
5720            ));
5721
5722            tester.pump();
5723
5724            let saving = bottom_sheet_context.clone();
5725            {
5726                let show = ShowBottomSheet::new(Rc::new(move |_app, context| {
5727                    saving.0.set(Some(context));
5728                    Container::new().into_widget()
5729                }));
5730                show.show(&mut tester.cell.borrow_mut(), scaffold_context.get())
5731            };
5732
5733            tester.pump();
5734
5735            assert_eq!(
5736                padding_of(tester, bottom_sheet_context.get()),
5737                EdgeInsets::only(50.0, 0.0, 50.0, 50.0)
5738            );
5739        });
5740    }
5741
5742    /// Dart's 'Scaffold.bottomSheet'. Dart's `ElevatedButton` in the sheet calls
5743    /// `showModalBottomSheet`; the case calls it from the button's context.
5744    #[test]
5745    fn a_scaffold_bottom_sheet_shows_and_its_modal_sheet_dismisses() {
5746        test_widgets(|tester| {
5747            let bottom_sheet_key = GlobalKey::new();
5748            let button_context = Saved::default();
5749            let sheet = Container::new()
5750                .key(bottom_sheet_key.clone().into())
5751                .alignment(AlignmentGeometry::CENTER)
5752                .height(200.0)
5753                .child(button_context.builder(|| text("showModalBottomSheet")))
5754                .into_widget();
5755            tester.pump_widget(material_app(
5756                m2(tester),
5757                Scaffold::new()
5758                    .body(placeholder(800.0))
5759                    .bottom_sheet(sheet)
5760                    .into_widget(),
5761            ));
5762
5763            assert_eq!(found(tester, "showModalBottomSheet"), 1);
5764            let rect = rect_of_key(tester, &bottom_sheet_key);
5765            assert_eq!(rect.size(), Size::new(800.0, 200.0));
5766            assert_eq!(rect.top_left(), Offset::new(0.0, 400.0));
5767
5768            // Show the modal bottomSheet
5769            Modal::default().show(
5770                tester,
5771                button_context.get(),
5772                sheet_builder("modal bottom sheet"),
5773            );
5774            tester.pump_and_settle();
5775            assert_eq!(found(tester, "modal bottom sheet"), 1);
5776
5777            // Dismiss the modal bottomSheet by tapping above the sheet
5778            tester.tap_at(Offset::new(20.0, 20.0), 1);
5779            tester.pump_and_settle();
5780            assert_eq!(found(tester, "modal bottom sheet"), 0);
5781            assert_eq!(found(tester, "showModalBottomSheet"), 1);
5782
5783            // Remove the persistent bottomSheet
5784            tester.pump_widget(material_app(
5785                m2(tester),
5786                Scaffold::new().body(placeholder(800.0)).into_widget(),
5787            ));
5788            tester.pump_and_settle();
5789            assert_eq!(found(tester, "showModalBottomSheet"), 0);
5790            assert!(!mounted(tester, &bottom_sheet_key));
5791        });
5792    }
5793
5794    /// Dart's 'Scaffold.bottomSheet should be updated without creating a new RO when the new
5795    /// widget has the same key and type.'.
5796    #[test]
5797    fn a_scaffold_bottom_sheet_of_the_same_type_keeps_its_render_object() {
5798        test_widgets(|tester| {
5799            // Regression test for https://github.com/flutter/flutter/issues/71435
5800            let build_frame = |tester: &WidgetTester, content: &'static str| {
5801                material_app(
5802                    m3(tester),
5803                    Scaffold::new()
5804                        .body(placeholder(800.0))
5805                        .bottom_sheet(text(content))
5806                        .into_widget(),
5807                )
5808            };
5809
5810            tester.pump_widget(build_frame(tester, "I love Flutter!"));
5811            let render_before_update =
5812                tester.render_box_of(only(find::text("I love Flutter!").evaluate(tester)));
5813
5814            tester.pump_widget(build_frame(tester, "Flutter is the best!"));
5815            tester.pump_and_settle();
5816            let render_after_update =
5817                tester.render_box_of(only(find::text("Flutter is the best!").evaluate(tester)));
5818
5819            assert_eq!(render_before_update, render_after_update);
5820        });
5821    }
5822
5823    /// Dart's 'Verify that visual properties are passed through' (persistent).
5824    #[test]
5825    fn visual_properties_are_passed_through_to_a_persistent_bottom_sheet() {
5826        test_widgets(|tester| {
5827            let scaffold_key = GlobalKey::new();
5828            let color = Colors::PINK.primary();
5829            let elevation = 9.0;
5830            let shape: ShapeBorderRef =
5831                ShapeBorderRef::new(waft_painting::BeveledRectangleBorder::new(
5832                    waft_painting::BorderSide::NONE,
5833                    waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(12.0)),
5834                ));
5835            let clip_behavior = Clip::AntiAlias;
5836
5837            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5838
5839            let scaffold = scaffold_state(tester, &scaffold_key);
5840            scaffold.show_bottom_sheet(
5841                &mut tester.cell.borrow_mut(),
5842                Rc::new(|_app, _context| {
5843                    texts_list(&["One", "Two", "Three"])
5844                        .shrink_wrap(true)
5845                        .primary(false)
5846                        .into_widget()
5847                }),
5848                Some(color),
5849                Some(elevation),
5850                Some(shape.clone()),
5851                Some(clip_behavior),
5852                None,
5853                None,
5854                None,
5855                None,
5856                None,
5857            );
5858
5859            tester.pump_and_settle();
5860
5861            let bottom_sheet = only(find::by_type::<BottomSheet>().evaluate(tester));
5862            tester.widget(bottom_sheet, |bottom_sheet: &BottomSheet| {
5863                assert_eq!(bottom_sheet.background_color, Some(color));
5864                assert_eq!(bottom_sheet.elevation, Some(elevation));
5865                assert!(**bottom_sheet.shape.as_ref().expect("a shape") == *shape);
5866                assert_eq!(bottom_sheet.clip_behavior, Some(clip_behavior));
5867            });
5868        });
5869    }
5870
5871    /// Dart's 'PersistentBottomSheetController.close dismisses the bottom sheet'.
5872    #[test]
5873    fn closing_the_persistent_bottom_sheet_controller_dismisses_the_sheet() {
5874        test_widgets(|tester| {
5875            let scaffold_key = GlobalKey::new();
5876            tester.pump_widget(app_with_scaffold(m3(tester), &scaffold_key));
5877
5878            let scaffold = scaffold_state(tester, &scaffold_key);
5879            let bottom_sheet = Persistent::default().show(
5880                tester,
5881                scaffold,
5882                Rc::new(|_app, _context| {
5883                    Builder::new(|_app, _context| Container::new().height(200.0).into_widget())
5884                        .into_widget()
5885                }),
5886            );
5887
5888            tester.pump();
5889            expect(tester, &find::by_type::<BottomSheet>(), finds_one_widget());
5890
5891            bottom_sheet.close(&mut tester.cell.borrow_mut());
5892            tester.pump();
5893            expect(tester, &find::by_type::<BottomSheet>(), finds_nothing());
5894        });
5895    }
5896
5897    // persistent_bottom_sheet_test.dart's 'keyboard inset' group.
5898
5899    /// The Material of the `index`th `BottomSheet` in tree order: Dart's
5900    /// `find.descendant(of: sheet, matching: find.byType(Material)).first`.
5901    fn material_of_sheet(tester: &WidgetTester, index: usize) -> Rect {
5902        let sheet = find::by_type::<BottomSheet>().evaluate(tester)[index];
5903        let material = tester.descendants_of_type::<Material>(sheet)[0];
5904        tester.get_rect(material)
5905    }
5906
5907    // The Scaffold's persistent bottom sheet is _StandardBottomSheet ->
5908    // BottomSheet -> Material. This finds that Material.
5909    fn inset_sheet_material(tester: &WidgetTester) -> Rect {
5910        material_of_sheet(tester, 0)
5911    }
5912
5913    /// Dart's `buildApp` of the group.
5914    struct KeyboardInsetApp {
5915        keyboard_height: f64,
5916        resize_to_avoid_bottom_inset: bool,
5917        bottom_navigation_bar: Option<WidgetRef>,
5918        floating_action_button: Option<WidgetRef>,
5919        floating_action_button_location: Option<crate::FloatingActionButtonLocationRef>,
5920        bottom_sheet: Option<WidgetRef>,
5921    }
5922
5923    impl KeyboardInsetApp {
5924        fn new(keyboard_height: f64) -> KeyboardInsetApp {
5925            KeyboardInsetApp {
5926                keyboard_height,
5927                resize_to_avoid_bottom_inset: true,
5928                bottom_navigation_bar: None,
5929                floating_action_button: None,
5930                floating_action_button_location: None,
5931                bottom_sheet: None,
5932            }
5933        }
5934
5935        /// The default sheet: `SizedBox(key: Key('content'), width: double.infinity,
5936        /// height: 100.0, child: Text('sheet'))`.
5937        fn content(content_key: &GlobalKey) -> WidgetRef {
5938            SizedBox::new()
5939                .key(content_key.clone().into())
5940                .width(f64::INFINITY)
5941                .height(100.0)
5942                .child(text("sheet"))
5943                .into_widget()
5944        }
5945
5946        fn build(self, tester: &WidgetTester, content_key: &GlobalKey) -> WidgetRef {
5947            let mut scaffold = Scaffold::new()
5948                .resize_to_avoid_bottom_inset(self.resize_to_avoid_bottom_inset)
5949                .bottom_sheet(
5950                    self.bottom_sheet
5951                        .unwrap_or_else(|| KeyboardInsetApp::content(content_key)),
5952                );
5953            if let Some(bottom_navigation_bar) = self.bottom_navigation_bar {
5954                scaffold = scaffold.bottom_navigation_bar(bottom_navigation_bar);
5955            }
5956            if let Some(floating_action_button) = self.floating_action_button {
5957                scaffold = scaffold.floating_action_button(floating_action_button);
5958            }
5959            if let Some(location) = self.floating_action_button_location {
5960                scaffold = scaffold.floating_action_button_location(location);
5961            }
5962            material_app(
5963                m3(tester),
5964                MediaQuery::new(
5965                    waft_widgets::MediaQueryData::new().view_insets(EdgeInsets::only(
5966                        0.0,
5967                        0.0,
5968                        0.0,
5969                        self.keyboard_height,
5970                    )),
5971                    scaffold,
5972                )
5973                .into_widget(),
5974            )
5975        }
5976    }
5977
5978    /// `MaterialApp(home: MediaQuery(viewInsets: bottom, child: Scaffold(key: scaffoldKey,
5979    /// body: const SizedBox.expand())))`.
5980    fn keyboard_app_with_scaffold(
5981        tester: &WidgetTester,
5982        keyboard_height: f64,
5983        scaffold_key: &GlobalKey,
5984    ) -> WidgetRef {
5985        material_app(
5986            m3(tester),
5987            MediaQuery::new(
5988                waft_widgets::MediaQueryData::new().view_insets(EdgeInsets::only(
5989                    0.0,
5990                    0.0,
5991                    0.0,
5992                    keyboard_height,
5993                )),
5994                Scaffold::new()
5995                    .key(scaffold_key.clone().into())
5996                    .body(SizedBox::expand()),
5997            )
5998            .into_widget(),
5999        )
6000    }
6001
6002    /// `SizedBox(height: height, child: Text('sheet'))` as a sheet builder.
6003    fn sheet_of_height(height: f64) -> WidgetBuilder {
6004        Rc::new(move |_app, _context| {
6005            SizedBox::new()
6006                .height(height)
6007                .child(text("sheet"))
6008                .into_widget()
6009        })
6010    }
6011
6012    fn docked_fab() -> WidgetRef {
6013        crate::floating_action_button::FloatingActionButton::new(Some(
6014            waft_foundation::Listener::new(|_| {}),
6015        ))
6016        .child(waft_widgets::Icon::new(Some(crate::icons::Icons::add())))
6017        .into_widget()
6018    }
6019
6020    #[test]
6021    fn the_sheet_material_extends_behind_the_keyboard_and_the_content_stays_above() {
6022        test_widgets(|tester| {
6023            let content = GlobalKey::new();
6024            tester.pump_widget(KeyboardInsetApp::new(0.0).build(tester, &content));
6025            assert_eq!(rect_of_key(tester, &content).top, 500.0);
6026            assert_eq!(rect_of_key(tester, &content).bottom, 600.0);
6027            assert_eq!(inset_sheet_material(tester).top, 500.0);
6028            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6029
6030            tester.pump_widget(KeyboardInsetApp::new(200.0).build(tester, &content));
6031            // Content avoids the keyboard exactly as before.
6032            assert_eq!(rect_of_key(tester, &content).top, 300.0);
6033            assert_eq!(rect_of_key(tester, &content).bottom, 400.0);
6034            // The sheet's own Material now continues to the bottom of the screen.
6035            assert_eq!(inset_sheet_material(tester).top, 300.0);
6036            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6037        });
6038    }
6039
6040    #[test]
6041    fn resize_to_avoid_bottom_inset_false_leaves_the_sheet_unchanged() {
6042        test_widgets(|tester| {
6043            let content = GlobalKey::new();
6044            let mut app = KeyboardInsetApp::new(200.0);
6045            app.resize_to_avoid_bottom_inset = false;
6046            tester.pump_widget(app.build(tester, &content));
6047            assert_eq!(rect_of_key(tester, &content).top, 500.0);
6048            assert_eq!(rect_of_key(tester, &content).bottom, 600.0);
6049            assert_eq!(inset_sheet_material(tester).top, 500.0);
6050            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6051        });
6052    }
6053
6054    #[test]
6055    fn the_sheet_material_stops_above_a_bottom_navigation_bar() {
6056        test_widgets(|tester| {
6057            let content = GlobalKey::new();
6058            let mut app = KeyboardInsetApp::new(200.0);
6059            app.bottom_navigation_bar = Some(SizedBox::new().height(50.0).into_widget());
6060            tester.pump_widget(app.build(tester, &content));
6061            assert_eq!(rect_of_key(tester, &content).top, 300.0);
6062            assert_eq!(rect_of_key(tester, &content).bottom, 400.0);
6063            // Extends down to the top of the bottom navigation bar, not past it.
6064            assert_eq!(inset_sheet_material(tester).top, 300.0);
6065            assert_eq!(inset_sheet_material(tester).bottom, 550.0);
6066        });
6067    }
6068
6069    #[test]
6070    fn a_docked_floating_action_button_straddles_the_top_edge_of_the_sheet_content() {
6071        test_widgets(|tester| {
6072            let content = GlobalKey::new();
6073            let fab_center_y = |tester: &WidgetTester| {
6074                let fab = find::by_type::<crate::floating_action_button::FloatingActionButton>()
6075                    .evaluate(tester)[0];
6076                tester.get_rect(fab).center().dy()
6077            };
6078            let app = |keyboard_height: f64| {
6079                let mut app = KeyboardInsetApp::new(keyboard_height);
6080                app.floating_action_button = Some(docked_fab());
6081                app.floating_action_button_location =
6082                    Some(<dyn crate::FloatingActionButtonLocation>::center_docked());
6083                app
6084            };
6085
6086            tester.pump_widget(app(0.0).build(tester, &content));
6087            // Within f32: global positions go through valo's f32 matrices (waft-gestures' Matrix4 entry), where Dart's are f64 and compare equal.
6088            assert_f32_equals(fab_center_y(tester), 500.0);
6089
6090            tester.pump_widget(app(200.0).build(tester, &content));
6091            tester.pump_and_settle();
6092            // Top of the content (300), not the top of the extended Material.
6093            assert_f32_equals(fab_center_y(tester), 300.0);
6094        });
6095    }
6096
6097    #[test]
6098    fn the_keyboard_appearing_keeps_the_sheet_contents_state_and_focus() {
6099        test_widgets(|tester| {
6100            let content = GlobalKey::new();
6101            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut());
6102            let sheet = || {
6103                SizedBox::new()
6104                    .height(100.0)
6105                    .child(crate::text_field::TextField::new().focus_node(focus_node.erase()))
6106                    .into_widget()
6107            };
6108            let app = |keyboard_height: f64| {
6109                let mut app = KeyboardInsetApp::new(keyboard_height);
6110                app.bottom_sheet = Some(sheet());
6111                app
6112            };
6113            let has_focus =
6114                |tester: &WidgetTester| focus_node.has_focus(&mut tester.cell.borrow_mut());
6115
6116            tester.pump_widget(app(0.0).build(tester, &content));
6117            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
6118            tester.pump();
6119            assert!(has_focus(tester));
6120            // The `EditableText`'s element, which holds its state.
6121            let before = only(find::by_type::<waft_widgets::EditableText>().evaluate(tester));
6122
6123            tester.pump_widget(app(200.0).build(tester, &content));
6124            tester.pump();
6125            assert!(has_focus(tester));
6126            assert_eq!(
6127                only(find::by_type::<waft_widgets::EditableText>().evaluate(tester)),
6128                before
6129            );
6130        });
6131    }
6132
6133    #[test]
6134    fn a_shown_bottom_sheet_can_still_be_flung_closed_with_the_keyboard_up() {
6135        test_widgets(|tester| {
6136            let scaffold_key = GlobalKey::new();
6137            tester.pump_widget(keyboard_app_with_scaffold(tester, 200.0, &scaffold_key));
6138            let scaffold = scaffold_state(tester, &scaffold_key);
6139            Persistent::default().show(tester, scaffold, sheet_of_height(100.0));
6140            tester.pump_and_settle();
6141            assert_eq!(rect_of_text(tester, "sheet").bottom, 400.0);
6142            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6143
6144            fling_text(tester, "sheet", Offset::new(0.0, 300.0), 2000.0);
6145            tester.pump_and_settle();
6146            assert_eq!(found(tester, "sheet"), 0);
6147        });
6148    }
6149
6150    #[test]
6151    fn a_shown_bottom_sheet_follows_the_drag_with_the_keyboard_up() {
6152        test_widgets(|tester| {
6153            const KEYBOARD_HEIGHT: f64 = 200.0;
6154            const CONTENT_HEIGHT: f64 = 100.0;
6155            const MATERIAL_HEIGHT: f64 = CONTENT_HEIGHT + KEYBOARD_HEIGHT;
6156            // The content is at the top of the Material, which ends at the bottom of
6157            // the 600px tall test screen.
6158            const CONTENT_TOP: f64 = 600.0 - MATERIAL_HEIGHT;
6159            let scaffold_key = GlobalKey::new();
6160            tester.pump_widget(keyboard_app_with_scaffold(
6161                tester,
6162                KEYBOARD_HEIGHT,
6163                &scaffold_key,
6164            ));
6165            let scaffold = scaffold_state(tester, &scaffold_key);
6166            Persistent::default().show(tester, scaffold, sheet_of_height(CONTENT_HEIGHT));
6167            tester.pump_and_settle();
6168            assert_eq!(rect_of_text(tester, "sheet").top, CONTENT_TOP);
6169            assert_eq!(inset_sheet_material(tester).height(), MATERIAL_HEIGHT);
6170
6171            // The whole sheet moves with the finger.
6172            const DRAG_DISTANCE: f64 = 100.0;
6173            let mut gesture = TestPointer::touch(1);
6174            let center = center_of_text(tester, "sheet");
6175            tester.down(&mut gesture, center);
6176            let move_by = |tester: &mut WidgetTester, gesture: &mut TestPointer, dy: f64| {
6177                let at = gesture.position + Offset::new(0.0, dy);
6178                tester.move_to(gesture, at, true);
6179            };
6180            move_by(tester, &mut gesture, 20.0); // Past the touch slop.
6181            tester.pump();
6182            move_by(tester, &mut gesture, DRAG_DISTANCE);
6183            tester.pump();
6184            assert_eq!(
6185                rect_of_text(tester, "sheet").top,
6186                CONTENT_TOP + DRAG_DISTANCE
6187            );
6188
6189            // More than half of the content, but less than half of the whole sheet,
6190            // including the part behind the keyboard: springs back open.
6191            tester.up(&gesture);
6192            tester.pump_and_settle();
6193            assert_eq!(rect_of_text(tester, "sheet").top, CONTENT_TOP);
6194
6195            // More than half of the whole sheet: closes.
6196            drag_text(tester, "sheet", Offset::new(0.0, MATERIAL_HEIGHT * 0.75));
6197            tester.pump_and_settle();
6198            assert_eq!(found(tester, "sheet"), 0);
6199        });
6200    }
6201
6202    #[test]
6203    fn the_max_height_constraint_bounds_the_content_not_the_material_behind_the_keyboard() {
6204        test_widgets(|tester| {
6205            let scaffold_key = GlobalKey::new();
6206            tester.pump_widget(keyboard_app_with_scaffold(tester, 200.0, &scaffold_key));
6207            let scaffold = scaffold_state(tester, &scaffold_key);
6208            Persistent {
6209                constraints: Some(BoxConstraints::new().max_height(250.0)),
6210                ..Persistent::default()
6211            }
6212            .show(tester, scaffold, sheet_of_height(400.0));
6213            tester.pump_and_settle();
6214            // The content gets the full 250 it is allowed, above the keyboard.
6215            assert_eq!(rect_of_text(tester, "sheet").top, 150.0);
6216            assert_eq!(rect_of_text(tester, "sheet").bottom, 400.0);
6217            // The Material is 250 + 200.
6218            assert_eq!(inset_sheet_material(tester).top, 150.0);
6219            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6220        });
6221    }
6222
6223    #[test]
6224    fn taps_in_the_material_behind_the_keyboard_do_not_reach_the_content() {
6225        test_widgets(|tester| {
6226            let content = GlobalKey::new();
6227            let tap_count = Rc::new(Cell::new(0));
6228            let mut app = KeyboardInsetApp::new(200.0);
6229            app.bottom_sheet = Some({
6230                let tap_count = Rc::clone(&tap_count);
6231                SizedBox::new()
6232                    .height(100.0)
6233                    .child(
6234                        waft_widgets::GestureDetector::new()
6235                            .behavior(waft_rendering::HitTestBehavior::Opaque)
6236                            .on_tap(waft_foundation::Listener::new(move |_| {
6237                                tap_count.set(tap_count.get() + 1)
6238                            }))
6239                            .child(text("sheet")),
6240                    )
6241                    .into_widget()
6242            });
6243            tester.pump_widget(app.build(tester, &content));
6244            assert_eq!(rect_of_text(tester, "sheet").bottom, 400.0);
6245            assert_eq!(inset_sheet_material(tester).bottom, 600.0);
6246
6247            // Inside the content.
6248            tester.tap_at(Offset::new(400.0, 350.0), 1);
6249            assert_eq!(tap_count.get(), 1);
6250
6251            // In the inset region, which only the keyboard can reach: the sheet's
6252            // Material absorbs the tap (as the Scaffold's own Material did before it
6253            // was covered), and the content is not hit.
6254            tester.tap_at(Offset::new(400.0, 500.0), 2);
6255            assert_eq!(tap_count.get(), 1);
6256        });
6257    }
6258
6259    #[test]
6260    fn a_scaffold_shorter_than_the_keyboard_inset_keeps_the_sheet_inside_its_bounds() {
6261        test_widgets(|tester| {
6262            let content = GlobalKey::new();
6263            // A 250px tall Scaffold centered on the 600px screen, so it spans y 175..425.
6264            let nested = |tester: &WidgetTester, keyboard_height: f64| {
6265                let theme = ThemeData::builder()
6266                    .bottom_sheet_theme(
6267                        BottomSheetThemeData::new()
6268                            .constraints(BoxConstraints::tight_for(None, Some(150.0))),
6269                    )
6270                    .build(&tester.cell.borrow());
6271                material_app(
6272                    theme,
6273                    MediaQuery::new(
6274                        waft_widgets::MediaQueryData::new().view_insets(EdgeInsets::only(
6275                            0.0,
6276                            0.0,
6277                            0.0,
6278                            keyboard_height,
6279                        )),
6280                        Center::new().child(
6281                            SizedBox::new().width(320.0).height(250.0).child(
6282                                Scaffold::new()
6283                                    .body(SizedBox::expand())
6284                                    .bottom_sheet(SizedBox::expand().key(content.clone().into())),
6285                            ),
6286                        ),
6287                    )
6288                    .into_widget(),
6289                )
6290            };
6291
6292            for keyboard_height in [0.0, 200.0, 400.0, 0.0] {
6293                tester.pump_widget(nested(tester, keyboard_height));
6294                tester.pump_and_settle();
6295                // The content gets whatever is left above the keyboard, at most the
6296                // theme's 150, exactly as before.
6297                assert_eq!(
6298                    rect_of_key(tester, &content).height(),
6299                    (250.0 - keyboard_height).clamp(0.0, 150.0)
6300                );
6301                // The Material always ends at the Scaffold's bottom edge and never
6302                // leaves the Scaffold, without any clipping.
6303                assert_eq!(inset_sheet_material(tester).bottom, 425.0);
6304                assert!(inset_sheet_material(tester).top >= 175.0);
6305            }
6306        });
6307    }
6308
6309    #[test]
6310    fn a_bottom_sheet_given_as_the_scaffolds_bottom_sheet_is_not_extended_twice() {
6311        test_widgets(|tester| {
6312            let content = GlobalKey::new();
6313            let mut app = KeyboardInsetApp::new(200.0);
6314            app.bottom_sheet = Some({
6315                let content = content.clone();
6316                BottomSheet::new(
6317                    Rc::new(|_app: &mut App| {}),
6318                    Rc::new(move |_app, _context| {
6319                        SizedBox::new()
6320                            .key(content.clone().into())
6321                            .width(f64::INFINITY)
6322                            .height(100.0)
6323                            .into_widget()
6324                    }),
6325                )
6326                .enable_drag(false)
6327                .into_widget()
6328            });
6329            tester.pump_widget(app.build(tester, &content));
6330            expect(tester, &find::by_type::<BottomSheet>(), finds_n_widgets(2));
6331
6332            // Only the Scaffold's own sheet extends behind the keyboard. The user's
6333            // sheet, and its Material, end with the content.
6334            assert_eq!(rect_of_key(tester, &content).bottom, 400.0);
6335            assert_eq!(material_of_sheet(tester, 0).bottom, 600.0);
6336            assert_eq!(material_of_sheet(tester, 1).bottom, 400.0);
6337        });
6338    }
6339
6340    // bottom_sheet_theme_test.dart
6341
6342    fn bottom_sheet_in_scaffold(theme: ThemeData, sheet: BottomSheet) -> WidgetRef {
6343        material_app(theme, Scaffold::new().body(sheet).into_widget())
6344    }
6345
6346    fn plain_sheet() -> BottomSheet {
6347        BottomSheet::new(
6348            Rc::new(|_app| {}),
6349            Rc::new(|_app, _context| Container::new().into_widget()),
6350        )
6351    }
6352
6353    /// Dart's `_bottomSheetTheme()`.
6354    fn orange_bottom_sheet_theme() -> BottomSheetThemeData {
6355        BottomSheetThemeData::new()
6356            .background_color(Colors::ORANGE.primary())
6357            .elevation(12.0)
6358            .shape(waft_painting::BeveledRectangleBorder::new(
6359                waft_painting::BorderSide::NONE,
6360                waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(12.0)),
6361            ))
6362            .clip_behavior(Clip::AntiAlias)
6363    }
6364
6365    fn shape_eq(a: Option<&dyn ShapeBorder>, b: Option<&dyn ShapeBorder>) -> bool {
6366        match (a, b) {
6367            (Some(a), Some(b)) => *a == *b,
6368            (None, None) => true,
6369            _ => false,
6370        }
6371    }
6372
6373    /// Dart's 'Material3 - Passing no BottomSheetThemeData returns defaults'.
6374    #[test]
6375    fn material3_passing_no_bottom_sheet_theme_returns_defaults() {
6376        test_widgets(|tester| {
6377            let theme = m3(tester);
6378            let surface_container_low = theme.color_scheme.surface_container_low();
6379            tester.pump_widget(bottom_sheet_in_scaffold(theme, plain_sheet()));
6380
6381            let default_shape: ShapeBorderRef =
6382                ShapeBorderRef::new(waft_painting::RoundedRectangleBorder::new(
6383                    waft_painting::BorderSide::NONE,
6384                    waft_painting::BorderRadiusGeometry::vertical(
6385                        waft_embedder::Radius::circular(28.0),
6386                        waft_embedder::Radius::ZERO,
6387                    ),
6388                ));
6389            tester.widget(sheet_material(tester), |material: &Material| {
6390                assert_eq!(material.color, Some(surface_container_low));
6391                assert_eq!(material.elevation, 1.0);
6392                assert!(shape_eq(material.shape.as_deref(), Some(&*default_shape)));
6393                assert_eq!(material.clip_behavior, Clip::None);
6394            });
6395        });
6396    }
6397
6398    /// Dart's 'Material2 - Passing no BottomSheetThemeData returns defaults'.
6399    #[test]
6400    fn material2_passing_no_bottom_sheet_theme_returns_defaults() {
6401        test_widgets(|tester| {
6402            tester.pump_widget(bottom_sheet_in_scaffold(m2(tester), plain_sheet()));
6403
6404            tester.widget(sheet_material(tester), |material: &Material| {
6405                assert_eq!(material.color, None);
6406                assert_eq!(material.elevation, 0.0);
6407                assert!(material.shape.is_none());
6408                assert_eq!(material.clip_behavior, Clip::None);
6409            });
6410        });
6411    }
6412
6413    /// Dart's 'BottomSheet uses values from BottomSheetThemeData'.
6414    #[test]
6415    fn a_bottom_sheet_uses_values_from_the_bottom_sheet_theme() {
6416        test_widgets(|tester| {
6417            let bottom_sheet_theme = orange_bottom_sheet_theme();
6418            let theme = ThemeData::builder()
6419                .bottom_sheet_theme(bottom_sheet_theme.clone())
6420                .build(&tester.cell.borrow());
6421            tester.pump_widget(bottom_sheet_in_scaffold(theme, plain_sheet()));
6422
6423            tester.widget(sheet_material(tester), |material: &Material| {
6424                assert_eq!(material.color, bottom_sheet_theme.background_color);
6425                assert_eq!(Some(material.elevation), bottom_sheet_theme.elevation);
6426                assert!(shape_eq(
6427                    material.shape.as_deref(),
6428                    bottom_sheet_theme.shape.as_deref()
6429                ));
6430                assert_eq!(
6431                    Some(material.clip_behavior),
6432                    bottom_sheet_theme.clip_behavior
6433                );
6434            });
6435        });
6436    }
6437
6438    /// Dart's 'BottomSheet widget properties take priority over theme'.
6439    #[test]
6440    fn bottom_sheet_widget_properties_take_priority_over_the_theme() {
6441        test_widgets(|tester| {
6442            let background_color = Colors::PURPLE.primary();
6443            let shadow_color = Colors::BLUE.primary();
6444            let elevation = 7.0;
6445            let shape: ShapeBorderRef =
6446                ShapeBorderRef::new(waft_painting::RoundedRectangleBorder::new(
6447                    waft_painting::BorderSide::NONE,
6448                    waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(9.0)),
6449                ));
6450            let clip_behavior = Clip::HardEdge;
6451
6452            let theme = ThemeData::builder()
6453                .bottom_sheet_theme(orange_bottom_sheet_theme())
6454                .build(&tester.cell.borrow());
6455            tester.pump_widget(bottom_sheet_in_scaffold(
6456                theme,
6457                plain_sheet()
6458                    .background_color(background_color)
6459                    .shadow_color(shadow_color)
6460                    .elevation(elevation)
6461                    .shape(shape.clone())
6462                    .clip_behavior(Clip::HardEdge),
6463            ));
6464
6465            tester.widget(sheet_material(tester), |material: &Material| {
6466                assert_eq!(material.color, Some(background_color));
6467                assert_eq!(material.shadow_color, Some(shadow_color));
6468                assert_eq!(material.elevation, elevation);
6469                assert!(shape_eq(material.shape.as_deref(), Some(&*shape)));
6470                assert_eq!(material.clip_behavior, clip_behavior);
6471            });
6472        });
6473    }
6474
6475    /// Dart's `bottomSheetWithElevations`: a scaffold whose body's context the case shows
6476    /// sheets from, where Dart's `RawMaterialButton`s show them.
6477    fn bottom_sheet_with_elevations(
6478        tester: &WidgetTester,
6479        bottom_sheet_theme: BottomSheetThemeData,
6480        use_material3: bool,
6481        saved: &Saved,
6482    ) -> WidgetRef {
6483        let theme = ThemeData::builder()
6484            .bottom_sheet_theme(bottom_sheet_theme)
6485            .use_material3(use_material3)
6486            .build(&tester.cell.borrow());
6487        material_app(
6488            theme,
6489            Scaffold::new()
6490                .body(saved.builder(|| Container::new().into_widget()))
6491                .into_widget(),
6492        )
6493    }
6494
6495    /// Dart's 'Show Modal' button.
6496    fn show_modal_from(tester: &WidgetTester, saved: &Saved) {
6497        Modal::default().show(
6498            tester,
6499            saved.get(),
6500            sheet_builder("This is a modal bottom sheet."),
6501        );
6502    }
6503
6504    /// Dart's 'Show Persistent' button.
6505    fn show_persistent_from(tester: &WidgetTester, saved: &Saved) {
6506        {
6507            let show = ShowBottomSheet::new(sheet_builder("This is a persistent bottom sheet."));
6508            show.show(&mut tester.cell.borrow_mut(), saved.get())
6509        };
6510    }
6511
6512    /// Dart's 'Modal bottom sheet-specific parameters are used for modal bottom sheets'.
6513    #[test]
6514    fn modal_specific_theme_parameters_are_used_for_modal_bottom_sheets() {
6515        test_widgets(|tester| {
6516            let saved = Saved::default();
6517            let modal_elevation = 5.0;
6518            let persistent_elevation = 7.0;
6519            let modal_background_color = Colors::YELLOW.primary();
6520            let modal_barrier_color = Colors::BLUE.primary();
6521            let persistent_background_color = Colors::RED.primary();
6522            let bottom_sheet_theme = BottomSheetThemeData::new()
6523                .elevation(persistent_elevation)
6524                .modal_elevation(modal_elevation)
6525                .background_color(persistent_background_color)
6526                .modal_background_color(modal_background_color)
6527                .modal_barrier_color(modal_barrier_color);
6528
6529            tester.pump_widget(bottom_sheet_with_elevations(
6530                tester,
6531                bottom_sheet_theme,
6532                true,
6533                &saved,
6534            ));
6535            show_modal_from(tester, &saved);
6536            tester.pump_and_settle();
6537
6538            tester.widget(sheet_material(tester), |material: &Material| {
6539                assert_eq!(material.elevation, modal_elevation);
6540                assert_eq!(material.color, Some(modal_background_color));
6541            });
6542
6543            let modal_barrier = *find::by_type::<ModalBarrier>()
6544                .evaluate(tester)
6545                .last()
6546                .expect("a modal barrier");
6547            tester.widget(modal_barrier, |modal_barrier: &ModalBarrier| {
6548                assert_eq!(modal_barrier.color, Some(modal_barrier_color));
6549            });
6550        });
6551    }
6552
6553    /// Dart's 'General bottom sheet parameters take priority over modal bottom
6554    /// sheet-specific parameters for persistent bottom sheets'.
6555    #[test]
6556    fn general_theme_parameters_win_over_modal_ones_for_persistent_bottom_sheets() {
6557        test_widgets(|tester| {
6558            let saved = Saved::default();
6559            let modal_elevation = 5.0;
6560            let persistent_elevation = 7.0;
6561            let modal_background_color = Colors::YELLOW.primary();
6562            let persistent_background_color = Colors::RED.primary();
6563            let bottom_sheet_theme = BottomSheetThemeData::new()
6564                .elevation(persistent_elevation)
6565                .modal_elevation(modal_elevation)
6566                .background_color(persistent_background_color)
6567                .modal_background_color(modal_background_color);
6568
6569            tester.pump_widget(bottom_sheet_with_elevations(
6570                tester,
6571                bottom_sheet_theme,
6572                true,
6573                &saved,
6574            ));
6575            show_persistent_from(tester, &saved);
6576            tester.pump_and_settle();
6577
6578            tester.widget(sheet_material(tester), |material: &Material| {
6579                assert_eq!(material.elevation, persistent_elevation);
6580                assert_eq!(material.color, Some(persistent_background_color));
6581            });
6582        });
6583    }
6584
6585    /// Dart's "Material3 - Modal bottom sheet-specific parameters don't apply to persistent
6586    /// bottom sheets".
6587    #[test]
6588    fn material3_modal_theme_parameters_do_not_apply_to_persistent_bottom_sheets() {
6589        test_widgets(|tester| {
6590            let saved = Saved::default();
6591            let bottom_sheet_theme = BottomSheetThemeData::new()
6592                .modal_elevation(5.0)
6593                .modal_background_color(Colors::YELLOW.primary());
6594
6595            tester.pump_widget(bottom_sheet_with_elevations(
6596                tester,
6597                bottom_sheet_theme,
6598                true,
6599                &saved,
6600            ));
6601            show_persistent_from(tester, &saved);
6602            tester.pump_and_settle();
6603
6604            let surface_container_low = Theme::of(&mut tester.cell.borrow_mut(), saved.get())
6605                .color_scheme
6606                .surface_container_low();
6607            tester.widget(sheet_material(tester), |material: &Material| {
6608                assert_eq!(material.elevation, 1.0);
6609                assert_eq!(material.color, Some(surface_container_low));
6610            });
6611        });
6612    }
6613
6614    /// Dart's "Material2 - Modal bottom sheet-specific parameters don't apply to persistent
6615    /// bottom sheets".
6616    #[test]
6617    fn material2_modal_theme_parameters_do_not_apply_to_persistent_bottom_sheets() {
6618        test_widgets(|tester| {
6619            let saved = Saved::default();
6620            let bottom_sheet_theme = BottomSheetThemeData::new()
6621                .modal_elevation(5.0)
6622                .modal_background_color(Colors::YELLOW.primary());
6623
6624            tester.pump_widget(bottom_sheet_with_elevations(
6625                tester,
6626                bottom_sheet_theme,
6627                false,
6628                &saved,
6629            ));
6630            show_persistent_from(tester, &saved);
6631            tester.pump_and_settle();
6632
6633            tester.widget(sheet_material(tester), |material: &Material| {
6634                assert_eq!(material.elevation, 0.0);
6635                assert_eq!(material.color, None);
6636            });
6637        });
6638    }
6639
6640    /// Dart's 'Throw if enable drag without an animation controller'. Dart catches the
6641    /// `FlutterError` the drag reports; here the debug assertion unwinds out of the drag.
6642    #[test]
6643    #[should_panic(expected = "'BottomSheet.animationController' cannot be null")]
6644    fn dragging_a_draggable_bottom_sheet_without_an_animation_controller_fails() {
6645        test_widgets(|tester| {
6646            // Regression test for https://github.com/flutter/flutter/issues/89168
6647            tester.pump_widget(material_app(
6648                m3(tester),
6649                BottomSheet::new(
6650                    Rc::new(|_app| {}),
6651                    Rc::new(|_app, _context| {
6652                        Container::new()
6653                            .height(200.0)
6654                            .color(Colors::RED.primary())
6655                            .child(text("BottomSheet"))
6656                            .into_widget()
6657                    }),
6658                )
6659                .into_widget(),
6660            ));
6661
6662            drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
6663        });
6664    }
6665
6666    /// Not a Dart case: what Dart's collector does with the curved animations and the proxy
6667    /// `_ModalBottomSheetState` makes, and with the drag-end curve each drag replaces; each is
6668    /// freed once nothing holds it.
6669    #[test]
6670    fn a_modal_bottom_sheet_frees_its_animations_as_it_disposes_them() {
6671        test_widgets(|tester| {
6672            let saved = Saved::default();
6673            tester.pump_widget(app_saving_context(tester, &saved));
6674            tester.pump();
6675            drop(Modal::default().show(tester, saved.get(), sheet_builder("BottomSheet")));
6676            tester.pump_and_settle();
6677            let state = |tester: &WidgetTester| {
6678                let sheet = find::by_type::<ModalBottomSheet>().evaluate(tester)[0];
6679                let app = tester.cell.borrow();
6680                sheet
6681                    .state_handle::<ModalBottomSheetState>(&app)
6682                    .expect("a ModalBottomSheet is stateful")
6683            };
6684            let drag_end_curve = |tester: &WidgetTester| {
6685                let state = state(tester);
6686                tester
6687                    .cell
6688                    .borrow()
6689                    .get(state)
6690                    .drag_end_curved_animation
6691                    .as_ref()
6692                    .expect("a drag ended")
6693                    .handle()
6694            };
6695            let (curved, proxy) = {
6696                let state = state(tester);
6697                let app = tester.cell.borrow();
6698                (
6699                    state.curved_sheet_animation(&app),
6700                    state.sheet_animation(&app),
6701                )
6702            };
6703
6704            drag_text(tester, "BottomSheet", Offset::new(0.0, 20.0));
6705            tester.pump_and_settle();
6706            let first_drag_end = drag_end_curve(tester);
6707            drag_text(tester, "BottomSheet", Offset::new(0.0, 20.0));
6708            tester.pump_and_settle();
6709            let second_drag_end = drag_end_curve(tester);
6710            tester.cell.checkpoint();
6711            assert!(!tester.cell.borrow().contains(first_drag_end));
6712            assert!(tester.cell.borrow().contains(second_drag_end));
6713
6714            drag_text(tester, "BottomSheet", Offset::new(0.0, 150.0));
6715            tester.pump_and_settle();
6716            assert_eq!(found(tester, "BottomSheet"), 0);
6717            tester.cell.checkpoint();
6718            let app = tester.cell.borrow();
6719            assert!(!app.contains(second_drag_end));
6720            assert!(!app.contains(curved));
6721            assert!(!app.contains(proxy));
6722        });
6723    }
6724}