Skip to main content

waft_material/
floating_action_button.rs

1//! Flutter counterpart: material_ui's `floating_action_button.dart`.
2//!
3//! The `scaffold.dart` that Dart's file imports is for its documentation only.
4
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{Clip, Color, Offset, Size, TextBaseline};
9use waft_foundation::{
10    AnyEq, App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, FlagProperty,
11    Listener, ObjectFlagProperty, StringProperty,
12};
13use waft_painting::{
14    AlignmentGeometry, CircleBorder, ColorProperty, EdgeInsetsDirectional, EdgeInsetsGeometry,
15    ShapeBorderRef, StadiumBorder, TextDirection, TextStyle,
16};
17use waft_rendering::{
18    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, PaintingContext, RenderBox,
19    RenderBoxData, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
20    RenderObjectWithChildMixin, RenderShiftedBox,
21};
22use waft_rendering::{RenderAligningShiftedBox, RenderAligningShiftedBoxData};
23use waft_services::MouseCursorRef;
24use waft_widgets::{
25    BuildContext, Directionality, FocusNodeRef, Hero, IconTheme, IconThemeData, IntoWidget, KeyRef,
26    MainAxisSize, MergeSemantics, Padding, RenderObjectWidget, Row, SingleChildRenderObjectWidget,
27    SizedBox, StatelessWidget, WidgetRef, WidgetStateMouseCursor, WidgetStateProperty,
28    WidgetStatePropertyRef,
29};
30
31use crate::button::RawMaterialButton;
32use crate::floating_action_button_theme::{
33    FloatingActionButtonTheme, FloatingActionButtonThemeData, FloatingActionButtonThemeDataGetters,
34};
35use crate::generated::fab_defaults_m3::FabDefaultsM3;
36use crate::theme::Theme;
37use crate::theme_data::MaterialTapTargetSize;
38use crate::theme_data_getters::DefaultsContext;
39use crate::tooltip::Tooltip;
40
41/// Dart's `_DefaultHeroTag`.
42///
43/// Dart only ever makes it as `const _DefaultHeroTag()`, one canonical instance, so the
44/// derived equality, which makes every value equal, is Dart's identity.
45#[derive(PartialEq, Eq, Hash)]
46struct DefaultHeroTag;
47
48impl Debug for DefaultHeroTag {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.write_str("<default FloatingActionButton tag>")
51    }
52}
53
54/// Dart's `const _DefaultHeroTag()`: one shared tag, so every floating action button that
55/// keeps the default matches every other.
56fn default_hero_tag() -> Rc<dyn AnyEq> {
57    thread_local! {
58        static TAG: Rc<dyn AnyEq> = Rc::new(DefaultHeroTag);
59    }
60    TAG.with(Rc::clone)
61}
62
63/// Dart's `_FloatingActionButtonType`.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub(crate) enum FloatingActionButtonType {
66    Regular,
67    Small,
68    Large,
69    Extended,
70}
71
72/// A Material Design floating action button.
73///
74/// A floating action button is a circular icon button that hovers over content
75/// to promote a primary action in the application. Floating action buttons are
76/// most commonly used in the `Scaffold::floating_action_button` field.
77///
78/// Use at most a single floating action button per screen. Floating action
79/// buttons should be used for positive actions such as "create", "share", or
80/// "navigate". (If more than one floating action button is used within a
81/// `Route`, then make sure that each button has a unique [`hero_tag`](Self::hero_tag),
82/// otherwise an exception will be thrown.)
83///
84/// If the [`on_pressed`](Self::on_pressed) callback is null, then the button will be disabled
85/// and will not react to touch. It is highly discouraged to disable a floating
86/// action button as there is no indication to the user that the button is
87/// disabled. Consider changing the [`background_color`](Self::background_color) if disabling
88/// the floating action button.
89///
90/// See also:
91///
92///  * `Scaffold`, in which floating action buttons typically live.
93///  * `ElevatedButton`, a filled button whose material elevates when pressed.
94///  * <https://material.io/design/components/buttons-floating-action-button.html>
95///  * <https://m3.material.io/components/floating-action-button>
96pub struct FloatingActionButton {
97    pub key: Option<KeyRef>,
98
99    /// The widget below this widget in the tree.
100    ///
101    /// Typically an `Icon`.
102    pub child: Option<WidgetRef>,
103
104    /// Text that describes the action that will occur when the button is pressed.
105    ///
106    /// This text is displayed when the user long-presses on the button and is
107    /// used for accessibility.
108    pub tooltip: Option<String>,
109
110    /// The default foreground color for icons and text within the button.
111    ///
112    /// If this property is null, then the ambient
113    /// [`FloatingActionButtonThemeData::foreground_color`] is used. If that property is also
114    /// null, then the `ColorScheme::on_primary_container` color of `ThemeData::color_scheme`
115    /// is used. If `ThemeData::use_material3` is set to false, then the
116    /// `ColorScheme::on_secondary` color of `ThemeData::color_scheme` is used.
117    pub foreground_color: Option<Color>,
118
119    /// The button's background color.
120    ///
121    /// If this property is null, then the ambient
122    /// [`FloatingActionButtonThemeData::background_color`] is used. If that property is also
123    /// null, then the `ColorScheme::primary_container` color of `ThemeData::color_scheme`
124    /// is used. If `ThemeData::use_material3` is set to false, then the
125    /// `ColorScheme::secondary` color of `ThemeData::color_scheme` is used.
126    pub background_color: Option<Color>,
127
128    /// The color to use for filling the button when the button has input focus.
129    ///
130    /// In Material3, defaults to `ColorScheme::on_primary_container` with opacity 0.1.
131    /// In Material 2, it defaults to `ThemeData::focus_color` for the current theme.
132    pub focus_color: Option<Color>,
133
134    /// The color to use for filling the button when the button has a pointer
135    /// hovering over it.
136    ///
137    /// Defaults to `ThemeData::hover_color` for the current theme in Material 2. In
138    /// Material 3, defaults to `ColorScheme::on_primary_container` with opacity 0.08.
139    pub hover_color: Option<Color>,
140
141    /// The splash color for this [`FloatingActionButton`]'s `InkWell`.
142    ///
143    /// If null, [`FloatingActionButtonThemeData::splash_color`] is used, if that is
144    /// null, `ThemeData::splash_color` is used in Material 2;
145    /// `ColorScheme::on_primary_container` with opacity 0.1 is used in Material 3.
146    pub splash_color: Option<Color>,
147
148    /// The tag to apply to the button's [`Hero`] widget.
149    ///
150    /// Defaults to a tag that matches other floating action buttons.
151    ///
152    /// Set this to null explicitly if you don't want the floating action button to
153    /// have a hero tag.
154    ///
155    /// If this is not explicitly set, then there can only be one
156    /// [`FloatingActionButton`] per route (that is, per screen), since otherwise
157    /// there would be a tag conflict (multiple heroes on one route can't have the
158    /// same tag). The Material Design specification recommends only using one
159    /// floating action button per screen.
160    pub hero_tag: Option<Rc<dyn AnyEq>>,
161
162    /// The callback that is called when the button is tapped or otherwise activated.
163    ///
164    /// If this is set to null, the button will be disabled.
165    pub on_pressed: Option<Listener>,
166
167    /// The cursor for a mouse pointer when it enters or is hovering over the
168    /// button.
169    ///
170    /// If this property is null, [`FloatingActionButtonThemeData::mouse_cursor`] is used.
171    /// If that is null, [`WidgetStateMouseCursor::adaptive_clickable`] will be used.
172    pub mouse_cursor: Option<MouseCursorRef>,
173
174    /// The z-coordinate at which to place this button relative to its parent.
175    ///
176    /// This controls the size of the shadow below the floating action button.
177    ///
178    /// Defaults to 6, the appropriate elevation for floating action buttons. The
179    /// value is always non-negative.
180    ///
181    /// See also:
182    ///
183    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
184    ///    is pressed.
185    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
186    ///    disabled.
187    pub elevation: Option<f64>,
188
189    /// The z-coordinate at which to place this button relative to its parent when
190    /// the button has the input focus.
191    ///
192    /// This controls the size of the shadow below the floating action button.
193    ///
194    /// Defaults to 8, the appropriate elevation for floating action buttons
195    /// while they have focus. The value is always non-negative.
196    ///
197    /// See also:
198    ///
199    ///  * [`elevation`](Self::elevation), the default elevation.
200    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
201    ///    is pressed.
202    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
203    ///    disabled.
204    pub focus_elevation: Option<f64>,
205
206    /// The z-coordinate at which to place this button relative to its parent when
207    /// the button is enabled and has a pointer hovering over it.
208    ///
209    /// This controls the size of the shadow below the floating action button.
210    ///
211    /// Defaults to 8, the appropriate elevation for floating action buttons while
212    /// they have a pointer hovering over them. The value is always non-negative.
213    ///
214    /// See also:
215    ///
216    ///  * [`elevation`](Self::elevation), the default elevation.
217    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
218    ///    is pressed.
219    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
220    ///    disabled.
221    pub hover_elevation: Option<f64>,
222
223    /// The z-coordinate at which to place this button relative to its parent when
224    /// the user is touching the button.
225    ///
226    /// This controls the size of the shadow below the floating action button.
227    ///
228    /// Defaults to 12, the appropriate elevation for floating action buttons
229    /// while they are being touched. The value is always non-negative.
230    ///
231    /// See also:
232    ///
233    ///  * [`elevation`](Self::elevation), the default elevation.
234    pub highlight_elevation: Option<f64>,
235
236    /// The z-coordinate at which to place this button when the button is disabled
237    /// ([`on_pressed`](Self::on_pressed) is null).
238    ///
239    /// This controls the size of the shadow below the floating action button.
240    ///
241    /// Defaults to the same value as [`elevation`](Self::elevation). Setting this to zero
242    /// makes the floating action button work similar to an `ElevatedButton` but the titular
243    /// "floating" effect is lost. The value is always non-negative.
244    ///
245    /// See also:
246    ///
247    ///  * [`elevation`](Self::elevation), the default elevation.
248    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
249    ///    is pressed.
250    pub disabled_elevation: Option<f64>,
251
252    /// Controls the size of this button.
253    ///
254    /// By default, floating action buttons are non-mini and have a height and
255    /// width of 56.0 logical pixels. Mini floating action buttons have a height
256    /// and width of 40.0 logical pixels with a layout width and height of 48.0
257    /// logical pixels. (The extra 4 pixels of padding on each side are added as a
258    /// result of the floating action button having [`MaterialTapTargetSize::Padded`]
259    /// set on the underlying [`RawMaterialButton::material_tap_target_size`].)
260    pub mini: bool,
261
262    /// The shape of the button's `Material`.
263    ///
264    /// The button's highlight and splash are clipped to this shape. If the
265    /// button has an elevation, then its drop shadow is defined by this
266    /// shape as well.
267    pub shape: Option<ShapeBorderRef>,
268
269    /// The content will be clipped (or not) according to this option.
270    ///
271    /// Defaults to [`Clip::None`].
272    pub clip_behavior: Clip,
273
274    /// True if this is an "extended" floating action button.
275    ///
276    /// Typically "extended" buttons have a [`StadiumBorder`] [`shape`](Self::shape)
277    /// and have been created with the [`FloatingActionButton::extended`]
278    /// constructor.
279    ///
280    /// The `Scaffold` animates the appearance of ordinary floating
281    /// action buttons with scale and rotation transitions. Extended
282    /// floating action buttons are scaled and faded in.
283    pub is_extended: bool,
284
285    /// An optional focus node to use as the focus node for this widget.
286    ///
287    /// See `Focus::focus_node`.
288    pub focus_node: Option<FocusNodeRef>,
289
290    /// True if this widget will be selected as the initial focus when no other node in its
291    /// scope is currently focused.
292    ///
293    /// See `Focus::autofocus`.
294    pub autofocus: bool,
295
296    /// Configures the minimum size of the tap target.
297    ///
298    /// Defaults to `ThemeData::material_tap_target_size`.
299    ///
300    /// See also:
301    ///
302    ///  * [`MaterialTapTargetSize`], for a description of how this affects tap targets.
303    pub material_tap_target_size: Option<MaterialTapTargetSize>,
304
305    /// Whether detected gestures should provide acoustic and/or haptic feedback.
306    ///
307    /// For example, on Android a tap will produce a clicking sound and a
308    /// long-press will produce a short vibration, when feedback is enabled.
309    ///
310    /// If null, [`FloatingActionButtonThemeData::enable_feedback`] is used.
311    /// If both are null, then default value is true.
312    ///
313    /// See also:
314    ///
315    ///  * `Feedback` for providing platform-specific feedback to certain actions.
316    pub enable_feedback: Option<bool>,
317
318    /// The spacing between the icon and the label for an extended
319    /// [`FloatingActionButton`].
320    ///
321    /// If null, [`FloatingActionButtonThemeData::extended_icon_label_spacing`] is used.
322    /// If that is also null, the default is 8.0.
323    pub extended_icon_label_spacing: Option<f64>,
324
325    /// The padding for an extended [`FloatingActionButton`]'s content.
326    ///
327    /// If null, [`FloatingActionButtonThemeData::extended_padding`] is used. If that
328    /// is also null, the default is
329    /// `EdgeInsetsDirectional.only(start: 16.0, end: 20.0)` if an icon is
330    /// provided, and `EdgeInsetsDirectional.only(start: 20.0, end: 20.0)` if not.
331    pub extended_padding: Option<EdgeInsetsGeometry>,
332
333    /// The text style for an extended [`FloatingActionButton`]'s label.
334    ///
335    /// If null, [`FloatingActionButtonThemeData::extended_text_style`] is used. If
336    /// that is also null, then `TextTheme::label_large` with a letter spacing of 1.2
337    /// is used.
338    pub extended_text_style: Option<TextStyle>,
339
340    floating_action_button_type: FloatingActionButtonType,
341
342    extended_label: Option<WidgetRef>,
343
344    /// Whether the unnamed constructor made this button, the only one that takes `mini`;
345    /// `mini(true)` makes its type `Small` too, so the type cannot tell.
346    unnamed_constructor: bool,
347}
348
349impl FloatingActionButton {
350    /// Creates a circular floating action button.
351    ///
352    /// The [`elevation`](Self::elevation), [`highlight_elevation`](Self::highlight_elevation),
353    /// and [`disabled_elevation`](Self::disabled_elevation) parameters, if specified, must be
354    /// non-negative.
355    pub fn new(on_pressed: Option<Listener>) -> FloatingActionButton {
356        FloatingActionButton {
357            key: None,
358            child: None,
359            tooltip: None,
360            foreground_color: None,
361            background_color: None,
362            focus_color: None,
363            hover_color: None,
364            splash_color: None,
365            hero_tag: Some(default_hero_tag()),
366            on_pressed,
367            mouse_cursor: None,
368            elevation: None,
369            focus_elevation: None,
370            hover_elevation: None,
371            highlight_elevation: None,
372            disabled_elevation: None,
373            mini: false,
374            shape: None,
375            clip_behavior: Clip::None,
376            is_extended: false,
377            focus_node: None,
378            autofocus: false,
379            material_tap_target_size: None,
380            enable_feedback: None,
381            extended_icon_label_spacing: None,
382            extended_padding: None,
383            extended_text_style: None,
384            floating_action_button_type: FloatingActionButtonType::Regular,
385            extended_label: None,
386            unnamed_constructor: true,
387        }
388    }
389
390    /// Creates a small circular floating action button.
391    ///
392    /// This constructor overrides the default size constraints of the floating
393    /// action button.
394    ///
395    /// The [`elevation`](Self::elevation), [`focus_elevation`](Self::focus_elevation),
396    /// [`hover_elevation`](Self::hover_elevation),
397    /// [`highlight_elevation`](Self::highlight_elevation), and
398    /// [`disabled_elevation`](Self::disabled_elevation) parameters, if specified, must be
399    /// non-negative.
400    pub fn small(on_pressed: Option<Listener>) -> FloatingActionButton {
401        FloatingActionButton {
402            floating_action_button_type: FloatingActionButtonType::Small,
403            mini: true,
404            unnamed_constructor: false,
405            ..FloatingActionButton::new(on_pressed)
406        }
407    }
408
409    /// Creates a large circular floating action button.
410    ///
411    /// This constructor overrides the default size constraints of the floating
412    /// action button.
413    ///
414    /// The [`elevation`](Self::elevation), [`focus_elevation`](Self::focus_elevation),
415    /// [`hover_elevation`](Self::hover_elevation),
416    /// [`highlight_elevation`](Self::highlight_elevation), and
417    /// [`disabled_elevation`](Self::disabled_elevation) parameters, if specified, must be
418    /// non-negative.
419    pub fn large(on_pressed: Option<Listener>) -> FloatingActionButton {
420        FloatingActionButton {
421            floating_action_button_type: FloatingActionButtonType::Large,
422            mini: false,
423            unnamed_constructor: false,
424            ..FloatingActionButton::new(on_pressed)
425        }
426    }
427
428    /// Creates a wider [`StadiumBorder`]-shaped floating action button with
429    /// an optional [`icon`](Self::icon) and a `label`.
430    ///
431    /// The [`elevation`](Self::elevation), [`highlight_elevation`](Self::highlight_elevation),
432    /// and [`disabled_elevation`](Self::disabled_elevation) parameters, if specified, must be
433    /// non-negative.
434    ///
435    /// See also:
436    ///  * <https://m3.material.io/components/extended-fab>
437    #[cfg_attr(debug_assertions, track_caller)]
438    pub fn extended<K>(
439        on_pressed: Option<Listener>,
440        label: impl IntoWidget<K>,
441    ) -> FloatingActionButton {
442        FloatingActionButton {
443            is_extended: true,
444            mini: false,
445            floating_action_button_type: FloatingActionButtonType::Extended,
446            extended_label: Some(label.into_widget()),
447            unnamed_constructor: false,
448            ..FloatingActionButton::new(on_pressed)
449        }
450    }
451
452    /// Dart `FloatingActionButton(key:)`.
453    pub fn key(mut self, key: KeyRef) -> FloatingActionButton {
454        self.key = Some(key);
455        self
456    }
457
458    /// Dart `FloatingActionButton(child:)`.
459    #[cfg_attr(debug_assertions, track_caller)]
460    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FloatingActionButton {
461        self.child = Some(child.into_widget());
462        self
463    }
464
465    /// Dart `FloatingActionButton(tooltip:)`.
466    pub fn tooltip(mut self, tooltip: impl Into<String>) -> FloatingActionButton {
467        self.tooltip = Some(tooltip.into());
468        self
469    }
470
471    /// Dart `FloatingActionButton(foregroundColor:)`.
472    pub fn foreground_color(mut self, foreground_color: Color) -> FloatingActionButton {
473        self.foreground_color = Some(foreground_color);
474        self
475    }
476
477    /// Dart `FloatingActionButton(backgroundColor:)`.
478    pub fn background_color(mut self, background_color: Color) -> FloatingActionButton {
479        self.background_color = Some(background_color);
480        self
481    }
482
483    /// Dart `FloatingActionButton(focusColor:)`.
484    pub fn focus_color(mut self, focus_color: Color) -> FloatingActionButton {
485        self.focus_color = Some(focus_color);
486        self
487    }
488
489    /// Dart `FloatingActionButton(hoverColor:)`.
490    pub fn hover_color(mut self, hover_color: Color) -> FloatingActionButton {
491        self.hover_color = Some(hover_color);
492        self
493    }
494
495    /// Dart `FloatingActionButton(splashColor:)`.
496    pub fn splash_color(mut self, splash_color: Color) -> FloatingActionButton {
497        self.splash_color = Some(splash_color);
498        self
499    }
500
501    /// Dart `FloatingActionButton(heroTag:)`; `None` is Dart's explicit `heroTag: null`.
502    pub fn hero_tag(mut self, hero_tag: Option<Rc<dyn AnyEq>>) -> FloatingActionButton {
503        self.hero_tag = hero_tag;
504        self
505    }
506
507    /// Dart `FloatingActionButton(elevation:)`.
508    pub fn elevation(mut self, elevation: f64) -> FloatingActionButton {
509        debug_assert!(elevation >= 0.0);
510        self.elevation = Some(elevation);
511        self
512    }
513
514    /// Dart `FloatingActionButton(focusElevation:)`.
515    pub fn focus_elevation(mut self, focus_elevation: f64) -> FloatingActionButton {
516        debug_assert!(focus_elevation >= 0.0);
517        self.focus_elevation = Some(focus_elevation);
518        self
519    }
520
521    /// Dart `FloatingActionButton(hoverElevation:)`.
522    pub fn hover_elevation(mut self, hover_elevation: f64) -> FloatingActionButton {
523        debug_assert!(hover_elevation >= 0.0);
524        self.hover_elevation = Some(hover_elevation);
525        self
526    }
527
528    /// Dart `FloatingActionButton(highlightElevation:)`.
529    pub fn highlight_elevation(mut self, highlight_elevation: f64) -> FloatingActionButton {
530        debug_assert!(highlight_elevation >= 0.0);
531        self.highlight_elevation = Some(highlight_elevation);
532        self
533    }
534
535    /// Dart `FloatingActionButton(disabledElevation:)`.
536    pub fn disabled_elevation(mut self, disabled_elevation: f64) -> FloatingActionButton {
537        debug_assert!(disabled_elevation >= 0.0);
538        self.disabled_elevation = Some(disabled_elevation);
539        self
540    }
541
542    /// Dart `FloatingActionButton(mouseCursor:)`.
543    pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> FloatingActionButton {
544        self.mouse_cursor = Some(mouse_cursor.into());
545        self
546    }
547
548    /// Dart `FloatingActionButton(mini:)`, an argument of the unnamed constructor only, which
549    /// picks the small type when it is true.
550    pub fn mini(mut self, mini: bool) -> FloatingActionButton {
551        debug_assert!(
552            self.unnamed_constructor,
553            "`mini` is an argument of the unnamed `FloatingActionButton` constructor only"
554        );
555        self.mini = mini;
556        self.floating_action_button_type = if mini {
557            FloatingActionButtonType::Small
558        } else {
559            FloatingActionButtonType::Regular
560        };
561        self
562    }
563
564    /// Dart `FloatingActionButton(shape:)`.
565    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> FloatingActionButton {
566        self.shape = Some(shape.into());
567        self
568    }
569
570    /// Dart `FloatingActionButton(clipBehavior:)`.
571    pub fn clip_behavior(mut self, clip_behavior: Clip) -> FloatingActionButton {
572        self.clip_behavior = clip_behavior;
573        self
574    }
575
576    /// Dart `FloatingActionButton(isExtended:)` and `FloatingActionButton.extended(isExtended:)`.
577    pub fn is_extended(mut self, is_extended: bool) -> FloatingActionButton {
578        debug_assert!(
579            self.unnamed_constructor
580                || self.floating_action_button_type == FloatingActionButtonType::Extended,
581            "`isExtended` is an argument of the unnamed and the `extended` `FloatingActionButton` \
582             constructors only"
583        );
584        self.is_extended = is_extended;
585        self
586    }
587
588    /// Dart `FloatingActionButton(focusNode:)`.
589    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> FloatingActionButton {
590        self.focus_node = Some(focus_node);
591        self
592    }
593
594    /// Dart `FloatingActionButton(autofocus:)`.
595    pub fn autofocus(mut self, autofocus: bool) -> FloatingActionButton {
596        self.autofocus = autofocus;
597        self
598    }
599
600    /// Dart `FloatingActionButton(materialTapTargetSize:)`.
601    pub fn material_tap_target_size(
602        mut self,
603        material_tap_target_size: MaterialTapTargetSize,
604    ) -> FloatingActionButton {
605        self.material_tap_target_size = Some(material_tap_target_size);
606        self
607    }
608
609    /// Dart `FloatingActionButton(enableFeedback:)`.
610    pub fn enable_feedback(mut self, enable_feedback: bool) -> FloatingActionButton {
611        self.enable_feedback = Some(enable_feedback);
612        self
613    }
614
615    /// Dart `FloatingActionButton.extended(extendedIconLabelSpacing:)`.
616    pub fn extended_icon_label_spacing(
617        mut self,
618        extended_icon_label_spacing: f64,
619    ) -> FloatingActionButton {
620        self.debug_assert_extended("extendedIconLabelSpacing");
621        self.extended_icon_label_spacing = Some(extended_icon_label_spacing);
622        self
623    }
624
625    /// Dart `FloatingActionButton.extended(extendedPadding:)`.
626    pub fn extended_padding(
627        mut self,
628        extended_padding: impl Into<EdgeInsetsGeometry>,
629    ) -> FloatingActionButton {
630        self.debug_assert_extended("extendedPadding");
631        self.extended_padding = Some(extended_padding.into());
632        self
633    }
634
635    /// Dart `FloatingActionButton.extended(extendedTextStyle:)`.
636    pub fn extended_text_style(mut self, extended_text_style: TextStyle) -> FloatingActionButton {
637        self.debug_assert_extended("extendedTextStyle");
638        self.extended_text_style = Some(extended_text_style);
639        self
640    }
641
642    /// Dart `FloatingActionButton.extended(icon:)`, which the constructor stores as
643    /// [`child`](Self::child).
644    #[cfg_attr(debug_assertions, track_caller)]
645    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> FloatingActionButton {
646        self.debug_assert_extended("icon");
647        self.child = Some(icon.into_widget());
648        self
649    }
650
651    /// Dart's other constructors set `argument` to null: only `extended` takes it.
652    fn debug_assert_extended(&self, argument: &str) {
653        debug_assert!(
654            self.floating_action_button_type == FloatingActionButtonType::Extended,
655            "`{argument}` is an argument of the `FloatingActionButton.extended` constructor only"
656        );
657    }
658
659    /// The defaults of the theme in `context`: Material 3's, or Material 2's when
660    /// `ThemeData::use_material3` is false.
661    fn defaults(
662        &self,
663        app: &mut App,
664        context: BuildContext,
665    ) -> Box<dyn FloatingActionButtonThemeDataGetters> {
666        let has_child = self.child.is_some();
667        if Theme::of(app, context).use_material3 {
668            Box::new(FabDefaultsM3::new(
669                context,
670                self.floating_action_button_type,
671                has_child,
672            ))
673        } else {
674            Box::new(FabDefaultsM2::new(
675                app,
676                context,
677                self.floating_action_button_type,
678                has_child,
679            ))
680        }
681    }
682
683    /// The extended button's `Row` children: Dart's `[?child, if (child != null && isExtended)
684    /// SizedBox(width: iconLabelSpacing), if (isExtended) _extendedLabel!]`.
685    fn extended_children(&self, icon_label_spacing: f64) -> Vec<WidgetRef> {
686        let mut children = Vec::new();
687        if let Some(child) = &self.child {
688            children.push(child.clone());
689        }
690        if self.child.is_some() && self.is_extended {
691            children.push(SizedBox::new().width(icon_label_spacing).into_widget());
692        }
693        if self.is_extended {
694            children.push(
695                self.extended_label
696                    .clone()
697                    .expect("FloatingActionButton.extended has a label"),
698            );
699        }
700        children
701    }
702}
703
704impl StatelessWidget for FloatingActionButton {
705    fn key(&self) -> Option<&KeyRef> {
706        self.key.as_ref()
707    }
708
709    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
710        properties.add(
711            ObjectFlagProperty::<String>::new(
712                "onPressed",
713                self.on_pressed.as_ref().map(|_| String::new()),
714            )
715            .if_null("disabled"),
716        );
717        properties.add(StringProperty::new("tooltip", self.tooltip.clone()).default_value(None));
718        properties
719            .add(ColorProperty::new("foregroundColor", self.foreground_color).default_value(None));
720        properties
721            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
722        properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
723        properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
724        properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
725        properties.add(
726            ObjectFlagProperty::<String>::new(
727                "heroTag",
728                self.hero_tag.as_ref().map(|_| String::new()),
729            )
730            .if_present("hero"),
731        );
732        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
733        properties
734            .add(DoubleProperty::new("focusElevation", self.focus_elevation).default_value(None));
735        properties
736            .add(DoubleProperty::new("hoverElevation", self.hover_elevation).default_value(None));
737        properties.add(
738            DoubleProperty::new("highlightElevation", self.highlight_elevation).default_value(None),
739        );
740        properties.add(
741            DoubleProperty::new("disabledElevation", self.disabled_elevation).default_value(None),
742        );
743        properties.add(
744            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
745                .default_value(None),
746        );
747        properties.add(
748            DiagnosticsProperty::<String>::new(
749                "focusNode",
750                self.focus_node.as_ref().map(|node| node.to_string(app)),
751            )
752            .default_value(None),
753        );
754        properties.add(FlagProperty::new("isExtended", Some(self.is_extended)).if_true("extended"));
755        properties.add(
756            DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
757                "materialTapTargetSize",
758                self.material_tap_target_size.map(waft_foundation::DartEnum),
759            )
760            .default_value(None),
761        );
762    }
763
764    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
765        let theme = Theme::of(app, context);
766        let floating_action_button_theme = FloatingActionButtonTheme::of(app, context);
767        let defaults = self.defaults(app, context);
768
769        let foreground_color = self
770            .foreground_color
771            .or(floating_action_button_theme.foreground_color)
772            .or_else(|| defaults.foreground_color(app))
773            .expect("the defaults give a foreground color");
774        let background_color = self
775            .background_color
776            .or(floating_action_button_theme.background_color)
777            .or_else(|| defaults.background_color(app))
778            .expect("the defaults give a background color");
779        let focus_color = self
780            .focus_color
781            .or(floating_action_button_theme.focus_color)
782            .or_else(|| defaults.focus_color(app))
783            .expect("the defaults give a focus color");
784        let hover_color = self
785            .hover_color
786            .or(floating_action_button_theme.hover_color)
787            .or_else(|| defaults.hover_color(app))
788            .expect("the defaults give a hover color");
789        let splash_color = self
790            .splash_color
791            .or(floating_action_button_theme.splash_color)
792            .or_else(|| defaults.splash_color(app))
793            .expect("the defaults give a splash color");
794        let elevation = self
795            .elevation
796            .or(floating_action_button_theme.elevation)
797            .or_else(|| defaults.elevation(app))
798            .expect("the defaults give an elevation");
799        let focus_elevation = self
800            .focus_elevation
801            .or(floating_action_button_theme.focus_elevation)
802            .or_else(|| defaults.focus_elevation(app))
803            .expect("the defaults give a focus elevation");
804        let hover_elevation = self
805            .hover_elevation
806            .or(floating_action_button_theme.hover_elevation)
807            .or_else(|| defaults.hover_elevation(app))
808            .expect("the defaults give a hover elevation");
809        let disabled_elevation = self
810            .disabled_elevation
811            .or(floating_action_button_theme.disabled_elevation)
812            .or_else(|| defaults.disabled_elevation(app))
813            .unwrap_or(elevation);
814        let highlight_elevation = self
815            .highlight_elevation
816            .or(floating_action_button_theme.highlight_elevation)
817            .or_else(|| defaults.highlight_elevation(app))
818            .expect("the defaults give a highlight elevation");
819        let material_tap_target_size = self
820            .material_tap_target_size
821            .unwrap_or(theme.material_tap_target_size);
822        let enable_feedback = self
823            .enable_feedback
824            .or(floating_action_button_theme.enable_feedback)
825            .or_else(|| defaults.enable_feedback(app))
826            .expect("the defaults give enable feedback");
827        let icon_size = floating_action_button_theme
828            .icon_size
829            .or_else(|| defaults.icon_size(app))
830            .expect("the defaults give an icon size");
831        let extended_text_style = self
832            .extended_text_style
833            .clone()
834            .or_else(|| floating_action_button_theme.extended_text_style.clone())
835            .or_else(|| defaults.extended_text_style(app))
836            .expect("the defaults give an extended text style")
837            .copy_with()
838            .color(foreground_color);
839        let shape = self
840            .shape
841            .clone()
842            .or_else(|| floating_action_button_theme.shape.clone())
843            .or_else(|| defaults.shape(app))
844            .expect("the defaults give a shape");
845
846        let size_constraints;
847        let mut resolved_child = self.child.as_ref().map(|child| {
848            IconTheme::merge(None, IconThemeData::new().size(icon_size), child.clone())
849        });
850        match self.floating_action_button_type {
851            FloatingActionButtonType::Regular => {
852                size_constraints = floating_action_button_theme
853                    .size_constraints
854                    .or_else(|| defaults.size_constraints(app))
855                    .expect("the defaults give size constraints");
856            }
857            FloatingActionButtonType::Small => {
858                size_constraints = floating_action_button_theme
859                    .small_size_constraints
860                    .or_else(|| defaults.small_size_constraints(app))
861                    .expect("the defaults give small size constraints");
862            }
863            FloatingActionButtonType::Large => {
864                size_constraints = floating_action_button_theme
865                    .large_size_constraints
866                    .or_else(|| defaults.large_size_constraints(app))
867                    .expect("the defaults give large size constraints");
868            }
869            FloatingActionButtonType::Extended => {
870                size_constraints = floating_action_button_theme
871                    .extended_size_constraints
872                    .or_else(|| defaults.extended_size_constraints(app))
873                    .expect("the defaults give extended size constraints");
874                let icon_label_spacing = self
875                    .extended_icon_label_spacing
876                    .or(floating_action_button_theme.extended_icon_label_spacing)
877                    .unwrap_or(8.0);
878                let padding = self
879                    .extended_padding
880                    .or(floating_action_button_theme.extended_padding)
881                    .or_else(|| defaults.extended_padding(app))
882                    .expect("the defaults give an extended padding");
883                resolved_child = Some(
884                    ChildOverflowBox {
885                        child: Some(
886                            Padding::new(padding)
887                                .child(
888                                    Row::new()
889                                        .main_axis_size(MainAxisSize::Min)
890                                        .children(self.extended_children(icon_label_spacing)),
891                                )
892                                .into_widget(),
893                        ),
894                    }
895                    .into_widget(),
896                );
897            }
898        }
899
900        let mut button = RawMaterialButton::new(self.on_pressed.clone())
901            .mouse_cursor(
902                effective_mouse_cursor(
903                    self.mouse_cursor.clone(),
904                    floating_action_button_theme.mouse_cursor.clone(),
905                )
906                .into(),
907            )
908            .elevation(elevation)
909            .focus_elevation(focus_elevation)
910            .hover_elevation(hover_elevation)
911            .highlight_elevation(highlight_elevation)
912            .disabled_elevation(disabled_elevation)
913            .constraints(size_constraints)
914            .material_tap_target_size(material_tap_target_size)
915            .fill_color(background_color)
916            .focus_color(focus_color)
917            .hover_color(hover_color)
918            .splash_color(splash_color)
919            .text_style(extended_text_style)
920            .shape(shape)
921            .clip_behavior(self.clip_behavior)
922            .autofocus(self.autofocus)
923            .enable_feedback(enable_feedback);
924        if let Some(focus_node) = self.focus_node.clone() {
925            button = button.focus_node(focus_node);
926        }
927        if let Some(resolved_child) = resolved_child {
928            button = button.child(resolved_child);
929        }
930        let mut result = button.into_widget();
931
932        if let Some(tooltip) = &self.tooltip {
933            result = Tooltip::new()
934                .message(tooltip.clone())
935                .child(result)
936                .into_widget();
937        }
938
939        if let Some(hero_tag) = &self.hero_tag {
940            result = Hero::new(Rc::clone(hero_tag), result).into_widget();
941        }
942
943        MergeSemantics::new().child(result).into_widget()
944    }
945}
946
947impl Debug for FloatingActionButton {
948    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949        let mut properties = f.debug_struct("FloatingActionButton");
950        if self.on_pressed.is_none() {
951            properties.field("on_pressed", &"disabled");
952        }
953        if let Some(tooltip) = &self.tooltip {
954            properties.field("tooltip", tooltip);
955        }
956        if let Some(foreground_color) = &self.foreground_color {
957            properties.field("foreground_color", foreground_color);
958        }
959        if let Some(background_color) = &self.background_color {
960            properties.field("background_color", background_color);
961        }
962        if let Some(focus_color) = &self.focus_color {
963            properties.field("focus_color", focus_color);
964        }
965        if let Some(hover_color) = &self.hover_color {
966            properties.field("hover_color", hover_color);
967        }
968        if let Some(splash_color) = &self.splash_color {
969            properties.field("splash_color", splash_color);
970        }
971        if self.hero_tag.is_some() {
972            properties.field("hero_tag", &"hero");
973        }
974        if let Some(elevation) = &self.elevation {
975            properties.field("elevation", elevation);
976        }
977        if let Some(focus_elevation) = &self.focus_elevation {
978            properties.field("focus_elevation", focus_elevation);
979        }
980        if let Some(hover_elevation) = &self.hover_elevation {
981            properties.field("hover_elevation", hover_elevation);
982        }
983        if let Some(highlight_elevation) = &self.highlight_elevation {
984            properties.field("highlight_elevation", highlight_elevation);
985        }
986        if let Some(disabled_elevation) = &self.disabled_elevation {
987            properties.field("disabled_elevation", disabled_elevation);
988        }
989        if let Some(shape) = &self.shape {
990            properties.field("shape", shape);
991        }
992        if let Some(focus_node) = &self.focus_node {
993            properties.field("focus_node", focus_node);
994        }
995        if self.is_extended {
996            properties.field("is_extended", &"extended");
997        }
998        if let Some(material_tap_target_size) = &self.material_tap_target_size {
999            properties.field("material_tap_target_size", material_tap_target_size);
1000        }
1001        properties.finish_non_exhaustive()
1002    }
1003}
1004
1005/// Dart's `_EffectiveMouseCursor`: a [`WidgetStateMouseCursor`] that [`RawMaterialButton`]
1006/// resolves against `WidgetState::Pressed`, `WidgetState::Hovered`, `WidgetState::Focused`
1007/// and `WidgetState::Disabled`.
1008fn effective_mouse_cursor(
1009    widget_cursor: Option<MouseCursorRef>,
1010    theme_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
1011) -> WidgetStateMouseCursor {
1012    WidgetStateMouseCursor::resolve_with(
1013        move |states| {
1014            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&widget_cursor, states)
1015                .or_else(|| {
1016                    theme_cursor
1017                        .as_ref()
1018                        .and_then(|theme_cursor| theme_cursor.resolve(states))
1019                })
1020                .unwrap_or_else(|| WidgetStateMouseCursor::adaptive_clickable().resolve(states))
1021        },
1022        Some("WidgetStateMouseCursor(FloatActionButton)"),
1023    )
1024}
1025
1026/// This widget's size matches its child's size unless its constraints
1027/// force it to be larger or smaller. The child is centered.
1028///
1029/// Used to encapsulate extended FABs whose size is fixed, using `Row`
1030/// and `MainAxisSize::Min`, to be as wide as their label and icon.
1031///
1032/// Dart's `_ChildOverflowBox`.
1033#[derive(Debug)]
1034struct ChildOverflowBox {
1035    child: Option<WidgetRef>,
1036}
1037
1038impl RenderObjectWidget for ChildOverflowBox {
1039    type RenderObject = RenderChildOverflowBox;
1040
1041    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1042        let text_direction = Directionality::of(app, context);
1043        RenderChildOverflowBox::new(app, Some(text_direction)).as_object()
1044    }
1045
1046    fn update_render_object(
1047        &self,
1048        app: &mut App,
1049        context: BuildContext,
1050        render_object: RenderHandle<RenderChildOverflowBox>,
1051    ) {
1052        let text_direction = Directionality::of(app, context);
1053        render_object.set_text_direction(app, Some(text_direction));
1054    }
1055}
1056
1057impl SingleChildRenderObjectWidget for ChildOverflowBox {
1058    fn child(&self) -> Option<&WidgetRef> {
1059        self.child.as_ref()
1060    }
1061}
1062
1063/// Dart's `_RenderChildOverflowBox`.
1064struct RenderChildOverflowBox {
1065    render_object: RenderObjectData,
1066    render_box: RenderBoxData,
1067    child: RenderObjectWithChildData<AnyRenderBox>,
1068    aligning: RenderAligningShiftedBoxData,
1069}
1070
1071impl RenderChildOverflowBox {
1072    fn new(
1073        app: &mut App,
1074        text_direction: Option<TextDirection>,
1075    ) -> RenderHandle<RenderChildOverflowBox> {
1076        RenderHandle::new_box(
1077            app,
1078            RenderChildOverflowBox {
1079                render_object: RenderObjectData::new(),
1080                render_box: RenderBoxData::new(),
1081                child: RenderObjectWithChildData::new(),
1082                aligning: RenderAligningShiftedBoxData::new(
1083                    AlignmentGeometry::CENTER,
1084                    text_direction,
1085                ),
1086            },
1087        )
1088    }
1089}
1090
1091impl RenderObjectWithChildMixin for RenderChildOverflowBox {
1092    type ChildType = AnyRenderBox;
1093
1094    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1095        &self.get(app).child
1096    }
1097
1098    fn child_data_mut(
1099        self: RenderHandle<Self>,
1100        app: &mut App,
1101    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1102        &mut self.get_mut(app).child
1103    }
1104}
1105
1106impl RenderShiftedBox for RenderChildOverflowBox {}
1107
1108impl RenderAligningShiftedBox for RenderChildOverflowBox {
1109    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
1110        &self.get(app).aligning
1111    }
1112
1113    fn aligning_data_mut(
1114        self: RenderHandle<Self>,
1115        app: &mut App,
1116    ) -> &mut RenderAligningShiftedBoxData {
1117        &mut self.get_mut(app).aligning
1118    }
1119}
1120
1121impl RenderObject for RenderChildOverflowBox {
1122    waft_rendering::render_object_accessors!();
1123
1124    fn debug_fill_properties(
1125        self: RenderHandle<Self>,
1126        app: &App,
1127        properties: &mut DiagnosticPropertiesBuilder,
1128    ) {
1129        // Dart's `_RenderChildOverflowBox` inherits `RenderAligningShiftedBox.debugFillProperties`.
1130        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
1131    }
1132
1133    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1134        let constraints = self.constraints(app);
1135        if let Some(child) = self.child(app) {
1136            child.layout(app, BoxConstraints::new(), true);
1137            let child_size = child.size(app);
1138            self.set_size(
1139                app,
1140                Size::new(
1141                    constraints
1142                        .min_width
1143                        .max(constraints.max_width.min(child_size.width())),
1144                    constraints
1145                        .min_height
1146                        .max(constraints.max_height.min(child_size.height())),
1147                ),
1148            );
1149            self.align_child(app);
1150        } else {
1151            self.set_size(app, constraints.biggest());
1152        }
1153    }
1154
1155    fn paint(
1156        self: RenderHandle<Self>,
1157        app: &mut App,
1158        context: &mut PaintingContext,
1159        offset: Offset,
1160    ) {
1161        RenderShiftedBox::paint(self, app, context, offset);
1162    }
1163
1164    fn visit_children(
1165        self: RenderHandle<Self>,
1166        app: &App,
1167        visitor: &mut dyn FnMut(AnyRenderObject),
1168    ) {
1169        if let Some(child) = self.child(app) {
1170            visitor(child.as_object());
1171        }
1172    }
1173}
1174
1175impl RenderBox for RenderChildOverflowBox {
1176    waft_rendering::render_box_accessors!();
1177
1178    fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
1179        0.0
1180    }
1181
1182    fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
1183        0.0
1184    }
1185
1186    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1187        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
1188    }
1189
1190    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1191        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
1192    }
1193
1194    fn compute_dry_layout(
1195        self: RenderHandle<Self>,
1196        app: &mut App,
1197        constraints: BoxConstraints,
1198    ) -> Size {
1199        if let Some(child) = self.child(app) {
1200            let child_size = child.get_dry_layout(app, BoxConstraints::new());
1201            Size::new(
1202                constraints
1203                    .min_width
1204                    .max(constraints.max_width.min(child_size.width())),
1205                constraints
1206                    .min_height
1207                    .max(constraints.max_height.min(child_size.height())),
1208            )
1209        } else {
1210            constraints.biggest()
1211        }
1212    }
1213
1214    fn compute_dry_baseline(
1215        self: RenderHandle<Self>,
1216        app: &mut App,
1217        constraints: BoxConstraints,
1218        baseline: TextBaseline,
1219    ) -> Option<f64> {
1220        RenderShiftedBox::compute_dry_baseline(self, app, constraints, baseline)
1221    }
1222
1223    fn compute_distance_to_actual_baseline(
1224        self: RenderHandle<Self>,
1225        app: &mut App,
1226        baseline: TextBaseline,
1227    ) -> Option<f64> {
1228        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1229    }
1230
1231    fn hit_test_children(
1232        self: RenderHandle<Self>,
1233        app: &mut App,
1234        result: &mut BoxHitTestResult<'_>,
1235        position: Offset,
1236    ) -> bool {
1237        RenderShiftedBox::hit_test_children(self, app, result, position)
1238    }
1239}
1240
1241/// Hand coded defaults based on Material Design 2.
1242///
1243/// Dart's `_FABDefaultsM2`.
1244struct FabDefaultsM2 {
1245    /// Dart's `super(..)` arguments.
1246    floating_action_button_theme_data: FloatingActionButtonThemeData,
1247    context: DefaultsContext,
1248    r#type: FloatingActionButtonType,
1249    has_child: bool,
1250}
1251
1252impl FabDefaultsM2 {
1253    fn new(
1254        app: &mut App,
1255        context: BuildContext,
1256        r#type: FloatingActionButtonType,
1257        has_child: bool,
1258    ) -> FabDefaultsM2 {
1259        FabDefaultsM2 {
1260            floating_action_button_theme_data: FloatingActionButtonThemeData::new()
1261                .elevation(6.0)
1262                .focus_elevation(6.0)
1263                .hover_elevation(8.0)
1264                .highlight_elevation(12.0)
1265                .enable_feedback(true)
1266                .size_constraints(BoxConstraints::tight_for(Some(56.0), Some(56.0)))
1267                .small_size_constraints(BoxConstraints::tight_for(Some(40.0), Some(40.0)))
1268                .large_size_constraints(BoxConstraints::tight_for(Some(96.0), Some(96.0)))
1269                .extended_size_constraints(BoxConstraints::tight_for(None, Some(48.0)))
1270                .extended_icon_label_spacing(8.0),
1271            context: DefaultsContext::with_theme(app, context),
1272            r#type,
1273            has_child,
1274        }
1275    }
1276}
1277
1278impl FloatingActionButtonThemeDataGetters for FabDefaultsM2 {
1279    fn floating_action_button_theme_data(&self) -> &FloatingActionButtonThemeData {
1280        &self.floating_action_button_theme_data
1281    }
1282
1283    fn foreground_color(&self, app: &mut App) -> Option<Color> {
1284        let theme = self.context.theme(app);
1285        let colors = &theme.color_scheme;
1286        Some(colors.on_secondary())
1287    }
1288
1289    fn background_color(&self, app: &mut App) -> Option<Color> {
1290        let theme = self.context.theme(app);
1291        let colors = &theme.color_scheme;
1292        Some(colors.secondary())
1293    }
1294
1295    fn focus_color(&self, app: &mut App) -> Option<Color> {
1296        let theme = self.context.theme(app);
1297        Some(theme.focus_color)
1298    }
1299
1300    fn hover_color(&self, app: &mut App) -> Option<Color> {
1301        let theme = self.context.theme(app);
1302        Some(theme.hover_color)
1303    }
1304
1305    fn splash_color(&self, app: &mut App) -> Option<Color> {
1306        let theme = self.context.theme(app);
1307        Some(theme.splash_color)
1308    }
1309
1310    fn shape(&self, _app: &mut App) -> Option<ShapeBorderRef> {
1311        let is_extended = self.r#type == FloatingActionButtonType::Extended;
1312        Some(if is_extended {
1313            ShapeBorderRef::new(StadiumBorder::default())
1314        } else {
1315            ShapeBorderRef::new(CircleBorder::default())
1316        })
1317    }
1318
1319    fn icon_size(&self, _app: &mut App) -> Option<f64> {
1320        let is_large = self.r#type == FloatingActionButtonType::Large;
1321        Some(if is_large { 36.0 } else { 24.0 })
1322    }
1323
1324    fn extended_padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
1325        let is_extended = self.r#type == FloatingActionButtonType::Extended;
1326        Some(
1327            EdgeInsetsDirectional::only(
1328                if self.has_child && is_extended {
1329                    16.0
1330                } else {
1331                    20.0
1332                },
1333                0.0,
1334                20.0,
1335                0.0,
1336            )
1337            .into(),
1338        )
1339    }
1340
1341    fn extended_text_style(&self, app: &mut App) -> Option<TextStyle> {
1342        let theme = self.context.theme(app);
1343        Some(
1344            theme
1345                .text_theme
1346                .label_large
1347                .as_ref()
1348                .expect("the text theme has a labelLarge style")
1349                .copy_with()
1350                .letter_spacing(1.2),
1351        )
1352    }
1353}
1354
1355#[cfg(test)]
1356mod tests {
1357    //! The cases of `test/floating_action_button_test.dart` and
1358    //! `test/floating_action_button_theme_test.dart`.
1359
1360    use std::cell::{Cell, RefCell};
1361    use std::time::Duration;
1362    use waft_painting::ShapeBorder;
1363    use waft_rendering::testing::{CanvasMethod, PaintCall, assert_paints, count_calls};
1364
1365    use waft_embedder::{Rect, TargetPlatform};
1366    use waft_painting::{BeveledRectangleBorder, BorderRadius, RoundedRectangleBorder};
1367    use waft_services::SystemMouseCursors;
1368    use waft_widgets::{
1369        Align, AnyElement, Center, FocusNode, GlobalKey, Icon, IconData, PhysicalShape, Text,
1370    };
1371
1372    use waft_widgets::testing::{
1373        TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
1374    };
1375
1376    use super::*;
1377    use crate::color_scheme::ColorScheme;
1378    use crate::icons::Icons;
1379    use crate::ink_well::InkWell;
1380    use crate::scaffold::Scaffold;
1381    use crate::test_support::{PaintInspection, material_app};
1382    use crate::theme_data::ThemeData;
1383
1384    fn noop() -> Option<Listener> {
1385        Some(Listener::new(|_app| {}))
1386    }
1387
1388    fn m3(tester: &WidgetTester) -> ThemeData {
1389        ThemeData::new(&tester.cell.borrow())
1390    }
1391
1392    fn m2(tester: &WidgetTester) -> ThemeData {
1393        ThemeData::builder()
1394            .use_material3(false)
1395            .build(&tester.cell.borrow())
1396    }
1397
1398    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1399        Directionality::new(TextDirection::Ltr, child).into_widget()
1400    }
1401
1402    /// `MaterialApp(theme: theme, home: Scaffold(floatingActionButton: fab))`.
1403    fn app_with(theme: ThemeData, fab: FloatingActionButton) -> WidgetRef {
1404        material_app(
1405            theme,
1406            Scaffold::new().floating_action_button(fab).into_widget(),
1407        )
1408    }
1409
1410    fn icon(data: IconData) -> Icon {
1411        Icon::new(Some(data))
1412    }
1413
1414    fn only(found: Vec<AnyElement>) -> AnyElement {
1415        assert_eq!(found.len(), 1, "one widget found");
1416        found[0]
1417    }
1418
1419    fn fab(tester: &WidgetTester) -> AnyElement {
1420        only(find::by_type::<FloatingActionButton>().evaluate(tester))
1421    }
1422
1423    fn key_rect(tester: &WidgetTester, key: &GlobalKey) -> Rect {
1424        let render = tester.render_object(key).as_box().expect("a render box");
1425        tester.get_rect(render)
1426    }
1427
1428    fn fab_rect(tester: &WidgetTester) -> Rect {
1429        tester.get_rect(fab(tester))
1430    }
1431
1432    fn icon_rect(tester: &WidgetTester) -> Rect {
1433        tester.get_rect(only(find::by_type::<Icon>().evaluate(tester)))
1434    }
1435
1436    /// Dart's `tester.widget<RawMaterialButton>(find.byType(RawMaterialButton))`.
1437    fn raw_button<R>(tester: &WidgetTester, read: impl FnOnce(&RawMaterialButton) -> R) -> R {
1438        tester.widget(
1439            only(find::by_type::<RawMaterialButton>().evaluate(tester)),
1440            read,
1441        )
1442    }
1443
1444    /// Dart's `tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation`.
1445    fn elevation(tester: &WidgetTester) -> f64 {
1446        tester.widget(
1447            only(find::by_type::<PhysicalShape>().evaluate(tester)),
1448            |shape: &PhysicalShape| shape.elevation,
1449        )
1450    }
1451
1452    /// Dart's `tester.press(find.byType(PhysicalShape))`.
1453    fn press_physical_shape(tester: &mut WidgetTester) -> TestPointer {
1454        let center = tester
1455            .get_rect(only(find::by_type::<PhysicalShape>().evaluate(tester)))
1456            .center();
1457        let mut touch = TestPointer::touch(1);
1458        tester.down(&mut touch, center);
1459        touch
1460    }
1461
1462    /// The colour of the icon's glyph: Dart's `_getRichText(tester).text.style!.color`.
1463    fn icon_color(tester: &WidgetTester) -> Option<Color> {
1464        tester.icon_style().color.as_deref().copied()
1465    }
1466
1467    /// Dart's `_getIconSize(tester)`: the `SizedBox` the `Icon` builds.
1468    fn icon_size(tester: &WidgetTester) -> (Option<f64>, Option<f64>) {
1469        let icon = only(find::by_type::<Icon>().evaluate(tester));
1470        let sized_box = find::by_type::<SizedBox>()
1471            .evaluate(tester)
1472            .into_iter()
1473            .find(|sized_box| tester.ancestors(*sized_box).contains(&icon))
1474            .expect("the Icon's SizedBox");
1475        tester.widget(sized_box, |sized_box: &SizedBox| {
1476            (sized_box.width, sized_box.height)
1477        })
1478    }
1479
1480    fn rounded(radius: f64) -> RoundedRectangleBorder {
1481        RoundedRectangleBorder::new(
1482            waft_painting::BorderSide::NONE,
1483            BorderRadius::all(waft_embedder::Radius::circular(radius)).into(),
1484        )
1485    }
1486
1487    fn assert_shape(tester: &WidgetTester, expected: &dyn ShapeBorder) {
1488        raw_button(tester, |button| {
1489            assert!(
1490                button.shape.eq_shape(expected),
1491                "{:?} is not {expected:?}",
1492                button.shape
1493            );
1494        });
1495    }
1496
1497    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
1498        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased::<waft_widgets::AnyFocusNode>()
1499    }
1500
1501    #[test]
1502    fn floating_action_button_control_test() {
1503        test_widgets(|tester| {
1504            let did_press_button = Rc::new(Cell::new(false));
1505            tester.pump_widget(ltr(Center::new().child(
1506                FloatingActionButton::new(Some(Listener::new({
1507                    let did_press_button = Rc::clone(&did_press_button);
1508                    move |_app| did_press_button.set(true)
1509                })))
1510                .child(icon(Icons::add())),
1511            )));
1512
1513            assert!(!did_press_button.get());
1514            let at = icon_rect(tester).center();
1515            tester.tap_at(at, 1);
1516            assert!(did_press_button.get());
1517        });
1518    }
1519
1520    #[test]
1521    fn floating_action_button_tooltip() {
1522        test_widgets(|tester| {
1523            let theme = m3(tester);
1524            tester.pump_widget(app_with(
1525                theme,
1526                FloatingActionButton::new(noop())
1527                    .tooltip("Add")
1528                    .child(icon(Icons::add())),
1529            ));
1530
1531            let at = icon_rect(tester).center();
1532            tester.tap_at(at, 1);
1533            let tooltips = find::by_type::<Tooltip>().evaluate(tester);
1534            let found = tooltips
1535                .into_iter()
1536                .filter(|tooltip| {
1537                    tester.widget(*tooltip, |tooltip: &Tooltip| {
1538                        tooltip.message.as_deref() == Some("Add")
1539                    })
1540                })
1541                .count();
1542            assert_eq!(found, 1);
1543        });
1544    }
1545
1546    /// Dart's `_rightEdgeOfFab(tester)`.
1547    fn right_edge_of_fab(tester: &WidgetTester) -> Offset {
1548        fab_rect(tester).center_right() - Offset::new(1.0, 0.0)
1549    }
1550
1551    fn long_press_at_right_edge_shows_tooltip(
1552        tester: &mut WidgetTester,
1553        fab: FloatingActionButton,
1554    ) {
1555        let theme = m3(tester);
1556        tester.pump_widget(app_with(theme, fab));
1557
1558        expect(tester, &find::text("Add"), finds_nothing());
1559        let at = right_edge_of_fab(tester);
1560        tester.long_press_at(at, 1);
1561        tester.pump_and_settle();
1562
1563        expect(tester, &find::text("Add"), finds_one_widget());
1564    }
1565
1566    // Regression test for: https://github.com/flutter/flutter/pull/21084
1567    #[test]
1568    fn floating_action_button_tooltip_long_press_button_edge() {
1569        test_widgets(|tester| {
1570            long_press_at_right_edge_shows_tooltip(
1571                tester,
1572                FloatingActionButton::new(noop())
1573                    .tooltip("Add")
1574                    .child(icon(Icons::add())),
1575            );
1576        });
1577    }
1578
1579    // Regression test for: https://github.com/flutter/flutter/pull/21084
1580    #[test]
1581    fn floating_action_button_tooltip_long_press_button_edge_no_child() {
1582        test_widgets(|tester| {
1583            long_press_at_right_edge_shows_tooltip(
1584                tester,
1585                FloatingActionButton::new(noop()).tooltip("Add"),
1586            );
1587        });
1588    }
1589
1590    fn hover_and_long_press_show_tooltip(tester: &mut WidgetTester, on_pressed: Option<Listener>) {
1591        let theme = m3(tester);
1592        tester.pump_widget(app_with(
1593            theme,
1594            FloatingActionButton::new(on_pressed).tooltip("Add"),
1595        ));
1596
1597        expect(tester, &find::text("Add"), finds_nothing());
1598
1599        // Test hover for tooltip.
1600        let mut mouse = TestPointer::mouse(1, 0);
1601        tester.add_pointer(&mut mouse, Offset::ZERO);
1602        tester.pump_and_settle();
1603        let center = fab_rect(tester).center();
1604        tester.move_to(&mut mouse, center, false);
1605        tester.pump_and_settle();
1606
1607        expect(tester, &find::text("Add"), finds_one_widget());
1608
1609        tester.move_to(&mut mouse, Offset::ZERO, false);
1610        tester.pump_and_settle();
1611
1612        expect(tester, &find::text("Add"), finds_nothing());
1613
1614        // Test long press for tooltip.
1615        let center = fab_rect(tester).center();
1616        tester.long_press_at(center, 2);
1617        tester.pump_and_settle();
1618
1619        expect(tester, &find::text("Add"), finds_one_widget());
1620    }
1621
1622    #[test]
1623    fn floating_action_button_tooltip_no_child() {
1624        test_widgets(|tester| hover_and_long_press_show_tooltip(tester, noop()));
1625    }
1626
1627    #[test]
1628    fn floating_action_button_tooltip_reacts_when_disabled() {
1629        test_widgets(|tester| hover_and_long_press_show_tooltip(tester, None));
1630    }
1631
1632    /// Dart's 'Floating Action Button elevation when highlighted - effect', for Material 3
1633    /// (`highlight` 6) and in its Material 2 group (12).
1634    fn elevation_when_highlighted(
1635        tester: &mut WidgetTester,
1636        theme: fn(&WidgetTester) -> ThemeData,
1637        highlight: f64,
1638    ) {
1639        tester.pump_widget(app_with(theme(tester), FloatingActionButton::new(noop())));
1640        assert_eq!(elevation(tester), 6.0);
1641        let gesture = press_physical_shape(tester);
1642        tester.pump();
1643        assert_eq!(elevation(tester), 6.0);
1644        tester.pump_by(Duration::from_secs(1));
1645        assert_eq!(elevation(tester), highlight);
1646        tester.pump_widget(app_with(
1647            theme(tester),
1648            FloatingActionButton::new(noop()).highlight_elevation(20.0),
1649        ));
1650        tester.pump();
1651        assert_eq!(elevation(tester), highlight);
1652        tester.pump_by(Duration::from_secs(1));
1653        assert_eq!(elevation(tester), 20.0);
1654        tester.up(&gesture);
1655        tester.pump();
1656        assert_eq!(elevation(tester), 20.0);
1657        tester.pump_by(Duration::from_secs(1));
1658        assert_eq!(elevation(tester), 6.0);
1659    }
1660
1661    #[test]
1662    fn floating_action_button_elevation_when_highlighted_effect() {
1663        test_widgets(|tester| elevation_when_highlighted(tester, m3, 6.0));
1664    }
1665
1666    #[test]
1667    fn material2_floating_action_button_elevation_when_highlighted_effect() {
1668        test_widgets(|tester| elevation_when_highlighted(tester, m2, 12.0));
1669    }
1670
1671    #[test]
1672    fn floating_action_button_elevation_when_disabled_defaults() {
1673        test_widgets(|tester| {
1674            let theme = m3(tester);
1675            tester.pump_widget(app_with(theme, FloatingActionButton::new(None)));
1676
1677            // Disabled elevation defaults to regular default elevation.
1678            assert_eq!(elevation(tester), 6.0);
1679        });
1680    }
1681
1682    #[test]
1683    fn floating_action_button_elevation_when_disabled_override() {
1684        test_widgets(|tester| {
1685            let theme = m3(tester);
1686            tester.pump_widget(app_with(
1687                theme,
1688                FloatingActionButton::new(None).disabled_elevation(0.0),
1689            ));
1690
1691            assert_eq!(elevation(tester), 0.0);
1692        });
1693    }
1694
1695    #[test]
1696    fn floating_action_button_elevation_when_disabled_effect() {
1697        test_widgets(|tester| {
1698            tester.pump_widget(app_with(m3(tester), FloatingActionButton::new(None)));
1699            assert_eq!(elevation(tester), 6.0);
1700            tester.pump_widget(app_with(
1701                m3(tester),
1702                FloatingActionButton::new(None).disabled_elevation(3.0),
1703            ));
1704            assert_eq!(elevation(tester), 6.0);
1705            tester.pump_by(Duration::from_secs(1));
1706            assert_eq!(elevation(tester), 3.0);
1707            tester.pump_widget(app_with(
1708                m3(tester),
1709                FloatingActionButton::new(noop()).disabled_elevation(3.0),
1710            ));
1711            assert_eq!(elevation(tester), 3.0);
1712            tester.pump_by(Duration::from_secs(1));
1713            assert_eq!(elevation(tester), 6.0);
1714        });
1715    }
1716
1717    /// Dart's 'Floating Action Button elevation when disabled while highlighted - effect', for
1718    /// Material 3 (`highlight` 6) and in its Material 2 group (12).
1719    fn elevation_when_disabled_while_highlighted(
1720        tester: &mut WidgetTester,
1721        theme: fn(&WidgetTester) -> ThemeData,
1722        highlight: f64,
1723    ) {
1724        tester.pump_widget(app_with(theme(tester), FloatingActionButton::new(noop())));
1725        assert_eq!(elevation(tester), 6.0);
1726        let _gesture = press_physical_shape(tester);
1727        tester.pump();
1728        assert_eq!(elevation(tester), 6.0);
1729        tester.pump_by(Duration::from_secs(1));
1730        assert_eq!(elevation(tester), highlight);
1731        tester.pump_widget(app_with(theme(tester), FloatingActionButton::new(None)));
1732        tester.pump();
1733        assert_eq!(elevation(tester), highlight);
1734        tester.pump_by(Duration::from_secs(1));
1735        assert_eq!(elevation(tester), 6.0);
1736        tester.pump_widget(app_with(theme(tester), FloatingActionButton::new(noop())));
1737        tester.pump();
1738        assert_eq!(elevation(tester), 6.0);
1739        tester.pump_by(Duration::from_secs(1));
1740        assert_eq!(elevation(tester), 6.0);
1741    }
1742
1743    #[test]
1744    fn floating_action_button_elevation_when_disabled_while_highlighted_effect() {
1745        test_widgets(|tester| elevation_when_disabled_while_highlighted(tester, m3, 6.0));
1746    }
1747
1748    #[test]
1749    fn material2_floating_action_button_elevation_when_disabled_while_highlighted_effect() {
1750        test_widgets(|tester| elevation_when_disabled_while_highlighted(tester, m2, 12.0));
1751    }
1752
1753    /// Dart's 'Floating Action Button states elevation', for Material 3 (`highlight` 6) and
1754    /// in its Material 2 group (12).
1755    fn states_elevation(
1756        tester: &mut WidgetTester,
1757        theme: fn(&WidgetTester) -> ThemeData,
1758        highlight: f64,
1759    ) {
1760        let focus_node = focus_node(tester);
1761        tester.pump_widget(material_app(
1762            theme(tester),
1763            Scaffold::new()
1764                .body(
1765                    FloatingActionButton::extended(noop(), Text::new("tooltip"))
1766                        .focus_node(focus_node.clone()),
1767                )
1768                .into_widget(),
1769        ));
1770
1771        // Default, not disabled.
1772        assert_eq!(elevation(tester), 6.0);
1773
1774        // Focused.
1775        focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1776        tester.pump_and_settle();
1777        assert_eq!(elevation(tester), 6.0);
1778
1779        // Hovered.
1780        let center = tester
1781            .get_rect(only(find::by_type::<PhysicalShape>().evaluate(tester)))
1782            .center();
1783        let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1784        tester.add_pointer(&mut mouse, Offset::ZERO);
1785        tester.move_to(&mut mouse, center, false);
1786        tester.pump_and_settle();
1787        assert_eq!(elevation(tester), 8.0);
1788
1789        // Highlighted (pressed).
1790        tester.down(&mut mouse, center);
1791        tester.pump(); // Start the splash and highlight animations.
1792        tester.pump_by(Duration::from_millis(800)); // Wait for splash and highlight to be well under way.
1793        assert_eq!(elevation(tester), highlight);
1794    }
1795
1796    #[test]
1797    fn floating_action_button_states_elevation() {
1798        test_widgets(|tester| states_elevation(tester, m3, 6.0));
1799    }
1800
1801    #[test]
1802    fn material2_floating_action_button_states_elevation() {
1803        test_widgets(|tester| states_elevation(tester, m2, 12.0));
1804    }
1805
1806    #[test]
1807    fn flat_action_button_mini_size_is_configurable_by_theme_data_material_tap_target_size() {
1808        test_widgets(|tester| {
1809            let mini_size = |tester: &mut WidgetTester, size: MaterialTapTargetSize| {
1810                let theme = ThemeData::builder()
1811                    .material_tap_target_size(size)
1812                    .build(&tester.cell.borrow());
1813                let key = GlobalKey::new();
1814                tester.pump_widget(material_app(
1815                    m3(tester),
1816                    Theme::new(
1817                        theme,
1818                        Scaffold::new().floating_action_button(
1819                            FloatingActionButton::new(None)
1820                                .key(key.clone().into())
1821                                .mini(true),
1822                        ),
1823                    )
1824                    .into_widget(),
1825                ));
1826                tester.get_size(&key)
1827            };
1828
1829            assert_eq!(
1830                mini_size(tester, MaterialTapTargetSize::Padded),
1831                Size::new(48.0, 48.0)
1832            );
1833            assert_eq!(
1834                mini_size(tester, MaterialTapTargetSize::ShrinkWrap),
1835                Size::new(40.0, 40.0)
1836            );
1837        });
1838    }
1839
1840    /// Dart's 'FloatingActionButton.isExtended' after its first frame: an extended button with
1841    /// an icon and a 100 wide label, `height` high and laid out as 16 icon 8 label 20.
1842    fn assert_extended_with_icon_layout(tester: &WidgetTester, height: f64) {
1843        assert!(tester.widget(fab(tester), |fab: &FloatingActionButton| fab.is_extended));
1844        expect(tester, &find::text("label"), finds_one_widget());
1845        expect(tester, &find::by_type::<Icon>(), finds_one_widget());
1846
1847        // Verify that the widget's height is `height` and that its internal
1848        // horizontal layout is: 16 icon 8 label 20
1849        let fab = fab_rect(tester);
1850        let icon = icon_rect(tester);
1851        let label = tester.get_rect(find::text("label"));
1852        assert_eq!(fab.height(), height);
1853        assert_eq!(icon.left - fab.left, 16.0);
1854        assert_eq!(label.left - icon.right, 8.0);
1855        assert_eq!(fab.right - label.right, 20.0);
1856
1857        // The overall width of the button is:
1858        // 168 = 16 + 24(icon) + 8 + 100(label) + 20
1859        assert_eq!(icon.width(), 24.0);
1860        assert_eq!(label.width(), 100.0);
1861        assert_eq!(fab.width(), 168.0);
1862    }
1863
1864    /// Dart's 'FloatingActionButton.isExtended (without icon)': a 100 wide label, `height`
1865    /// high and laid out as 20 label 20.
1866    fn assert_extended_without_icon_layout(tester: &WidgetTester, height: f64) {
1867        assert!(tester.widget(fab(tester), |fab: &FloatingActionButton| fab.is_extended));
1868        expect(tester, &find::text("label"), finds_one_widget());
1869        expect(tester, &find::by_type::<Icon>(), finds_nothing());
1870
1871        // Verify that the widget's height is `height` and that its internal
1872        // horizontal layout is: 20 label 20
1873        let fab = fab_rect(tester);
1874        let label = tester.get_rect(find::text("label"));
1875        assert_eq!(fab.height(), height);
1876        assert_eq!(label.left - fab.left, 20.0);
1877        assert_eq!(fab.right - label.right, 20.0);
1878
1879        // The overall width of the button is:
1880        // 140 = 20 + 100(label) + 20
1881        assert_eq!(label.width(), 100.0);
1882        assert_eq!(fab.width(), 140.0);
1883    }
1884
1885    fn sized_label() -> SizedBox {
1886        SizedBox::new().width(100.0).child(Text::new("label"))
1887    }
1888
1889    #[test]
1890    fn floating_action_button_is_extended() {
1891        test_widgets(|tester| {
1892            tester.pump_widget(app_with(m3(tester), FloatingActionButton::new(None)));
1893
1894            assert!(!tester.widget(fab(tester), |fab: &FloatingActionButton| fab.is_extended));
1895            assert_shape(tester, &rounded(16.0));
1896
1897            tester.pump_widget(app_with(
1898                m3(tester),
1899                FloatingActionButton::extended(None, sized_label()).icon(icon(Icons::android())),
1900            ));
1901
1902            assert_shape(tester, &rounded(16.0));
1903            assert_extended_with_icon_layout(tester, 56.0);
1904        });
1905    }
1906
1907    #[test]
1908    fn floating_action_button_is_extended_without_icon() {
1909        test_widgets(|tester| {
1910            tester.pump_widget(app_with(
1911                m3(tester),
1912                FloatingActionButton::extended(None, sized_label()),
1913            ));
1914
1915            assert_shape(tester, &rounded(16.0));
1916            assert_extended_without_icon_layout(tester, 56.0);
1917        });
1918    }
1919
1920    #[test]
1921    fn material2_floating_action_button_is_extended() {
1922        test_widgets(|tester| {
1923            tester.pump_widget(app_with(m2(tester), FloatingActionButton::new(None)));
1924
1925            assert!(!tester.widget(fab(tester), |fab: &FloatingActionButton| fab.is_extended));
1926            assert_shape(tester, &CircleBorder::default());
1927
1928            tester.pump_widget(app_with(
1929                m2(tester),
1930                FloatingActionButton::extended(None, sized_label()).icon(icon(Icons::android())),
1931            ));
1932
1933            assert_shape(tester, &StadiumBorder::default());
1934            assert_extended_with_icon_layout(tester, 48.0);
1935        });
1936    }
1937
1938    #[test]
1939    fn material2_floating_action_button_is_extended_without_icon() {
1940        test_widgets(|tester| {
1941            tester.pump_widget(app_with(
1942                m2(tester),
1943                FloatingActionButton::extended(None, sized_label()),
1944            ));
1945
1946            assert_shape(tester, &StadiumBorder::default());
1947            assert_extended_without_icon_layout(tester, 48.0);
1948        });
1949    }
1950
1951    /// `MaterialApp(home: Scaffold(body: Builder(..), floatingActionButton: ..))` with the
1952    /// hero controller `MaterialApp` gives its navigator. Returns the body's context.
1953    fn two_fabs(
1954        tester: &mut WidgetTester,
1955        body: FloatingActionButton,
1956        fab: FloatingActionButton,
1957    ) -> BuildContext {
1958        let context: Rc<Cell<Option<BuildContext>>> = Rc::default();
1959        let body = Rc::new(RefCell::new(Some(body)));
1960        let theme = m3(tester);
1961        let controller = waft_widgets::HeroController::new(&mut tester.cell.borrow_mut());
1962        tester.pump_widget(
1963            waft_widgets::HeroControllerScope::new(
1964                controller,
1965                material_app(
1966                    theme,
1967                    Scaffold::new()
1968                        .body(waft_widgets::Builder::new({
1969                            let context = Rc::clone(&context);
1970                            move |_app, built| {
1971                                context.set(Some(built));
1972                                body.borrow_mut().take().expect("built once").into_widget()
1973                            }
1974                        }))
1975                        .floating_action_button(fab)
1976                        .into_widget(),
1977                ),
1978            )
1979            .into_widget(),
1980        );
1981        context.get().expect("the body built")
1982    }
1983
1984    /// Dart's `Navigator.push(context, PageRouteBuilder(pageBuilder: (..) => Placeholder()))`.
1985    fn push_page(tester: &WidgetTester, context: BuildContext) {
1986        let mut app = tester.cell.borrow_mut();
1987        let page_builder: waft_widgets::RoutePageBuilder =
1988            Rc::new(|_app, _context, _, _| SizedBox::expand().into_widget());
1989        let route = waft_widgets::PageRouteBuilder::new(&mut app, page_builder);
1990        drop(waft_widgets::Navigator::push(
1991            &mut app,
1992            context,
1993            route.erase(),
1994        ));
1995    }
1996
1997    #[test]
1998    fn floating_action_button_hero_tag() {
1999        test_widgets(|tester| {
2000            let context = two_fabs(
2001                tester,
2002                FloatingActionButton::new(None).hero_tag(Some(Rc::new(1))),
2003                FloatingActionButton::new(None).hero_tag(Some(Rc::new(2))),
2004            );
2005            push_page(tester, context);
2006            // this would fail if heroTag was the same on both FloatingActionButtons (see below).
2007            tester.pump();
2008        });
2009    }
2010
2011    /// Dart pushes a `MaterialPageRoute` from the scaffold's button; a `PageRouteBuilder`,
2012    /// whose page has no transition of its own, carries the hero flight here.
2013    #[test]
2014    fn extended_fab_hero_transitions_succeed() {
2015        // Regression test for https://github.com/flutter/flutter/issues/18782
2016        test_widgets(|tester| {
2017            let theme = m3(tester);
2018            let controller = waft_widgets::HeroController::new(&mut tester.cell.borrow_mut());
2019            let second_page: waft_widgets::RoutePageBuilder = Rc::new(|_app, context, _, _| {
2020                Scaffold::new()
2021                    .floating_action_button(
2022                        FloatingActionButton::extended(noop(), Text::new("X"))
2023                            .icon(icon(Icons::add())),
2024                    )
2025                    .body(
2026                        Center::new().child(crate::elevated_button::ElevatedButton::new(
2027                            Some(Listener::new(move |app| {
2028                                waft_widgets::Navigator::pop(app, context, None);
2029                            })),
2030                            Some(Text::new("POP").into_widget()),
2031                        )),
2032                    )
2033                    .into_widget()
2034            });
2035            let first_page = Scaffold::new()
2036                .floating_action_button(waft_widgets::Builder::new(move |_app, context| {
2037                    // define context of Navigator.push()
2038                    let second_page = Rc::clone(&second_page);
2039                    FloatingActionButton::extended(
2040                        Some(Listener::new(move |app| {
2041                            let route =
2042                                waft_widgets::PageRouteBuilder::new(app, Rc::clone(&second_page));
2043                            drop(waft_widgets::Navigator::push(app, context, route.erase()));
2044                        })),
2045                        Text::new("A long FAB label"),
2046                    )
2047                    .icon(icon(Icons::add()))
2048                    .into_widget()
2049                }))
2050                .body(Center::new().child(Text::new("Hello World")));
2051            tester.pump_widget(
2052                waft_widgets::HeroControllerScope::new(
2053                    controller,
2054                    material_app(theme, first_page.into_widget()),
2055                )
2056                .into_widget(),
2057            );
2058
2059            let long_fab = "A long FAB label";
2060            let short_fab = "X";
2061            let hello_world = "Hello World";
2062
2063            expect(tester, &find::text(long_fab), finds_one_widget());
2064            expect(tester, &find::text(short_fab), finds_nothing());
2065            expect(tester, &find::text(hello_world), finds_one_widget());
2066
2067            let at = tester.get_rect(find::text(long_fab)).center();
2068            tester.tap_at(at, 1);
2069            tester.pump_and_settle();
2070
2071            expect(tester, &find::text(short_fab), finds_one_widget());
2072            expect(tester, &find::text(long_fab), finds_nothing());
2073
2074            // Trigger a hero transition from shortFAB to longFAB.
2075            let at = tester.get_rect(find::text("POP")).center();
2076            tester.tap_at(at, 2);
2077            tester.pump_and_settle();
2078
2079            expect(tester, &find::text(long_fab), finds_one_widget());
2080            expect(tester, &find::text(short_fab), finds_nothing());
2081            expect(tester, &find::text(hello_world), finds_one_widget());
2082        });
2083    }
2084
2085    /// Not in Flutter's file: the duplicate-tag cases assert the message names the default
2086    /// tag, which waft-widgets' assert does not carry; this pins the tag they share.
2087    #[test]
2088    fn every_floating_action_button_shares_one_default_hero_tag() {
2089        let a = FloatingActionButton::new(None)
2090            .hero_tag
2091            .expect("a default tag");
2092        let b = FloatingActionButton::extended(None, SizedBox::new())
2093            .hero_tag
2094            .expect("a default tag");
2095        assert!(Rc::ptr_eq(&a, &b));
2096        assert_eq!(format!("{a:?}"), "<default FloatingActionButton tag>");
2097        assert!(
2098            FloatingActionButton::new(None)
2099                .hero_tag(None)
2100                .hero_tag
2101                .is_none()
2102        );
2103    }
2104
2105    #[test]
2106    fn floating_action_button_changes_mouse_cursor_when_hovered() {
2107        test_widgets(|tester| {
2108            let top_left = |fab: FloatingActionButton| {
2109                Scaffold::new()
2110                    .body(
2111                        Align::new()
2112                            .alignment(AlignmentGeometry::TOP_LEFT)
2113                            .child(fab),
2114                    )
2115                    .into_widget()
2116            };
2117            tester.pump_widget(material_app(
2118                m3(tester),
2119                top_left(
2120                    FloatingActionButton::extended(noop(), Text::new("label"))
2121                        .mouse_cursor(SystemMouseCursors::TEXT)
2122                        .icon(icon(Icons::android())),
2123                ),
2124            ));
2125
2126            let mut mouse = TestPointer::mouse(1, 0);
2127            let center = fab_rect(tester).center();
2128            tester.add_pointer(&mut mouse, center);
2129
2130            tester.pump();
2131
2132            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
2133            assert!(*tester.active_cursor(1) == *text);
2134
2135            tester.pump_widget(material_app(
2136                m3(tester),
2137                top_left(
2138                    FloatingActionButton::new(noop())
2139                        .mouse_cursor(SystemMouseCursors::TEXT)
2140                        .child(icon(Icons::add())),
2141                ),
2142            ));
2143
2144            let center = fab_rect(tester).center();
2145            tester.move_to(&mut mouse, center, false);
2146            assert!(*tester.active_cursor(1) == *text);
2147
2148            // Test default cursor
2149            tester.pump_widget(material_app(
2150                m3(tester),
2151                top_left(FloatingActionButton::new(noop()).child(icon(Icons::add()))),
2152            ));
2153
2154            let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
2155            assert!(*tester.active_cursor(1) == *basic);
2156
2157            // Test default cursor when disabled
2158            tester.pump_widget(material_app(
2159                m3(tester),
2160                top_left(FloatingActionButton::new(None).child(icon(Icons::add()))),
2161            ));
2162
2163            assert!(*tester.active_cursor(1) == *basic);
2164        });
2165    }
2166
2167    #[test]
2168    fn floating_action_button_has_no_clip_by_default() {
2169        test_widgets(|tester| {
2170            let focus_node = focus_node(tester);
2171            tester.pump_widget(ltr(FloatingActionButton::new(Some(Listener::new(
2172                |_app| {
2173                    // to make sure the button is enabled
2174                },
2175            )))
2176            .focus_node(focus_node.clone())));
2177
2178            focus_node.unfocus(&mut tester.cell.borrow_mut(), Default::default());
2179            tester.pump();
2180
2181            let render = tester.render_box_of(fab(tester)).as_object();
2182            let clips = count_calls(&tester.painted_ops(render), CanvasMethod::Clip);
2183            assert_eq!(clips, 0);
2184        });
2185    }
2186
2187    #[test]
2188    fn foreground_color_applies_to_icon_on_fab() {
2189        test_widgets(|tester| {
2190            let foreground_color = Color::new(0xcafefeed);
2191
2192            tester.pump_widget(material_app(
2193                m3(tester),
2194                FloatingActionButton::new(noop())
2195                    .foreground_color(foreground_color)
2196                    .child(icon(Icons::access_alarm()))
2197                    .into_widget(),
2198            ));
2199
2200            assert_eq!(icon_color(tester), Some(foreground_color));
2201        });
2202    }
2203
2204    #[test]
2205    fn floating_action_button_uses_custom_splash_color() {
2206        test_widgets(|tester| {
2207            let splash_color = Color::new(0xcafefeed);
2208
2209            tester.pump_widget(material_app(
2210                m2(tester),
2211                FloatingActionButton::new(noop())
2212                    .splash_color(splash_color)
2213                    .child(icon(Icons::access_alarm()))
2214                    .into_widget(),
2215            ));
2216
2217            let center = fab_rect(tester).center();
2218            let mut touch = TestPointer::touch(1);
2219            tester.down(&mut touch, center);
2220            tester.pump_and_settle();
2221
2222            assert_paints(
2223                tester.ink_list().ops(),
2224                &[PaintCall::circle(Some(splash_color))],
2225            );
2226        });
2227    }
2228
2229    #[test]
2230    fn extended_fab_does_not_show_label_when_is_extended_is_false() {
2231        test_widgets(|tester| {
2232            let icon_key = GlobalKey::new();
2233            let label_key = GlobalKey::new();
2234
2235            tester.pump_widget(ltr(FloatingActionButton::extended(
2236                noop(),
2237                Text::new("").key(label_key.clone().into()),
2238            )
2239            .is_extended(false)
2240            .icon(icon(Icons::add()).key(icon_key.clone().into()))));
2241
2242            // Verify that Icon is present and label is not.
2243            let app = tester.cell.borrow();
2244            assert!(icon_key.current_context(&app).is_some());
2245            assert!(label_key.current_context(&app).is_none());
2246        });
2247    }
2248
2249    #[test]
2250    fn floating_action_button_small_configures_correct_size() {
2251        test_widgets(|tester| {
2252            let key = GlobalKey::new();
2253            tester.pump_widget(app_with(
2254                m3(tester),
2255                FloatingActionButton::small(None)
2256                    .key(key.clone().into())
2257                    .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap),
2258            ));
2259
2260            assert_eq!(tester.get_size(&key), Size::new(40.0, 40.0));
2261        });
2262    }
2263
2264    #[test]
2265    fn floating_action_button_large_configures_correct_size() {
2266        test_widgets(|tester| {
2267            let key = GlobalKey::new();
2268            tester.pump_widget(app_with(
2269                m3(tester),
2270                FloatingActionButton::large(None).key(key.clone().into()),
2271            ));
2272
2273            assert_eq!(tester.get_size(&key), Size::new(96.0, 96.0));
2274        });
2275    }
2276
2277    /// The spacing and padding cases: the label's left minus the icon's right, the icon's
2278    /// left minus the button's, and the button's right minus the label's.
2279    fn extended_gaps(
2280        tester: &WidgetTester,
2281        icon_key: &GlobalKey,
2282        label_key: &GlobalKey,
2283    ) -> [f64; 3] {
2284        let fab = fab_rect(tester);
2285        let icon = key_rect(tester, icon_key);
2286        let label = key_rect(tester, label_key);
2287        [
2288            label.left - icon.right,
2289            icon.left - fab.left,
2290            fab.right - label.right,
2291        ]
2292    }
2293
2294    #[test]
2295    fn floating_action_button_extended_can_customize_spacing() {
2296        test_widgets(|tester| {
2297            let icon_key = GlobalKey::new();
2298            let label_key = GlobalKey::new();
2299            let spacing = 33.0;
2300            let padding = EdgeInsetsDirectional::only(5.0, 0.0, 6.0, 0.0);
2301
2302            tester.pump_widget(app_with(
2303                m3(tester),
2304                FloatingActionButton::extended(noop(), Text::new("").key(label_key.clone().into()))
2305                    .icon(icon(Icons::add()).key(icon_key.clone().into()))
2306                    .extended_icon_label_spacing(spacing)
2307                    .extended_padding(padding),
2308            ));
2309
2310            assert_eq!(
2311                extended_gaps(tester, &icon_key, &label_key),
2312                [spacing, padding.start, padding.end]
2313            );
2314        });
2315    }
2316
2317    #[test]
2318    fn floating_action_button_extended_can_customize_text_style() {
2319        test_widgets(|tester| {
2320            let style = TextStyle::new().letter_spacing(2.0);
2321
2322            tester.pump_widget(app_with(
2323                m2(tester),
2324                FloatingActionButton::extended(noop(), Text::new(""))
2325                    .icon(icon(Icons::add()))
2326                    .extended_text_style(style.clone()),
2327            ));
2328
2329            // The color comes from the default color scheme's onSecondary value.
2330            raw_button(tester, |button| {
2331                assert_eq!(
2332                    button.text_style,
2333                    Some(style.copy_with().color(Color::new(0xffffffff)))
2334                );
2335            });
2336        });
2337    }
2338
2339    /// Records the haptic feedback the platform is asked for.
2340    #[derive(Default)]
2341    struct FeedbackTester {
2342        haptics: RefCell<Vec<waft_embedder::HapticFeedbackType>>,
2343    }
2344
2345    impl waft_embedder::Haptics for FeedbackTester {
2346        fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
2347            self.haptics.borrow_mut().push(kind);
2348        }
2349    }
2350
2351    /// Dart's `feedback` group: taps `fab` under `theme` and returns whether its `InkWell`
2352    /// asks for feedback, which is what the click sound count stands for while the click
2353    /// system sound waits with `SystemSound`, and checks that no haptic was asked for.
2354    fn tap_feedback(
2355        theme: Option<FloatingActionButtonThemeData>,
2356        fab: FloatingActionButton,
2357    ) -> bool {
2358        let feedback = Rc::new(FeedbackTester::default());
2359        let platform = waft_test::TestPlatform::new()
2360            .on(TargetPlatform::Android)
2361            .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
2362        let mut tester = WidgetTester::with_platform(platform);
2363        let tester = &mut tester;
2364        let fab = fab.child(icon(Icons::access_alarm()));
2365        let home = match theme {
2366            Some(fab_theme) => {
2367                let theme = ThemeData::builder()
2368                    .floating_action_button_theme(fab_theme)
2369                    .build(&tester.cell.borrow());
2370                Theme::new(theme, fab).into_widget()
2371            }
2372            None => fab.into_widget(),
2373        };
2374        tester.pump_widget(material_app(m3(tester), home));
2375
2376        let at = tester
2377            .get_rect(only(find::by_type::<RawMaterialButton>().evaluate(tester)))
2378            .center();
2379        tester.tap_at(at, 1);
2380        tester.pump_by(Duration::from_secs(1));
2381        assert!(feedback.haptics.borrow().is_empty());
2382        tester.widget(
2383            only(find::by_type::<InkWell>().evaluate(tester)),
2384            |ink_well: &InkWell| ink_well.ink_response.enable_feedback,
2385        )
2386    }
2387
2388    #[test]
2389    fn floating_action_button_with_enabled_feedback() {
2390        test_widgets(|_| {
2391            assert!(tap_feedback(
2392                None,
2393                FloatingActionButton::new(noop()).enable_feedback(true)
2394            ));
2395        });
2396    }
2397
2398    #[test]
2399    fn floating_action_button_with_disabled_feedback() {
2400        test_widgets(|_| {
2401            assert!(!tap_feedback(
2402                None,
2403                FloatingActionButton::new(noop()).enable_feedback(false)
2404            ));
2405        });
2406    }
2407
2408    #[test]
2409    fn floating_action_button_with_enabled_feedback_by_default() {
2410        test_widgets(|_| {
2411            assert!(tap_feedback(None, FloatingActionButton::new(noop())));
2412        });
2413    }
2414
2415    #[test]
2416    fn floating_action_button_with_disabled_feedback_using_floating_action_button_theme() {
2417        test_widgets(|_| {
2418            assert!(!tap_feedback(
2419                Some(FloatingActionButtonThemeData::new().enable_feedback(false)),
2420                FloatingActionButton::new(noop()),
2421            ));
2422        });
2423    }
2424
2425    #[test]
2426    fn floating_action_button_enable_feedback_is_overridden_by_floating_action_button_theme_data_enable_feedback()
2427     {
2428        test_widgets(|_| {
2429            assert!(tap_feedback(
2430                Some(FloatingActionButtonThemeData::new().enable_feedback(false)),
2431                FloatingActionButton::new(noop()).enable_feedback(true),
2432            ));
2433        });
2434    }
2435
2436    #[test]
2437    fn floating_action_button_does_not_crash_at_zero_area() {
2438        test_widgets(|tester| {
2439            tester.pump_widget(material_app(
2440                m3(tester),
2441                Scaffold::new()
2442                    .floating_action_button(
2443                        Center::new()
2444                            .child(SizedBox::shrink().child(FloatingActionButton::new(noop()))),
2445                    )
2446                    .into_widget(),
2447            ));
2448            assert_eq!(fab_rect(tester).size(), Size::ZERO);
2449        });
2450    }
2451
2452    // floating_action_button_theme_test.dart
2453
2454    /// `MaterialApp(theme: ThemeData(floatingActionButtonTheme: fab_theme), home: Scaffold(
2455    /// floatingActionButton: fab))`, with `Center` in the scaffold's place.
2456    fn app_with_fab_theme(
2457        tester: &mut WidgetTester,
2458        fab_theme: FloatingActionButtonThemeData,
2459        fab: FloatingActionButton,
2460    ) {
2461        let theme = ThemeData::builder()
2462            .floating_action_button_theme(fab_theme)
2463            .build(&tester.cell.borrow());
2464        tester.pump_widget(app_with(theme, fab));
2465    }
2466
2467    #[test]
2468    fn material3_default_values_are_used_when_no_floating_action_button_or_floating_action_button_theme_data_properties_are_specified()
2469     {
2470        test_widgets(|tester| {
2471            let color_scheme = ColorScheme::light();
2472            let theme = ThemeData::from(color_scheme.clone()).build(&tester.cell.borrow());
2473            tester.pump_widget(app_with(
2474                theme,
2475                FloatingActionButton::new(noop()).child(icon(Icons::add())),
2476            ));
2477
2478            raw_button(tester, |button| {
2479                assert_eq!(button.fill_color, Some(color_scheme.primary_container()));
2480            });
2481            assert_eq!(
2482                icon_color(tester),
2483                Some(color_scheme.on_primary_container())
2484            );
2485
2486            // These defaults come directly from the [FloatingActionButton].
2487            raw_button(tester, |button| {
2488                assert_eq!(button.elevation, 6.0);
2489                assert_eq!(button.highlight_elevation, 6.0);
2490                assert!(button.shape.eq_shape(&rounded(16.0)));
2491                #[allow(deprecated)]
2492                let splash = color_scheme.on_primary_container().with_opacity(0.1);
2493                assert_eq!(button.splash_color, Some(splash));
2494                assert_eq!(
2495                    button.constraints,
2496                    BoxConstraints::tight_for(Some(56.0), Some(56.0))
2497                );
2498            });
2499            assert_eq!(icon_size(tester), (Some(24.0), Some(24.0)));
2500        });
2501    }
2502
2503    #[test]
2504    fn material2_default_values_are_used_when_no_floating_action_button_or_floating_action_button_theme_data_properties_are_specified()
2505     {
2506        test_widgets(|tester| {
2507            let color_scheme = ColorScheme::light();
2508            let theme = ThemeData::from(color_scheme.clone())
2509                .use_material3(false)
2510                .build(&tester.cell.borrow());
2511            let default_splash_color = m3(tester).splash_color;
2512            tester.pump_widget(app_with(
2513                theme,
2514                FloatingActionButton::new(noop()).child(icon(Icons::add())),
2515            ));
2516
2517            raw_button(tester, |button| {
2518                assert_eq!(button.fill_color, Some(color_scheme.secondary()));
2519            });
2520            assert_eq!(icon_color(tester), Some(color_scheme.on_secondary()));
2521
2522            // These defaults come directly from the [FloatingActionButton].
2523            raw_button(tester, |button| {
2524                assert_eq!(button.elevation, 6.0);
2525                assert_eq!(button.highlight_elevation, 12.0);
2526                assert!(button.shape.eq_shape(&CircleBorder::default()));
2527                assert_eq!(button.splash_color, Some(default_splash_color));
2528                assert_eq!(
2529                    button.constraints,
2530                    BoxConstraints::tight_for(Some(56.0), Some(56.0))
2531                );
2532            });
2533            assert_eq!(icon_size(tester), (Some(24.0), Some(24.0)));
2534        });
2535    }
2536
2537    /// The fields a theme or widget case sets, as the button resolves them.
2538    struct Resolved {
2539        background_color: Color,
2540        foreground_color: Color,
2541        splash_color: Color,
2542        elevation: f64,
2543        disabled_elevation: f64,
2544        highlight_elevation: f64,
2545        shape: ShapeBorderRef,
2546    }
2547
2548    impl Resolved {
2549        fn local() -> Resolved {
2550            Resolved {
2551                background_color: Color::new(0x00000001),
2552                foreground_color: Color::new(0x00000002),
2553                splash_color: Color::new(0x00000003),
2554                elevation: 7.0,
2555                disabled_elevation: 1.0,
2556                highlight_elevation: 13.0,
2557                shape: ShapeBorderRef::new(StadiumBorder::default()),
2558            }
2559        }
2560
2561        fn theme_data(&self) -> FloatingActionButtonThemeData {
2562            FloatingActionButtonThemeData::new()
2563                .background_color(self.background_color)
2564                .foreground_color(self.foreground_color)
2565                .splash_color(self.splash_color)
2566                .elevation(self.elevation)
2567                .disabled_elevation(self.disabled_elevation)
2568                .highlight_elevation(self.highlight_elevation)
2569                .shape(self.shape.clone())
2570        }
2571
2572        /// The ambient theme the priority cases override.
2573        fn overridden() -> FloatingActionButtonThemeData {
2574            FloatingActionButtonThemeData::new()
2575                .background_color(Color::new(0x00000004))
2576                .foreground_color(Color::new(0x00000005))
2577                .splash_color(Color::new(0x00000006))
2578                .elevation(23.0)
2579                .disabled_elevation(11.0)
2580                .highlight_elevation(43.0)
2581                .shape(BeveledRectangleBorder::default())
2582        }
2583
2584        fn assert_shown(&self, tester: &WidgetTester) {
2585            raw_button(tester, |button| {
2586                assert_eq!(button.fill_color, Some(self.background_color));
2587            });
2588            assert_eq!(icon_color(tester), Some(self.foreground_color));
2589            raw_button(tester, |button| {
2590                assert_eq!(button.elevation, self.elevation);
2591                assert_eq!(button.disabled_elevation, self.disabled_elevation);
2592                assert_eq!(button.highlight_elevation, self.highlight_elevation);
2593                assert!(button.shape.eq_shape(&*self.shape));
2594                assert_eq!(button.splash_color, Some(self.splash_color));
2595            });
2596        }
2597    }
2598
2599    fn add_button() -> FloatingActionButton {
2600        FloatingActionButton::new(noop()).child(icon(Icons::add()))
2601    }
2602
2603    #[test]
2604    fn floating_action_button_theme_data_values_are_used_when_no_floating_action_button_properties_are_specified()
2605     {
2606        test_widgets(|tester| {
2607            let resolved = Resolved {
2608                background_color: Color::new(0xBEEFBEEF),
2609                foreground_color: Color::new(0xFACEFACE),
2610                splash_color: Color::new(0xCAFEFEED),
2611                ..Resolved::local()
2612            };
2613            let constraints = BoxConstraints::tight_for(Some(100.0), Some(100.0));
2614
2615            app_with_fab_theme(
2616                tester,
2617                resolved.theme_data().size_constraints(constraints),
2618                add_button(),
2619            );
2620
2621            resolved.assert_shown(tester);
2622            raw_button(tester, |button| assert_eq!(button.constraints, constraints));
2623        });
2624    }
2625
2626    #[test]
2627    fn floating_action_button_values_take_priority_over_floating_action_button_theme_data_values_when_both_properties_are_specified()
2628     {
2629        test_widgets(|tester| {
2630            let resolved = Resolved::local();
2631            app_with_fab_theme(
2632                tester,
2633                Resolved::overridden(),
2634                add_button()
2635                    .background_color(resolved.background_color)
2636                    .foreground_color(resolved.foreground_color)
2637                    .splash_color(resolved.splash_color)
2638                    .elevation(resolved.elevation)
2639                    .disabled_elevation(resolved.disabled_elevation)
2640                    .highlight_elevation(resolved.highlight_elevation)
2641                    .shape(resolved.shape.clone()),
2642            );
2643
2644            resolved.assert_shown(tester);
2645        });
2646    }
2647
2648    #[test]
2649    fn local_floating_action_button_theme_properties_are_used() {
2650        test_widgets(|tester| {
2651            let resolved = Resolved::local();
2652            tester.pump_widget(material_app(
2653                m3(tester),
2654                FloatingActionButtonTheme::new(
2655                    resolved.theme_data(),
2656                    Scaffold::new().floating_action_button(add_button()),
2657                )
2658                .into_widget(),
2659            ));
2660
2661            resolved.assert_shown(tester);
2662        });
2663    }
2664
2665    #[test]
2666    fn local_floating_action_button_theme_takes_priority_over_theme_data_floating_action_button_theme()
2667     {
2668        test_widgets(|tester| {
2669            let resolved = Resolved::local();
2670            let theme = ThemeData::builder()
2671                .floating_action_button_theme(Resolved::overridden())
2672                .build(&tester.cell.borrow());
2673            tester.pump_widget(material_app(
2674                theme,
2675                FloatingActionButtonTheme::new(
2676                    resolved.theme_data(),
2677                    Scaffold::new().floating_action_button(add_button()),
2678                )
2679                .into_widget(),
2680            ));
2681
2682            resolved.assert_shown(tester);
2683        });
2684    }
2685
2686    #[test]
2687    fn floating_action_button_uses_a_custom_shape_when_specified_in_the_theme() {
2688        test_widgets(|tester| {
2689            let custom_shape = BeveledRectangleBorder::default();
2690
2691            tester.pump_widget(app_with(
2692                m3(tester),
2693                FloatingActionButton::new(noop()).shape(custom_shape),
2694            ));
2695
2696            assert_shape(tester, &custom_shape);
2697        });
2698    }
2699
2700    #[test]
2701    fn floating_action_button_small_uses_custom_constraints_when_specified_in_the_theme() {
2702        test_widgets(|tester| {
2703            let constraints = BoxConstraints::tight_for(Some(100.0), Some(100.0));
2704            let icon_size_value = 24.0;
2705
2706            app_with_fab_theme(
2707                tester,
2708                FloatingActionButtonThemeData::new().small_size_constraints(constraints),
2709                FloatingActionButton::small(noop()).child(icon(Icons::add())),
2710            );
2711
2712            raw_button(tester, |button| assert_eq!(button.constraints, constraints));
2713            assert_eq!(
2714                icon_size(tester),
2715                (Some(icon_size_value), Some(icon_size_value))
2716            );
2717        });
2718    }
2719
2720    #[test]
2721    fn floating_action_button_large_uses_custom_constraints_when_specified_in_the_theme() {
2722        test_widgets(|tester| {
2723            let constraints = BoxConstraints::tight_for(Some(100.0), Some(100.0));
2724            let icon_size_value = 36.0;
2725
2726            app_with_fab_theme(
2727                tester,
2728                FloatingActionButtonThemeData::new().large_size_constraints(constraints),
2729                FloatingActionButton::large(noop()).child(icon(Icons::add())),
2730            );
2731
2732            raw_button(tester, |button| assert_eq!(button.constraints, constraints));
2733            assert_eq!(
2734                icon_size(tester),
2735                (Some(icon_size_value), Some(icon_size_value))
2736            );
2737        });
2738    }
2739
2740    /// The extended theme cases: a `theme` (Material 3 on `ColorScheme.light()`, or Material 2)
2741    /// carrying `fab_theme`, and an extended button labelled "Extended" with `customize`
2742    /// applied. Returns the gaps of [`extended_gaps`].
2743    fn extended_case(
2744        tester: &mut WidgetTester,
2745        use_material3: bool,
2746        fab_theme: FloatingActionButtonThemeData,
2747        customize: impl FnOnce(FloatingActionButton) -> FloatingActionButton,
2748    ) -> [f64; 3] {
2749        let icon_key = GlobalKey::new();
2750        let label_key = GlobalKey::new();
2751        let builder = ThemeData::builder()
2752            .use_material3(use_material3)
2753            .floating_action_button_theme(fab_theme);
2754        let builder = if use_material3 {
2755            builder.color_scheme(ColorScheme::light())
2756        } else {
2757            builder
2758        };
2759        let theme = builder.build(&tester.cell.borrow());
2760        tester.pump_widget(app_with(
2761            theme,
2762            customize(
2763                FloatingActionButton::extended(
2764                    noop(),
2765                    Text::new("Extended").key(label_key.clone().into()),
2766                )
2767                .icon(icon(Icons::add()).key(icon_key.clone().into())),
2768            ),
2769        ));
2770        extended_gaps(tester, &icon_key, &label_key)
2771    }
2772
2773    /// The text colour the extended cases expect: `ColorScheme.light().onPrimaryContainer` in
2774    /// Material 3, and the default colour scheme's `onSecondary`, white, in Material 2.
2775    fn extended_text_color(use_material3: bool) -> Color {
2776        if use_material3 {
2777            ColorScheme::light().on_primary_container()
2778        } else {
2779            Color::new(0xffffffff)
2780        }
2781    }
2782
2783    fn extended_uses_custom_properties_when_specified_in_the_theme(
2784        tester: &mut WidgetTester,
2785        use_material3: bool,
2786    ) {
2787        let constraints = BoxConstraints::tight_for(None, Some(100.0));
2788        let icon_label_spacing = 33.0;
2789        let padding = EdgeInsetsDirectional::only(5.0, 0.0, 6.0, 0.0);
2790        let text_style = TextStyle::new().letter_spacing(2.0);
2791
2792        let gaps = extended_case(
2793            tester,
2794            use_material3,
2795            FloatingActionButtonThemeData::new()
2796                .extended_size_constraints(constraints)
2797                .extended_icon_label_spacing(icon_label_spacing)
2798                .extended_padding(padding)
2799                .extended_text_style(text_style.clone()),
2800            |fab| fab,
2801        );
2802
2803        raw_button(tester, |button| assert_eq!(button.constraints, constraints));
2804        assert_eq!(gaps, [icon_label_spacing, padding.start, padding.end]);
2805        raw_button(tester, |button| {
2806            assert_eq!(
2807                button.text_style,
2808                Some(
2809                    text_style
2810                        .copy_with()
2811                        .color(extended_text_color(use_material3))
2812                )
2813            );
2814        });
2815    }
2816
2817    #[test]
2818    fn material3_floating_action_button_extended_uses_custom_properties_when_specified_in_the_theme()
2819     {
2820        test_widgets(|tester| {
2821            extended_uses_custom_properties_when_specified_in_the_theme(tester, true)
2822        });
2823    }
2824
2825    #[test]
2826    fn material2_floating_action_button_extended_uses_custom_properties_when_specified_in_the_theme()
2827     {
2828        test_widgets(|tester| {
2829            extended_uses_custom_properties_when_specified_in_the_theme(tester, false);
2830        });
2831    }
2832
2833    fn extended_custom_properties_take_priority_over_theme(
2834        tester: &mut WidgetTester,
2835        use_material3: bool,
2836    ) {
2837        let icon_label_spacing = 33.0;
2838        let padding = EdgeInsetsDirectional::only(5.0, 0.0, 6.0, 0.0);
2839        let text_style = TextStyle::new().letter_spacing(2.0);
2840
2841        let gaps = extended_case(
2842            tester,
2843            use_material3,
2844            FloatingActionButtonThemeData::new()
2845                .extended_icon_label_spacing(25.0)
2846                .extended_padding(EdgeInsetsDirectional::only(7.0, 0.0, 8.0, 0.0))
2847                .extended_text_style(TextStyle::new().letter_spacing(3.0)),
2848            |fab| {
2849                fab.extended_icon_label_spacing(icon_label_spacing)
2850                    .extended_padding(padding)
2851                    .extended_text_style(text_style.clone())
2852            },
2853        );
2854
2855        assert_eq!(gaps, [icon_label_spacing, padding.start, padding.end]);
2856        raw_button(tester, |button| {
2857            assert_eq!(
2858                button.text_style,
2859                Some(
2860                    text_style
2861                        .copy_with()
2862                        .color(extended_text_color(use_material3))
2863                )
2864            );
2865        });
2866    }
2867
2868    #[test]
2869    fn material3_floating_action_button_extended_custom_properties_takes_priority_over_floating_action_button_theme_data_spacing()
2870     {
2871        test_widgets(|tester| extended_custom_properties_take_priority_over_theme(tester, true));
2872    }
2873
2874    #[test]
2875    fn material2_floating_action_button_extended_custom_properties_takes_priority_over_floating_action_button_theme_data_spacing()
2876     {
2877        test_widgets(|tester| extended_custom_properties_take_priority_over_theme(tester, false));
2878    }
2879
2880    #[test]
2881    fn floating_action_button_mouse_cursor_uses_floating_action_button_theme_data_mouse_cursor_when_specified()
2882     {
2883        test_widgets(|tester| {
2884            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
2885            app_with_fab_theme(
2886                tester,
2887                FloatingActionButtonThemeData::new().mouse_cursor(<dyn WidgetStateProperty<
2888                    Option<MouseCursorRef>,
2889                >>::all(Some(
2890                    text.clone(),
2891                ))),
2892                add_button(),
2893            );
2894
2895            tester.pump_and_settle();
2896            let mut mouse = TestPointer::mouse(1, 0);
2897            tester.add_pointer(&mut mouse, Offset::ZERO);
2898            let center = fab_rect(tester).center();
2899            tester.move_to(&mut mouse, center, false);
2900            tester.pump_and_settle();
2901            assert!(*tester.active_cursor(1) == *text);
2902        });
2903    }
2904
2905    /// Dart's `_RenderChildOverflowBox` fills no properties of its own; it inherits
2906    /// `RenderAligningShiftedBox.debugFillProperties`.
2907    #[test]
2908    fn a_child_overflow_box_fills_the_properties_it_inherits() {
2909        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
2910
2911        let cell = AppCell::new();
2912        let mut app = cell.borrow_mut();
2913        let overflow = RenderChildOverflowBox::new(&mut app, Some(TextDirection::Ltr));
2914        let mut properties = DiagnosticPropertiesBuilder::new();
2915        RenderObject::debug_fill_properties(overflow, &app, &mut properties);
2916        let names: Vec<&str> = properties
2917            .properties
2918            .iter()
2919            .filter_map(|property| property.name())
2920            .collect();
2921        assert_eq!(names, ["alignment", "textDirection"]);
2922    }
2923}