Skip to main content

waft_material/
floating_action_button_location.rs

1//! Flutter counterpart: material_ui's `floating_action_button_location.dart`.
2//!
3//! The standard locations and animators are per-thread `Rc`s handed out by functions on the
4//! trait objects, so the scaffold compares them as Dart compares its `const` instances: by
5//! identity (`Rc::ptr_eq`).
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9use std::time::Duration;
10
11use waft_animation::{
12    AlwaysStoppedAnimation, Animation, AnimationLazyListenerData, AnimationLazyListenerMixin,
13    AnimationLocalListenersData, AnimationLocalListenersMixin, AnimationLocalStatusListenersData,
14    AnimationLocalStatusListenersMixin, AnimationRef, AnimationStatus, AnimationStatusListener,
15    AnyAnimation, CompoundAnimation, Curve, CurveTween, Curves, Drive, Interval, ReverseAnimation,
16    Threshold, Tween, compound_did_start_listening, compound_did_stop_listening,
17};
18use waft_embedder::{Offset, TextDirection};
19use waft_foundation::{App, Handle, Listener, Ref};
20
21use crate::scaffold::ScaffoldPrelayoutGeometry;
22
23/// The margin that a `FloatingActionButton` should leave between it and the
24/// edge of the screen.
25///
26/// [`FloatingActionButtonLocation::end_float`](dyn FloatingActionButtonLocation::end_float)
27/// uses this to set the appropriate margin between the `FloatingActionButton` and the end of
28/// the screen.
29pub const K_FLOATING_ACTION_BUTTON_MARGIN: f64 = 16.0;
30
31/// The amount of time the `FloatingActionButton` takes to transition in or out.
32///
33/// The `Scaffold` uses this to set the duration of `FloatingActionButton`
34/// motion, entrance, and exit animations.
35pub const K_FLOATING_ACTION_BUTTON_SEGUE: Duration = Duration::from_millis(200);
36
37/// The fraction of a circle the `FloatingActionButton` should turn when it enters.
38///
39/// Its value corresponds to 0.125 of a full circle, equivalent to 45 degrees or pi/4 radians.
40pub const K_FLOATING_ACTION_BUTTON_TURN_INTERVAL: f64 = 0.125;
41
42/// If a `FloatingActionButton` is used on a `Scaffold` in certain positions,
43/// it is moved [`K_MINI_BUTTON_OFFSET_ADJUSTMENT`] pixels closer to the edge of the screen.
44///
45/// This is intended to be used with `FloatingActionButton.mini` set to true,
46/// so that the floating action button appears to align with `CircleAvatar`s
47/// in the `ListTile.leading` slot of a `ListTile` in a `ListView` in the
48/// `Scaffold.body`.
49///
50/// More specifically:
51/// * In the following positions, the `FloatingActionButton` is moved *horizontally*
52///   closer to the edge of the screen:
53///   * `FloatingActionButtonLocation.miniStartTop`
54///   * `FloatingActionButtonLocation.miniStartFloat`
55///   * `FloatingActionButtonLocation.miniStartDocked`
56///   * `FloatingActionButtonLocation.miniEndTop`
57///   * `FloatingActionButtonLocation.miniEndFloat`
58///   * `FloatingActionButtonLocation.miniEndDocked`
59/// * In the following positions, the `FloatingActionButton` is moved *vertically*
60///   closer to the bottom of the screen:
61///   * `FloatingActionButtonLocation.miniStartFloat`
62///   * `FloatingActionButtonLocation.miniCenterFloat`
63///   * `FloatingActionButtonLocation.miniEndFloat`
64pub const K_MINI_BUTTON_OFFSET_ADJUSTMENT: f64 = 4.0;
65
66/// An object that defines a position for the `FloatingActionButton`
67/// based on the `Scaffold`'s [`ScaffoldPrelayoutGeometry`].
68///
69/// Flutter provides [`FloatingActionButtonLocation`]s for the common
70/// `FloatingActionButton` placements in Material Design applications. These
71/// locations are available as functions on `dyn FloatingActionButtonLocation`
72/// (`<dyn FloatingActionButtonLocation>::end_float()`).
73///
74/// See also:
75///
76///  * `FloatingActionButton`, which is a circular button typically shown in the
77///    bottom right corner of the app.
78///  * [`FloatingActionButtonAnimator`], which is used to animate the
79///    `Scaffold.floatingActionButton` from one [`FloatingActionButtonLocation`] to
80///    another.
81///  * [`ScaffoldPrelayoutGeometry`], the geometry that
82///    [`FloatingActionButtonLocation`]s use to position the `FloatingActionButton`.
83pub trait FloatingActionButtonLocation: Debug + 'static {
84    /// Places the `FloatingActionButton` based on the `Scaffold`'s layout.
85    ///
86    /// This uses a [`ScaffoldPrelayoutGeometry`], which the `Scaffold` constructs
87    /// during its layout phase after it has laid out every widget it can lay out
88    /// except the `FloatingActionButton`. The `Scaffold` uses the [`Offset`]
89    /// returned from this method to position the `FloatingActionButton` and
90    /// complete its layout.
91    fn get_offset(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry) -> Offset;
92}
93
94/// A shared [`FloatingActionButtonLocation`], compared by identity as Dart compares its
95/// locations.
96pub type FloatingActionButtonLocationRef = Rc<dyn FloatingActionButtonLocation>;
97
98/// Defines a function on `dyn FloatingActionButtonLocation` handing out clones of one
99/// per-thread `Rc` of a standard location: Dart's `static const`.
100macro_rules! standard_locations {
101    ($( $(#[$doc:meta])* $name:ident = $value:expr; )*) => {
102        impl dyn FloatingActionButtonLocation {
103            $(
104                $(#[$doc])*
105                pub fn $name() -> FloatingActionButtonLocationRef {
106                    thread_local! {
107                        static LOCATION: FloatingActionButtonLocationRef = Rc::new($value);
108                    }
109                    LOCATION.with(Rc::clone)
110                }
111            )*
112        }
113    };
114}
115
116standard_locations! {
117    /// Start-aligned `FloatingActionButton`, floating over the transition between
118    /// the `Scaffold.appBar` and the `Scaffold.body`.
119    ///
120    /// To align a floating action button with `CircleAvatar`s in the
121    /// `ListTile.leading` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
122    /// use [`mini_start_top`](Self::mini_start_top) and set `FloatingActionButton.mini` to
123    /// true.
124    ///
125    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
126    /// or that use a `SliverAppBar` in the scaffold body itself.
127    start_top = StartTopFabLocation;
128
129    /// Start-aligned `FloatingActionButton`, floating over the transition between
130    /// the `Scaffold.appBar` and the `Scaffold.body`, optimized for mini floating
131    /// action buttons.
132    ///
133    /// This is intended to be used with `FloatingActionButton.mini` set to true,
134    /// so that the floating action button appears to align with `CircleAvatar`s
135    /// in the `ListTile.leading` slot of a `ListTile` in a `ListView` in the
136    /// `Scaffold.body`.
137    ///
138    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
139    /// or that use a `SliverAppBar` in the scaffold body itself.
140    mini_start_top = MiniStartTopFabLocation;
141
142    /// Centered `FloatingActionButton`, floating over the transition between
143    /// the `Scaffold.appBar` and the `Scaffold.body`.
144    ///
145    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
146    /// or that use a `SliverAppBar` in the scaffold body itself.
147    center_top = CenterTopFabLocation;
148
149    /// Centered `FloatingActionButton`, floating over the transition between
150    /// the `Scaffold.appBar` and the `Scaffold.body`, intended to be used with
151    /// `FloatingActionButton.mini` set to true.
152    ///
153    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
154    /// or that use a `SliverAppBar` in the scaffold body itself.
155    mini_center_top = MiniCenterTopFabLocation;
156
157    /// End-aligned `FloatingActionButton`, floating over the transition between
158    /// the `Scaffold.appBar` and the `Scaffold.body`.
159    ///
160    /// To align a floating action button with `CircleAvatar`s in the
161    /// `ListTile.trailing` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
162    /// use [`mini_end_top`](Self::mini_end_top) and set `FloatingActionButton.mini` to true.
163    ///
164    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
165    /// or that use a `SliverAppBar` in the scaffold body itself.
166    end_top = EndTopFabLocation;
167
168    /// End-aligned `FloatingActionButton`, floating over the transition between
169    /// the `Scaffold.appBar` and the `Scaffold.body`, optimized for mini floating
170    /// action buttons.
171    ///
172    /// This is intended to be used with `FloatingActionButton.mini` set to true,
173    /// so that the floating action button appears to align with `CircleAvatar`s
174    /// in the `ListTile.trailing` slot of a `ListTile` in a `ListView` in the
175    /// `Scaffold.body`.
176    ///
177    /// This is unlikely to be a useful location for apps that lack a top `AppBar`
178    /// or that use a `SliverAppBar` in the scaffold body itself.
179    mini_end_top = MiniEndTopFabLocation;
180
181    /// Start-aligned `FloatingActionButton`, floating at the bottom of the screen.
182    ///
183    /// To align a floating action button with `CircleAvatar`s in the
184    /// `ListTile.leading` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
185    /// use [`mini_start_float`](Self::mini_start_float) and set `FloatingActionButton.mini`
186    /// to true.
187    start_float = StartFloatFabLocation;
188
189    /// Start-aligned `FloatingActionButton`, floating at the bottom of the screen,
190    /// optimized for mini floating action buttons.
191    ///
192    /// This is intended to be used with `FloatingActionButton.mini` set to true,
193    /// so that the floating action button appears to align with `CircleAvatar`s
194    /// in the `ListTile.leading` slot of a `ListTile` in a `ListView` in the
195    /// `Scaffold.body`.
196    ///
197    /// Compared to [`start_float`](Self::start_float), floating action
198    /// buttons using this location will move horizontally _and_ vertically
199    /// closer to the edges, by [`K_MINI_BUTTON_OFFSET_ADJUSTMENT`] each.
200    mini_start_float = MiniStartFloatFabLocation;
201
202    /// Centered `FloatingActionButton`, floating at the bottom of the screen.
203    ///
204    /// To position a mini floating action button, use
205    /// [`mini_center_float`](Self::mini_center_float) and set `FloatingActionButton.mini` to
206    /// true.
207    center_float = CenterFloatFabLocation;
208
209    /// Centered `FloatingActionButton`, floating at the bottom of the screen,
210    /// optimized for mini floating action buttons.
211    ///
212    /// This is intended to be used with `FloatingActionButton.mini` set to true,
213    /// so that the floating action button appears to align horizontally with
214    /// the locations [`mini_start_float`](Self::mini_start_float)
215    /// and [`mini_end_float`](Self::mini_end_float).
216    ///
217    /// Compared to [`center_float`](Self::center_float), floating action
218    /// buttons using this location will move vertically down
219    /// by [`K_MINI_BUTTON_OFFSET_ADJUSTMENT`].
220    mini_center_float = MiniCenterFloatFabLocation;
221
222    /// End-aligned `FloatingActionButton`, floating at the bottom of the screen.
223    ///
224    /// This is the default alignment of `FloatingActionButton`s in Material applications.
225    ///
226    /// To align a floating action button with `CircleAvatar`s in the
227    /// `ListTile.trailing` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
228    /// use [`mini_end_float`](Self::mini_end_float) and set `FloatingActionButton.mini` to
229    /// true.
230    end_float = EndFloatFabLocation;
231
232    /// End-aligned `FloatingActionButton`, floating at the bottom of the screen,
233    /// optimized for mini floating action buttons.
234    ///
235    /// This is intended to be used with `FloatingActionButton.mini` set to true,
236    /// so that the floating action button appears to align with `CircleAvatar`s
237    /// in the `ListTile.trailing` slot of a `ListTile` in a `ListView` in the
238    /// `Scaffold.body`.
239    ///
240    /// Compared to [`end_float`](Self::end_float), floating action
241    /// buttons using this location will move horizontally _and_ vertically
242    /// closer to the edges, by [`K_MINI_BUTTON_OFFSET_ADJUSTMENT`] each.
243    mini_end_float = MiniEndFloatFabLocation;
244
245    /// Start-aligned `FloatingActionButton`, floating over the
246    /// `Scaffold.bottomNavigationBar` so that the center of the floating
247    /// action button lines up with the top of the bottom navigation bar.
248    ///
249    /// To align a floating action button with `CircleAvatar`s in the
250    /// `ListTile.leading` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
251    /// use [`mini_start_docked`](Self::mini_start_docked) and set
252    /// `FloatingActionButton.mini` to true.
253    ///
254    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
255    /// the bottom app bar can include a "notch" in its shape that accommodates
256    /// the overlapping floating action button.
257    ///
258    /// This is unlikely to be a useful location for apps that lack a bottom
259    /// navigation bar.
260    start_docked = StartDockedFabLocation;
261
262    /// Start-aligned `FloatingActionButton`, floating over the
263    /// `Scaffold.bottomNavigationBar` so that the center of the floating
264    /// action button lines up with the top of the bottom navigation bar,
265    /// optimized for mini floating action buttons.
266    ///
267    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
268    /// the bottom app bar can include a "notch" in its shape that accommodates
269    /// the overlapping floating action button.
270    ///
271    /// This is intended to be used with `FloatingActionButton.mini` set to true,
272    /// so that the floating action button appears to align with `CircleAvatar`s
273    /// in the `ListTile.leading` slot of a `ListTile` in a `ListView` in the
274    /// `Scaffold.body`.
275    ///
276    /// This is unlikely to be a useful location for apps that lack a bottom
277    /// navigation bar.
278    mini_start_docked = MiniStartDockedFabLocation;
279
280    /// Centered `FloatingActionButton`, floating over the
281    /// `Scaffold.bottomNavigationBar` so that the center of the floating
282    /// action button lines up with the top of the bottom navigation bar.
283    ///
284    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
285    /// the bottom app bar can include a "notch" in its shape that accommodates
286    /// the overlapping floating action button.
287    ///
288    /// This is unlikely to be a useful location for apps that lack a bottom
289    /// navigation bar.
290    center_docked = CenterDockedFabLocation;
291
292    /// Centered `FloatingActionButton`, floating over the
293    /// `Scaffold.bottomNavigationBar` so that the center of the floating
294    /// action button lines up with the top of the bottom navigation bar;
295    /// intended to be used with `FloatingActionButton.mini` set to true.
296    ///
297    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
298    /// the bottom app bar can include a "notch" in its shape that accommodates
299    /// the overlapping floating action button.
300    ///
301    /// This is unlikely to be a useful location for apps that lack a bottom
302    /// navigation bar.
303    mini_center_docked = MiniCenterDockedFabLocation;
304
305    /// End-aligned `FloatingActionButton`, floating over the
306    /// `Scaffold.bottomNavigationBar` so that the center of the floating
307    /// action button lines up with the top of the bottom navigation bar.
308    ///
309    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
310    /// the bottom app bar can include a "notch" in its shape that accommodates
311    /// the overlapping floating action button.
312    ///
313    /// This is unlikely to be a useful location for apps that lack a bottom
314    /// navigation bar.
315    end_docked = EndDockedFabLocation;
316
317    /// End-aligned `FloatingActionButton`, floating over the
318    /// `Scaffold.bottomNavigationBar` so that the center of the floating
319    /// action button lines up with the top of the bottom navigation bar,
320    /// optimized for mini floating action buttons.
321    ///
322    /// To align a floating action button with `CircleAvatar`s in the
323    /// `ListTile.trailing` slots of `ListTile`s in a `ListView` in the `Scaffold.body`,
324    /// use [`mini_end_docked`](Self::mini_end_docked) and set `FloatingActionButton.mini` to
325    /// true.
326    ///
327    /// If the value of `Scaffold.bottomNavigationBar` is a `BottomAppBar`,
328    /// the bottom app bar can include a "notch" in its shape that accommodates
329    /// the overlapping floating action button.
330    ///
331    /// This is intended to be used with `FloatingActionButton.mini` set to true,
332    /// so that the floating action button appears to align with `CircleAvatar`s
333    /// in the `ListTile.trailing` slot of a `ListTile` in a `ListView` in the
334    /// `Scaffold.body`.
335    ///
336    /// This is unlikely to be a useful location for apps that lack a bottom
337    /// navigation bar.
338    mini_end_docked = MiniEndDockedFabLocation;
339
340    /// End-aligned `FloatingActionButton`, floating over the
341    /// `Scaffold.bottomNavigationBar` so that the floating
342    /// action button lines up with the center of the bottom navigation bar.
343    ///
344    /// This is unlikely to be a useful location for apps which has a `BottomNavigationBar`
345    /// or a non material 3 `BottomAppBar`.
346    end_contained = EndContainedFabLocation;
347}
348
349/// A base trait that simplifies building [`FloatingActionButtonLocation`]s when
350/// used with the mixins [`FabTopOffsetY`], [`FabFloatOffsetY`], [`FabDockedOffsetY`],
351/// [`FabStartOffsetX`], [`FabCenterOffsetX`], [`FabEndOffsetX`], and
352/// [`FabMiniOffsetAdjustment`].
353///
354/// A subclass of [`FloatingActionButtonLocation`] which implements its
355/// [`get_offset`](FloatingActionButtonLocation::get_offset) method using three other methods:
356/// [`get_offset_x`](Self::get_offset_x), [`get_offset_y`](Self::get_offset_y), and
357/// [`is_mini`](Self::is_mini).
358///
359/// Different mixins on this class override different methods, so that combining
360/// a set of mixins creates a floating action button location. A location implements the
361/// mixins it uses and forwards [`get_offset_x`](Self::get_offset_x),
362/// [`get_offset_y`](Self::get_offset_y) and [`is_mini`](Self::is_mini) to them, and its
363/// [`FloatingActionButtonLocation::get_offset`] to [`StandardFabLocation::get_offset`].
364///
365/// For example: the location `<dyn FloatingActionButtonLocation>::mini_end_top()`
366/// is based on a type that implements [`StandardFabLocation`]
367/// with the mixins [`FabMiniOffsetAdjustment`], [`FabEndOffsetX`], and [`FabTopOffsetY`].
368///
369/// You can create your own implementation of [`StandardFabLocation`]
370/// to implement a custom [`FloatingActionButtonLocation`].
371pub trait StandardFabLocation: FloatingActionButtonLocation {
372    /// Obtains the x-offset to place the `FloatingActionButton` based on the
373    /// `Scaffold`'s layout.
374    ///
375    /// Used by [`get_offset`](Self::get_offset) to compute its x-coordinate.
376    fn get_offset_x(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64;
377
378    /// Obtains the y-offset to place the `FloatingActionButton` based on the
379    /// `Scaffold`'s layout.
380    ///
381    /// Used by [`get_offset`](Self::get_offset) to compute its y-coordinate.
382    fn get_offset_y(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64;
383
384    /// A function returning whether this [`StandardFabLocation`] is optimized for
385    /// mini `FloatingActionButton`s.
386    fn is_mini(&self) -> bool {
387        false
388    }
389
390    /// Dart's `StandardFabLocation.getOffset` override, which the implementing location's
391    /// [`FloatingActionButtonLocation::get_offset`] calls.
392    fn get_offset(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry) -> Offset {
393        let adjustment = if StandardFabLocation::is_mini(self) {
394            K_MINI_BUTTON_OFFSET_ADJUSTMENT
395        } else {
396            0.0
397        };
398        Offset::new(
399            StandardFabLocation::get_offset_x(self, scaffold_geometry, adjustment),
400            StandardFabLocation::get_offset_y(self, scaffold_geometry, adjustment),
401        )
402    }
403}
404
405/// Calculates x-offset for left-aligned [`FloatingActionButtonLocation`]s; Dart's
406/// `StandardFabLocation._leftOffsetX`.
407fn left_offset_x(scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
408    K_FLOATING_ACTION_BUTTON_MARGIN + scaffold_geometry.min_insets.left - adjustment
409}
410
411/// Calculates x-offset for right-aligned [`FloatingActionButtonLocation`]s; Dart's
412/// `StandardFabLocation._rightOffsetX`.
413fn right_offset_x(scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
414    scaffold_geometry.scaffold_size.width()
415        - K_FLOATING_ACTION_BUTTON_MARGIN
416        - scaffold_geometry.min_insets.right
417        - scaffold_geometry.floating_action_button_size.width()
418        + adjustment
419}
420
421/// Mixin for a "top" floating action button location, such as
422/// `<dyn FloatingActionButtonLocation>::start_top()`.
423///
424/// The `adjustment`, typically [`K_MINI_BUTTON_OFFSET_ADJUSTMENT`], is ignored in the
425/// Y axis of "top" positions. For "top" positions, the X offset is adjusted to
426/// move closer to the edge of the screen. This is so that a minified floating
427/// action button appears to align with `CircleAvatar`s in the
428/// `ListTile.leading` slot of a `ListTile` in a `ListView` in the
429/// `Scaffold.body`.
430pub trait FabTopOffsetY: StandardFabLocation {
431    /// Calculates y-offset for [`FloatingActionButtonLocation`]s floating over
432    /// the transition between the `Scaffold.appBar` and the `Scaffold.body`.
433    fn get_offset_y(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
434        let _ = adjustment;
435        if scaffold_geometry.content_top > scaffold_geometry.min_view_padding.top {
436            let fab_half_height = scaffold_geometry.floating_action_button_size.height() / 2.0;
437            return scaffold_geometry.content_top - fab_half_height;
438        }
439        // Otherwise, ensure we are placed within the bounds of a safe area.
440        scaffold_geometry.min_view_padding.top
441    }
442}
443
444/// Mixin for a "float" floating action button location, such as
445/// `<dyn FloatingActionButtonLocation>::center_float()`.
446pub trait FabFloatOffsetY: StandardFabLocation {
447    /// Calculates y-offset for [`FloatingActionButtonLocation`]s floating at
448    /// the bottom of the screen.
449    fn get_offset_y(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
450        let content_bottom = scaffold_geometry.content_bottom;
451        let bottom_content_height = scaffold_geometry.scaffold_size.height() - content_bottom;
452        let bottom_sheet_height = scaffold_geometry.bottom_sheet_size.height();
453        let fab_height = scaffold_geometry.floating_action_button_size.height();
454        let snack_bar_height = scaffold_geometry.snack_bar_size.height();
455        let safe_margin = f64::max(
456            K_FLOATING_ACTION_BUTTON_MARGIN,
457            scaffold_geometry.min_view_padding.bottom - bottom_content_height
458                + K_FLOATING_ACTION_BUTTON_MARGIN,
459        );
460
461        let mut fab_y = content_bottom - fab_height - safe_margin;
462        if snack_bar_height > 0.0 {
463            fab_y = f64::min(
464                fab_y,
465                content_bottom - snack_bar_height - fab_height - K_FLOATING_ACTION_BUTTON_MARGIN,
466            );
467        }
468        if bottom_sheet_height > 0.0 {
469            fab_y = f64::min(
470                fab_y,
471                content_bottom - bottom_sheet_height - fab_height / 2.0,
472            );
473        }
474        fab_y + adjustment
475    }
476}
477
478/// Mixin for a "docked" floating action button location, such as
479/// `<dyn FloatingActionButtonLocation>::end_docked()`.
480pub trait FabDockedOffsetY: StandardFabLocation {
481    /// Calculates y-offset for [`FloatingActionButtonLocation`]s floating over the
482    /// `Scaffold.bottomNavigationBar` so that the center of the floating
483    /// action button lines up with the top of the bottom navigation bar.
484    fn get_offset_y(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
485        let _ = adjustment;
486        let content_bottom = scaffold_geometry.content_bottom;
487        let content_margin = scaffold_geometry.scaffold_size.height() - content_bottom;
488        let bottom_view_padding = scaffold_geometry.min_view_padding.bottom;
489        let bottom_sheet_height = scaffold_geometry.bottom_sheet_size.height();
490        let fab_height = scaffold_geometry.floating_action_button_size.height();
491        let snack_bar_height = scaffold_geometry.snack_bar_size.height();
492        let bottom_min_inset = scaffold_geometry.min_insets.bottom;
493
494        let safe_margin = if content_margin > bottom_min_inset + fab_height / 2.0 {
495            // If contentMargin is higher than bottomMinInset enough to display the
496            // FAB without clipping, don't provide a margin
497            0.0
498        } else if bottom_min_inset == 0.0 {
499            // If bottomMinInset is zero(the software keyboard is not on the screen)
500            // provide bottomViewPadding as margin
501            bottom_view_padding
502        } else {
503            // Provide a margin that would shift the FAB enough so that it stays away
504            // from the keyboard
505            fab_height / 2.0 + K_FLOATING_ACTION_BUTTON_MARGIN
506        };
507
508        let mut fab_y = content_bottom - fab_height / 2.0 - safe_margin;
509        // The FAB should sit with a margin between it and the snack bar.
510        if snack_bar_height > 0.0 {
511            fab_y = f64::min(
512                fab_y,
513                content_bottom - snack_bar_height - fab_height - K_FLOATING_ACTION_BUTTON_MARGIN,
514            );
515        }
516        // The FAB should sit with its center in front of the top of the bottom sheet.
517        if bottom_sheet_height > 0.0 {
518            fab_y = f64::min(
519                fab_y,
520                content_bottom - bottom_sheet_height - fab_height / 2.0,
521            );
522        }
523        let max_fab_y = scaffold_geometry.scaffold_size.height() - fab_height - safe_margin;
524        f64::min(max_fab_y, fab_y)
525    }
526}
527
528/// Mixin for a "contained" floating action button location, such as
529/// `<dyn FloatingActionButtonLocation>::end_contained()`.
530pub trait FabContainedOffsetY: StandardFabLocation {
531    /// Calculates y-offset for [`FloatingActionButtonLocation`]s floating over the
532    /// `Scaffold.bottomNavigationBar` so that the center of the floating
533    /// action button lines up with the center of the bottom navigation bar.
534    fn get_offset_y(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
535        let _ = adjustment;
536        let content_bottom = scaffold_geometry.content_bottom;
537        let content_margin = scaffold_geometry.scaffold_size.height() - content_bottom;
538        let bottom_view_padding = scaffold_geometry.min_view_padding.bottom;
539        let fab_height = scaffold_geometry.floating_action_button_size.height();
540
541        let safe_margin = if content_margin > bottom_view_padding + fab_height {
542            // If contentMargin is higher than bottomViewPadding enough to display the
543            // FAB without clipping, don't provide a margin
544            0.0
545        } else {
546            bottom_view_padding
547        };
548
549        // This is to compute the distance between the content bottom to the top edge
550        // of the floating action button. This can be negative if content margin is
551        // too small.
552        let content_bottom_to_fab_top = (content_margin - bottom_view_padding - fab_height) / 2.0;
553        let fab_y = content_bottom + content_bottom_to_fab_top;
554        let max_fab_y = scaffold_geometry.scaffold_size.height() - fab_height - safe_margin;
555
556        f64::min(max_fab_y, fab_y)
557    }
558}
559
560/// Mixin for a "start" floating action button location, such as
561/// `<dyn FloatingActionButtonLocation>::start_top()`.
562pub trait FabStartOffsetX: StandardFabLocation {
563    /// Calculates x-offset for start-aligned [`FloatingActionButtonLocation`]s.
564    fn get_offset_x(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
565        match scaffold_geometry.text_direction {
566            TextDirection::Rtl => right_offset_x(scaffold_geometry, adjustment),
567            TextDirection::Ltr => left_offset_x(scaffold_geometry, adjustment),
568        }
569    }
570}
571
572/// Mixin for a "center" floating action button location, such as
573/// `<dyn FloatingActionButtonLocation>::center_float()`.
574pub trait FabCenterOffsetX: StandardFabLocation {
575    /// Calculates x-offset for center-aligned [`FloatingActionButtonLocation`]s.
576    fn get_offset_x(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
577        let _ = adjustment;
578        (scaffold_geometry.scaffold_size.width()
579            - scaffold_geometry.floating_action_button_size.width())
580            / 2.0
581    }
582}
583
584/// Mixin for an "end" floating action button location, such as
585/// `<dyn FloatingActionButtonLocation>::end_docked()`.
586pub trait FabEndOffsetX: StandardFabLocation {
587    /// Calculates x-offset for end-aligned [`FloatingActionButtonLocation`]s.
588    fn get_offset_x(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry, adjustment: f64) -> f64 {
589        match scaffold_geometry.text_direction {
590            TextDirection::Rtl => left_offset_x(scaffold_geometry, adjustment),
591            TextDirection::Ltr => right_offset_x(scaffold_geometry, adjustment),
592        }
593    }
594}
595
596/// Mixin for a "mini" floating action button location, such as
597/// `<dyn FloatingActionButtonLocation>::mini_start_top()`.
598pub trait FabMiniOffsetAdjustment: StandardFabLocation {
599    /// Dart's `isMini` override.
600    fn is_mini(&self) -> bool {
601        true
602    }
603}
604
605/// Declares one of Dart's private standard locations: a unit struct that extends
606/// [`StandardFabLocation`] with an x mixin and a y mixin (and, when `mini`, with
607/// [`FabMiniOffsetAdjustment`]), and whose `Debug` is Dart's `toString`.
608macro_rules! standard_fab_location {
609    ($name:ident, $label:literal, $x:ident, $y:ident $(, $mini:ident)?) => {
610        #[doc = concat!("Dart's `_", stringify!($name), "`.")]
611        struct $name;
612
613        impl FloatingActionButtonLocation for $name {
614            fn get_offset(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry) -> Offset {
615                StandardFabLocation::get_offset(self, scaffold_geometry)
616            }
617        }
618
619        impl StandardFabLocation for $name {
620            fn get_offset_x(
621                &self,
622                scaffold_geometry: &ScaffoldPrelayoutGeometry,
623                adjustment: f64,
624            ) -> f64 {
625                $x::get_offset_x(self, scaffold_geometry, adjustment)
626            }
627
628            fn get_offset_y(
629                &self,
630                scaffold_geometry: &ScaffoldPrelayoutGeometry,
631                adjustment: f64,
632            ) -> f64 {
633                $y::get_offset_y(self, scaffold_geometry, adjustment)
634            }
635
636            $(
637                fn is_mini(&self) -> bool {
638                    $mini::is_mini(self)
639                }
640            )?
641        }
642
643        $(impl $mini for $name {})?
644        impl $x for $name {}
645        impl $y for $name {}
646
647        impl Debug for $name {
648            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649                f.write_str(concat!("FloatingActionButtonLocation.", $label))
650            }
651        }
652    };
653}
654
655standard_fab_location!(
656    StartTopFabLocation,
657    "startTop",
658    FabStartOffsetX,
659    FabTopOffsetY
660);
661standard_fab_location!(
662    MiniStartTopFabLocation,
663    "miniStartTop",
664    FabStartOffsetX,
665    FabTopOffsetY,
666    FabMiniOffsetAdjustment
667);
668standard_fab_location!(
669    CenterTopFabLocation,
670    "centerTop",
671    FabCenterOffsetX,
672    FabTopOffsetY
673);
674standard_fab_location!(
675    MiniCenterTopFabLocation,
676    "miniCenterTop",
677    FabCenterOffsetX,
678    FabTopOffsetY,
679    FabMiniOffsetAdjustment
680);
681standard_fab_location!(EndTopFabLocation, "endTop", FabEndOffsetX, FabTopOffsetY);
682standard_fab_location!(
683    MiniEndTopFabLocation,
684    "miniEndTop",
685    FabEndOffsetX,
686    FabTopOffsetY,
687    FabMiniOffsetAdjustment
688);
689standard_fab_location!(
690    StartFloatFabLocation,
691    "startFloat",
692    FabStartOffsetX,
693    FabFloatOffsetY
694);
695standard_fab_location!(
696    MiniStartFloatFabLocation,
697    "miniStartFloat",
698    FabStartOffsetX,
699    FabFloatOffsetY,
700    FabMiniOffsetAdjustment
701);
702standard_fab_location!(
703    CenterFloatFabLocation,
704    "centerFloat",
705    FabCenterOffsetX,
706    FabFloatOffsetY
707);
708standard_fab_location!(
709    MiniCenterFloatFabLocation,
710    "miniCenterFloat",
711    FabCenterOffsetX,
712    FabFloatOffsetY,
713    FabMiniOffsetAdjustment
714);
715standard_fab_location!(
716    EndFloatFabLocation,
717    "endFloat",
718    FabEndOffsetX,
719    FabFloatOffsetY
720);
721standard_fab_location!(
722    MiniEndFloatFabLocation,
723    "miniEndFloat",
724    FabEndOffsetX,
725    FabFloatOffsetY,
726    FabMiniOffsetAdjustment
727);
728standard_fab_location!(
729    StartDockedFabLocation,
730    "startDocked",
731    FabStartOffsetX,
732    FabDockedOffsetY
733);
734standard_fab_location!(
735    MiniStartDockedFabLocation,
736    "miniStartDocked",
737    FabStartOffsetX,
738    FabDockedOffsetY,
739    FabMiniOffsetAdjustment
740);
741standard_fab_location!(
742    CenterDockedFabLocation,
743    "centerDocked",
744    FabCenterOffsetX,
745    FabDockedOffsetY
746);
747standard_fab_location!(
748    MiniCenterDockedFabLocation,
749    "miniCenterDocked",
750    FabCenterOffsetX,
751    FabDockedOffsetY,
752    FabMiniOffsetAdjustment
753);
754standard_fab_location!(
755    EndDockedFabLocation,
756    "endDocked",
757    FabEndOffsetX,
758    FabDockedOffsetY
759);
760standard_fab_location!(
761    MiniEndDockedFabLocation,
762    "miniEndDocked",
763    FabEndOffsetX,
764    FabDockedOffsetY,
765    FabMiniOffsetAdjustment
766);
767standard_fab_location!(
768    EndContainedFabLocation,
769    "endContained",
770    FabEndOffsetX,
771    FabContainedOffsetY
772);
773
774/// Provider of animations to move the `FloatingActionButton` between
775/// [`FloatingActionButtonLocation`]s.
776///
777/// The `Scaffold` uses `Scaffold.floatingActionButtonAnimator` to define:
778///
779///  * The [`Offset`] of the `FloatingActionButton` between the old and new
780///    [`FloatingActionButtonLocation`]s as part of the transition animation.
781///  * An `Animation` to scale the `FloatingActionButton` during the transition.
782///  * An `Animation` to rotate the `FloatingActionButton` during the transition.
783///  * Where to start a new animation from if an animation is interrupted.
784///
785/// See also:
786///
787///  * `FloatingActionButton`, which is a circular button typically shown in the
788///    bottom right corner of the app.
789///  * [`FloatingActionButtonLocation`], which the `Scaffold` uses to place the
790///    `Scaffold.floatingActionButton` within the `Scaffold`'s layout.
791pub trait FloatingActionButtonAnimator: Debug + 'static {
792    /// Gets the `FloatingActionButton`'s position relative to the origin of the
793    /// `Scaffold` based on `progress`.
794    ///
795    /// `begin` is the [`Offset`] provided by the previous
796    /// [`FloatingActionButtonLocation`].
797    ///
798    /// `end` is the [`Offset`] provided by the new
799    /// [`FloatingActionButtonLocation`].
800    ///
801    /// `progress` is the current progress of the transition animation.
802    /// When `progress` is 0.0, the returned [`Offset`] should be equal to `begin`.
803    /// when `progress` is 1.0, the returned [`Offset`] should be equal to `end`.
804    fn get_offset(&self, begin: Offset, end: Offset, progress: f64) -> Offset;
805
806    /// Animates the scale of the `FloatingActionButton`.
807    ///
808    /// The animation should both start and end with a value of 1.0.
809    ///
810    /// For example, to create an animation that linearly scales out and then back in,
811    /// you could join animations that pass each other with a `TrainHoppingAnimation`.
812    fn get_scale_animation(&self, app: &mut App, parent: AnimationRef<f64>) -> AnimationRef<f64>;
813
814    /// Animates the rotation of `Scaffold.floatingActionButton`.
815    ///
816    /// The animation should both start and end with a value of 0.0 or 1.0.
817    ///
818    /// The animation values are a fraction of a full circle, with 0.0 and 1.0
819    /// corresponding to 0 and 360 degrees, while 0.5 corresponds to 180 degrees.
820    ///
821    /// For example, to create a rotation animation that rotates the
822    /// `FloatingActionButton` through a full circle, drive a `Tween` from 0.0 to 1.0 with
823    /// `parent`.
824    fn get_rotation_animation(&self, app: &mut App, parent: AnimationRef<f64>)
825    -> AnimationRef<f64>;
826
827    /// Gets the progress value to restart a motion animation from when the animation is
828    /// interrupted.
829    ///
830    /// `previous_value` is the value of the animation before it was interrupted.
831    ///
832    /// The restart of the animation will affect all three parts of the motion animation:
833    /// offset animation, scale animation, and rotation animation.
834    ///
835    /// An interruption triggers if the `Scaffold` is given a new
836    /// [`FloatingActionButtonLocation`] while it is still animating a transition between two
837    /// previous [`FloatingActionButtonLocation`]s.
838    ///
839    /// A sensible default is usually 0.0, which is the same as restarting
840    /// the animation from the beginning, regardless of the original state of the animation.
841    fn get_animation_restart(&self, previous_value: f64) -> f64 {
842        let _ = previous_value;
843        0.0
844    }
845}
846
847/// A shared [`FloatingActionButtonAnimator`], compared by identity as Dart compares its
848/// animators.
849pub type FloatingActionButtonAnimatorRef = Rc<dyn FloatingActionButtonAnimator>;
850
851impl dyn FloatingActionButtonAnimator {
852    /// Moves the `FloatingActionButton` by scaling out and then in at a new
853    /// [`FloatingActionButtonLocation`].
854    ///
855    /// This animator shrinks the `FloatingActionButton` down until it disappears, then
856    /// grows it back to full size at its new [`FloatingActionButtonLocation`].
857    ///
858    /// This is the default `FloatingActionButton` motion animation.
859    pub fn scaling() -> FloatingActionButtonAnimatorRef {
860        thread_local! {
861            static ANIMATOR: FloatingActionButtonAnimatorRef = Rc::new(ScalingFabMotionAnimator);
862        }
863        ANIMATOR.with(Rc::clone)
864    }
865
866    /// Creates an instance of [`FloatingActionButtonAnimator`] where the
867    /// `FloatingActionButton` does not animate on entrance and exit when
868    /// [`FloatingActionButtonLocation`] is shown or hidden and when transitioning between
869    /// [`FloatingActionButtonLocation`]s.
870    pub fn no_animation() -> FloatingActionButtonAnimatorRef {
871        thread_local! {
872            static ANIMATOR: FloatingActionButtonAnimatorRef =
873                Rc::new(NoAnimationFabMotionAnimator);
874        }
875        ANIMATOR.with(Rc::clone)
876    }
877}
878
879/// Dart's `_ScalingFabMotionAnimator`.
880#[derive(Debug)]
881struct ScalingFabMotionAnimator;
882
883/// Dart's `static final` tweens of `_ScalingFabMotionAnimator`, kept per [`App`] and made on
884/// first use. They are shared by every animation the animator returns, so the `App` keeps them for
885/// its life.
886#[derive(Default)]
887struct ScalingFabMotionAnimatorStatics {
888    rotation_tween: Option<Ref<Tween<f64>>>,
889    threshold_center_tween: Option<Ref<CurveTween>>,
890}
891
892impl ScalingFabMotionAnimator {
893    // Because we only see the last half of the rotation tween,
894    // it needs to go twice as far.
895    fn rotation_tween(app: &mut App) -> Ref<Tween<f64>> {
896        let statics = app.singleton::<ScalingFabMotionAnimatorStatics>();
897        if let Some(rotation_tween) = app.get(statics).rotation_tween.clone() {
898            return rotation_tween;
899        }
900        let rotation_tween = Tween::new(
901            app,
902            Some(1.0 - K_FLOATING_ACTION_BUTTON_TURN_INTERVAL * 2.0),
903            Some(1.0),
904        );
905        app.get_mut(statics).rotation_tween = Some(rotation_tween.clone());
906        rotation_tween
907    }
908
909    fn threshold_center_tween(app: &mut App) -> Ref<CurveTween> {
910        let statics = app.singleton::<ScalingFabMotionAnimatorStatics>();
911        if let Some(threshold_center_tween) = app.get(statics).threshold_center_tween.clone() {
912            return threshold_center_tween;
913        }
914        let threshold_center_tween = CurveTween::new(app, Rc::new(Threshold::new(0.5)));
915        app.get_mut(statics).threshold_center_tween = Some(threshold_center_tween.clone());
916        threshold_center_tween
917    }
918}
919
920impl FloatingActionButtonAnimator for ScalingFabMotionAnimator {
921    fn get_offset(&self, begin: Offset, end: Offset, progress: f64) -> Offset {
922        if progress < 0.5 { begin } else { end }
923    }
924
925    fn get_scale_animation(&self, app: &mut App, parent: AnimationRef<f64>) -> AnimationRef<f64> {
926        // Animate the scale down from 1 to 0 in the first half of the animation
927        // then from 0 back to 1 in the second half.
928        let curve: Rc<dyn Curve> = Rc::new(Interval::new(0.5, 1.0, Curves::ease()));
929        let flipped_tween = CurveTween::new(app, Rc::new(Rc::clone(&curve).flipped()));
930        let flipped = parent.drive(app, flipped_tween);
931        let first = ReverseAnimation::new(app, flipped).into_erased();
932        let curve_tween = CurveTween::new(app, curve);
933        let next = parent.drive(app, curve_tween);
934        app.create(AnimationSwap::new(first, next, parent, 0.5))
935            .into_erased()
936    }
937
938    fn get_rotation_animation(
939        &self,
940        app: &mut App,
941        parent: AnimationRef<f64>,
942    ) -> AnimationRef<f64> {
943        // This rotation will turn on the way in, but not on the way out.
944        let rotation_tween = ScalingFabMotionAnimator::rotation_tween(app);
945        let first = parent.drive(app, rotation_tween);
946        let threshold_center_tween = ScalingFabMotionAnimator::threshold_center_tween(app);
947        let threshold = parent.drive(app, threshold_center_tween);
948        let next = ReverseAnimation::new(app, threshold).into_erased();
949        app.create(AnimationSwap::new(first, next, parent, 0.5))
950            .into_erased()
951    }
952
953    // If the animation was just starting, we'll continue from where we left off.
954    // If the animation was finishing, we'll treat it as if we were starting at that point in
955    // reverse. This avoids a size jump during the animation.
956    fn get_animation_restart(&self, previous_value: f64) -> f64 {
957        f64::min(1.0 - previous_value, previous_value)
958    }
959}
960
961/// Dart's `_NoAnimationFabMotionAnimator`.
962#[derive(Debug)]
963struct NoAnimationFabMotionAnimator;
964
965/// Dart's `const AlwaysStoppedAnimation<double>(1.0)`, which Dart canonicalizes into one
966/// object, kept per [`App`] and made on first use; the `App` keeps it for its life.
967#[derive(Default)]
968struct AlwaysStoppedAtOne {
969    animation: Option<Ref<AlwaysStoppedAnimation<f64>>>,
970}
971
972impl AlwaysStoppedAtOne {
973    fn instance(app: &mut App) -> AnimationRef<f64> {
974        let statics = app.singleton::<AlwaysStoppedAtOne>();
975        if let Some(animation) = app.get(statics).animation.clone() {
976            return animation.into_erased();
977        }
978        let animation = app.create(AlwaysStoppedAnimation::new(1.0));
979        app.get_mut(statics).animation = Some(animation.clone());
980        animation.into_erased()
981    }
982}
983
984impl FloatingActionButtonAnimator for NoAnimationFabMotionAnimator {
985    fn get_offset(&self, begin: Offset, end: Offset, progress: f64) -> Offset {
986        let _ = (begin, progress);
987        end
988    }
989
990    fn get_rotation_animation(
991        &self,
992        app: &mut App,
993        parent: AnimationRef<f64>,
994    ) -> AnimationRef<f64> {
995        let _ = parent;
996        AlwaysStoppedAtOne::instance(app)
997    }
998
999    fn get_scale_animation(&self, app: &mut App, parent: AnimationRef<f64>) -> AnimationRef<f64> {
1000        let _ = parent;
1001        AlwaysStoppedAtOne::instance(app)
1002    }
1003}
1004
1005/// An animation that swaps from one animation to the next when the
1006/// [`parent`](Self::parent) passes [`swap_threshold`](Self::swap_threshold).
1007///
1008/// The value of this animation is the value of `first` when `parent.value` <
1009/// [`swap_threshold`](Self::swap_threshold) and the value of `next` otherwise.
1010struct AnimationSwap<T: Clone + PartialEq + 'static> {
1011    first: AnimationRef<T>,
1012    next: AnimationRef<T>,
1013    parent: AnimationRef<f64>,
1014    swap_threshold: f64,
1015    last_status: Option<AnimationStatus>,
1016    last_value: Option<T>,
1017    lazy_listener: AnimationLazyListenerData,
1018    local_listeners: AnimationLocalListenersData,
1019    local_status_listeners: AnimationLocalStatusListenersData,
1020}
1021
1022impl<T: Clone + PartialEq + 'static> AnimationSwap<T> {
1023    /// Creates an [`AnimationSwap`].
1024    ///
1025    /// Either argument can be an [`AnimationSwap`] itself to combine multiple
1026    /// animations.
1027    fn new(
1028        first: AnimationRef<T>,
1029        next: AnimationRef<T>,
1030        parent: AnimationRef<f64>,
1031        swap_threshold: f64,
1032    ) -> AnimationSwap<T> {
1033        AnimationSwap {
1034            first,
1035            next,
1036            parent,
1037            swap_threshold,
1038            last_status: None,
1039            last_value: None,
1040            lazy_listener: AnimationLazyListenerData::new(),
1041            local_listeners: AnimationLocalListenersData::new(),
1042            local_status_listeners: AnimationLocalStatusListenersData::new(),
1043        }
1044    }
1045}
1046
1047impl<T: Clone + PartialEq + 'static> AnimationLazyListenerMixin for AnimationSwap<T> {
1048    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
1049        &app.get(self).lazy_listener
1050    }
1051
1052    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
1053        &mut app.get_mut(self).lazy_listener
1054    }
1055
1056    fn did_start_listening(self: Handle<Self>, app: &mut App) {
1057        compound_did_start_listening::<AnimationSwap<T>, T>(self, app)
1058    }
1059
1060    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
1061        compound_did_stop_listening::<AnimationSwap<T>, T>(self, app)
1062    }
1063}
1064
1065impl<T: Clone + PartialEq + 'static> AnimationLocalListenersMixin for AnimationSwap<T> {
1066    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
1067        &app.get(self).local_listeners
1068    }
1069
1070    fn local_listeners_data_mut(
1071        self: Handle<Self>,
1072        app: &mut App,
1073    ) -> &mut AnimationLocalListenersData {
1074        &mut app.get_mut(self).local_listeners
1075    }
1076
1077    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1078        AnimationLazyListenerMixin::did_register_listener(self, app)
1079    }
1080
1081    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1082        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1083    }
1084}
1085
1086impl<T: Clone + PartialEq + 'static> AnimationLocalStatusListenersMixin for AnimationSwap<T> {
1087    fn local_status_listeners_data(
1088        self: Handle<Self>,
1089        app: &App,
1090    ) -> &AnimationLocalStatusListenersData {
1091        &app.get(self).local_status_listeners
1092    }
1093
1094    fn local_status_listeners_data_mut(
1095        self: Handle<Self>,
1096        app: &mut App,
1097    ) -> &mut AnimationLocalStatusListenersData {
1098        &mut app.get_mut(self).local_status_listeners
1099    }
1100
1101    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1102        AnimationLazyListenerMixin::did_register_listener(self, app)
1103    }
1104
1105    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1106        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1107    }
1108}
1109
1110impl<T: Clone + PartialEq + 'static> CompoundAnimation<T> for AnimationSwap<T> {
1111    fn first(self: Handle<Self>, app: &App) -> AnyAnimation<T> {
1112        app.get(self).first.handle()
1113    }
1114
1115    fn next(self: Handle<Self>, app: &App) -> AnyAnimation<T> {
1116        app.get(self).next.handle()
1117    }
1118
1119    fn last_status(self: Handle<Self>, app: &App) -> Option<AnimationStatus> {
1120        app.get(self).last_status
1121    }
1122
1123    fn last_status_mut(self: Handle<Self>, app: &mut App) -> &mut Option<AnimationStatus> {
1124        &mut app.get_mut(self).last_status
1125    }
1126
1127    fn last_value(self: Handle<Self>, app: &App) -> &Option<T> {
1128        &app.get(self).last_value
1129    }
1130
1131    fn last_value_mut(self: Handle<Self>, app: &mut App) -> &mut Option<T> {
1132        &mut app.get_mut(self).last_value
1133    }
1134}
1135
1136// Dart: `class _AnimationSwap<T> extends CompoundAnimation<T>`.
1137impl<T: Clone + PartialEq + 'static> Animation<T> for AnimationSwap<T> {
1138    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1139        AnimationLocalListenersMixin::add_listener(self, app, listener)
1140    }
1141
1142    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1143        AnimationLocalListenersMixin::remove_listener(self, app, listener)
1144    }
1145
1146    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1147        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
1148    }
1149
1150    fn remove_status_listener(
1151        self: Handle<Self>,
1152        app: &mut App,
1153        listener: &AnimationStatusListener,
1154    ) {
1155        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
1156    }
1157
1158    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1159        CompoundAnimation::status(self, app)
1160    }
1161
1162    fn value(self: Handle<Self>, app: &App) -> T {
1163        let animation = app.get(self);
1164        if animation.parent.value(app) < animation.swap_threshold {
1165            animation.first.value(app)
1166        } else {
1167            animation.next.value(app)
1168        }
1169    }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    //! The cases of `test/floating_action_button_location_test.dart`.
1175    //!
1176    //! Dart's `_singleFabScaffold` and `buildTest` put a `BottomNavigationBar` in the scaffold,
1177    //! which is not ported. A case whose asserted values do not depend on it is ported without
1178    //! it, and says so; a case whose values depend on its height waits for it (listed at the
1179    //! end of this module).
1180    use waft_widgets::Text;
1181
1182    use std::cell::RefCell;
1183
1184    use waft_animation::AlwaysStoppedAnimation;
1185    use waft_embedder::{Rect, Size};
1186    use waft_foundation::Listenable;
1187    use waft_painting::EdgeInsets;
1188    use waft_rendering::CustomPainter;
1189    use waft_scheduler::SchedulerBinding;
1190    use waft_widgets::{
1191        AnyElement, BuildContext, Builder, Center, CustomPaint, Directionality, GlobalKey,
1192        IntoWidget, KeyRef, MediaQuery, MediaQueryData, PreferredSizeWidgetRef, RotationTransition,
1193        SizedBox, State, StateData, StatefulWidget, WidgetRef, WidgetsBinding, downcast_widget,
1194    };
1195
1196    use waft_widgets::testing::{
1197        WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
1198    };
1199
1200    use super::*;
1201    use crate::app_bar::AppBar;
1202    use crate::floating_action_button::FloatingActionButton;
1203    use crate::material_localizations::tests::us_english;
1204    use crate::scaffold::{
1205        Scaffold, ScaffoldGeometry, ScaffoldGeometryNotifier, ScaffoldMessenger,
1206    };
1207    use crate::snack_bar::SnackBar;
1208    use crate::test_support::material_app;
1209    use crate::theme_data::ThemeData;
1210
1211    /// Dart's `const FloatingActionButton(onPressed: null, child: Text('1'))`.
1212    fn default_fab() -> FloatingActionButton {
1213        FloatingActionButton::new(None).child(Text::new("1"))
1214    }
1215
1216    /// Dart's `_buildFrame`.
1217    fn build_frame(
1218        fab: Option<FloatingActionButton>,
1219        location: Option<FloatingActionButtonLocationRef>,
1220        listener: Option<WidgetRef>,
1221        text_direction: TextDirection,
1222        view_insets: EdgeInsets,
1223        bab: Option<WidgetRef>,
1224    ) -> WidgetRef {
1225        let mut scaffold = Scaffold::new().app_bar(PreferredSizeWidgetRef::new(
1226            AppBar::new().title(Text::new("FabLocation Test")),
1227        ));
1228        if let Some(location) = location {
1229            scaffold = scaffold.floating_action_button_location(location);
1230        }
1231        if let Some(fab) = fab {
1232            scaffold = scaffold.floating_action_button(fab);
1233        }
1234        if let Some(bab) = bab {
1235            scaffold = scaffold.bottom_navigation_bar(bab);
1236        }
1237        if let Some(listener) = listener {
1238            scaffold = scaffold.body(listener);
1239        }
1240        us_english(Directionality::new(
1241            text_direction,
1242            MediaQuery::new(MediaQueryData::new().view_insets(view_insets), scaffold).into_widget(),
1243        ))
1244    }
1245
1246    /// `_buildFrame(location:)` with Dart's other defaults.
1247    fn frame(location: Option<FloatingActionButtonLocationRef>) -> WidgetRef {
1248        build_frame(
1249            Some(default_fab()),
1250            location,
1251            None,
1252            TextDirection::Ltr,
1253            EdgeInsets::only(0.0, 0.0, 0.0, 200.0),
1254            None,
1255        )
1256    }
1257
1258    fn fab_box(tester: &WidgetTester) -> waft_rendering::AnyRenderBox {
1259        let found = find::by_type::<FloatingActionButton>().evaluate(tester);
1260        assert_eq!(found.len(), 1, "one FloatingActionButton");
1261        tester.render_box_of(found[0])
1262    }
1263
1264    /// `tester.getCenter(find.byType(FloatingActionButton))`.
1265    fn fab_center(tester: &WidgetTester) -> Offset {
1266        let render = fab_box(tester);
1267        let app = tester.cell.borrow();
1268        let size = render.size(&app);
1269        render.local_to_global(&app, size.center(Offset::ZERO), None)
1270    }
1271
1272    /// `tester.getTopLeft(find.byType(FloatingActionButton))`.
1273    fn fab_top_left(tester: &WidgetTester) -> Offset {
1274        let render = fab_box(tester);
1275        let app = tester.cell.borrow();
1276        render.local_to_global(&app, Offset::ZERO, None)
1277    }
1278
1279    /// `tester.getTopRight(find.byType(FloatingActionButton))`.
1280    fn fab_top_right(tester: &WidgetTester) -> Offset {
1281        let render = fab_box(tester);
1282        let app = tester.cell.borrow();
1283        let size = render.size(&app);
1284        render.local_to_global(&app, Offset::new(size.width(), 0.0), None)
1285    }
1286
1287    fn transient_callback_count(tester: &WidgetTester) -> usize {
1288        SchedulerBinding::transient_callback_count(&mut tester.cell.borrow_mut())
1289    }
1290
1291    /// The tolerance of a position read through `local_to_global` across the FAB's
1292    /// `RotationTransition`: `Matrix4` is valo's f32 matrix (waft-gestures' PORTING.md), so a
1293    /// rotated position is exact only to f32 where Dart's f64 one is exact.
1294    const POSITION_TOLERANCE: f64 = 1e-4;
1295
1296    /// Dart's `expect(x, y)` on a coordinate read through the FAB's transitions.
1297    fn assert_coordinate_eq(actual: f64, expected: f64) {
1298        assert!(
1299            (actual - expected).abs() < POSITION_TOLERANCE,
1300            "{actual} is not {expected}"
1301        );
1302    }
1303
1304    /// Dart's `expect(offset, Offset(..))` on a point read through the FAB's transitions.
1305    fn assert_offset_eq(actual: Offset, expected: Offset) {
1306        assert!(
1307            (actual.dx() - expected.dx()).abs() < POSITION_TOLERANCE
1308                && (actual.dy() - expected.dy()).abs() < POSITION_TOLERANCE,
1309            "{actual:?} is not {expected:?}"
1310        );
1311    }
1312
1313    /// Dart's `rectMoreOrLessEquals`, within [`POSITION_TOLERANCE`] for the reason there.
1314    fn assert_rect_more_or_less_equals(actual: Rect, expected: Rect) {
1315        let close = |a: f64, b: f64| (a - b).abs() < POSITION_TOLERANCE;
1316        assert!(
1317            close(actual.left, expected.left)
1318                && close(actual.top, expected.top)
1319                && close(actual.right, expected.right)
1320                && close(actual.bottom, expected.bottom),
1321            "{actual:?} is not {expected:?}"
1322        );
1323    }
1324
1325    /// Dart's `_StartTopFloatingActionButtonLocation`.
1326    #[derive(Debug)]
1327    struct StartTopFloatingActionButtonLocation;
1328
1329    impl FloatingActionButtonLocation for StartTopFloatingActionButtonLocation {
1330        fn get_offset(&self, scaffold_geometry: &ScaffoldPrelayoutGeometry) -> Offset {
1331            let fab_x = match scaffold_geometry.text_direction {
1332                TextDirection::Rtl => {
1333                    let start_padding =
1334                        K_FLOATING_ACTION_BUTTON_MARGIN + scaffold_geometry.min_insets.right;
1335                    scaffold_geometry.scaffold_size.width()
1336                        - scaffold_geometry.floating_action_button_size.width()
1337                        - start_padding
1338                }
1339                TextDirection::Ltr => {
1340                    K_FLOATING_ACTION_BUTTON_MARGIN + scaffold_geometry.min_insets.left
1341                }
1342            };
1343            let fab_y = scaffold_geometry.content_top
1344                - (scaffold_geometry.floating_action_button_size.height() / 2.0);
1345            Offset::new(fab_x, fab_y)
1346        }
1347    }
1348
1349    /// Dart's `_NoScalingFabAnimator`.
1350    #[derive(Debug)]
1351    struct NoScalingFabAnimator;
1352
1353    impl FloatingActionButtonAnimator for NoScalingFabAnimator {
1354        fn get_offset(&self, begin: Offset, end: Offset, progress: f64) -> Offset {
1355            if progress < 0.5 { begin } else { end }
1356        }
1357
1358        fn get_scale_animation(
1359            &self,
1360            app: &mut App,
1361            _parent: AnimationRef<f64>,
1362        ) -> AnimationRef<f64> {
1363            app.create(AlwaysStoppedAnimation::new(1.0))
1364                .into_erased::<AnyAnimation<f64>>()
1365        }
1366
1367        fn get_rotation_animation(
1368            &self,
1369            app: &mut App,
1370            _parent: AnimationRef<f64>,
1371        ) -> AnimationRef<f64> {
1372            app.create(AlwaysStoppedAnimation::new(1.0))
1373                .into_erased::<AnyAnimation<f64>>()
1374        }
1375    }
1376
1377    // Basic floating action button locations
1378
1379    // 'still animates motion when the floating action button is null'.
1380    #[test]
1381    fn a_null_floating_action_button_still_animates_its_motion() {
1382        test_widgets(|tester| {
1383            let null_frame = |location| {
1384                build_frame(
1385                    None,
1386                    location,
1387                    None,
1388                    TextDirection::Ltr,
1389                    EdgeInsets::only(0.0, 0.0, 0.0, 200.0),
1390                    None,
1391                )
1392            };
1393            tester.pump_widget(null_frame(None));
1394
1395            expect(
1396                tester,
1397                &find::by_type::<FloatingActionButton>(),
1398                finds_nothing(),
1399            );
1400            assert_eq!(transient_callback_count(tester), 0);
1401
1402            tester.pump_widget(null_frame(Some(
1403                <dyn FloatingActionButtonLocation>::end_float(),
1404            )));
1405
1406            expect(
1407                tester,
1408                &find::by_type::<FloatingActionButton>(),
1409                finds_nothing(),
1410            );
1411            assert!(transient_callback_count(tester) > 0);
1412
1413            tester.pump_widget(null_frame(Some(
1414                <dyn FloatingActionButtonLocation>::center_float(),
1415            )));
1416
1417            expect(
1418                tester,
1419                &find::by_type::<FloatingActionButton>(),
1420                finds_nothing(),
1421            );
1422            assert!(transient_callback_count(tester) > 0);
1423        });
1424    }
1425
1426    // 'moves fab from center to end and back'.
1427    #[test]
1428    fn the_fab_moves_from_center_to_end_and_back() {
1429        test_widgets(|tester| {
1430            tester.pump_widget(frame(Some(<dyn FloatingActionButtonLocation>::end_float())));
1431
1432            assert_offset_eq(fab_center(tester), Offset::new(756.0, 356.0));
1433            assert_eq!(transient_callback_count(tester), 0);
1434
1435            tester.pump_widget(frame(Some(
1436                <dyn FloatingActionButtonLocation>::center_float(),
1437            )));
1438
1439            assert!(transient_callback_count(tester) > 0);
1440
1441            tester.pump_and_settle();
1442
1443            assert_offset_eq(fab_center(tester), Offset::new(400.0, 356.0));
1444            assert_eq!(transient_callback_count(tester), 0);
1445
1446            tester.pump_widget(frame(Some(<dyn FloatingActionButtonLocation>::end_float())));
1447
1448            assert!(transient_callback_count(tester) > 0);
1449
1450            tester.pump_and_settle();
1451
1452            assert_offset_eq(fab_center(tester), Offset::new(756.0, 356.0));
1453            assert_eq!(transient_callback_count(tester), 0);
1454        });
1455    }
1456
1457    // 'moves to and from custom-defined positions'.
1458    #[test]
1459    fn the_fab_moves_to_and_from_a_custom_location() {
1460        test_widgets(|tester| {
1461            tester.pump_widget(frame(Some(Rc::new(StartTopFloatingActionButtonLocation))));
1462
1463            assert_offset_eq(fab_center(tester), Offset::new(44.0, 56.0));
1464
1465            tester.pump_widget(frame(Some(
1466                <dyn FloatingActionButtonLocation>::center_float(),
1467            )));
1468            assert!(transient_callback_count(tester) > 0);
1469
1470            tester.pump_and_settle();
1471
1472            assert_offset_eq(fab_center(tester), Offset::new(400.0, 356.0));
1473            assert_eq!(transient_callback_count(tester), 0);
1474
1475            tester.pump_widget(frame(Some(Rc::new(StartTopFloatingActionButtonLocation))));
1476
1477            assert!(transient_callback_count(tester) > 0);
1478
1479            tester.pump_and_settle();
1480
1481            assert_offset_eq(fab_center(tester), Offset::new(44.0, 56.0));
1482            assert_eq!(transient_callback_count(tester), 0);
1483        });
1484    }
1485
1486    // interrupts in-progress animations without jumps
1487
1488    /// What the scaffold's geometry and the FAB's rotations were at one geometry notification:
1489    /// Dart's `check` reads them in the listener; here the listener records them and
1490    /// [`check_steps`] runs Dart's checks over the record.
1491    struct Step {
1492        rect: Option<Size>,
1493        rotations: Vec<f64>,
1494    }
1495
1496    // The maximum amounts we expect the fab width and height to change
1497    // during one step of a transition.
1498    const MAX_DELTA_WIDTH: f64 = 12.5;
1499    const MAX_DELTA_HEIGHT: f64 = 12.5;
1500
1501    // The maximum amounts we expect the fab icon to rotate during one step
1502    // of a transition.
1503    const MAX_DELTA_ROTATION: f64 = 0.09;
1504
1505    /// Dart's `_GeometryCachePainter`: caches the scaffold's geometry when it paints, the
1506    /// only time it can be read.
1507    struct GeometryCachePainter {
1508        geometry_listenable: Ref<ScaffoldGeometryNotifier>,
1509        repaint: Rc<dyn Listenable>,
1510        value: Rc<RefCell<Option<ScaffoldGeometry>>>,
1511    }
1512
1513    impl CustomPainter for GeometryCachePainter {
1514        fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
1515            Some(&self.repaint)
1516        }
1517
1518        fn paint(&self, app: &mut App, _canvas: &mut waft_embedder::Canvas, _size: Size) {
1519            *self.value.borrow_mut() = Some(self.geometry_listenable.value(app));
1520        }
1521
1522        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
1523            true
1524        }
1525
1526        fn as_any(&self) -> &dyn std::any::Any {
1527            self
1528        }
1529    }
1530
1531    /// Dart's `_GeometryListener`, keyed so the case can reach its state.
1532    #[derive(Debug)]
1533    struct GeometryListener {
1534        key: KeyRef,
1535    }
1536
1537    impl StatefulWidget for GeometryListener {
1538        type State = GeometryListenerState;
1539
1540        fn key(&self) -> Option<&KeyRef> {
1541            Some(&self.key)
1542        }
1543
1544        fn create_state(&self) -> GeometryListenerState {
1545            GeometryListenerState {
1546                state: StateData::new(),
1547                geometry_listenable: None,
1548                cache: Rc::new(RefCell::new(None)),
1549            }
1550        }
1551    }
1552
1553    /// Dart's `_GeometryListenerState`.
1554    struct GeometryListenerState {
1555        state: StateData<GeometryListener>,
1556        geometry_listenable: Option<Ref<ScaffoldGeometryNotifier>>,
1557        cache: Rc<RefCell<Option<ScaffoldGeometry>>>,
1558    }
1559
1560    impl State for GeometryListenerState {
1561        type Widget = GeometryListener;
1562        waft_widgets::state_accessors!();
1563
1564        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1565            let context = self.context(app);
1566            let new_listenable = Scaffold::geometry_of(app, context);
1567            if app.get(self).geometry_listenable.as_ref() == Some(&new_listenable) {
1568                return;
1569            }
1570            app.get_mut(self).geometry_listenable = Some(new_listenable);
1571            app.get_mut(self).cache = Rc::new(RefCell::new(None));
1572        }
1573
1574        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1575            let geometry_listenable = app
1576                .get(self)
1577                .geometry_listenable
1578                .clone()
1579                .expect("dependencies");
1580            CustomPaint::new()
1581                .painter(GeometryCachePainter {
1582                    geometry_listenable: geometry_listenable.clone(),
1583                    repaint: Rc::new(geometry_listenable),
1584                    value: Rc::clone(&app.get(self).cache),
1585                })
1586                .into_widget()
1587        }
1588    }
1589
1590    /// Every mounted element, parents first.
1591    fn elements(app: &mut App) -> Vec<AnyElement> {
1592        let root = WidgetsBinding::instance(app).root_element(app);
1593        let mut all = Vec::new();
1594        let mut pending: Vec<AnyElement> = root.into_iter().collect();
1595        while let Some(element) = pending.pop() {
1596            all.push(element);
1597            let mut children = Vec::new();
1598            element.visit_children(app, &mut |child| children.push(child));
1599            pending.extend(children.into_iter().rev());
1600        }
1601        all
1602    }
1603
1604    /// Dart's `setupListener`: from now on, every geometry notification records a [`Step`].
1605    fn setup_listener(tester: &WidgetTester, key: &GlobalKey) -> Rc<RefCell<Vec<Step>>> {
1606        let steps = Rc::new(RefCell::new(Vec::new()));
1607        let mut app = tester.cell.borrow_mut();
1608        let state = key
1609            .current_state::<GeometryListenerState>(&app)
1610            .expect("the listener's state");
1611        let listenable = app
1612            .get(state)
1613            .geometry_listenable
1614            .clone()
1615            .expect("dependencies");
1616        listenable.add_listener(
1617            &mut app,
1618            waft_foundation::Listener::new({
1619                let steps = Rc::clone(&steps);
1620                move |app| {
1621                    let geometry = *app.get(state).cache.borrow();
1622                    let rect = geometry
1623                        .and_then(|geometry| geometry.floating_action_button_area)
1624                        .map(|area| area.size());
1625                    let rotations = elements(app)
1626                        .into_iter()
1627                        .filter_map(|element| {
1628                            downcast_widget::<RotationTransition>(&**element.widget(app))
1629                                .map(|transition| transition.turns().value(app))
1630                        })
1631                        .collect();
1632                    steps.borrow_mut().push(Step { rect, rotations });
1633                }
1634            }),
1635        );
1636        steps
1637    }
1638
1639    /// Dart's `check`, run over every recorded notification in order.
1640    fn check_steps(steps: &[Step]) {
1641        let mut previous_rect: Option<Size> = None;
1642        let mut previous_rotations: Option<&[f64]> = None;
1643        for step in steps {
1644            let current_rect = step.rect;
1645            // Measure the delta in width and height of the rect, and check that
1646            // it never grows by more than a safe amount.
1647            if let (Some(previous), Some(current)) = (previous_rect, current_rect) {
1648                let delta_width = current.width() - previous.width();
1649                let delta_height = current.height() - previous.height();
1650                assert!(
1651                    delta_width.abs() <= MAX_DELTA_WIDTH,
1652                    "The Floating Action Button's width should not change faster than \
1653                     {MAX_DELTA_WIDTH} per animation step.\nPrevious rect: {previous:?}, \
1654                     current rect: {current:?}"
1655                );
1656                assert!(
1657                    delta_height.abs() <= MAX_DELTA_HEIGHT,
1658                    "The Floating Action Button's width should not change faster than \
1659                     {MAX_DELTA_HEIGHT} per animation step.\nPrevious rect: {previous:?}, \
1660                     current rect: {current:?}"
1661                );
1662            }
1663            previous_rect = current_rect;
1664
1665            // Measure the delta in rotation.
1666            // Check that it never grows by more than a safe amount.
1667            //
1668            // There may be multiple transitions all active at
1669            // the same time. We are concerned only with the closest one.
1670            let current_rotations = &step.rotations;
1671            if previous_rotations.is_some_and(|previous| !previous.is_empty())
1672                && !current_rotations.is_empty()
1673                && previous_rect.is_some()
1674                && current_rect.is_some()
1675            {
1676                let previous = previous_rotations.expect("checked");
1677                let deltas: Vec<f64> = current_rotations
1678                    .iter()
1679                    .map(|current_rotation| {
1680                        // Dart's loop keeps the last delta: `minDelta = delta` precedes the
1681                        // `min`.
1682                        let mut min_delta = 0.0;
1683                        for previous_rotation in previous {
1684                            let delta = (previous_rotation - current_rotation).abs();
1685                            min_delta = delta;
1686                            min_delta = f64::min(delta, min_delta);
1687                        }
1688                        min_delta
1689                    })
1690                    .collect();
1691
1692                assert!(
1693                    deltas.iter().any(|delta| *delta < MAX_DELTA_ROTATION),
1694                    "The Floating Action Button's rotation should not change faster than \
1695                     {MAX_DELTA_ROTATION} per animation step.\nDetected deltas were: \
1696                     {deltas:?}\nPrevious values: {previous:?}, current values: \
1697                     {current_rotations:?}"
1698                );
1699            }
1700            previous_rotations = Some(current_rotations);
1701        }
1702    }
1703
1704    fn listener_frame(
1705        key: &GlobalKey,
1706        fab: Option<FloatingActionButton>,
1707        location: FloatingActionButtonLocationRef,
1708    ) -> WidgetRef {
1709        build_frame(
1710            fab,
1711            Some(location),
1712            Some(
1713                GeometryListener {
1714                    key: key.clone().into(),
1715                }
1716                .into_widget(),
1717            ),
1718            TextDirection::Ltr,
1719            EdgeInsets::only(0.0, 0.0, 0.0, 200.0),
1720            None,
1721        )
1722    }
1723
1724    // 'moving the fab to centerFloat'.
1725    #[test]
1726    fn moving_the_fab_to_center_float_does_not_jump() {
1727        test_widgets(|tester| {
1728            let listener = GlobalKey::new();
1729            // Create a scaffold with the fab at endFloat
1730            tester.pump_widget(listener_frame(
1731                &listener,
1732                Some(default_fab()),
1733                <dyn FloatingActionButtonLocation>::end_float(),
1734            ));
1735            let steps = setup_listener(tester, &listener);
1736
1737            // Move the fab to centerFloat'
1738            tester.pump_widget(listener_frame(
1739                &listener,
1740                Some(default_fab()),
1741                <dyn FloatingActionButtonLocation>::center_float(),
1742            ));
1743            tester.pump_and_settle();
1744            check_steps(&steps.borrow());
1745            assert!(!steps.borrow().is_empty());
1746        });
1747    }
1748
1749    // 'interrupting motion towards the StartTop location.'.
1750    #[test]
1751    fn interrupting_motion_towards_the_start_top_location_does_not_jump() {
1752        test_widgets(|tester| {
1753            let listener = GlobalKey::new();
1754            tester.pump_widget(listener_frame(
1755                &listener,
1756                Some(default_fab()),
1757                <dyn FloatingActionButtonLocation>::center_float(),
1758            ));
1759            let steps = setup_listener(tester, &listener);
1760
1761            // Move the fab to the top start after creating the fab.
1762            tester.pump_widget(listener_frame(
1763                &listener,
1764                Some(default_fab()),
1765                Rc::new(StartTopFloatingActionButtonLocation),
1766            ));
1767            tester.pump_by(K_FLOATING_ACTION_BUTTON_SEGUE / 2);
1768
1769            // Interrupt motion to move to the end float
1770            tester.pump_widget(listener_frame(
1771                &listener,
1772                Some(default_fab()),
1773                <dyn FloatingActionButtonLocation>::end_float(),
1774            ));
1775            tester.pump_and_settle();
1776            check_steps(&steps.borrow());
1777            assert!(!steps.borrow().is_empty());
1778        });
1779    }
1780
1781    // 'interrupting entrance to remove the fab.'.
1782    #[test]
1783    fn interrupting_the_entrance_to_remove_the_fab_does_not_jump() {
1784        test_widgets(|tester| {
1785            let listener = GlobalKey::new();
1786            tester.pump_widget(listener_frame(
1787                &listener,
1788                None,
1789                <dyn FloatingActionButtonLocation>::center_float(),
1790            ));
1791            let steps = setup_listener(tester, &listener);
1792
1793            // Animate the fab in.
1794            tester.pump_widget(listener_frame(
1795                &listener,
1796                Some(default_fab()),
1797                <dyn FloatingActionButtonLocation>::end_float(),
1798            ));
1799            tester.pump_by(K_FLOATING_ACTION_BUTTON_SEGUE / 2);
1800
1801            // Remove the fab.
1802            tester.pump_widget(listener_frame(
1803                &listener,
1804                None,
1805                <dyn FloatingActionButtonLocation>::end_float(),
1806            ));
1807            tester.pump_and_settle();
1808            check_steps(&steps.borrow());
1809            assert!(!steps.borrow().is_empty());
1810        });
1811    }
1812
1813    // 'interrupting entrance of a new fab.'.
1814    #[test]
1815    fn interrupting_the_entrance_of_a_new_fab_does_not_jump() {
1816        test_widgets(|tester| {
1817            let listener = GlobalKey::new();
1818            tester.pump_widget(listener_frame(
1819                &listener,
1820                None,
1821                <dyn FloatingActionButtonLocation>::end_float(),
1822            ));
1823            let steps = setup_listener(tester, &listener);
1824
1825            // Bring in a new fab.
1826            tester.pump_widget(listener_frame(
1827                &listener,
1828                Some(default_fab()),
1829                <dyn FloatingActionButtonLocation>::center_float(),
1830            ));
1831            tester.pump_by(K_FLOATING_ACTION_BUTTON_SEGUE / 2);
1832
1833            // Interrupt motion to move the fab.
1834            tester.pump_widget(listener_frame(
1835                &listener,
1836                Some(default_fab()),
1837                <dyn FloatingActionButtonLocation>::end_float(),
1838            ));
1839            tester.pump_and_settle();
1840            check_steps(&steps.borrow());
1841            assert!(!steps.borrow().is_empty());
1842        });
1843    }
1844
1845    fn bab_frame(location: FloatingActionButtonLocationRef, bab: Option<f64>) -> WidgetRef {
1846        build_frame(
1847            Some(default_fab()),
1848            Some(location),
1849            None,
1850            TextDirection::Ltr,
1851            EdgeInsets::ZERO,
1852            bab.map(|height| SizedBox::new().height(height).into_widget()),
1853        )
1854    }
1855
1856    // 'Docked floating action button locations'.
1857    #[test]
1858    fn docked_locations_center_the_fab_on_the_top_of_the_bottom_bar() {
1859        test_widgets(|tester| {
1860            tester.pump_widget(bab_frame(
1861                <dyn FloatingActionButtonLocation>::end_docked(),
1862                Some(100.0),
1863            ));
1864
1865            // Scaffold 800x600, FAB is 56x56, BAB is 800x100, FAB's center is
1866            // at the top of the BAB.
1867            assert_offset_eq(fab_center(tester), Offset::new(756.0, 500.0));
1868
1869            tester.pump_widget(bab_frame(
1870                <dyn FloatingActionButtonLocation>::center_docked(),
1871                Some(100.0),
1872            ));
1873            tester.pump_and_settle();
1874            assert_offset_eq(fab_center(tester), Offset::new(400.0, 500.0));
1875
1876            tester.pump_widget(bab_frame(
1877                <dyn FloatingActionButtonLocation>::end_docked(),
1878                Some(100.0),
1879            ));
1880            tester.pump_and_settle();
1881            assert_offset_eq(fab_center(tester), Offset::new(756.0, 500.0));
1882        });
1883    }
1884
1885    // 'Docked floating action button locations: no BAB, small BAB'.
1886    #[test]
1887    fn docked_locations_keep_the_fab_on_screen_without_or_with_a_small_bottom_bar() {
1888        test_widgets(|tester| {
1889            tester.pump_widget(bab_frame(
1890                <dyn FloatingActionButtonLocation>::end_docked(),
1891                None,
1892            ));
1893            assert_offset_eq(fab_center(tester), Offset::new(756.0, 572.0));
1894
1895            tester.pump_widget(bab_frame(
1896                <dyn FloatingActionButtonLocation>::end_docked(),
1897                Some(16.0),
1898            ));
1899            assert_offset_eq(fab_center(tester), Offset::new(756.0, 572.0));
1900        });
1901    }
1902
1903    // 'Contained floating action button locations'.
1904    #[test]
1905    fn contained_locations_center_the_fab_in_the_bottom_bar() {
1906        test_widgets(|tester| {
1907            tester.pump_widget(bab_frame(
1908                <dyn FloatingActionButtonLocation>::end_contained(),
1909                Some(100.0),
1910            ));
1911
1912            // Scaffold 800x600, FAB is 56x56, BAB is 800x100, FAB's center is
1913            // at the top of the BAB.
1914            // Formula: scaffold height - BAB height + FAB height / 2 + BAB top & bottom margins.
1915            assert_offset_eq(fab_center(tester), Offset::new(756.0, 550.0));
1916        });
1917    }
1918
1919    /// Dart's `_singleFabScaffold`, without its `BottomNavigationBar` (see the module docs).
1920    fn single_fab_scaffold(
1921        app: &App,
1922        location: FloatingActionButtonLocationRef,
1923        animator: Option<FloatingActionButtonAnimatorRef>,
1924    ) -> WidgetRef {
1925        let mut scaffold = Scaffold::new()
1926            .app_bar(PreferredSizeWidgetRef::new(
1927                AppBar::new().title(Text::new("FloatingActionButtonLocation Test.")),
1928            ))
1929            .floating_action_button(
1930                FloatingActionButton::new(Some(waft_foundation::Listener::new(|_app| {})))
1931                    .child(Text::new("beach_access")),
1932            )
1933            .floating_action_button_location(location);
1934        if let Some(animator) = animator {
1935            scaffold = scaffold.floating_action_button_animator(animator);
1936        }
1937        material_app(
1938            ThemeData::builder().use_material3(false).build(app),
1939            Directionality::new(TextDirection::Ltr, scaffold).into_widget(),
1940        )
1941    }
1942
1943    // Moves involving new locations: 'Animator can be updated', without the
1944    // BottomNavigationBar, which only moves the FAB vertically: every value asserted is
1945    // horizontal.
1946    #[test]
1947    fn the_animator_can_be_updated() {
1948        test_widgets(|tester| {
1949            let mut fab_animator = <dyn FloatingActionButtonAnimator>::scaling();
1950            let mut fab_location = <dyn FloatingActionButtonLocation>::start_float();
1951
1952            let animation_duration = K_FLOATING_ACTION_BUTTON_SEGUE * 2;
1953            let quarter = animation_duration / 4;
1954
1955            let frame = |tester: &WidgetTester,
1956                         location: &FloatingActionButtonLocationRef,
1957                         animator: &FloatingActionButtonAnimatorRef| {
1958                single_fab_scaffold(
1959                    &tester.cell.borrow(),
1960                    Rc::clone(location),
1961                    Some(Rc::clone(animator)),
1962                )
1963            };
1964            let root = frame(tester, &fab_location, &fab_animator);
1965            tester.pump_widget(root);
1966
1967            expect(
1968                tester,
1969                &find::by_type::<FloatingActionButton>(),
1970                finds_one_widget(),
1971            );
1972            assert_eq!(transient_callback_count(tester), 0);
1973            assert_coordinate_eq(fab_center(tester).dx(), 44.0);
1974
1975            fab_location = <dyn FloatingActionButtonLocation>::end_float();
1976            let root = frame(tester, &fab_location, &fab_animator);
1977            tester.pump_widget(root);
1978
1979            // Dart's `lessThan(16.0)` holds through the f64 rounding of the FAB's full-turn
1980            // rotation, which leaves the corner 7e-15 inside; valo's f32 rotation leaves it
1981            // 6e-6 outside, so the bound is Dart's within POSITION_TOLERANCE.
1982            assert!(fab_top_left(tester).dx() < 16.0 + POSITION_TOLERANCE);
1983
1984            tester.pump_by(quarter);
1985            assert!(fab_top_left(tester).dx() > 16.0);
1986
1987            tester.pump_by(quarter);
1988            assert_coordinate_eq(fab_center(tester).dx(), 756.0);
1989            assert!(fab_top_right(tester).dx() < 800.0 - 16.0);
1990
1991            tester.pump_by(quarter);
1992            assert!(fab_top_right(tester).dx() < 800.0 - 16.0);
1993
1994            tester.pump_by(quarter);
1995            assert_coordinate_eq(fab_top_right(tester).dx(), 800.0 - 16.0);
1996
1997            fab_location = <dyn FloatingActionButtonLocation>::start_float();
1998            fab_animator = Rc::new(NoScalingFabAnimator);
1999            let root = frame(tester, &fab_location, &fab_animator);
2000            tester.pump_widget(root);
2001
2002            tester.pump_by(quarter);
2003            assert_coordinate_eq(fab_center(tester).dx(), 756.0);
2004            assert_coordinate_eq(fab_top_right(tester).dx(), 800.0 - 16.0);
2005
2006            tester.pump_by(quarter);
2007            assert_coordinate_eq(fab_center(tester).dx(), 44.0);
2008            // As above: Dart's bound within POSITION_TOLERANCE.
2009            assert!(fab_top_left(tester).dx() < 16.0 + POSITION_TOLERANCE);
2010        });
2011    }
2012
2013    // Locations account for safe interactive areas
2014
2015    /// Dart's `buildTest`, without `bottomNavigationBar:`, which waits.
2016    #[allow(clippy::too_many_arguments, reason = "Dart's buildTest arguments")]
2017    fn build_test(
2018        app: &App,
2019        location: FloatingActionButtonLocationRef,
2020        data: MediaQueryData,
2021        key: &GlobalKey,
2022        mini: bool,
2023        app_bar: bool,
2024        bottom_sheet: bool,
2025        resize_to_avoid_bottom_inset: bool,
2026    ) -> WidgetRef {
2027        let key = key.clone();
2028        let mut scaffold = Scaffold::new()
2029            .resize_to_avoid_bottom_inset(resize_to_avoid_bottom_inset)
2030            .floating_action_button_location(location)
2031            .floating_action_button(Builder::new(move |_app, context| {
2032                FloatingActionButton::new(Some(waft_foundation::Listener::new(move |app| {
2033                    ScaffoldMessenger::of(app, context).show_snack_bar(
2034                        app,
2035                        SnackBar::new(Text::new("Snacky!")),
2036                        None,
2037                    );
2038                })))
2039                .mini(mini)
2040                .key(key.clone().into())
2041                .child(Text::new("FAB"))
2042                .into_widget()
2043            }));
2044        if bottom_sheet {
2045            scaffold = scaffold.bottom_sheet(
2046                SizedBox::new()
2047                    .height(100.0)
2048                    .child(Center::new().child(Text::new("BottomSheet"))),
2049            );
2050        }
2051        if app_bar {
2052            scaffold = scaffold.app_bar(PreferredSizeWidgetRef::new(
2053                AppBar::new().title(Text::new("Demo")),
2054            ));
2055        }
2056        material_app(
2057            ThemeData::builder().use_material3(false).build(app),
2058            MediaQuery::new(data, scaffold).into_widget(),
2059        )
2060    }
2061
2062    struct SafeAreaCase {
2063        location: FloatingActionButtonLocationRef,
2064        mini: bool,
2065        key: GlobalKey,
2066        next_pointer: i64,
2067    }
2068
2069    impl SafeAreaCase {
2070        fn new(location: FloatingActionButtonLocationRef, mini: bool) -> SafeAreaCase {
2071            SafeAreaCase {
2072                location,
2073                mini,
2074                key: GlobalKey::new(),
2075                next_pointer: 1,
2076            }
2077        }
2078
2079        /// `tester.pumpWidget(buildTest(location, data, key, mini:, bottomSheet:,
2080        /// resizeToAvoidBottomInset:))`.
2081        fn pump(
2082            &self,
2083            tester: &mut WidgetTester,
2084            data: MediaQueryData,
2085            bottom_sheet: bool,
2086            resize_to_avoid_bottom_inset: bool,
2087        ) {
2088            self.pump_with(
2089                tester,
2090                data,
2091                false,
2092                bottom_sheet,
2093                resize_to_avoid_bottom_inset,
2094            );
2095        }
2096
2097        /// [`pump`](Self::pump) with `buildTest(appBar:)`.
2098        fn pump_with(
2099            &self,
2100            tester: &mut WidgetTester,
2101            data: MediaQueryData,
2102            app_bar: bool,
2103            bottom_sheet: bool,
2104            resize_to_avoid_bottom_inset: bool,
2105        ) {
2106            let root = build_test(
2107                &tester.cell.borrow(),
2108                Rc::clone(&self.location),
2109                data,
2110                &self.key,
2111                self.mini,
2112                app_bar,
2113                bottom_sheet,
2114                resize_to_avoid_bottom_inset,
2115            );
2116            tester.pump_widget(root);
2117        }
2118
2119        fn rect(&self, tester: &WidgetTester) -> Rect {
2120            tester.get_rect(&self.key)
2121        }
2122
2123        /// `tester.tap(find.byKey(floatingActionButton))` and `pumpAndSettle`: shows a snack
2124        /// bar.
2125        fn tap_and_settle(&mut self, tester: &mut WidgetTester) {
2126            let center = tester.get_center(&self.key);
2127            tester.tap_at(center, self.next_pointer);
2128            self.next_pointer += 1;
2129            tester.pump_and_settle();
2130        }
2131    }
2132
2133    const KEYBOARD_HEIGHT: f64 = 200.0;
2134    const VIEW_PADDING: f64 = 50.0;
2135
2136    fn view_padding_bottom() -> MediaQueryData {
2137        MediaQueryData::new().view_padding(EdgeInsets::only(0.0, 0.0, 0.0, VIEW_PADDING))
2138    }
2139
2140    fn view_padding_bottom_with_keyboard() -> MediaQueryData {
2141        view_padding_bottom().view_insets(EdgeInsets::only(0.0, 0.0, 0.0, KEYBOARD_HEIGHT))
2142    }
2143
2144    /// Dart's `runFloatTests`, without the `BottomNavigationBar` steps, which wait.
2145    fn run_float_tests(
2146        tester: &mut WidgetTester,
2147        location: FloatingActionButtonLocationRef,
2148        default_rect: Rect,
2149        bottom_sheet_rect: Rect,
2150        snack_bar_rect: Rect,
2151        mini: bool,
2152    ) {
2153        let mut case = SafeAreaCase::new(location, mini);
2154        // Default
2155        case.pump(tester, view_padding_bottom(), false, true);
2156        assert_rect_more_or_less_equals(case.rect(tester), default_rect);
2157        // Present keyboard and check position, should change
2158        case.pump(tester, view_padding_bottom_with_keyboard(), false, true);
2159        assert_rect_more_or_less_equals(
2160            case.rect(tester),
2161            default_rect.translate(0.0, VIEW_PADDING - KEYBOARD_HEIGHT),
2162        );
2163
2164        // With resizeToAvoidBottomInset: false
2165        // With keyboard presented, should maintain default position
2166        case.pump(tester, view_padding_bottom_with_keyboard(), false, false);
2167        assert_rect_more_or_less_equals(case.rect(tester), default_rect);
2168
2169        // BottomSheet default
2170        case.pump(tester, view_padding_bottom(), true, true);
2171        assert_rect_more_or_less_equals(case.rect(tester), bottom_sheet_rect);
2172        // Present keyboard and check position, bottomSheet and FAB both resize
2173        case.pump(tester, view_padding_bottom_with_keyboard(), true, true);
2174        assert_rect_more_or_less_equals(
2175            case.rect(tester),
2176            bottom_sheet_rect.translate(0.0, -KEYBOARD_HEIGHT),
2177        );
2178
2179        // bottomSheet with resizeToAvoidBottomInset: false
2180        // With keyboard presented, should maintain default bottomSheet position
2181        case.pump(tester, view_padding_bottom_with_keyboard(), true, false);
2182        assert_rect_more_or_less_equals(case.rect(tester), bottom_sheet_rect);
2183
2184        // SnackBar default
2185        case.pump(tester, view_padding_bottom(), false, true);
2186        case.tap_and_settle(tester); // Show SnackBar
2187        assert_rect_more_or_less_equals(case.rect(tester), snack_bar_rect);
2188
2189        // SnackBar when resized for presented keyboard
2190        case.pump(tester, view_padding_bottom_with_keyboard(), false, true);
2191        case.tap_and_settle(tester); // Show SnackBar
2192        assert_rect_more_or_less_equals(
2193            case.rect(tester),
2194            snack_bar_rect.translate(
2195                0.0,
2196                -KEYBOARD_HEIGHT + K_FLOATING_ACTION_BUTTON_MARGIN / 2.0,
2197            ),
2198        );
2199    }
2200
2201    // 'startFloat', without the BottomNavigationBar steps.
2202    #[test]
2203    fn start_float_accounts_for_safe_interactive_areas() {
2204        test_widgets(|tester| {
2205            run_float_tests(
2206                tester,
2207                <dyn FloatingActionButtonLocation>::start_float(),
2208                Rect::from_ltrb(16.0, 478.0, 72.0, 534.0),
2209                Rect::from_ltrb(16.0, 472.0, 72.0, 528.0),
2210                Rect::from_ltrb(16.0, 478.0, 72.0, 534.0),
2211                false,
2212            );
2213        });
2214    }
2215
2216    // 'miniStartFloat', without the BottomNavigationBar steps.
2217    #[test]
2218    fn mini_start_float_accounts_for_safe_interactive_areas() {
2219        test_widgets(|tester| {
2220            run_float_tests(
2221                tester,
2222                <dyn FloatingActionButtonLocation>::mini_start_float(),
2223                Rect::from_ltrb(12.0, 490.0, 60.0, 538.0),
2224                Rect::from_ltrb(12.0, 480.0, 60.0, 528.0),
2225                Rect::from_ltrb(12.0, 490.0, 60.0, 538.0),
2226                true,
2227            );
2228        });
2229    }
2230
2231    // 'centerFloat', without the BottomNavigationBar steps.
2232    #[test]
2233    fn center_float_accounts_for_safe_interactive_areas() {
2234        test_widgets(|tester| {
2235            run_float_tests(
2236                tester,
2237                <dyn FloatingActionButtonLocation>::center_float(),
2238                Rect::from_ltrb(372.0, 478.0, 428.0, 534.0),
2239                Rect::from_ltrb(372.0, 472.0, 428.0, 528.0),
2240                Rect::from_ltrb(372.0, 478.0, 428.0, 534.0),
2241                false,
2242            );
2243        });
2244    }
2245
2246    // 'miniCenterFloat', without the BottomNavigationBar steps.
2247    #[test]
2248    fn mini_center_float_accounts_for_safe_interactive_areas() {
2249        test_widgets(|tester| {
2250            run_float_tests(
2251                tester,
2252                <dyn FloatingActionButtonLocation>::mini_center_float(),
2253                Rect::from_ltrb(376.0, 490.0, 424.0, 538.0),
2254                Rect::from_ltrb(376.0, 480.0, 424.0, 528.0),
2255                Rect::from_ltrb(376.0, 490.0, 424.0, 538.0),
2256                true,
2257            );
2258        });
2259    }
2260
2261    // 'endFloat', without the BottomNavigationBar steps.
2262    #[test]
2263    fn end_float_accounts_for_safe_interactive_areas() {
2264        test_widgets(|tester| {
2265            run_float_tests(
2266                tester,
2267                <dyn FloatingActionButtonLocation>::end_float(),
2268                Rect::from_ltrb(728.0, 478.0, 784.0, 534.0),
2269                Rect::from_ltrb(728.0, 472.0, 784.0, 528.0),
2270                Rect::from_ltrb(728.0, 478.0, 784.0, 534.0),
2271                false,
2272            );
2273        });
2274    }
2275
2276    // 'miniEndFloat', without the BottomNavigationBar steps.
2277    #[test]
2278    fn mini_end_float_accounts_for_safe_interactive_areas() {
2279        test_widgets(|tester| {
2280            run_float_tests(
2281                tester,
2282                <dyn FloatingActionButtonLocation>::mini_end_float(),
2283                Rect::from_ltrb(740.0, 490.0, 788.0, 538.0),
2284                Rect::from_ltrb(740.0, 480.0, 788.0, 528.0),
2285                Rect::from_ltrb(740.0, 490.0, 788.0, 538.0),
2286                true,
2287            );
2288        });
2289    }
2290
2291    /// Dart's `runDockedTests`, without the `BottomNavigationBar` steps (every step that
2292    /// reads `bottomSheetRect` has one), which wait.
2293    fn run_docked_tests(
2294        tester: &mut WidgetTester,
2295        location: FloatingActionButtonLocationRef,
2296        default_rect: Rect,
2297        snack_bar_rect: Rect,
2298        mini: bool,
2299    ) {
2300        const SCAFFOLD_HEIGHT: f64 = 600.0;
2301        let mut case = SafeAreaCase::new(location, mini);
2302        // Default
2303        case.pump(tester, view_padding_bottom(), false, true);
2304        assert_rect_more_or_less_equals(case.rect(tester), default_rect);
2305        // Present keyboard and check position, should change
2306        case.pump(tester, view_padding_bottom_with_keyboard(), false, true);
2307        assert_rect_more_or_less_equals(
2308            case.rect(tester),
2309            default_rect.translate(
2310                0.0,
2311                VIEW_PADDING - KEYBOARD_HEIGHT - K_FLOATING_ACTION_BUTTON_MARGIN,
2312            ),
2313        );
2314        // The FAB should be away from the keyboard
2315        assert!(case.rect(tester).bottom < SCAFFOLD_HEIGHT - KEYBOARD_HEIGHT);
2316
2317        // With resizeToAvoidBottomInset: false
2318        // With keyboard presented, should maintain default position
2319        case.pump(tester, view_padding_bottom_with_keyboard(), false, false);
2320        assert_rect_more_or_less_equals(case.rect(tester), default_rect);
2321
2322        // SnackBar default
2323        case.pump(tester, view_padding_bottom(), false, true);
2324        case.tap_and_settle(tester); // Show SnackBar
2325        assert_rect_more_or_less_equals(case.rect(tester), snack_bar_rect);
2326
2327        // SnackBar when resized for presented keyboard
2328        case.pump(tester, view_padding_bottom_with_keyboard(), false, true);
2329        case.tap_and_settle(tester); // Show SnackBar
2330        assert_rect_more_or_less_equals(
2331            case.rect(tester),
2332            snack_bar_rect.translate(0.0, -KEYBOARD_HEIGHT),
2333        );
2334        // The FAB should be away from the keyboard
2335        assert!(case.rect(tester).bottom < SCAFFOLD_HEIGHT - KEYBOARD_HEIGHT);
2336    }
2337
2338    // 'startDocked', without the BottomNavigationBar steps.
2339    #[test]
2340    fn start_docked_accounts_for_safe_interactive_areas() {
2341        test_widgets(|tester| {
2342            run_docked_tests(
2343                tester,
2344                <dyn FloatingActionButtonLocation>::start_docked(),
2345                Rect::from_ltrb(16.0, 494.0, 72.0, 550.0),
2346                Rect::from_ltrb(16.0, 486.0, 72.0, 542.0),
2347                false,
2348            );
2349        });
2350    }
2351
2352    // 'miniStartDocked', without the BottomNavigationBar steps.
2353    #[test]
2354    fn mini_start_docked_accounts_for_safe_interactive_areas() {
2355        test_widgets(|tester| {
2356            run_docked_tests(
2357                tester,
2358                <dyn FloatingActionButtonLocation>::mini_start_docked(),
2359                Rect::from_ltrb(12.0, 502.0, 60.0, 550.0),
2360                Rect::from_ltrb(12.0, 494.0, 60.0, 542.0),
2361                true,
2362            );
2363        });
2364    }
2365
2366    // 'centerDocked', without the BottomNavigationBar steps.
2367    #[test]
2368    fn center_docked_accounts_for_safe_interactive_areas() {
2369        test_widgets(|tester| {
2370            run_docked_tests(
2371                tester,
2372                <dyn FloatingActionButtonLocation>::center_docked(),
2373                Rect::from_ltrb(372.0, 494.0, 428.0, 550.0),
2374                Rect::from_ltrb(372.0, 486.0, 428.0, 542.0),
2375                false,
2376            );
2377        });
2378    }
2379
2380    // 'miniCenterDocked', without the BottomNavigationBar steps.
2381    #[test]
2382    fn mini_center_docked_accounts_for_safe_interactive_areas() {
2383        test_widgets(|tester| {
2384            run_docked_tests(
2385                tester,
2386                <dyn FloatingActionButtonLocation>::mini_center_docked(),
2387                Rect::from_ltrb(376.0, 502.0, 424.0, 550.0),
2388                Rect::from_ltrb(376.0, 494.0, 424.0, 542.0),
2389                true,
2390            );
2391        });
2392    }
2393
2394    // 'endDocked', without the BottomNavigationBar steps.
2395    #[test]
2396    fn end_docked_accounts_for_safe_interactive_areas() {
2397        test_widgets(|tester| {
2398            run_docked_tests(
2399                tester,
2400                <dyn FloatingActionButtonLocation>::end_docked(),
2401                Rect::from_ltrb(728.0, 494.0, 784.0, 550.0),
2402                Rect::from_ltrb(728.0, 486.0, 784.0, 542.0),
2403                false,
2404            );
2405        });
2406    }
2407
2408    // 'miniEndDocked', without the BottomNavigationBar steps.
2409    #[test]
2410    fn mini_end_docked_accounts_for_safe_interactive_areas() {
2411        test_widgets(|tester| {
2412            run_docked_tests(
2413                tester,
2414                <dyn FloatingActionButtonLocation>::mini_end_docked(),
2415                Rect::from_ltrb(740.0, 502.0, 788.0, 550.0),
2416                Rect::from_ltrb(740.0, 494.0, 788.0, 542.0),
2417                true,
2418            );
2419        });
2420    }
2421
2422    /// Dart's `runTopTests`.
2423    fn run_top_tests(
2424        tester: &mut WidgetTester,
2425        location: FloatingActionButtonLocationRef,
2426        default_rect: Rect,
2427        app_bar_rect: Rect,
2428        mini: bool,
2429    ) {
2430        let case = SafeAreaCase::new(location, mini);
2431        // Default
2432        case.pump(
2433            tester,
2434            MediaQueryData::new().view_padding(EdgeInsets::only(0.0, VIEW_PADDING, 0.0, 0.0)),
2435            false,
2436            true,
2437        );
2438        assert_rect_more_or_less_equals(case.rect(tester), default_rect);
2439
2440        // AppBar default
2441        case.pump_with(
2442            tester,
2443            MediaQueryData::new().view_padding(EdgeInsets::only(0.0, VIEW_PADDING, 0.0, 0.0)),
2444            true,
2445            false,
2446            true,
2447        );
2448        assert_rect_more_or_less_equals(case.rect(tester), app_bar_rect);
2449    }
2450
2451    // 'startTop'.
2452    #[test]
2453    fn start_top_accounts_for_safe_interactive_areas() {
2454        test_widgets(|tester| {
2455            run_top_tests(
2456                tester,
2457                <dyn FloatingActionButtonLocation>::start_top(),
2458                Rect::from_ltrb(16.0, 50.0, 72.0, 106.0),
2459                // Positioned relative to AppBar
2460                Rect::from_ltrb(16.0, 28.0, 72.0, 84.0),
2461                false,
2462            );
2463        });
2464    }
2465
2466    // 'miniStartTop'.
2467    #[test]
2468    fn mini_start_top_accounts_for_safe_interactive_areas() {
2469        test_widgets(|tester| {
2470            run_top_tests(
2471                tester,
2472                <dyn FloatingActionButtonLocation>::mini_start_top(),
2473                Rect::from_ltrb(12.0, 50.0, 60.0, 98.0),
2474                // Positioned relative to AppBar
2475                Rect::from_ltrb(12.0, 32.0, 60.0, 80.0),
2476                true,
2477            );
2478        });
2479    }
2480
2481    // 'centerTop'.
2482    #[test]
2483    fn center_top_accounts_for_safe_interactive_areas() {
2484        test_widgets(|tester| {
2485            run_top_tests(
2486                tester,
2487                <dyn FloatingActionButtonLocation>::center_top(),
2488                Rect::from_ltrb(372.0, 50.0, 428.0, 106.0),
2489                // Positioned relative to AppBar
2490                Rect::from_ltrb(372.0, 28.0, 428.0, 84.0),
2491                false,
2492            );
2493        });
2494    }
2495
2496    // 'miniCenterTop'.
2497    #[test]
2498    fn mini_center_top_accounts_for_safe_interactive_areas() {
2499        test_widgets(|tester| {
2500            run_top_tests(
2501                tester,
2502                <dyn FloatingActionButtonLocation>::mini_center_top(),
2503                Rect::from_ltrb(376.0, 50.0, 424.0, 98.0),
2504                // Positioned relative to AppBar
2505                Rect::from_ltrb(376.0, 32.0, 424.0, 80.0),
2506                true,
2507            );
2508        });
2509    }
2510
2511    // 'endTop'.
2512    #[test]
2513    fn end_top_accounts_for_safe_interactive_areas() {
2514        test_widgets(|tester| {
2515            run_top_tests(
2516                tester,
2517                <dyn FloatingActionButtonLocation>::end_top(),
2518                Rect::from_ltrb(728.0, 50.0, 784.0, 106.0),
2519                // Positioned relative to AppBar
2520                Rect::from_ltrb(728.0, 28.0, 784.0, 84.0),
2521                false,
2522            );
2523        });
2524    }
2525
2526    // 'miniEndTop'.
2527    #[test]
2528    fn mini_end_top_accounts_for_safe_interactive_areas() {
2529        test_widgets(|tester| {
2530            run_top_tests(
2531                tester,
2532                <dyn FloatingActionButtonLocation>::mini_end_top(),
2533                Rect::from_ltrb(740.0, 50.0, 788.0, 98.0),
2534                // Positioned relative to AppBar
2535                Rect::from_ltrb(740.0, 32.0, 788.0, 80.0),
2536                true,
2537            );
2538        });
2539    }
2540
2541    /// `MaterialApp(home: Directionality(textDirection, Scaffold(appBar: AppBar(),
2542    /// floatingActionButton: const FloatingActionButton(onPressed: null),
2543    /// floatingActionButtonLocation: location)))`; the LTR cases have no `Directionality` of
2544    /// their own, and the app's is left to right.
2545    fn top_location_rect(
2546        tester: &mut WidgetTester,
2547        location: FloatingActionButtonLocationRef,
2548        text_direction: TextDirection,
2549    ) -> Rect {
2550        let theme = ThemeData::new(&tester.cell.borrow());
2551        let key = GlobalKey::new();
2552        tester.pump_widget(material_app(
2553            theme,
2554            Directionality::new(
2555                text_direction,
2556                Scaffold::new()
2557                    .app_bar(PreferredSizeWidgetRef::new(AppBar::new()))
2558                    .floating_action_button(FloatingActionButton::new(None).key(key.clone().into()))
2559                    .floating_action_button_location(location),
2560            )
2561            .into_widget(),
2562        ));
2563        tester.get_rect(&key)
2564    }
2565
2566    // 'Start-top floating action button location LTR'.
2567    #[test]
2568    fn the_start_top_location_left_to_right() {
2569        test_widgets(|tester| {
2570            assert_rect_more_or_less_equals(
2571                top_location_rect(
2572                    tester,
2573                    <dyn FloatingActionButtonLocation>::start_top(),
2574                    TextDirection::Ltr,
2575                ),
2576                Rect::from_ltwh(16.0, 28.0, 56.0, 56.0),
2577            );
2578        });
2579    }
2580
2581    // 'End-top floating action button location RTL'.
2582    #[test]
2583    fn the_end_top_location_right_to_left() {
2584        test_widgets(|tester| {
2585            assert_rect_more_or_less_equals(
2586                top_location_rect(
2587                    tester,
2588                    <dyn FloatingActionButtonLocation>::end_top(),
2589                    TextDirection::Rtl,
2590                ),
2591                Rect::from_ltwh(16.0, 28.0, 56.0, 56.0),
2592            );
2593        });
2594    }
2595
2596    // 'Start-top floating action button location RTL'.
2597    #[test]
2598    fn the_start_top_location_right_to_left() {
2599        test_widgets(|tester| {
2600            assert_rect_more_or_less_equals(
2601                top_location_rect(
2602                    tester,
2603                    <dyn FloatingActionButtonLocation>::start_top(),
2604                    TextDirection::Rtl,
2605                ),
2606                Rect::from_ltwh(800.0 - 56.0 - 16.0, 28.0, 56.0, 56.0),
2607            );
2608        });
2609    }
2610
2611    // 'End-top floating action button location LTR'.
2612    #[test]
2613    fn the_end_top_location_left_to_right() {
2614        test_widgets(|tester| {
2615            assert_rect_more_or_less_equals(
2616                top_location_rect(
2617                    tester,
2618                    <dyn FloatingActionButtonLocation>::end_top(),
2619                    TextDirection::Ltr,
2620                ),
2621                Rect::from_ltwh(800.0 - 56.0 - 16.0, 28.0, 56.0, 56.0),
2622            );
2623        });
2624    }
2625
2626    // Waiting:
2627    //  * CircleAvatar: 'Mini-start-top floating action button location'.
2628    //  * BottomNavigationBar: every case of 'New Floating Action Button Locations' and 'Custom
2629    //    Floating Action Button Locations', 'Moves between new locations and new locations',
2630    //    'Moves between new locations and old locations', 'Moves between new locations and old
2631    //    locations with custom animator', and the BottomNavigationBar steps of the float and
2632    //    docked cases of 'Locations account for safe interactive areas'.
2633}