Skip to main content

waft_material/
drawer.rs

1//! Flutter counterpart: material_ui's `drawer.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{
8    Animation, AnimationBehavior, AnimationController, AnimationStatus, AnimationStatusListener,
9};
10use waft_embedder::{Clip, Color, TargetPlatform, TextDirection};
11use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
12use waft_gestures::{DragDownDetails, DragEndDetails, DragStartBehavior, DragUpdateDetails};
13use waft_painting::{AlignmentGeometry, ShapeBorderRef};
14use waft_rendering::{BoxConstraints, HitTestBehavior};
15use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
16use waft_widgets::{
17    Align, AnyModalRoute, BlockSemantics, BuildContext, ColoredBox, ConstrainedBox, Directionality,
18    ExcludeSemantics, FocusNodeLeaf, FocusScope, FocusScopeNode, GestureDetector, GlobalKey,
19    InheritedWidget, IntoWidget, KeyRef, LimitedBox, LocalHistoryEntry, MediaQuery,
20    RepaintBoundary, Semantics, SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
21    SizedBox, Stack, State, StateData, StatefulWidget, StatelessWidget, WidgetRef, downcast_widget,
22};
23
24use crate::colors::Colors;
25use crate::debug::debug_check_has_material_localizations;
26use crate::drawer_theme::{DrawerTheme, DrawerThemeData, DrawerThemeDataGetters};
27use crate::generated::drawer_defaults_m3::DrawerDefaultsM3;
28use crate::list_tile::ListTileStyle;
29use crate::list_tile_theme::ListTileTheme;
30use crate::material::Material;
31use crate::material_localizations::MaterialLocalizations;
32use crate::theme::Theme;
33
34/// The possible alignments of a [`Drawer`].
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum DrawerAlignment {
37    /// Denotes that the [`Drawer`] is at the start side of the `Scaffold`.
38    ///
39    /// This corresponds to the left side when the text direction is left-to-right
40    /// and the right side when the text direction is right-to-left.
41    Start,
42
43    /// Denotes that the [`Drawer`] is at the end side of the `Scaffold`.
44    ///
45    /// This corresponds to the right side when the text direction is left-to-right
46    /// and the left side when the text direction is right-to-left.
47    End,
48}
49
50// TODO(eseidel): Draw width should vary based on device size:
51// https://material.io/design/components/navigation-drawer.html#specs
52
53// Mobile:
54// Width = Screen width − 56 dp
55// Maximum width: 320dp
56// Maximum width applies only when using a left nav. When using a right nav,
57// the panel can cover the full width of the screen.
58
59// Desktop/Tablet:
60// Maximum width for a left nav is 400dp.
61// The right nav can vary depending on content.
62
63const K_WIDTH: f64 = 304.0;
64const K_EDGE_DRAG_WIDTH: f64 = 20.0;
65const K_MIN_FLING_VELOCITY: f64 = 365.0;
66const K_BASE_SETTLE_DURATION: Duration = Duration::from_millis(246);
67
68/// A Material Design panel that slides in horizontally from the edge of a
69/// `Scaffold` to show navigation links in an application.
70///
71/// There is a Material 3 version of this component, `NavigationDrawer`,
72/// that's preferred for applications that are configured for Material 3
73/// (see `ThemeData::use_material3`).
74///
75/// Drawers are typically used with the `Scaffold::drawer` property. The child of
76/// the drawer is usually a `ListView` whose first child is a `DrawerHeader`
77/// that displays status information about the current user. The remaining
78/// drawer children are often constructed with `ListTile`s, often concluding
79/// with an `AboutListTile`.
80///
81/// The `AppBar` automatically displays an appropriate `IconButton` to show the
82/// [`Drawer`] when a [`Drawer`] is available in the `Scaffold`. The `Scaffold`
83/// automatically handles the edge-swipe gesture to show the drawer.
84///
85/// An open drawer may be closed with a swipe to close gesture, pressing the
86/// escape key, by tapping the scrim, or by calling pop route function such as
87/// `Navigator::pop`.
88///
89/// See also:
90///
91///  * `Scaffold::drawer`, where one specifies a [`Drawer`] so that it can be
92///    shown.
93///  * `Scaffold::of`, to obtain the current `ScaffoldState`, which manages the
94///    display and animation of the drawer.
95///  * `ScaffoldState::open_drawer`, which displays its [`Drawer`], if any.
96///  * <https://material.io/design/components/navigation-drawer.html>
97#[derive(Debug, Default)]
98pub struct Drawer {
99    pub key: Option<KeyRef>,
100
101    /// Sets the color of the `Material` that holds all of the [`Drawer`]'s
102    /// contents.
103    ///
104    /// If this is null, then [`DrawerThemeData::background_color`] is used. If that
105    /// is also null, then it falls back to `Material`'s default.
106    pub background_color: Option<Color>,
107
108    /// The z-coordinate at which to place this drawer relative to its parent.
109    ///
110    /// This controls the size of the shadow below the drawer.
111    ///
112    /// If this is null, then [`DrawerThemeData::elevation`] is used. If that
113    /// is also null, then it defaults to 16.0.
114    pub elevation: Option<f64>,
115
116    /// The color used to paint a drop shadow under the drawer's `Material`,
117    /// which reflects the drawer's [`elevation`](Self::elevation).
118    ///
119    /// If null and `ThemeData::use_material3` is true then no drop shadow will
120    /// be rendered.
121    ///
122    /// If null and `ThemeData::use_material3` is false then it will default to
123    /// `ThemeData::shadow_color`.
124    ///
125    /// See also:
126    ///   * `Material::shadow_color`, which describes how the drop shadow is painted.
127    ///   * [`elevation`](Self::elevation), which affects how the drop shadow is painted.
128    ///   * [`surface_tint_color`](Self::surface_tint_color), which can be used to indicate
129    ///     elevation through tinting the background color.
130    pub shadow_color: Option<Color>,
131
132    /// The color used as a surface tint overlay on the drawer's background color,
133    /// which reflects the drawer's [`elevation`](Self::elevation).
134    ///
135    /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
136    /// introduced a set of tone-based surfaces and surface containers in its `ColorScheme`,
137    /// which provide more flexibility. The intention is to eventually remove surface tint color from
138    /// the framework.
139    ///
140    /// To disable this feature, set [`surface_tint_color`](Self::surface_tint_color) to
141    /// `Colors::TRANSPARENT`.
142    ///
143    /// Defaults to `Colors::TRANSPARENT`.
144    ///
145    /// See also:
146    ///   * `Material::surface_tint_color`, which describes how the surface tint will
147    ///     be applied to the background color of the drawer.
148    ///   * [`elevation`](Self::elevation), which affects the opacity of the surface tint.
149    ///   * [`shadow_color`](Self::shadow_color), which can be used to indicate elevation
150    ///     through a drop shadow.
151    pub surface_tint_color: Option<Color>,
152
153    /// The shape of the drawer.
154    ///
155    /// Defines the drawer's `Material::shape`.
156    ///
157    /// If this is null, then [`DrawerThemeData::shape`] is used. If that
158    /// is also null, then it falls back to `Material`'s default.
159    pub shape: Option<ShapeBorderRef>,
160
161    /// The width of the drawer.
162    ///
163    /// If this is null, then [`DrawerThemeData::width`] is used. If that is also
164    /// null, then it falls back to the Material spec's default (304.0).
165    pub width: Option<f64>,
166
167    /// The widget below this widget in the tree.
168    ///
169    /// Typically a `ListView`.
170    pub child: Option<WidgetRef>,
171
172    /// The semantic label of the drawer used by accessibility frameworks to
173    /// announce screen transitions when the drawer is opened and closed.
174    ///
175    /// If this label is not provided, it will default to
176    /// `MaterialLocalizations::drawer_label`.
177    pub semantic_label: Option<String>,
178
179    /// The `clip_behavior` argument specifies how to clip the drawer's
180    /// [`shape`](Self::shape).
181    ///
182    /// If the drawer has a [`shape`](Self::shape), it defaults to [`Clip::HardEdge`].
183    /// Otherwise, defaults to [`Clip::None`].
184    pub clip_behavior: Option<Clip>,
185}
186
187impl Drawer {
188    /// Creates a Material Design drawer; Dart's optional named arguments are the setters.
189    ///
190    /// Typically used in the `Scaffold::drawer` property.
191    ///
192    /// The [`elevation`](Self::elevation) must be non-negative.
193    pub fn new() -> Drawer {
194        Drawer::default()
195    }
196
197    /// Dart `Drawer(key:)`.
198    pub fn key(mut self, key: KeyRef) -> Drawer {
199        self.key = Some(key);
200        self
201    }
202
203    /// Dart `Drawer(backgroundColor:)`.
204    pub fn background_color(mut self, background_color: Color) -> Drawer {
205        self.background_color = Some(background_color);
206        self
207    }
208
209    /// Dart `Drawer(elevation:)`.
210    pub fn elevation(mut self, elevation: f64) -> Drawer {
211        debug_assert!(elevation >= 0.0);
212        self.elevation = Some(elevation);
213        self
214    }
215
216    /// Dart `Drawer(shadowColor:)`.
217    pub fn shadow_color(mut self, shadow_color: Color) -> Drawer {
218        self.shadow_color = Some(shadow_color);
219        self
220    }
221
222    /// Dart `Drawer(surfaceTintColor:)`.
223    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> Drawer {
224        self.surface_tint_color = Some(surface_tint_color);
225        self
226    }
227
228    /// Dart `Drawer(shape:)`.
229    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> Drawer {
230        self.shape = Some(shape.into());
231        self
232    }
233
234    /// Dart `Drawer(width:)`.
235    pub fn width(mut self, width: f64) -> Drawer {
236        self.width = Some(width);
237        self
238    }
239
240    /// Dart `Drawer(child:)`.
241    #[cfg_attr(debug_assertions, track_caller)]
242    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Drawer {
243        self.child = Some(child.into_widget());
244        self
245    }
246
247    /// Dart `Drawer(semanticLabel:)`.
248    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> Drawer {
249        self.semantic_label = Some(semantic_label.into());
250        self
251    }
252
253    /// Dart `Drawer(clipBehavior:)`.
254    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Drawer {
255        self.clip_behavior = Some(clip_behavior);
256        self
257    }
258}
259
260impl StatelessWidget for Drawer {
261    fn key(&self) -> Option<&KeyRef> {
262        self.key.as_ref()
263    }
264
265    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
266        debug_assert!(debug_check_has_material_localizations(app, context));
267        let drawer_theme = DrawerTheme::of(app, context);
268        let label = match app.platform().target_platform() {
269            TargetPlatform::IOS | TargetPlatform::MacOS => self.semantic_label.clone(),
270            TargetPlatform::Android
271            | TargetPlatform::Fuchsia
272            | TargetPlatform::Linux
273            | TargetPlatform::Windows => {
274                Some(self.semantic_label.clone().unwrap_or_else(|| {
275                    <dyn MaterialLocalizations>::of(app, context).drawer_label()
276                }))
277            }
278        };
279        let use_material3 = Theme::of(app, context).use_material3;
280        let is_drawer_start = DrawerController::maybe_of(app, context)
281            .map(|controller| controller.alignment)
282            != Some(DrawerAlignment::End);
283        let defaults: Box<dyn DrawerThemeDataGetters> = if use_material3 {
284            Box::new(DrawerDefaultsM3::new(context))
285        } else {
286            Box::new(DrawerDefaultsM2::new(context))
287        };
288        let effective_shape: Option<ShapeBorderRef> = self.shape.clone().or_else(|| {
289            if is_drawer_start {
290                drawer_theme.shape.clone().or_else(|| defaults.shape(app))
291            } else {
292                drawer_theme
293                    .end_shape
294                    .clone()
295                    .or_else(|| defaults.end_shape(app))
296            }
297        });
298        let clip_behavior = if effective_shape.is_some() {
299            self.clip_behavior
300                .or(drawer_theme.clip_behavior)
301                .or_else(|| defaults.clip_behavior(app))
302                .expect("the defaults give a clip behavior")
303        } else {
304            Clip::None
305        };
306        let mut material = Material::new()
307            .elevation(
308                self.elevation
309                    .or(drawer_theme.elevation)
310                    .or_else(|| defaults.elevation(app))
311                    .expect("the defaults give an elevation"),
312            )
313            .clip_behavior(clip_behavior);
314        material.color = self
315            .background_color
316            .or(drawer_theme.background_color)
317            .or_else(|| defaults.background_color(app));
318        material.shadow_color = self
319            .shadow_color
320            .or(drawer_theme.shadow_color)
321            .or_else(|| defaults.shadow_color(app));
322        material.surface_tint_color = self
323            .surface_tint_color
324            .or(drawer_theme.surface_tint_color)
325            .or_else(|| defaults.surface_tint_color(app));
326        material.shape = effective_shape;
327        material.child = self.child.clone();
328        let mut semantics = Semantics::new()
329            .scopes_route(true)
330            .names_route(true)
331            .explicit_child_nodes(true);
332        if let Some(label) = label {
333            semantics = semantics.label(label);
334        }
335        semantics
336            .child(
337                ConstrainedBox::new(BoxConstraints::expand(
338                    Some(self.width.or(drawer_theme.width).unwrap_or(K_WIDTH)),
339                    None,
340                ))
341                .child(material),
342            )
343            .into_widget()
344    }
345}
346
347/// Signature for the callback that's called when a [`DrawerController`] is
348/// opened or closed.
349pub type DrawerCallback = Rc<dyn Fn(&mut App, bool)>;
350
351/// Dart's `_DrawerControllerScope`.
352#[derive(Debug)]
353struct DrawerControllerScope {
354    /// The [`DrawerController`] widget, held as the reference the element was given.
355    controller: WidgetRef,
356    child: WidgetRef,
357}
358
359impl DrawerControllerScope {
360    fn controller(&self) -> &DrawerController {
361        downcast_widget::<DrawerController>(&*self.controller)
362            .expect("the scope holds a DrawerController")
363    }
364}
365
366impl InheritedWidget for DrawerControllerScope {
367    fn key(&self) -> Option<&KeyRef> {
368        None
369    }
370
371    fn child(&self) -> &WidgetRef {
372        &self.child
373    }
374
375    fn update_should_notify(&self, old: &DrawerControllerScope) -> bool {
376        !Rc::ptr_eq(&self.controller, &old.controller)
377    }
378}
379
380/// Provides interactive behavior for [`Drawer`] widgets.
381///
382/// Rarely used directly. Drawer controllers are typically created automatically
383/// by `Scaffold` widgets.
384///
385/// The drawer controller provides the ability to open and close a drawer, either
386/// via an animation or via user interaction. When closed, the drawer collapses
387/// to a translucent gesture detector that can be used to listen for edge
388/// swipes.
389///
390/// See also:
391///
392///  * [`Drawer`], a container with the default width of a drawer.
393///  * `Scaffold::drawer`, the `Scaffold` slot for showing a drawer.
394pub struct DrawerController {
395    pub key: Option<KeyRef>,
396
397    /// The widget below this widget in the tree.
398    ///
399    /// Typically a [`Drawer`].
400    pub child: WidgetRef,
401
402    /// The alignment of the [`Drawer`].
403    ///
404    /// This controls the direction in which the user should swipe to open and
405    /// close the drawer.
406    pub alignment: DrawerAlignment,
407
408    /// Optional callback that is called when a [`Drawer`] is opened or closed.
409    pub drawer_callback: Option<DrawerCallback>,
410
411    /// Whether tapping the barrier behind the [`Drawer`] dismisses it.
412    ///
413    /// Defaults to true.
414    ///
415    /// If false, tapping the barrier will not dismiss the drawer.
416    pub drawer_barrier_dismissible: bool,
417
418    /// Determines the way that drag start behavior is handled.
419    ///
420    /// If set to [`DragStartBehavior::Start`], the drag behavior used for opening
421    /// and closing a drawer will begin at the position where the drag gesture won
422    /// the arena. If set to [`DragStartBehavior::Down`] it will begin at the position
423    /// where a down event is first detected.
424    ///
425    /// In general, setting this to [`DragStartBehavior::Start`] will make drag
426    /// animation smoother and setting it to [`DragStartBehavior::Down`] will make
427    /// drag behavior feel slightly more reactive.
428    ///
429    /// By default, the drag start behavior is [`DragStartBehavior::Start`].
430    ///
431    /// See also:
432    ///
433    ///  * `DragGestureRecognizer::drag_start_behavior`, which gives an example for
434    ///    the different behaviors.
435    pub drag_start_behavior: DragStartBehavior,
436
437    /// The color to use for the scrim that obscures the underlying content while
438    /// a drawer is open.
439    ///
440    /// If this is null, then [`DrawerThemeData::scrim_color`] is used. If that
441    /// is also null, then it defaults to `Colors::BLACK54`.
442    pub scrim_color: Option<Color>,
443
444    /// Determines if the [`Drawer`] can be opened with a drag gesture.
445    ///
446    /// By default, the drag gesture is enabled.
447    pub enable_open_drag_gesture: bool,
448
449    /// The width of the area within which a horizontal swipe will open the
450    /// drawer.
451    ///
452    /// By default, the value used is 20.0 added to the padding edge of
453    /// `MediaQuery::padding_of(context)` that corresponds to [`alignment`](Self::alignment).
454    /// This ensures that the drag area for notched devices is not obscured. For
455    /// example, if [`alignment`](Self::alignment) is set to [`DrawerAlignment::Start`] and
456    /// `Directionality::of(context)` is set to [`TextDirection::Ltr`],
457    /// 20.0 will be added to `MediaQuery::padding_of(context).left`.
458    pub edge_drag_width: Option<f64>,
459
460    /// Whether or not the drawer is opened or closed.
461    ///
462    /// This parameter is primarily used by the state restoration framework
463    /// to restore the drawer's animation controller to the open or closed state
464    /// depending on what was last saved to the target platform before the
465    /// application was killed.
466    pub is_drawer_open: bool,
467}
468
469impl DrawerController {
470    /// Creates a controller for a [`Drawer`]; Dart's optional named arguments are the
471    /// setters.
472    ///
473    /// Rarely used directly.
474    ///
475    /// The [`child`](Self::child) argument is typically a [`Drawer`].
476    #[cfg_attr(debug_assertions, track_caller)]
477    pub fn new<K>(child: impl IntoWidget<K>, alignment: DrawerAlignment) -> DrawerController {
478        DrawerController {
479            key: None,
480            child: child.into_widget(),
481            alignment,
482            drawer_callback: None,
483            drawer_barrier_dismissible: true,
484            drag_start_behavior: DragStartBehavior::Start,
485            scrim_color: None,
486            enable_open_drag_gesture: true,
487            edge_drag_width: None,
488            is_drawer_open: false,
489        }
490    }
491
492    /// Dart `DrawerController(key:)`.
493    pub fn key(mut self, key: GlobalKey) -> DrawerController {
494        self.key = Some(key.into());
495        self
496    }
497
498    /// Dart `DrawerController(isDrawerOpen:)`.
499    pub fn is_drawer_open(mut self, is_drawer_open: bool) -> DrawerController {
500        self.is_drawer_open = is_drawer_open;
501        self
502    }
503
504    /// Dart `DrawerController(drawerCallback:)`.
505    pub fn drawer_callback(mut self, drawer_callback: DrawerCallback) -> DrawerController {
506        self.drawer_callback = Some(drawer_callback);
507        self
508    }
509
510    /// Dart `DrawerController(dragStartBehavior:)`.
511    pub fn drag_start_behavior(
512        mut self,
513        drag_start_behavior: DragStartBehavior,
514    ) -> DrawerController {
515        self.drag_start_behavior = drag_start_behavior;
516        self
517    }
518
519    /// Dart `DrawerController(scrimColor:)`.
520    pub fn scrim_color(mut self, scrim_color: Color) -> DrawerController {
521        self.scrim_color = Some(scrim_color);
522        self
523    }
524
525    /// Dart `DrawerController(edgeDragWidth:)`.
526    pub fn edge_drag_width(mut self, edge_drag_width: f64) -> DrawerController {
527        self.edge_drag_width = Some(edge_drag_width);
528        self
529    }
530
531    /// Dart `DrawerController(enableOpenDragGesture:)`.
532    pub fn enable_open_drag_gesture(mut self, enable_open_drag_gesture: bool) -> DrawerController {
533        self.enable_open_drag_gesture = enable_open_drag_gesture;
534        self
535    }
536
537    /// Dart `DrawerController(drawerBarrierDismissible:)`.
538    pub fn drawer_barrier_dismissible(
539        mut self,
540        drawer_barrier_dismissible: bool,
541    ) -> DrawerController {
542        self.drawer_barrier_dismissible = drawer_barrier_dismissible;
543        self
544    }
545
546    /// The closest instance of [`DrawerController`] that encloses the given
547    /// context, or null if none is found.
548    ///
549    /// Typical usage is as follows:
550    ///
551    /// ```text
552    /// let controller = DrawerController::maybe_of(app, context);
553    /// ```
554    ///
555    /// Calling this method will create a dependency on the closest
556    /// [`DrawerController`] in the `context`, if there is one.
557    ///
558    /// See also:
559    ///
560    /// * [`DrawerController::of`], which is similar to this method, but asserts
561    ///   if no [`DrawerController`] ancestor is found.
562    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<&DrawerController> {
563        context
564            .depend_on_inherited_widget_of_exact_type::<DrawerControllerScope>(app)
565            .map(DrawerControllerScope::controller)
566    }
567
568    /// The closest instance of [`DrawerController`] that encloses the given
569    /// context.
570    ///
571    /// If no instance is found, this method will assert in debug mode and throw
572    /// an exception in release mode.
573    ///
574    /// Calling this method will create a dependency on the closest
575    /// [`DrawerController`] in the `context`.
576    ///
577    /// Typical usage is as follows:
578    ///
579    /// ```text
580    /// let controller = DrawerController::of(app, context);
581    /// ```
582    pub fn of(app: &mut App, context: BuildContext) -> &DrawerController {
583        if DrawerController::maybe_of(app, context).is_none() {
584            panic!(
585                "DrawerController.of() was called with a context that does not contain a \
586                 DrawerController widget.\nNo DrawerController widget ancestor could be found \
587                 starting from the context that was passed to DrawerController.of(). This can \
588                 happen because you are using a widget that looks for a DrawerController \
589                 ancestor, but no such ancestor exists.\nThe context used was:\n  {}",
590                context.widget(app).type_name(),
591            );
592        }
593        DrawerController::maybe_of(app, context).expect("checked above")
594    }
595}
596
597impl Debug for DrawerController {
598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599        f.debug_struct("DrawerController")
600            .field("key", &self.key)
601            .field("alignment", &self.alignment)
602            .field("is_drawer_open", &self.is_drawer_open)
603            .field("drag_start_behavior", &self.drag_start_behavior)
604            .field("scrim_color", &self.scrim_color)
605            .field("edge_drag_width", &self.edge_drag_width)
606            .field("enable_open_drag_gesture", &self.enable_open_drag_gesture)
607            .field(
608                "drawer_barrier_dismissible",
609                &self.drawer_barrier_dismissible,
610            )
611            .finish_non_exhaustive()
612    }
613}
614
615impl StatefulWidget for DrawerController {
616    type State = DrawerControllerState;
617
618    fn key(&self) -> Option<&KeyRef> {
619        self.key.as_ref()
620    }
621
622    fn create_state(&self) -> DrawerControllerState {
623        DrawerControllerState {
624            state: StateData::new(),
625            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
626            disposed: false,
627            history_entry: None,
628            focus_scope_node: None,
629            controller: None,
630            drawer_key: GlobalKey::new(),
631            previously_opened: false,
632            gesture_detector_key: GlobalKey::new(),
633        }
634    }
635}
636
637/// State for a [`DrawerController`].
638///
639/// Typically used by a `Scaffold` to [`open`](Self::open) and [`close`](Self::close) the
640/// drawer.
641pub struct DrawerControllerState {
642    state: StateData<DrawerController>,
643    single_ticker_provider: SingleTickerProviderStateMixinData,
644    disposed: bool,
645    history_entry: Option<Ref<LocalHistoryEntry>>,
646    /// Dart's field initializer `FocusScopeNode()`, made where `init_state` starts.
647    focus_scope_node: Option<Ref<FocusScopeNode>>,
648    controller: Option<Ref<AnimationController>>,
649    drawer_key: GlobalKey,
650    previously_opened: bool,
651    gesture_detector_key: GlobalKey,
652}
653
654impl DrawerControllerState {
655    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
656        app.get(self)
657            .controller
658            .handle()
659            .expect("created in init_state")
660    }
661
662    fn focus_scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
663        app.get(self)
664            .focus_scope_node
665            .handle()
666            .expect("created in init_state")
667    }
668
669    fn animation_changed(self: Handle<Self>, app: &mut App) {
670        self.set_state(app, |_state| {
671            // The animation controller's state is our build state, and it changed already.
672        });
673    }
674
675    fn ensure_history_entry(self: Handle<Self>, app: &mut App) {
676        if app.get(self).history_entry.is_none() {
677            let context = self.context(app);
678            let route: Option<AnyModalRoute> = AnyModalRoute::of(app, context);
679            if let Some(route) = route {
680                let history_entry = LocalHistoryEntry::new(app)
681                    .on_remove(
682                        app,
683                        Listener::handle_method(self, Self::handle_history_entry_removed),
684                    )
685                    .implies_app_bar_dismissal(app, false);
686                app.get_mut(self).history_entry = Some(history_entry.clone());
687                route.add_local_history_entry(app, history_entry);
688                let focus_scope_node = self.focus_scope_node(app);
689                FocusScope::of(app, context, true).set_first_focus(app, focus_scope_node);
690            }
691        }
692    }
693
694    fn remove_history_entry(self: Handle<Self>, app: &mut App) {
695        if let Some(history_entry) = app.get(self).history_entry.handle() {
696            history_entry.remove(app);
697        }
698        app.get_mut(self).history_entry = None;
699    }
700
701    fn animation_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
702        match status {
703            AnimationStatus::Forward => self.ensure_history_entry(app),
704            AnimationStatus::Reverse | AnimationStatus::Dismissed => {
705                self.remove_history_entry(app);
706            }
707            AnimationStatus::Completed => {}
708        }
709    }
710
711    fn handle_history_entry_removed(self: Handle<Self>, app: &mut App) {
712        app.get_mut(self).history_entry = None;
713        if app.get(self).disposed || !self.mounted(app) {
714            return;
715        }
716        let controller = self.controller(app);
717        if !controller.is_dismissed(app) && controller.status(app) != AnimationStatus::Reverse {
718            self.close(app);
719        }
720    }
721
722    fn handle_drag_down(self: Handle<Self>, app: &mut App, _details: DragDownDetails) {
723        self.controller(app).stop(app, true);
724        self.ensure_history_entry(app);
725    }
726
727    fn handle_drag_cancel(self: Handle<Self>, app: &mut App) {
728        let controller = self.controller(app);
729        if controller.is_dismissed(app) || Animation::is_animating(controller, app) {
730            return;
731        }
732        if controller.value(app) < 0.5 {
733            self.close(app);
734        } else {
735            self.open(app);
736        }
737    }
738
739    fn width(self: Handle<Self>, app: &mut App) -> f64 {
740        let drawer_key = app.get(self).drawer_key.clone();
741        let size = drawer_key
742            .current_context(app)
743            .and_then(|context| context.find_render_object(app))
744            .and_then(|render_object| render_object.as_box())
745            .map(|render_box| render_box.size(app));
746        // return K_WIDTH if drawer not being shown currently
747        size.map_or(K_WIDTH, |size| size.width())
748    }
749
750    fn direction_factor(self: Handle<Self>, app: &mut App) -> f64 {
751        let context = self.context(app);
752        match (Directionality::of(app, context), self.widget(app).alignment) {
753            (TextDirection::Rtl, DrawerAlignment::Start) => -1.0,
754            (TextDirection::Rtl, DrawerAlignment::End) => 1.0,
755            (TextDirection::Ltr, DrawerAlignment::Start) => 1.0,
756            (TextDirection::Ltr, DrawerAlignment::End) => -1.0,
757        }
758    }
759
760    fn r#move(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
761        let controller = self.controller(app);
762        let primary_delta = details
763            .primary_delta
764            .expect("a horizontal drag has a primary delta");
765        let delta = primary_delta / self.width(app) * self.direction_factor(app);
766        controller.set_value(app, controller.value(app) + delta);
767
768        let opened = controller.value(app) > 0.5;
769        if opened != app.get(self).previously_opened
770            && let Some(drawer_callback) = self.widget(app).drawer_callback.clone()
771        {
772            drawer_callback(app, opened);
773        }
774        app.get_mut(self).previously_opened = opened;
775    }
776
777    fn settle(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
778        let controller = self.controller(app);
779        if controller.is_dismissed(app) {
780            return;
781        }
782        let x_velocity = details.velocity.pixels_per_second.dx();
783        if x_velocity.abs() >= K_MIN_FLING_VELOCITY {
784            let visual_velocity = x_velocity / self.width(app) * self.direction_factor(app);
785
786            drop(controller.fling(app, visual_velocity, None, None));
787            if visual_velocity < 0.0 {
788                // We explicitly remove the history entry here because the drawer may already be
789                // animating closed (status == AnimationStatus.reverse) when the drag begins.
790                // In that case, flinging it closed again does not change the animation status,
791                // so the status listener will not fire.
792                self.remove_history_entry(app);
793            }
794            if let Some(drawer_callback) = self.widget(app).drawer_callback.clone() {
795                drawer_callback(app, visual_velocity > 0.0);
796            }
797        } else if controller.value(app) < 0.5 {
798            self.close(app);
799        } else {
800            self.open(app);
801        }
802    }
803
804    /// Starts an animation to open the drawer.
805    ///
806    /// Typically called by `ScaffoldState::open_drawer`.
807    pub fn open(self: Handle<Self>, app: &mut App) {
808        drop(self.controller(app).fling(app, 1.0, None, None));
809        if let Some(drawer_callback) = self.widget(app).drawer_callback.clone() {
810            drawer_callback(app, true);
811        }
812    }
813
814    /// Starts an animation to close the drawer.
815    pub fn close(self: Handle<Self>, app: &mut App) {
816        drop(self.controller(app).fling(app, -1.0, None, None));
817        // Explicitly removed here for the same reason as in settle.
818        self.remove_history_entry(app);
819        if let Some(drawer_callback) = self.widget(app).drawer_callback.clone() {
820            drawer_callback(app, false);
821        }
822    }
823
824    fn drawer_outer_alignment(self: Handle<Self>, app: &App) -> AlignmentGeometry {
825        match self.widget(app).alignment {
826            DrawerAlignment::Start => AlignmentGeometry::CENTER_START,
827            DrawerAlignment::End => AlignmentGeometry::CENTER_END,
828        }
829    }
830
831    fn drawer_inner_alignment(self: Handle<Self>, app: &App) -> AlignmentGeometry {
832        match self.widget(app).alignment {
833            DrawerAlignment::Start => AlignmentGeometry::CENTER_END,
834            DrawerAlignment::End => AlignmentGeometry::CENTER_START,
835        }
836    }
837
838    fn build_drawer(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
839        let is_desktop = match Theme::of(app, context).platform {
840            TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => false,
841            TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => true,
842        };
843
844        let drag_area_width = match self.widget(app).edge_drag_width {
845            Some(edge_drag_width) => edge_drag_width,
846            None => {
847                let alignment = self.widget(app).alignment;
848                K_EDGE_DRAG_WIDTH
849                    + match (alignment, Directionality::of(app, context)) {
850                        (DrawerAlignment::Start, TextDirection::Ltr) => {
851                            MediaQuery::padding_of(app, context).left
852                        }
853                        (DrawerAlignment::Start, TextDirection::Rtl) => {
854                            MediaQuery::padding_of(app, context).right
855                        }
856                        (DrawerAlignment::End, TextDirection::Rtl) => {
857                            MediaQuery::padding_of(app, context).left
858                        }
859                        (DrawerAlignment::End, TextDirection::Ltr) => {
860                            MediaQuery::padding_of(app, context).right
861                        }
862                    }
863            }
864        };
865
866        let controller = self.controller(app);
867        let gesture_detector_key = app.get(self).gesture_detector_key.clone();
868        if controller.is_dismissed(app) {
869            if self.widget(app).enable_open_drag_gesture && !is_desktop {
870                Align::new()
871                    .alignment(self.drawer_outer_alignment(app))
872                    .child(
873                        GestureDetector::new()
874                            .key(gesture_detector_key.into())
875                            .on_horizontal_drag_update(Rc::new(
876                                move |app: &mut App, details: DragUpdateDetails| {
877                                    self.r#move(app, details);
878                                },
879                            ))
880                            .on_horizontal_drag_end(Rc::new(
881                                move |app: &mut App, details: DragEndDetails| {
882                                    self.settle(app, details);
883                                },
884                            ))
885                            .behavior(HitTestBehavior::Translucent)
886                            .drag_start_behavior(self.widget(app).drag_start_behavior)
887                            .child(LimitedBox::new().max_height(0.0).child(
888                                SizedBox::new().width(drag_area_width).height(f64::INFINITY),
889                            )),
890                    )
891                    .into_widget()
892            } else {
893                SizedBox::shrink().into_widget()
894            }
895        } else {
896            let platform_has_back_button = match app.platform().target_platform() {
897                TargetPlatform::Android => true,
898                TargetPlatform::IOS
899                | TargetPlatform::MacOS
900                | TargetPlatform::Fuchsia
901                | TargetPlatform::Linux
902                | TargetPlatform::Windows => false,
903            };
904
905            let scrim_color = match self.widget(app).scrim_color {
906                Some(scrim_color) => scrim_color,
907                None => DrawerTheme::of(app, context)
908                    .scrim_color
909                    .unwrap_or(Colors::BLACK54),
910            };
911            let effective_scrim_color = scrim_color.with_values(
912                Some(scrim_color.a * controller.value(app)),
913                None,
914                None,
915                None,
916                None,
917            );
918            let drawer_scrim = ColoredBox::new(effective_scrim_color).child(
919                LimitedBox::new()
920                    .max_width(0.0)
921                    .max_height(0.0)
922                    .child(SizedBox::expand()),
923            );
924
925            let mut barrier = GestureDetector::new().child(
926                Semantics::new()
927                    .label(
928                        <dyn MaterialLocalizations>::of(app, context).modal_barrier_dismiss_label(),
929                    )
930                    .child(drawer_scrim),
931            );
932            if self.widget(app).drawer_barrier_dismissible {
933                barrier = barrier.on_tap(Listener::handle_method(self, Self::close));
934            }
935
936            let drawer_key = app.get(self).drawer_key.clone();
937            let focus_scope_node = app
938                .get(self)
939                .focus_scope_node
940                .clone()
941                .expect("created in init_state");
942            let child = DrawerControllerScope {
943                controller: context.widget(app).clone(),
944                child: RepaintBoundary::new()
945                    .child(
946                        Stack::new().children([
947                            BlockSemantics::new()
948                                .child(
949                                    ExcludeSemantics::new()
950                                        // On Android, the back button is used to dismiss a modal.
951                                        .excluding(platform_has_back_button)
952                                        .child(barrier),
953                                )
954                                .into_widget(),
955                            Align::new()
956                                .alignment(self.drawer_outer_alignment(app))
957                                .child(
958                                    Align::new()
959                                        .alignment(self.drawer_inner_alignment(app))
960                                        .width_factor(controller.value(app))
961                                        .child(
962                                            RepaintBoundary::new().child(
963                                                FocusScope::new(self.widget(app).child.clone())
964                                                    .key(drawer_key.into())
965                                                    .node(focus_scope_node),
966                                            ),
967                                        ),
968                                )
969                                .into_widget(),
970                        ]),
971                    )
972                    .into_widget(),
973            };
974
975            if is_desktop {
976                return child.into_widget();
977            }
978
979            GestureDetector::new()
980                .key(gesture_detector_key.into())
981                .on_horizontal_drag_down(Rc::new(move |app: &mut App, details: DragDownDetails| {
982                    self.handle_drag_down(app, details);
983                }))
984                .on_horizontal_drag_update(Rc::new(
985                    move |app: &mut App, details: DragUpdateDetails| {
986                        self.r#move(app, details);
987                    },
988                ))
989                .on_horizontal_drag_end(Rc::new(move |app: &mut App, details: DragEndDetails| {
990                    self.settle(app, details);
991                }))
992                .on_horizontal_drag_cancel(Listener::handle_method(self, Self::handle_drag_cancel))
993                .drag_start_behavior(self.widget(app).drag_start_behavior)
994                .child(child)
995                .into_widget()
996        }
997    }
998}
999
1000impl SingleTickerProviderStateMixin for DrawerControllerState {
1001    fn single_ticker_provider_data(
1002        self: Handle<Self>,
1003        app: &App,
1004    ) -> &SingleTickerProviderStateMixinData {
1005        &app.get(self).single_ticker_provider
1006    }
1007
1008    fn single_ticker_provider_data_mut(
1009        self: Handle<Self>,
1010        app: &mut App,
1011    ) -> &mut SingleTickerProviderStateMixinData {
1012        &mut app.get_mut(self).single_ticker_provider
1013    }
1014}
1015
1016impl TickerProviderObject for DrawerControllerState {
1017    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1018        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1019    }
1020}
1021
1022impl State for DrawerControllerState {
1023    type Widget = DrawerController;
1024    waft_widgets::state_accessors!();
1025
1026    fn init_state(self: Handle<Self>, app: &mut App) {
1027        let focus_scope_node = FocusScopeNode::new(app);
1028        app.get_mut(self).focus_scope_node = Some(focus_scope_node);
1029        let value = if self.widget(app).is_drawer_open {
1030            1.0
1031        } else {
1032            0.0
1033        };
1034        let controller = AnimationController::new(
1035            app,
1036            Some(value),
1037            Some(K_BASE_SETTLE_DURATION),
1038            None,
1039            0.0,
1040            1.0,
1041            AnimationBehavior::Normal,
1042            self,
1043        );
1044        app.get_mut(self).controller = Some(controller.clone());
1045        controller.add_listener(app, Listener::handle_method(self, Self::animation_changed));
1046        controller.add_status_listener(
1047            app,
1048            AnimationStatusListener::handle_method(self, Self::animation_status_changed),
1049        );
1050    }
1051
1052    fn activate(self: Handle<Self>, app: &mut App) {
1053        SingleTickerProviderStateMixin::activate(self, app);
1054    }
1055
1056    fn dispose(self: Handle<Self>, app: &mut App) {
1057        app.get_mut(self).disposed = true;
1058        self.remove_history_entry(app);
1059        self.controller(app).dispose(app);
1060        self.focus_scope_node(app).dispose(app);
1061        SingleTickerProviderStateMixin::dispose(self, app);
1062    }
1063
1064    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DrawerController) {
1065        let controller = self.controller(app);
1066        if controller.status(app).is_animating() {
1067            return; // Don't snap the drawer open or shut while the user is dragging.
1068        }
1069        let is_drawer_open = self.widget(app).is_drawer_open;
1070        if is_drawer_open != old_widget.is_drawer_open {
1071            controller.set_value(app, if is_drawer_open { 1.0 } else { 0.0 });
1072        }
1073    }
1074
1075    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1076        debug_assert!(debug_check_has_material_localizations(app, context));
1077        ListTileTheme::merge(self.build_drawer(app, context))
1078            .style(ListTileStyle::Drawer)
1079            .into_widget()
1080    }
1081}
1082
1083/// Dart's `_DrawerDefaultsM2`.
1084struct DrawerDefaultsM2 {
1085    /// Dart's `super(..)` arguments.
1086    drawer_theme_data: DrawerThemeData,
1087    context: BuildContext,
1088}
1089
1090impl DrawerDefaultsM2 {
1091    fn new(context: BuildContext) -> DrawerDefaultsM2 {
1092        DrawerDefaultsM2 {
1093            drawer_theme_data: DrawerThemeData::new()
1094                .elevation(16.0)
1095                .clip_behavior(Clip::HardEdge),
1096            context,
1097        }
1098    }
1099}
1100
1101impl DrawerThemeDataGetters for DrawerDefaultsM2 {
1102    fn drawer_theme_data(&self) -> &DrawerThemeData {
1103        &self.drawer_theme_data
1104    }
1105
1106    fn shadow_color(&self, app: &mut App) -> Option<Color> {
1107        Some(Theme::of(app, self.context).shadow_color)
1108    }
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113    //! The cases of `test/drawer_test.dart` and `test/drawer_theme_test.dart`'s widget cases.
1114    //! scaffold_test.dart's drawer cases are in `scaffold.rs`.
1115
1116    use std::cell::{Cell, RefCell};
1117    use waft_painting::ShapeBorder;
1118
1119    use waft_embedder::{Offset, Radius, Size};
1120    use waft_painting::{BorderRadius, BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
1121    use waft_rendering::AnyRenderBox;
1122    use waft_widgets::{
1123        AnyElement, Builder, Center, Container, ListView, ModalBarrier, MouseRegion, Orientation,
1124        OrientationBuilder, PreferredSizeWidgetRef, Text,
1125    };
1126
1127    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
1128
1129    use super::*;
1130    use crate::app_bar::AppBar;
1131    use crate::drawer_header::DrawerHeader;
1132    use crate::icons::Icons;
1133    use crate::list_tile::ListTile;
1134    use crate::scaffold::{Scaffold, ScaffoldState};
1135    use crate::test_support::{is_same_color_as, restorable_material_app};
1136    use crate::text_button::TextButton;
1137    use crate::theme_data::ThemeData;
1138    use crate::tooltip::tests::{m2, m3, pump_app};
1139
1140    /// Dart's `scaffoldKey.currentState!`, or `tester.firstState(find.byType(Scaffold))` of the
1141    /// one scaffold, which the case keys.
1142    fn scaffold_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<ScaffoldState> {
1143        key.current_state::<ScaffoldState>(&tester.cell.borrow_mut())
1144            .expect("a mounted scaffold")
1145    }
1146
1147    fn open_drawer(tester: &WidgetTester, key: &GlobalKey) {
1148        let state = scaffold_state(tester, key);
1149        state.open_drawer(&mut tester.cell.borrow_mut());
1150    }
1151
1152    fn open_end_drawer(tester: &WidgetTester, key: &GlobalKey) {
1153        let state = scaffold_state(tester, key);
1154        state.open_end_drawer(&mut tester.cell.borrow_mut());
1155    }
1156
1157    fn close_drawer(tester: &WidgetTester, key: &GlobalKey) {
1158        let state = scaffold_state(tester, key);
1159        state.close_drawer(&mut tester.cell.borrow_mut());
1160    }
1161
1162    fn close_end_drawer(tester: &WidgetTester, key: &GlobalKey) {
1163        let state = scaffold_state(tester, key);
1164        state.close_end_drawer(&mut tester.cell.borrow_mut());
1165    }
1166
1167    fn is_drawer_open(tester: &WidgetTester, key: &GlobalKey) -> bool {
1168        scaffold_state(tester, key).is_drawer_open(&tester.cell.borrow())
1169    }
1170
1171    fn is_end_drawer_open(tester: &WidgetTester, key: &GlobalKey) -> bool {
1172        scaffold_state(tester, key).is_end_drawer_open(&tester.cell.borrow())
1173    }
1174
1175    fn found(tester: &WidgetTester, text: &str) -> usize {
1176        find::text(text).evaluate(tester).len()
1177    }
1178
1179    fn drawers(tester: &WidgetTester) -> usize {
1180        find::by_type::<Drawer>().evaluate(tester).len()
1181    }
1182
1183    fn drawer_box(tester: &WidgetTester) -> AnyRenderBox {
1184        let drawer = *find::by_type::<Drawer>()
1185            .evaluate(tester)
1186            .first()
1187            .expect("a drawer");
1188        tester.render_box_of(drawer)
1189    }
1190
1191    fn drawer_width(tester: &WidgetTester) -> f64 {
1192        drawer_box(tester).size(&tester.cell.borrow()).width()
1193    }
1194
1195    /// `find.descendant(of: find.byType(Drawer), matching: find.byType(Material))`, first.
1196    fn drawer_material(tester: &WidgetTester) -> AnyElement {
1197        let drawer = *find::by_type::<Drawer>()
1198            .evaluate(tester)
1199            .first()
1200            .expect("a drawer");
1201        *find::by_type::<Material>()
1202            .evaluate(tester)
1203            .iter()
1204            .find(|material| tester.ancestors(**material).contains(&drawer))
1205            .expect("a material in the drawer")
1206    }
1207
1208    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
1209        tester.widget(drawer_material(tester), read)
1210    }
1211
1212    fn material_shape(tester: &WidgetTester) -> Option<ShapeBorderRef> {
1213        material(tester, |material| material.shape.clone())
1214    }
1215
1216    /// The scrim: the `ColoredBox` of a [`DrawerController`] outside its drawer, which Dart
1217    /// finds by its `Semantics` label.
1218    fn scrim_color(tester: &WidgetTester) -> Color {
1219        let controllers = find::by_type::<DrawerController>().evaluate(tester);
1220        let drawers = find::by_type::<Drawer>().evaluate(tester);
1221        let scrim = *find::by_type::<ColoredBox>()
1222            .evaluate(tester)
1223            .iter()
1224            .find(|colored_box| {
1225                let ancestors = tester.ancestors(**colored_box);
1226                controllers
1227                    .iter()
1228                    .any(|controller| ancestors.contains(controller))
1229                    && !drawers.iter().any(|drawer| ancestors.contains(drawer))
1230            })
1231            .expect("a scrim");
1232        tester.widget(scrim, |colored_box: &ColoredBox| colored_box.color.color())
1233    }
1234
1235    fn top_left(tester: &WidgetTester, element: AnyElement) -> Offset {
1236        tester.get_rect(element).top_left()
1237    }
1238
1239    fn rounded(border_radius: BorderRadius) -> RoundedRectangleBorder {
1240        RoundedRectangleBorder::new(BorderSide::NONE, border_radius.into())
1241    }
1242
1243    fn assert_shape(tester: &WidgetTester, expected: Option<RoundedRectangleBorder>) {
1244        let shape = material_shape(tester);
1245        assert_eq!(
1246            shape.as_deref(),
1247            expected.as_ref().map(|shape| shape as &dyn ShapeBorder)
1248        );
1249    }
1250
1251    /// `Scaffold(key: key, drawer: Text(drawer), body: Container())`.
1252    fn text_drawer_scaffold(key: &GlobalKey, drawer: &str) -> Scaffold {
1253        Scaffold::new()
1254            .key(key.clone().into())
1255            .drawer(Text::new(drawer))
1256            .body(Container::new())
1257    }
1258
1259    // drawer_test.dart 'Material2 - Drawer control test' and 'Material3 - Drawer control test'.
1260    fn drawer_control_test(
1261        tester: &mut WidgetTester,
1262        theme: fn(&App) -> ThemeData,
1263        header_divider: f64,
1264    ) {
1265        let key = GlobalKey::new();
1266        let container_key = GlobalKey::new();
1267        let saved_context = Rc::new(Cell::new(None));
1268        let (scaffold, container, saved) = (
1269            key.clone(),
1270            container_key.clone(),
1271            Rc::clone(&saved_context),
1272        );
1273        pump_app(tester, theme, move |_app| {
1274            Builder::new(move |_app, context| {
1275                saved.set(Some(context));
1276
1277                Scaffold::new()
1278                    .key(scaffold.clone().into())
1279                    .drawer(
1280                        Drawer::new().child(
1281                            ListView::new().children([
1282                                DrawerHeader::new(Some(
1283                                    Container::new()
1284                                        .key(container.clone().into())
1285                                        .child(Text::new("header"))
1286                                        .into_widget(),
1287                                ))
1288                                .into_widget(),
1289                                ListTile::new()
1290                                    .leading(waft_widgets::Icon::new(Some(Icons::archive())))
1291                                    .title(Text::new("Archive"))
1292                                    .into_widget(),
1293                            ]),
1294                        ),
1295                    )
1296                    .into_widget()
1297            })
1298            .into_widget()
1299        });
1300
1301        assert_eq!(found(tester, "Archive"), 0);
1302        open_drawer(tester, &key);
1303
1304        tester.pump();
1305        assert_eq!(found(tester, "Archive"), 1);
1306        tester.pump_by(Duration::from_secs(1));
1307        assert_eq!(found(tester, "Archive"), 1);
1308
1309        let header = *find::by_type::<DrawerHeader>()
1310            .evaluate(tester)
1311            .first()
1312            .expect("a header");
1313        let header_size = tester.render_box_of(header).size(&tester.cell.borrow());
1314        assert_eq!(header_size.height(), 160.0 + 8.0 + 1.0); // height + bottom margin + bottom edge
1315
1316        let container_size = tester
1317            .render_object(&container_key)
1318            .as_box()
1319            .expect("a render box")
1320            .size(&tester.cell.borrow());
1321        assert_eq!(container_size.width(), header_size.width() - 2.0 * 16.0);
1322        assert_eq!(
1323            container_size.height(),
1324            header_size.height() - 2.0 * 16.0 - header_divider
1325        );
1326
1327        assert_eq!(found(tester, "header"), 1);
1328
1329        {
1330            let context = saved_context.get().expect("the builder built");
1331            let mut app = tester.cell.borrow_mut();
1332            waft_widgets::Navigator::pop(&mut app, context, None);
1333        }
1334        tester.pump(); // drawer should be starting to animate away
1335        assert_eq!(found(tester, "Archive"), 1);
1336        tester.pump_by(Duration::from_secs(1)); // animation done
1337        assert_eq!(found(tester, "Archive"), 0);
1338    }
1339
1340    #[test]
1341    fn material2_drawer_control_test() {
1342        test_widgets(|tester| drawer_control_test(tester, m2, 0.0));
1343    }
1344
1345    #[test]
1346    fn material3_drawer_control_test() {
1347        // Header divider thickness is 1.0 in Material 3.
1348        test_widgets(|tester| drawer_control_test(tester, m3, 1.0));
1349    }
1350
1351    #[test]
1352    fn drawer_tap_test() {
1353        test_widgets(|tester| {
1354            let key = GlobalKey::new();
1355            pump_app(tester, m3, |_app| {
1356                text_drawer_scaffold(&key, "drawer").into_widget()
1357            });
1358            tester.pump(); // no effect
1359            assert_eq!(found(tester, "drawer"), 0);
1360            open_drawer(tester, &key);
1361            tester.pump(); // drawer should be starting to animate in
1362            assert_eq!(found(tester, "drawer"), 1);
1363            tester.pump_by(Duration::from_secs(1)); // animation done
1364            assert_eq!(found(tester, "drawer"), 1);
1365            let at = tester.get_rect(find::text("drawer")).center();
1366            tester.tap_at(at, 1);
1367            tester.pump(); // nothing should have happened
1368            assert_eq!(found(tester, "drawer"), 1);
1369            tester.pump_by(Duration::from_secs(1)); // ditto
1370            assert_eq!(found(tester, "drawer"), 1);
1371            tester.tap_at(Offset::new(750.0, 100.0), 2); // on the mask
1372            tester.pump();
1373            tester.pump_by(Duration::from_millis(10));
1374            // drawer should be starting to animate away
1375            assert_eq!(found(tester, "drawer"), 1);
1376            tester.pump_by(Duration::from_secs(1)); // animation done
1377            assert_eq!(found(tester, "drawer"), 0);
1378        });
1379    }
1380
1381    #[test]
1382    fn drawer_hover_test() {
1383        test_widgets(|tester| {
1384            let key = GlobalKey::new();
1385            let logs = Rc::new(RefCell::new(Vec::<&'static str>::new()));
1386            let mut gesture = TestPointer::mouse(1, 0);
1387            // Start out of hoverTarget
1388            tester.add_pointer(&mut gesture, Offset::new(100.0, 100.0));
1389
1390            let log = Rc::clone(&logs);
1391            pump_app(tester, m3, |_app| {
1392                let (enter, hover, exit) = (Rc::clone(&log), Rc::clone(&log), Rc::clone(&log));
1393                Scaffold::new()
1394                    .key(key.clone().into())
1395                    .drawer(Text::new("drawer"))
1396                    .body(
1397                        Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
1398                            MouseRegion::new()
1399                                .on_enter(Rc::new(move |_app, _event| {
1400                                    enter.borrow_mut().push("enter");
1401                                }))
1402                                .on_hover(Rc::new(move |_app, _event| {
1403                                    hover.borrow_mut().push("hover");
1404                                }))
1405                                .on_exit(Rc::new(move |_app, _event| {
1406                                    exit.borrow_mut().push("exit");
1407                                }))
1408                                .child(SizedBox::new().width(10.0).height(10.0)),
1409                        ),
1410                    )
1411                    .into_widget()
1412            });
1413            assert!(logs.borrow().is_empty());
1414            assert_eq!(found(tester, "drawer"), 0);
1415
1416            // When drawer is closed, hover is interactable
1417            tester.move_to(&mut gesture, Offset::new(5.0, 5.0), false);
1418            tester.pump(); // no effect
1419            assert_eq!(*logs.borrow(), ["enter", "hover"]);
1420            logs.borrow_mut().clear();
1421
1422            tester.move_to(&mut gesture, Offset::new(20.0, 20.0), false);
1423            tester.pump(); // no effect
1424            assert_eq!(*logs.borrow(), ["exit"]);
1425            logs.borrow_mut().clear();
1426
1427            // When drawer is open, hover is uninteractable
1428            open_drawer(tester, &key);
1429            tester.pump_by(Duration::from_secs(1)); // animation done
1430            assert_eq!(found(tester, "drawer"), 1);
1431
1432            tester.move_to(&mut gesture, Offset::new(5.0, 5.0), false);
1433            tester.pump(); // no effect
1434            assert!(logs.borrow().is_empty());
1435            logs.borrow_mut().clear();
1436
1437            tester.move_to(&mut gesture, Offset::new(20.0, 20.0), false);
1438            tester.pump(); // no effect
1439            assert!(logs.borrow().is_empty());
1440            logs.borrow_mut().clear();
1441
1442            // Close drawer, hover is interactable again
1443            tester.tap_at(Offset::new(750.0, 100.0), 2); // on the mask
1444            tester.pump();
1445            tester.pump_by(Duration::from_secs(1)); // animation done
1446            assert_eq!(found(tester, "drawer"), 0);
1447
1448            tester.move_to(&mut gesture, Offset::new(5.0, 5.0), false);
1449            tester.pump(); // no effect
1450            assert_eq!(*logs.borrow(), ["enter", "hover"]);
1451            logs.borrow_mut().clear();
1452
1453            tester.move_to(&mut gesture, Offset::new(20.0, 20.0), false);
1454            tester.pump(); // no effect
1455            assert_eq!(*logs.borrow(), ["exit"]);
1456            logs.borrow_mut().clear();
1457        });
1458    }
1459
1460    #[test]
1461    fn scaffold_drawer_scrim_color() {
1462        test_widgets(|tester| {
1463            let key = GlobalKey::new();
1464            let build_frame = |tester: &mut WidgetTester, drawer_scrim_color: Option<Color>| {
1465                pump_app(tester, m3, |_app| {
1466                    let mut scaffold =
1467                        Scaffold::new()
1468                            .key(key.clone().into())
1469                            .drawer(Drawer::new().child(Builder::new(|_app, context| {
1470                                GestureDetector::new()
1471                                    .on_tap(Listener::new(move |app| {
1472                                        waft_widgets::Navigator::pop(app, context, None);
1473                                    })) // close drawer
1474                                    .into_widget()
1475                            })));
1476                    if let Some(drawer_scrim_color) = drawer_scrim_color {
1477                        scaffold = scaffold.drawer_scrim_color(drawer_scrim_color);
1478                    }
1479                    scaffold.into_widget()
1480                });
1481            };
1482
1483            let check_scrim = |tester: &mut WidgetTester, color: Color| {
1484                open_drawer(tester, &key);
1485                tester.pump();
1486                assert!(is_same_color_as(
1487                    scrim_color(tester),
1488                    color.with_values(Some(0.0), None, None, None, None)
1489                ));
1490
1491                tester.pump_and_settle();
1492                assert!(is_same_color_as(scrim_color(tester), color));
1493
1494                let at = tester.get_rect(drawer_box(tester)).center();
1495                tester.tap_at(at, 1);
1496                tester.pump_and_settle();
1497                assert_eq!(drawers(tester), 0);
1498            };
1499
1500            // Default drawerScrimColor
1501            build_frame(tester, None);
1502            check_scrim(tester, Colors::BLACK54);
1503
1504            // Specific drawerScrimColor
1505            build_frame(tester, Some(Color::new(0xFF323232)));
1506            check_scrim(tester, Color::new(0xFF323232));
1507        });
1508    }
1509
1510    #[test]
1511    fn open_close_drawers_by_flinging() {
1512        test_widgets(|tester| {
1513            let key = GlobalKey::new();
1514            pump_app(tester, m3, |_app| {
1515                Scaffold::new()
1516                    .key(key.clone().into())
1517                    .drawer(Drawer::new().child(Text::new("start drawer")))
1518                    .end_drawer(Drawer::new().child(Text::new("end drawer")))
1519                    .into_widget()
1520            });
1521
1522            // In the beginning, drawers are closed
1523            assert!(!is_drawer_open(tester, &key));
1524            assert!(!is_end_drawer_open(tester, &key));
1525            let size = WidgetTester::SIZE;
1526
1527            // A fling from the left opens the start drawer
1528            tester.fling_from(
1529                Offset::new(0.0, size.height() / 2.0),
1530                Offset::new(80.0, 0.0),
1531                500.0,
1532                1,
1533            );
1534            tester.pump_and_settle();
1535            assert!(is_drawer_open(tester, &key));
1536            assert!(!is_end_drawer_open(tester, &key));
1537
1538            // Now, a fling from the right closes the drawer
1539            tester.fling_from(
1540                Offset::new(size.width() - 1.0, size.height() / 2.0),
1541                Offset::new(-80.0, 0.0),
1542                500.0,
1543                2,
1544            );
1545            tester.pump_and_settle();
1546            assert!(!is_drawer_open(tester, &key));
1547            assert!(!is_end_drawer_open(tester, &key));
1548
1549            // Another fling from the right opens the end drawer
1550            tester.fling_from(
1551                Offset::new(size.width() - 1.0, size.height() / 2.0),
1552                Offset::new(-80.0, 0.0),
1553                500.0,
1554                3,
1555            );
1556            tester.pump_and_settle();
1557            assert!(!is_drawer_open(tester, &key));
1558            assert!(is_end_drawer_open(tester, &key));
1559
1560            // And a fling from the left closes it
1561            tester.fling_from(
1562                Offset::new(0.0, size.height() / 2.0),
1563                Offset::new(80.0, 0.0),
1564                500.0,
1565                4,
1566            );
1567            tester.pump_and_settle();
1568            assert!(!is_drawer_open(tester, &key));
1569            assert!(!is_end_drawer_open(tester, &key));
1570        });
1571    }
1572
1573    #[test]
1574    fn open_close_drawer_by_dragging() {
1575        test_widgets(|tester| {
1576            pump_app(
1577                tester,
1578                |app| {
1579                    ThemeData::builder()
1580                        .platform(TargetPlatform::Android)
1581                        .build(app)
1582                },
1583                |_app| Scaffold::new().drawer(Drawer::new()).into_widget(),
1584            );
1585
1586            let mut gesture = TestPointer::touch(1);
1587            let drawer_position = |tester: &WidgetTester| {
1588                assert_eq!(drawers(tester), 1);
1589                tester.get_rect(drawer_box(tester)).left
1590            };
1591            // `gesture.moveBy(by)`.
1592            let move_by = |tester: &mut WidgetTester, gesture: &mut TestPointer, by: Offset| {
1593                let at = gesture.position + by;
1594                tester.move_to(gesture, at, true);
1595            };
1596
1597            // Pointer down (drawer is closed).
1598            tester.down(&mut gesture, Offset::new(2.0, 2.0));
1599            tester.pump();
1600            assert_eq!(drawers(tester), 0);
1601
1602            // Open drawer slightly.
1603            move_by(tester, &mut gesture, Offset::new(20.0, 0.0));
1604            tester.pump();
1605            assert!(drawer_position(tester) < 0.0);
1606
1607            // Open drawer more than halfway.
1608            move_by(tester, &mut gesture, Offset::new(200.0, 0.0));
1609            tester.pump();
1610            assert!(drawer_position(tester) < 0.0);
1611
1612            // Drawer is fully open.
1613            move_by(tester, &mut gesture, Offset::new(200.0, 0.0));
1614            tester.pump();
1615            assert_eq!(drawer_position(tester), 0.0);
1616
1617            // Drawer is less than halfway closed.
1618            move_by(tester, &mut gesture, Offset::new(-100.0, 0.0));
1619            tester.pump();
1620            assert!((drawer_position(tester) - -100.0).abs() < 1e-10);
1621
1622            // Drawer is more than halfway closed.
1623            move_by(tester, &mut gesture, Offset::new(-100.0, 0.0));
1624            tester.pump();
1625            assert!((drawer_position(tester) - -200.0).abs() < 1e-10);
1626
1627            // Drawer is completely closed.
1628            tester.move_to(&mut gesture, Offset::ZERO, true);
1629            tester.pump();
1630            assert_eq!(drawers(tester), 0);
1631        });
1632    }
1633
1634    #[test]
1635    fn close_drawer_with_navigator_pop() {
1636        test_widgets(|tester| {
1637            let key = GlobalKey::new();
1638            let button_pressed = Rc::new(Cell::new(false));
1639            let (scaffold, pressed) = (key.clone(), Rc::clone(&button_pressed));
1640            pump_app(tester, m3, move |_app| {
1641                Builder::new(move |_app, context| {
1642                    let pressed = Rc::clone(&pressed);
1643                    Scaffold::new()
1644                        .key(scaffold.clone().into())
1645                        .drawer(
1646                            Drawer::new().child(
1647                                ListView::new().children([
1648                                    Text::new("drawer").into_widget(),
1649                                    TextButton::new(
1650                                        Some(Listener::new(move |app| {
1651                                            waft_widgets::Navigator::pop(app, context, None);
1652                                        })),
1653                                        Some(Text::new("close")),
1654                                    )
1655                                    .into_widget(),
1656                                ]),
1657                            ),
1658                        )
1659                        .body(TextButton::new(
1660                            Some(Listener::new(move |_app| pressed.set(true))),
1661                            Some(Text::new("button")),
1662                        ))
1663                        .into_widget()
1664                })
1665                .into_widget()
1666            });
1667
1668            // Open the drawer.
1669            open_drawer(tester, &key);
1670            tester.pump(); // drawer should be starting to animate in
1671            assert_eq!(found(tester, "drawer"), 1);
1672
1673            // Tap the close button to pop the drawer route.
1674            tester.pump_by(Duration::from_millis(100));
1675            let at = tester.get_rect(find::text("close")).center();
1676            tester.tap_at(at, 1);
1677            tester.pump();
1678            tester.pump_by(Duration::from_secs(1));
1679            assert_eq!(found(tester, "drawer"), 0);
1680
1681            // Confirm that a button in the scaffold body is still clickable.
1682            let at = tester.get_rect(find::text("button")).center();
1683            tester.tap_at(at, 2);
1684            assert!(button_pressed.get());
1685        });
1686    }
1687
1688    fn drawer_closing_can_be_canceled_by_gesture(
1689        tester: &mut WidgetTester,
1690        text_direction: TextDirection,
1691    ) {
1692        let key = GlobalKey::new();
1693        pump_app(tester, m3, |_app| {
1694            Directionality::new(
1695                text_direction,
1696                Scaffold::new()
1697                    .drawer_drag_start_behavior(DragStartBehavior::Down)
1698                    .key(key.clone().into())
1699                    .drawer(
1700                        Drawer::new().child(
1701                            ListView::new().children([
1702                                Text::new("drawer").into_widget(),
1703                                Container::new()
1704                                    .height(1000.0)
1705                                    .color(Colors::BLUE.shade500())
1706                                    .into_widget(),
1707                            ]),
1708                        ),
1709                    )
1710                    .body(Container::new()),
1711            )
1712            .into_widget()
1713        });
1714        let ltr = text_direction == TextDirection::Ltr;
1715        // The edge of the text facing the drawer's edge.
1716        let text_edge = |tester: &WidgetTester| {
1717            let rect = tester.get_rect(find::text("drawer"));
1718            if ltr { rect.left } else { rect.right }
1719        };
1720        assert_eq!(found(tester, "drawer"), 0);
1721        open_drawer(tester, &key);
1722        tester.pump(); // drawer should be starting to animate in
1723        assert_eq!(found(tester, "drawer"), 1);
1724        tester.pump_by(Duration::from_secs(1)); // animation done
1725        assert_eq!(found(tester, "drawer"), 1);
1726
1727        tester.tap_at(Offset::new(if ltr { 750.0 } else { 50.0 }, 100.0), 1); // on the mask
1728        tester.pump();
1729        tester.pump_by(Duration::from_millis(10));
1730        // drawer should be starting to animate away
1731        let text_start = text_edge(tester);
1732        if ltr {
1733            assert!(text_start < 0.0);
1734        } else {
1735            assert!(text_start > 800.0);
1736        }
1737
1738        let mut gesture = TestPointer::touch(2);
1739        tester.down(
1740            &mut gesture,
1741            Offset::new(if ltr { 100.0 } else { 700.0 }, 100.0),
1742        );
1743        // drawer should be stopped.
1744        tester.pump();
1745        tester.pump_by(Duration::from_millis(10));
1746        assert_eq!(text_edge(tester), text_start);
1747
1748        let at = gesture.position + Offset::new(if ltr { 50.0 } else { -50.0 }, 0.0);
1749        tester.move_to(&mut gesture, at, true);
1750        // drawer should be returning to visible
1751        tester.pump();
1752        tester.pump_by(Duration::from_secs(1));
1753        assert_eq!(text_edge(tester), if ltr { 0.0 } else { 800.0 });
1754
1755        tester.up(&gesture);
1756    }
1757
1758    #[test]
1759    fn drawer_closing_can_be_canceled_by_gesture_ltr() {
1760        test_widgets(|tester| {
1761            drawer_closing_can_be_canceled_by_gesture(tester, TextDirection::Ltr)
1762        });
1763    }
1764
1765    #[test]
1766    fn drawer_closing_can_be_canceled_by_gesture_rtl() {
1767        test_widgets(|tester| {
1768            drawer_closing_can_be_canceled_by_gesture(tester, TextDirection::Rtl)
1769        });
1770    }
1771
1772    /// Dart's `tester.pumpWidget(MaterialApp(restorationScopeId: 'app', home: scaffold()))` on
1773    /// a tester whose host restores `data`: a new one for each `restartAndRestore` and
1774    /// `restoreFrom`.
1775    fn restored(
1776        data: Option<waft_embedder::RestorationMap>,
1777        scaffold: &dyn Fn() -> Scaffold,
1778    ) -> WidgetTester {
1779        let mut tester = WidgetTester::restoring(data);
1780        let theme = m3(&tester.cell.borrow());
1781        tester.pump_widget(restorable_material_app(
1782            "app",
1783            theme,
1784            scaffold().into_widget(),
1785        ));
1786        tester
1787    }
1788
1789    /// drawer_test.dart's null-restorationId cases: the drawer of `text_drawer_scaffold(key,
1790    /// text)` opened, then a restart.
1791    fn null_restoration_id(text: &'static str) {
1792        let key = GlobalKey::new();
1793        let scaffold = || text_drawer_scaffold(&key, text);
1794        let mut tester = restored(None, &scaffold);
1795        let tester = &mut tester;
1796        tester.pump(); // no effect
1797        assert_eq!(found(tester, text), 0);
1798        open_drawer(tester, &key);
1799        tester.pump_and_settle();
1800        assert_eq!(found(tester, text), 1);
1801
1802        let mut tester = restored(tester.restoration_data(), &scaffold);
1803        let tester = &mut tester;
1804        // Drawer state should not have been saved.
1805        assert_eq!(found(tester, text), 0);
1806    }
1807
1808    #[test]
1809    fn scaffold_drawer_null_restoration_id() {
1810        test_widgets(|_| null_restoration_id("drawer"));
1811    }
1812
1813    #[test]
1814    fn scaffold_end_drawer_null_restoration_id() {
1815        // Dart's case gives its text as the start drawer.
1816        test_widgets(|_| null_restoration_id("endDrawer"));
1817    }
1818
1819    #[test]
1820    fn scaffold_drawer_state_restoration_test() {
1821        test_widgets(|_| {
1822            let key = GlobalKey::new();
1823            let scaffold = || {
1824                Scaffold::new()
1825                    .key(key.clone().into())
1826                    .restoration_id("scaffold")
1827                    .drawer(Text::new("drawer"))
1828                    .body(Container::new())
1829            };
1830            let mut tester = restored(None, &scaffold);
1831            let tester = &mut tester;
1832            tester.pump(); // no effect
1833            assert_eq!(found(tester, "drawer"), 0);
1834            open_drawer(tester, &key);
1835            tester.pump_and_settle();
1836            assert_eq!(found(tester, "drawer"), 1);
1837
1838            let mut tester = restored(tester.restoration_data(), &scaffold);
1839            let tester = &mut tester;
1840            assert_eq!(found(tester, "drawer"), 1);
1841
1842            let data = tester.restoration_data();
1843            tester.tap_at(Offset::new(750.0, 100.0), 1); // on the mask
1844            tester.pump_and_settle();
1845            assert_eq!(found(tester, "drawer"), 0);
1846
1847            let mut tester = restored(data, &scaffold);
1848            let tester = &mut tester;
1849            assert_eq!(found(tester, "drawer"), 1);
1850        });
1851    }
1852
1853    #[test]
1854    fn scaffold_end_drawer_state_restoration_test() {
1855        test_widgets(|_| {
1856            let key = GlobalKey::new();
1857            let scaffold = || {
1858                Scaffold::new()
1859                    .key(key.clone().into())
1860                    .restoration_id("scaffold")
1861                    .end_drawer(Text::new("endDrawer"))
1862                    .body(Container::new())
1863            };
1864            let mut tester = restored(None, &scaffold);
1865            let tester = &mut tester;
1866            tester.pump(); // no effect
1867            assert_eq!(found(tester, "endDrawer"), 0);
1868            open_end_drawer(tester, &key);
1869            tester.pump_and_settle();
1870            assert_eq!(found(tester, "endDrawer"), 1);
1871
1872            let mut tester = restored(tester.restoration_data(), &scaffold);
1873            let tester = &mut tester;
1874            assert_eq!(found(tester, "endDrawer"), 1);
1875
1876            let data = tester.restoration_data();
1877            tester.tap_at(Offset::new(750.0, 100.0), 1); // on the mask
1878            tester.pump_and_settle();
1879            assert_eq!(found(tester, "endDrawer"), 0);
1880
1881            let mut tester = restored(data, &scaffold);
1882            let tester = &mut tester;
1883            assert_eq!(found(tester, "endDrawer"), 1);
1884        });
1885    }
1886
1887    #[test]
1888    fn both_drawer_and_end_drawer_state_restoration_test() {
1889        test_widgets(|_| {
1890            let key = GlobalKey::new();
1891            let scaffold = || {
1892                Scaffold::new()
1893                    .restoration_id("scaffold")
1894                    .key(key.clone().into())
1895                    .drawer(Text::new("drawer"))
1896                    .end_drawer(Text::new("endDrawer"))
1897                    .body(Container::new())
1898            };
1899            let shown =
1900                |tester: &WidgetTester| (found(tester, "drawer"), found(tester, "endDrawer"));
1901            let mut tester = restored(None, &scaffold);
1902            let tester = &mut tester;
1903            tester.pump(); // no effect
1904            assert_eq!(shown(tester), (0, 0));
1905            open_drawer(tester, &key);
1906            tester.pump_and_settle();
1907            assert_eq!(shown(tester), (1, 0));
1908
1909            let mut tester = restored(tester.restoration_data(), &scaffold);
1910            let tester = &mut tester;
1911            assert_eq!(shown(tester), (1, 0));
1912
1913            let data = tester.restoration_data();
1914            tester.tap_at(Offset::new(750.0, 100.0), 1); // on the mask
1915            tester.pump_and_settle();
1916            assert_eq!(shown(tester), (0, 0));
1917
1918            let mut tester = restored(data, &scaffold);
1919            let tester = &mut tester;
1920            assert_eq!(shown(tester), (1, 0));
1921
1922            tester.tap_at(Offset::new(750.0, 100.0), 1); // on the mask
1923            tester.pump_and_settle();
1924            assert_eq!(shown(tester), (0, 0));
1925
1926            open_end_drawer(tester, &key);
1927            tester.pump_and_settle();
1928            assert_eq!(shown(tester), (0, 1));
1929
1930            let mut tester = restored(tester.restoration_data(), &scaffold);
1931            let tester = &mut tester;
1932            assert_eq!(shown(tester), (0, 1));
1933
1934            let data = tester.restoration_data();
1935            tester.tap_at(Offset::new(750.0, 100.0), 1); // on the mask
1936            tester.pump_and_settle();
1937            assert_eq!(shown(tester), (0, 0));
1938
1939            let mut tester = restored(data, &scaffold);
1940            let tester = &mut tester;
1941            assert_eq!(shown(tester), (0, 1));
1942        });
1943    }
1944
1945    #[test]
1946    fn scaffold_state_close_drawer() {
1947        test_widgets(|tester| {
1948            let key = GlobalKey::new();
1949            pump_app(tester, m3, |_app| {
1950                text_drawer_scaffold(&key, "Drawer").into_widget()
1951            });
1952
1953            assert_eq!(found(tester, "Drawer"), 0);
1954
1955            open_drawer(tester, &key);
1956            tester.pump_and_settle();
1957            assert_eq!(found(tester, "Drawer"), 1);
1958
1959            close_drawer(tester, &key);
1960            tester.pump_and_settle();
1961            assert_eq!(found(tester, "Drawer"), 0);
1962        });
1963    }
1964
1965    #[test]
1966    fn scaffold_state_close_drawer_do_not_crash_if_drawer_is_already_closed() {
1967        test_widgets(|tester| {
1968            let key = GlobalKey::new();
1969            pump_app(tester, m3, |_app| {
1970                text_drawer_scaffold(&key, "Drawer").into_widget()
1971            });
1972
1973            assert_eq!(found(tester, "Drawer"), 0);
1974
1975            close_drawer(tester, &key);
1976            tester.pump_and_settle();
1977            assert_eq!(found(tester, "Drawer"), 0);
1978        });
1979    }
1980
1981    #[test]
1982    fn scaffold_state_close_end_drawer() {
1983        test_widgets(|tester| {
1984            let key = GlobalKey::new();
1985            pump_app(tester, m3, |_app| {
1986                Scaffold::new()
1987                    .key(key.clone().into())
1988                    .end_drawer(Text::new("endDrawer"))
1989                    .body(Container::new())
1990                    .into_widget()
1991            });
1992
1993            assert_eq!(found(tester, "endDrawer"), 0);
1994
1995            open_end_drawer(tester, &key);
1996            tester.pump_and_settle();
1997            assert_eq!(found(tester, "endDrawer"), 1);
1998
1999            close_end_drawer(tester, &key);
2000            tester.pump_and_settle();
2001            assert_eq!(found(tester, "endDrawer"), 0);
2002        });
2003    }
2004
2005    /// drawer_test's 'Disposing drawer/endDrawer does not crash if … is open and framework is
2006    /// locked': a portrait scaffold with the drawer `drawer_of` gives it, opened by `open`, which
2007    /// turning the view to landscape replaces, disposing the open drawer's controller while the
2008    /// framework is locked.
2009    fn dispose_open_drawer_on_rotation(
2010        tester: &mut WidgetTester,
2011        drawer_of: fn(Scaffold) -> Scaffold,
2012        label: &'static str,
2013        open: fn(&WidgetTester, &GlobalKey),
2014    ) {
2015        // Regression test for https://github.com/flutter/flutter/issues/34978
2016        tester.view().set_physical_size(Size::new(1800.0, 2400.0));
2017        let key = GlobalKey::new();
2018        let portrait_key = key.clone();
2019        pump_app(tester, m3, move |_app| {
2020            let portrait_key = portrait_key.clone();
2021            OrientationBuilder::new(move |_app, _context, orientation| match orientation {
2022                Orientation::Portrait => {
2023                    drawer_of(Scaffold::new().key(portrait_key.clone().into()))
2024                        .body(Container::new())
2025                        .into_widget()
2026                }
2027                Orientation::Landscape => Scaffold::new()
2028                    .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
2029                    .body(Container::new())
2030                    .into_widget(),
2031            })
2032            .into_widget()
2033        });
2034        assert_eq!(found(tester, label), 0);
2035
2036        open(tester, &key);
2037        tester.pump_and_settle();
2038        assert_eq!(found(tester, label), 1);
2039
2040        // Change the orientation and cause the drawer controller to be disposed
2041        // while the framework is locked.
2042        tester.view().set_physical_size(Size::new(2400.0, 1800.0));
2043        tester.pump_and_settle();
2044        assert!(
2045            find::by_type::<crate::action_buttons::BackButton>()
2046                .evaluate(tester)
2047                .is_empty()
2048        );
2049    }
2050
2051    #[test]
2052    fn disposing_drawer_does_not_crash_if_drawer_is_open_and_framework_is_locked() {
2053        test_widgets(|tester| {
2054            dispose_open_drawer_on_rotation(
2055                tester,
2056                |scaffold| scaffold.drawer(Text::new("drawer")),
2057                "drawer",
2058                open_drawer,
2059            );
2060        });
2061    }
2062
2063    #[test]
2064    fn disposing_end_drawer_does_not_crash_if_end_drawer_is_open_and_framework_is_locked() {
2065        test_widgets(|tester| {
2066            dispose_open_drawer_on_rotation(
2067                tester,
2068                |scaffold| scaffold.end_drawer(Text::new("endDrawer")),
2069                "endDrawer",
2070                open_end_drawer,
2071            );
2072        });
2073    }
2074
2075    #[test]
2076    fn drawer_width_defaults_to_material_spec() {
2077        test_widgets(|tester| {
2078            let key = GlobalKey::new();
2079            pump_app(tester, m3, |_app| {
2080                Scaffold::new()
2081                    .key(key.clone().into())
2082                    .drawer(Drawer::new())
2083                    .into_widget()
2084            });
2085
2086            open_drawer(tester, &key);
2087
2088            tester.pump();
2089            tester.pump_by(Duration::from_secs(1));
2090
2091            assert_eq!(drawer_width(tester), 304.0);
2092        });
2093    }
2094
2095    #[test]
2096    fn drawer_width_can_be_customized_by_parameter() {
2097        test_widgets(|tester| {
2098            const SMALL_WIDTH: f64 = 200.0;
2099
2100            let key = GlobalKey::new();
2101            pump_app(tester, m3, |_app| {
2102                Scaffold::new()
2103                    .key(key.clone().into())
2104                    .drawer(Drawer::new().width(SMALL_WIDTH))
2105                    .into_widget()
2106            });
2107
2108            open_drawer(tester, &key);
2109
2110            tester.pump_and_settle();
2111
2112            assert_eq!(drawer_width(tester), SMALL_WIDTH);
2113        });
2114    }
2115
2116    /// drawer_test.dart's default shape cases: `Scaffold(drawer: Drawer(), endDrawer:
2117    /// Drawer())`, under `text_direction` where the case gives one; the start drawer opened,
2118    /// a tap at (750, 300), then the end drawer opened.
2119    fn drawer_default_shape(
2120        tester: &mut WidgetTester,
2121        theme: fn(&App) -> ThemeData,
2122        text_direction: Option<TextDirection>,
2123        start_shape: Option<RoundedRectangleBorder>,
2124        end_shape: Option<RoundedRectangleBorder>,
2125    ) {
2126        let key = GlobalKey::new();
2127        pump_app(tester, theme, |_app| {
2128            let scaffold = Scaffold::new()
2129                .key(key.clone().into())
2130                .drawer(Drawer::new())
2131                .end_drawer(Drawer::new());
2132            match text_direction {
2133                Some(text_direction) => Directionality::new(text_direction, scaffold).into_widget(),
2134                None => scaffold.into_widget(),
2135            }
2136        });
2137
2138        // Open the drawer.
2139        open_drawer(tester, &key);
2140        tester.pump();
2141        tester.pump_by(Duration::from_secs(1));
2142
2143        // Test the drawer shape.
2144        assert_shape(tester, start_shape);
2145
2146        // Close the opened drawer.
2147        tester.tap_at(Offset::new(750.0, 300.0), 1);
2148        tester.pump_and_settle();
2149
2150        // Open the end drawer.
2151        open_end_drawer(tester, &key);
2152        tester.pump();
2153        tester.pump_by(Duration::from_secs(1));
2154
2155        // Test the end drawer shape.
2156        assert_shape(tester, end_shape);
2157    }
2158
2159    fn right_rounded() -> RoundedRectangleBorder {
2160        rounded(BorderRadius::only(
2161            Radius::ZERO,
2162            Radius::circular(16.0),
2163            Radius::ZERO,
2164            Radius::circular(16.0),
2165        ))
2166    }
2167
2168    fn left_rounded() -> RoundedRectangleBorder {
2169        rounded(BorderRadius::only(
2170            Radius::circular(16.0),
2171            Radius::ZERO,
2172            Radius::circular(16.0),
2173            Radius::ZERO,
2174        ))
2175    }
2176
2177    #[test]
2178    fn material3_drawer_default_shape_ltr() {
2179        test_widgets(|tester| {
2180            drawer_default_shape(
2181                tester,
2182                m3,
2183                Some(TextDirection::Ltr),
2184                Some(right_rounded()),
2185                Some(left_rounded()),
2186            );
2187        });
2188    }
2189
2190    #[test]
2191    fn material3_drawer_default_shape_rtl() {
2192        test_widgets(|tester| {
2193            drawer_default_shape(
2194                tester,
2195                m3,
2196                Some(TextDirection::Rtl),
2197                Some(left_rounded()),
2198                Some(right_rounded()),
2199            );
2200        });
2201    }
2202
2203    #[test]
2204    fn material2_drawer_default_shape() {
2205        test_widgets(|tester| drawer_default_shape(tester, m2, None, None, None));
2206    }
2207
2208    /// drawer_test.dart's clip behavior cases: the default, then the drawer `second` makes.
2209    fn drawer_clip_behavior(
2210        tester: &mut WidgetTester,
2211        theme: fn(&App) -> ThemeData,
2212        default_clip: Clip,
2213        second: fn() -> Drawer,
2214        second_clip: Clip,
2215    ) {
2216        let key = GlobalKey::new();
2217        pump_app(tester, theme, |_app| {
2218            Scaffold::new()
2219                .key(key.clone().into())
2220                .drawer(Drawer::new())
2221                .into_widget()
2222        });
2223
2224        // Open the drawer.
2225        open_drawer(tester, &key);
2226        tester.pump();
2227        tester.pump_by(Duration::from_secs(1));
2228
2229        // Test default clip behavior.
2230        assert_eq!(
2231            material(tester, |material| material.clip_behavior),
2232            default_clip
2233        );
2234
2235        close_drawer(tester, &key);
2236        tester.pump_and_settle();
2237
2238        // Provide a custom clip behavior.
2239        pump_app(tester, theme, |_app| {
2240            Scaffold::new()
2241                .key(key.clone().into())
2242                .drawer(second())
2243                .into_widget()
2244        });
2245
2246        // Open the drawer again.
2247        open_drawer(tester, &key);
2248        tester.pump();
2249        tester.pump_by(Duration::from_secs(1));
2250
2251        // Clip behavior is now updated.
2252        assert_eq!(
2253            material(tester, |material| material.clip_behavior),
2254            second_clip
2255        );
2256    }
2257
2258    #[test]
2259    fn material3_drawer_clip_behavior() {
2260        test_widgets(|tester| {
2261            drawer_clip_behavior(
2262                tester,
2263                m3,
2264                Clip::HardEdge,
2265                || Drawer::new().clip_behavior(Clip::AntiAlias),
2266                Clip::AntiAlias,
2267            );
2268        });
2269    }
2270
2271    #[test]
2272    fn material2_drawer_clip_behavior() {
2273        test_widgets(|tester| {
2274            drawer_clip_behavior(
2275                tester,
2276                m2,
2277                Clip::None,
2278                || {
2279                    Drawer::new()
2280                        .clip_behavior(Clip::HardEdge)
2281                        .shape(RoundedRectangleBorder::default())
2282                },
2283                Clip::HardEdge,
2284            );
2285        });
2286    }
2287
2288    /// drawer_test.dart's barrier cases: an end drawer opened, closed, opened again, and a
2289    /// tap on the route's barrier at (400, 300).
2290    fn drawer_barrier(tester: &mut WidgetTester, drawer_barrier_dismissible: bool) {
2291        let key = GlobalKey::new();
2292        pump_app(tester, m2, |_app| {
2293            Scaffold::new()
2294                .key(key.clone().into())
2295                .drawer_barrier_dismissible(drawer_barrier_dismissible)
2296                .app_bar(PreferredSizeWidgetRef::new(
2297                    AppBar::new().title(Text::new("Drawer Dismissible")),
2298                ))
2299                .end_drawer(
2300                    Drawer::new()
2301                        .background_color(Colors::WHITE)
2302                        .width(300.0)
2303                        .child(Text::new("Drawer")),
2304                )
2305                .body(
2306                    Container::new()
2307                        .color(Colors::WHITE)
2308                        .width(600.0)
2309                        .height(600.0)
2310                        .child(Center::new().child(Text::new("Drawer Dismissible"))),
2311                )
2312                .into_widget()
2313        });
2314
2315        // Check the flag is set at the Scaffold level.
2316        let scaffold = find::by_type::<Scaffold>().evaluate(tester)[0];
2317        assert_eq!(
2318            tester.widget(scaffold, |scaffold: &Scaffold| scaffold
2319                .drawer_barrier_dismissible),
2320            drawer_barrier_dismissible
2321        );
2322
2323        // Verify whether the drawer barrier is dismissible via the state
2324        let state = scaffold_state(tester, &key);
2325        assert_eq!(
2326            state.is_drawer_barrier_dismissible(&tester.cell.borrow()),
2327            drawer_barrier_dismissible
2328        );
2329
2330        // Open the drawer initially.
2331        open_end_drawer(tester, &key);
2332
2333        tester.pump_and_settle();
2334
2335        // Check that the drawer open.
2336        assert_eq!(drawers(tester), 1);
2337
2338        // Close the drawer programmatically.
2339        close_end_drawer(tester, &key);
2340        tester.pump_and_settle();
2341
2342        assert_eq!(drawers(tester), 0);
2343
2344        // Open it again, and make sure the drawer is available.
2345        open_end_drawer(tester, &key);
2346        tester.pump_and_settle();
2347
2348        assert_eq!(drawers(tester), 1);
2349
2350        // Find the ModalBarrier.
2351        let modal_barriers = find::by_type::<ModalBarrier>().evaluate(tester);
2352        assert_eq!(modal_barriers.len(), 1);
2353
2354        // Calculate a point to tap outside the Drawer.
2355        // This example taps on the ModalBarrier somewhere outside its boundaries.
2356        let modal_barrier_center = Offset::new(400.0, 300.0);
2357        let tap_position = top_left(tester, modal_barriers[0]) + modal_barrier_center;
2358
2359        // Tap on the ModalBarrier.
2360        tester.tap_at(tap_position, 1);
2361        tester.pump_and_settle();
2362
2363        assert_eq!(
2364            drawers(tester),
2365            if drawer_barrier_dismissible { 0 } else { 1 }
2366        );
2367    }
2368
2369    #[test]
2370    fn drawer_barrier_is_dismissible_by_default() {
2371        test_widgets(|tester| {
2372            assert!(Scaffold::new().drawer_barrier_dismissible);
2373            // Make sure the drawer is gone, since the drawerBarrierDismissible flag is set to
2374            // true by default.
2375            drawer_barrier(tester, true);
2376        });
2377    }
2378
2379    #[test]
2380    fn drawer_can_be_configured_as_not_dismissible() {
2381        test_widgets(|tester| {
2382            // Make sure the drawer is still present, and that tapping on the modal barrier
2383            // didn't dismiss it, since the drawerBarrierDismissible property is set to false.
2384            drawer_barrier(tester, false);
2385        });
2386    }
2387
2388    /// drawer_test.dart's escape key cases: the drawer opened, and the escape key sent.
2389    fn escape_key(tester: &mut WidgetTester, drawer_barrier_dismissible: Option<bool>) -> usize {
2390        let key = GlobalKey::new();
2391        pump_app(tester, m3, |_app| {
2392            let mut scaffold = Scaffold::new()
2393                .key(key.clone().into())
2394                .drawer(Drawer::new().child(Text::new("drawer")));
2395            if let Some(drawer_barrier_dismissible) = drawer_barrier_dismissible {
2396                scaffold = scaffold.drawer_barrier_dismissible(drawer_barrier_dismissible);
2397            }
2398            scaffold.into_widget()
2399        });
2400
2401        let state = scaffold_state(tester, &key);
2402        assert_eq!(
2403            state.is_drawer_barrier_dismissible(&tester.cell.borrow()),
2404            drawer_barrier_dismissible.unwrap_or(true)
2405        );
2406
2407        // Open the drawer.
2408        open_drawer(tester, &key);
2409        tester.pump_and_settle();
2410        assert_eq!(found(tester, "drawer"), 1);
2411
2412        tester.send_key_event(
2413            waft_services::PhysicalKeyboardKey::ESCAPE,
2414            waft_services::LogicalKeyboardKey::ESCAPE,
2415        );
2416        tester.pump_and_settle();
2417        found(tester, "drawer")
2418    }
2419
2420    #[test]
2421    fn drawer_can_be_dismissed_with_the_escape_key_by_default() {
2422        // Close the drawer with the escape key.
2423        test_widgets(|tester| assert_eq!(escape_key(tester, None), 0));
2424    }
2425
2426    #[test]
2427    fn drawer_cannot_be_dismissed_with_the_escape_key_when_drawer_barrier_dismissible_is_false() {
2428        // Try to close the drawer with the escape key, and verify it does not close.
2429        test_widgets(|tester| assert_eq!(escape_key(tester, Some(false)), 1));
2430    }
2431
2432    /// The widget the one `Drawer`'s element built: a new one each time the drawer builds.
2433    fn drawer_built_child(tester: &WidgetTester) -> WidgetRef {
2434        let drawer = *find::by_type::<Drawer>()
2435            .evaluate(tester)
2436            .first()
2437            .expect("a drawer");
2438        let app = tester.cell.borrow();
2439        drawer.children(&app)[0].widget(&app).clone()
2440    }
2441
2442    /// Not a Dart case: Dart's `_DrawerDefaultsM3.shape` reads `Directionality.of` only when
2443    /// the drawer reaches it, so a drawer with its own shape does not depend on the text
2444    /// direction.
2445    #[test]
2446    fn a_material3_drawer_with_its_own_shape_does_not_depend_on_the_text_direction() {
2447        test_widgets(|tester| {
2448            let drawer = Drawer::new()
2449                .shape(RoundedRectangleBorder::new(
2450                    BorderSide::NONE,
2451                    BorderRadiusGeometry::circular(4.0),
2452                ))
2453                .into_widget();
2454            let home = |text_direction: TextDirection| {
2455                let drawer = drawer.clone();
2456                move |_app: &mut App| Directionality::new(text_direction, drawer).into_widget()
2457            };
2458            pump_app(tester, m3, home(TextDirection::Ltr));
2459            let built = drawer_built_child(tester);
2460            pump_app(tester, m3, home(TextDirection::Rtl));
2461            assert!(waft_widgets::same_widget(
2462                &built,
2463                &drawer_built_child(tester)
2464            ));
2465
2466            // Without a shape of its own, the drawer reads the direction for its default.
2467            let drawer = Drawer::new().into_widget();
2468            let home = |text_direction: TextDirection| {
2469                let drawer = drawer.clone();
2470                move |_app: &mut App| Directionality::new(text_direction, drawer).into_widget()
2471            };
2472            pump_app(tester, m3, home(TextDirection::Ltr));
2473            let built = drawer_built_child(tester);
2474            pump_app(tester, m3, home(TextDirection::Rtl));
2475            assert!(!waft_widgets::same_widget(
2476                &built,
2477                &drawer_built_child(tester)
2478            ));
2479        });
2480    }
2481
2482    /// Not a Dart case: each getter of Dart's `_DrawerDefaultsM3` computes only its own value,
2483    /// so reading the elevation and the colours reads no `Directionality`, which this context
2484    /// does not have.
2485    #[test]
2486    fn the_material3_drawer_defaults_compute_only_the_value_asked_for() {
2487        test_widgets(|tester| {
2488            // The elevation and the shadow colour the builder read.
2489            type Read = Option<(Option<f64>, Option<Color>)>;
2490            let read: Rc<RefCell<Read>> = Rc::default();
2491            let read_in_builder = Rc::clone(&read);
2492            tester.pump_widget(
2493                Builder::new(move |app, context| {
2494                    let defaults = DrawerDefaultsM3::new(context);
2495                    *read_in_builder.borrow_mut() =
2496                        Some((defaults.elevation(app), defaults.shadow_color(app)));
2497                    SizedBox::new().into_widget()
2498                })
2499                .into_widget(),
2500            );
2501            assert_eq!(
2502                read.borrow_mut().take(),
2503                Some((Some(1.0), Some(Colors::TRANSPARENT)))
2504            );
2505        });
2506    }
2507
2508    // Regression test for https://github.com/flutter/flutter/issues/6537
2509    #[test]
2510    fn drawer_and_drawer_header_do_not_crash_at_zero_area() {
2511        test_widgets(|tester| {
2512            pump_app(tester, m3, move |_app| {
2513                Center::new()
2514                    .child(SizedBox::shrink().child(
2515                        Drawer::new().child(DrawerHeader::new(Some(Text::new("X").into_widget()))),
2516                    ))
2517                    .into_widget()
2518            });
2519            assert_eq!(drawer_box(tester).size(&tester.cell.borrow()), Size::ZERO);
2520            let header = *find::by_type::<DrawerHeader>()
2521                .evaluate(tester)
2522                .first()
2523                .expect("a header");
2524            assert_eq!(
2525                tester.render_box_of(header).size(&tester.cell.borrow()),
2526                Size::ZERO
2527            );
2528        });
2529    }
2530
2531    fn will_handle_pop_internally(tester: &WidgetTester, text: &str) -> bool {
2532        let element = *find::text(text).evaluate(tester).first().expect("the text");
2533        let mut app = tester.cell.borrow_mut();
2534        let route = AnyModalRoute::of(&mut app, element).expect("a modal route");
2535        route.as_route().will_handle_pop_internally(&app)
2536    }
2537
2538    /// Dart's `Scaffold.of(tester.element(find.text(text)))`.
2539    fn scaffold_of(tester: &WidgetTester, text: &str) -> Handle<ScaffoldState> {
2540        let element = *find::text(text).evaluate(tester).first().expect("the text");
2541        Scaffold::of(&mut tester.cell.borrow_mut(), element)
2542    }
2543
2544    /// The pushed `MaterialPageRoute`'s page of drawer_test.dart's leak cases, as the home
2545    /// page: `MaterialPageRoute` is not ported.
2546    fn second_page(drawer: impl FnOnce(Scaffold, Drawer) -> Scaffold) -> WidgetRef {
2547        drawer(
2548            Scaffold::new()
2549                .app_bar(PreferredSizeWidgetRef::new(
2550                    AppBar::new().title(Text::new("Second")),
2551                ))
2552                .body(Center::new().child(Text::new("Second Body"))),
2553            Drawer::new().child(Text::new("Drawer Item")),
2554        )
2555        .into_widget()
2556    }
2557
2558    fn ios(app: &App) -> ThemeData {
2559        ThemeData::builder()
2560            .platform(TargetPlatform::IOS)
2561            .build(app)
2562    }
2563
2564    // drawer_test.dart 'Drawer double tap to close does not leak LocalHistoryEntry', up to
2565    // its swipe back.
2566    #[test]
2567    fn drawer_double_tap_to_close_does_not_leak_local_history_entry() {
2568        test_widgets(|tester| {
2569            pump_app(tester, ios, |_app| {
2570                second_page(|scaffold, drawer| scaffold.end_drawer(drawer))
2571            });
2572            tester.pump_and_settle();
2573
2574            // Open the end drawer.
2575            let scaffold = scaffold_of(tester, "Second Body");
2576            scaffold.open_end_drawer(&mut tester.cell.borrow_mut());
2577            tester.pump_and_settle();
2578
2579            // Rapid double tap on the scrim.
2580            // Use manual pointer events to simulate tapping the scrim twice rapidly.
2581            tester.tap_at(Offset::new(10.0, 200.0), 1);
2582
2583            // Pump once to start the closing animation ticker.
2584            tester.pump();
2585            // Advance time by 150ms so the drawer is more than half closed.
2586            tester.pump_by(Duration::from_millis(150));
2587
2588            tester.tap_at(Offset::new(10.0, 200.0), 2);
2589
2590            tester.pump_and_settle();
2591
2592            // The drawer should be closed.
2593            assert_eq!(found(tester, "Drawer Item"), 0);
2594
2595            // The history entry should have been removed, meaning it won't handle pop internally.
2596            assert!(!will_handle_pop_internally(tester, "Second Body"));
2597        });
2598    }
2599
2600    // drawer_test.dart 'Drawer drag while closing does not leak LocalHistoryEntry'.
2601    #[test]
2602    fn drawer_drag_while_closing_does_not_leak_local_history_entry() {
2603        test_widgets(|tester| {
2604            pump_app(tester, ios, |_app| {
2605                second_page(|scaffold, drawer| scaffold.drawer(drawer))
2606            });
2607            tester.pump_and_settle();
2608
2609            // Open the drawer.
2610            let scaffold = scaffold_of(tester, "Second Body");
2611            scaffold.open_drawer(&mut tester.cell.borrow_mut());
2612            tester.pump_and_settle();
2613
2614            assert!(will_handle_pop_internally(tester, "Second Body"));
2615
2616            // Start closing the drawer programmatically to begin the closing animation.
2617            let scaffold = scaffold_of(tester, "Second Body");
2618            scaffold.close_drawer(&mut tester.cell.borrow_mut());
2619
2620            // Pump once to start the closing animation ticker.
2621            tester.pump();
2622            // Advance time so the drawer is in the middle of closing.
2623            tester.pump_by(Duration::from_millis(100));
2624
2625            // While it is closing (status == AnimationStatus.reverse), grab the drawer.
2626            // This triggers _handleDragDown, which adds the history entry back.
2627            let mut gesture = TestPointer::touch(1);
2628            tester.down(&mut gesture, Offset::new(50.0, 200.0));
2629            tester.pump();
2630
2631            // The history entry should have been re-added.
2632            assert!(will_handle_pop_internally(tester, "Second Body"));
2633
2634            // Drag it closed again by dragging left and releasing.
2635            let at = gesture.position + Offset::new(-20.0, 0.0);
2636            tester.move_to(&mut gesture, at, true);
2637            tester.pump();
2638            tester.up(&gesture);
2639
2640            tester.pump();
2641
2642            assert!(!will_handle_pop_internally(tester, "Second Body"));
2643
2644            tester.pump_and_settle();
2645
2646            assert_eq!(found(tester, "Drawer Item"), 0);
2647        });
2648    }
2649
2650    /// drawer_theme_test.dart's `_drawerMaterial`, `_scrim` and `_drawerRenderBox` readings.
2651    struct Seen {
2652        color: Option<Color>,
2653        elevation: f64,
2654        shadow_color: Option<Color>,
2655        surface_tint_color: Option<Color>,
2656        shape: Option<ShapeBorderRef>,
2657        scrim_color: Color,
2658        width: f64,
2659        clip_behavior: Clip,
2660    }
2661
2662    /// The drawer `drawer` makes, as the start drawer or the end drawer of the `Scaffold` keyed
2663    /// `key` that `home` builds, opened and settled, as the theme cases read it.
2664    fn opened_drawer(
2665        tester: &mut WidgetTester,
2666        theme: impl FnOnce(&App) -> ThemeData,
2667        alignment: DrawerAlignment,
2668        drawer: impl Fn() -> Drawer + 'static,
2669        home: impl Fn(Scaffold) -> WidgetRef + 'static,
2670    ) -> Seen {
2671        let key = GlobalKey::new();
2672        let scaffold_key = key.clone();
2673        pump_app(tester, theme, move |_app| {
2674            let scaffold = Scaffold::new().key(scaffold_key.clone().into());
2675            home(match alignment {
2676                DrawerAlignment::Start => scaffold.drawer(drawer()),
2677                DrawerAlignment::End => scaffold.end_drawer(drawer()),
2678            })
2679        });
2680        match alignment {
2681            DrawerAlignment::Start => open_drawer(tester, &key),
2682            DrawerAlignment::End => open_end_drawer(tester, &key),
2683        }
2684        tester.pump_and_settle();
2685        let (color, elevation, shadow_color, surface_tint_color, clip_behavior) =
2686            material(tester, |material| {
2687                (
2688                    material.color,
2689                    material.elevation,
2690                    material.shadow_color,
2691                    material.surface_tint_color,
2692                    material.clip_behavior,
2693                )
2694            });
2695        Seen {
2696            color,
2697            elevation,
2698            shadow_color,
2699            surface_tint_color,
2700            shape: material_shape(tester),
2701            scrim_color: scrim_color(tester),
2702            width: drawer_width(tester),
2703            clip_behavior,
2704        }
2705    }
2706
2707    fn theme_defaults(
2708        tester: &mut WidgetTester,
2709        theme: fn(&App) -> ThemeData,
2710        alignment: DrawerAlignment,
2711        shape: Option<RoundedRectangleBorder>,
2712    ) {
2713        let seen = opened_drawer(
2714            tester,
2715            theme,
2716            alignment,
2717            Drawer::new,
2718            IntoWidget::into_widget,
2719        );
2720        let theme = { theme(&tester.cell.borrow()) };
2721        if theme.use_material3 {
2722            assert_eq!(seen.color, Some(theme.color_scheme.surface_container_low()));
2723            assert_eq!(seen.elevation, 1.0);
2724            assert_eq!(seen.shadow_color, Some(Colors::TRANSPARENT));
2725            assert_eq!(seen.surface_tint_color, Some(Colors::TRANSPARENT));
2726            assert_eq!(seen.clip_behavior, Clip::HardEdge);
2727        } else {
2728            assert_eq!(seen.color, None);
2729            assert_eq!(seen.elevation, 16.0);
2730            assert_eq!(seen.shadow_color, Some(theme.shadow_color));
2731            assert_eq!(seen.surface_tint_color, None);
2732            assert_eq!(seen.clip_behavior, Clip::None);
2733        }
2734        assert_eq!(
2735            seen.shape.as_deref(),
2736            shape.as_ref().map(|shape| shape as &dyn ShapeBorder)
2737        );
2738        assert_eq!(seen.scrim_color, Colors::BLACK54);
2739        assert_eq!(seen.width, 304.0);
2740    }
2741
2742    #[test]
2743    fn material2_default_values_are_used_when_no_drawer_or_drawer_theme_data_properties_are_specified()
2744     {
2745        test_widgets(|tester| theme_defaults(tester, m2, DrawerAlignment::Start, None));
2746    }
2747
2748    #[test]
2749    fn material3_default_values_are_used_when_no_drawer_or_drawer_theme_data_properties_are_specified()
2750     {
2751        test_widgets(|tester| {
2752            theme_defaults(
2753                tester,
2754                m3,
2755                DrawerAlignment::Start,
2756                Some(rounded(BorderRadius::horizontal(
2757                    Radius::ZERO,
2758                    Radius::circular(16.0),
2759                ))),
2760            );
2761        });
2762    }
2763
2764    #[test]
2765    fn material2_default_values_are_used_when_no_drawer_or_drawer_theme_data_properties_are_specified_in_end_drawer()
2766     {
2767        test_widgets(|tester| theme_defaults(tester, m2, DrawerAlignment::End, None));
2768    }
2769
2770    #[test]
2771    fn material3_default_values_are_used_when_no_drawer_or_drawer_theme_data_properties_are_specified_in_end_drawer()
2772     {
2773        test_widgets(|tester| {
2774            theme_defaults(
2775                tester,
2776                m3,
2777                DrawerAlignment::End,
2778                Some(rounded(BorderRadius::horizontal(
2779                    Radius::circular(16.0),
2780                    Radius::ZERO,
2781                ))),
2782            );
2783        });
2784    }
2785
2786    const BACKGROUND_COLOR: Color = Color::new(0x00000001);
2787    const SCRIM_COLOR: Color = Color::new(0x00000002);
2788    const ELEVATION: f64 = 7.0;
2789    const SHADOW_COLOR: Color = Color::new(0x00000003);
2790    const SURFACE_TINT_COLOR: Color = Color::new(0x00000004);
2791    const WIDTH: f64 = 200.0;
2792    const CLIP_BEHAVIOR: Clip = Clip::AntiAlias;
2793
2794    fn shape() -> RoundedRectangleBorder {
2795        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(16.0))
2796    }
2797
2798    fn assert_given_values(seen: &Seen) {
2799        assert_eq!(seen.color, Some(BACKGROUND_COLOR));
2800        assert_eq!(seen.elevation, ELEVATION);
2801        assert_eq!(seen.shadow_color, Some(SHADOW_COLOR));
2802        assert_eq!(seen.surface_tint_color, Some(SURFACE_TINT_COLOR));
2803        assert_eq!(seen.shape.as_deref(), Some(&shape() as &dyn ShapeBorder));
2804        assert_eq!(seen.scrim_color, SCRIM_COLOR);
2805        assert_eq!(seen.width, WIDTH);
2806        assert_eq!(seen.clip_behavior, CLIP_BEHAVIOR);
2807    }
2808
2809    fn given_theme() -> DrawerThemeData {
2810        DrawerThemeData::new()
2811            .background_color(BACKGROUND_COLOR)
2812            .scrim_color(SCRIM_COLOR)
2813            .elevation(ELEVATION)
2814            .shadow_color(SHADOW_COLOR)
2815            .surface_tint_color(SURFACE_TINT_COLOR)
2816            .shape(shape())
2817            .width(WIDTH)
2818            .clip_behavior(CLIP_BEHAVIOR)
2819    }
2820
2821    #[test]
2822    fn drawer_theme_data_values_are_used_when_no_drawer_properties_are_specified() {
2823        test_widgets(|tester| {
2824            let seen = opened_drawer(
2825                tester,
2826                |app| ThemeData::builder().drawer_theme(given_theme()).build(app),
2827                DrawerAlignment::Start,
2828                Drawer::new,
2829                IntoWidget::into_widget,
2830            );
2831            assert_given_values(&seen);
2832        });
2833    }
2834
2835    fn other_theme() -> DrawerThemeData {
2836        DrawerThemeData::new()
2837            .background_color(Color::new(0x00000005))
2838            .scrim_color(Color::new(0x00000006))
2839            .elevation(13.0)
2840            .shape(RoundedRectangleBorder::new(
2841                BorderSide::NONE,
2842                BorderRadiusGeometry::circular(29.0),
2843            ))
2844            .width(400.0)
2845            .clip_behavior(Clip::AntiAliasWithSaveLayer)
2846    }
2847
2848    #[test]
2849    fn drawer_values_take_priority_over_drawer_theme_data_values_when_both_properties_are_specified()
2850     {
2851        test_widgets(|tester| {
2852            let seen = opened_drawer(
2853                tester,
2854                |app| ThemeData::builder().drawer_theme(other_theme()).build(app),
2855                DrawerAlignment::Start,
2856                || {
2857                    Drawer::new()
2858                        .background_color(BACKGROUND_COLOR)
2859                        .elevation(ELEVATION)
2860                        .shadow_color(SHADOW_COLOR)
2861                        .surface_tint_color(SURFACE_TINT_COLOR)
2862                        .shape(shape())
2863                        .width(WIDTH)
2864                        .clip_behavior(CLIP_BEHAVIOR)
2865                },
2866                |scaffold| scaffold.drawer_scrim_color(SCRIM_COLOR).into_widget(),
2867            );
2868            assert_given_values(&seen);
2869        });
2870    }
2871
2872    #[test]
2873    fn drawer_theme_values_take_priority_over_theme_data_drawer_theme_values_when_both_properties_are_specified()
2874     {
2875        test_widgets(|tester| {
2876            let seen = opened_drawer(
2877                tester,
2878                |app| {
2879                    ThemeData::builder()
2880                        .drawer_theme(
2881                            other_theme()
2882                                .shadow_color(Color::new(0x00000007))
2883                                .surface_tint_color(Color::new(0x00000007)),
2884                        )
2885                        .build(app)
2886                },
2887                DrawerAlignment::Start,
2888                Drawer::new,
2889                |scaffold| DrawerTheme::new(given_theme(), scaffold).into_widget(),
2890            );
2891            assert_given_values(&seen);
2892        });
2893    }
2894
2895    /// `DrawerController(isDrawerOpen:)`, which the scaffold sets from its restored state: the
2896    /// drawer shows at once, fully open, and a rebuild with false closes it at once.
2897    #[test]
2898    fn is_drawer_open_opens_the_drawer_at_once() {
2899        test_widgets(|tester| {
2900            let pump = |tester: &mut WidgetTester, is_drawer_open: bool| {
2901                pump_app(tester, m3, move |_app| {
2902                    Material::new()
2903                        .child(
2904                            DrawerController::new(Text::new("drawer"), DrawerAlignment::Start)
2905                                .is_drawer_open(is_drawer_open),
2906                        )
2907                        .into_widget()
2908                });
2909            };
2910            pump(tester, true);
2911            assert_eq!(found(tester, "drawer"), 1);
2912            assert_eq!(tester.get_rect(find::text("drawer")).left, 0.0);
2913
2914            pump(tester, false);
2915            assert_eq!(found(tester, "drawer"), 0);
2916        });
2917    }
2918}