Skip to main content

waft_material/
filled_button.rs

1//! Flutter counterpart: material_ui's `filled_button.dart`, with its parts
2//! `generated/filled_button_defaults_m3.g.dart` and
3//! `generated/filled_tonal_button_defaults_m3.g.dart`.
4//!
5//! Dart's `FilledButton.icon`, `FilledButton.tonalIcon` and `FilledButton.styleFrom` take
6//! named arguments the body combines (the icon child reads `style`; `styleFrom` derives its
7//! overlay color from two of them), so each is a value collecting them, [`FilledButtonIcon`]
8//! and [`FilledButtonStyleFromBuilder`], that converts once every argument is given.
9#![allow(deprecated)]
10
11use std::fmt::{self, Debug};
12use std::rc::Rc;
13use std::time::Duration;
14
15use waft_embedder::{Clip, Color, Size, clamp_double, lerp_double};
16use waft_foundation::{App, DiagnosticPropertiesBuilder, Listener};
17use waft_painting::{
18    AlignmentGeometry, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef, TextStyle,
19};
20use waft_services::MouseCursorRef;
21use waft_widgets::{
22    BuildContext, Flexible, IntoWidget, KeyRef, MainAxisSize, MediaQuery, Row, StatefulKind,
23    StatefulWidget, StatelessWidget, WidgetRef, WidgetState, WidgetStateProperty,
24    WidgetStatePropertyRef, WidgetStates,
25};
26
27use crate::button_style::ButtonStyleGetters;
28use crate::button_style::{ButtonLayerBuilder, ButtonStyle};
29use crate::button_style_button::{
30    ButtonStyleButton, ButtonStyleButtonData, ButtonStyleState, IconAlignment,
31};
32use crate::filled_button_theme::FilledButtonTheme;
33use crate::generated::filled_button_defaults_m3::FilledButtonDefaultsM3;
34use crate::generated::filled_tonal_button_defaults_m3::FilledTonalButtonDefaultsM3;
35use crate::ink_well::InteractiveInkFeatureFactoryRef;
36use crate::material_state::MaterialStatePropertyAll;
37use crate::theme::Theme;
38use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41enum FilledButtonVariant {
42    Filled,
43    Tonal,
44}
45
46/// A Material Design filled button.
47///
48/// Filled buttons have the most visual impact after the `FloatingActionButton`,
49/// and should be used for important, final actions that complete a flow,
50/// like **Save**, **Join now**, or **Confirm**.
51///
52/// A filled button is a label `child` displayed on a `Material`
53/// widget. The label's `Text` and `Icon` widgets are displayed in
54/// `style`'s [`ButtonStyle::foreground_color`] and the button's filled
55/// background is the [`ButtonStyle::background_color`].
56///
57/// The filled button's default style is defined by
58/// [`default_style_of`](ButtonStyleButton::default_style_of). The style of this filled
59/// button can be overridden with its `style` parameter. The style of all filled
60/// buttons in a subtree can be overridden with the
61/// [`FilledButtonTheme`], and the style of all of the filled
62/// buttons in an app can be overridden with the `Theme`'s
63/// `ThemeData::filled_button_theme` property.
64///
65/// The static [`style_from`](Self::style_from) method is a convenient way to create a
66/// filled button [`ButtonStyle`] from simple values.
67///
68/// If `on_pressed` and `on_long_press` callbacks are null, then the
69/// button will be disabled.
70///
71/// To create a 'filled tonal' button, use [`FilledButton::tonal`].
72///
73/// ## Visual density effects
74///
75/// The button's appearance is affected by the [`VisualDensity`] from the enclosing
76/// `Theme` or from its `style`. Visual density adjusts the [`ButtonStyle::padding`]
77/// and [`ButtonStyle::minimum_size`] to accommodate different UI densities across platforms.
78/// See [`VisualDensity`] for more details on how it affects component layout and
79/// the platform-specific defaults.
80///
81/// See also:
82///
83///  * `ElevatedButton`, a filled button whose material elevates when pressed.
84///  * `OutlinedButton`, a button with an outlined border and no fill color.
85///  * `TextButton`, a button with no outline or fill color.
86///  * <https://material.io/design/components/buttons.html>
87///  * <https://m3.material.io/components/buttons>
88pub struct FilledButton {
89    button_style_button: ButtonStyleButtonData,
90    variant: FilledButtonVariant,
91    add_padding: bool,
92}
93
94impl FilledButton {
95    /// Create a FilledButton.
96    #[cfg_attr(debug_assertions, track_caller)]
97    pub fn new<K>(on_pressed: Option<Listener>, child: Option<impl IntoWidget<K>>) -> FilledButton {
98        FilledButton::with_child(
99            FilledButtonVariant::Filled,
100            on_pressed,
101            match child {
102                Some(child) => Some(child.into_widget()),
103                None => None,
104            },
105        )
106    }
107
108    /// Create a filled button from [`icon`](FilledButtonIcon::icon) and `label`.
109    ///
110    /// The icon and label are arranged in a row with padding at the start and end
111    /// and a gap between them.
112    ///
113    /// If [`icon`](FilledButtonIcon::icon) is null, this constructor will create a
114    /// [`FilledButton`] that doesn't display an icon.
115    ///
116    /// The alignment of the icon within the button is set by
117    /// [`icon_alignment`](FilledButtonIcon::icon_alignment); see [`IconAlignment`].
118    #[cfg_attr(debug_assertions, track_caller)]
119    pub fn icon<K>(on_pressed: Option<Listener>, label: impl IntoWidget<K>) -> FilledButtonIcon {
120        FilledButtonIcon::new(FilledButtonVariant::Filled, on_pressed, label.into_widget())
121    }
122
123    /// Create a tonal variant of FilledButton.
124    ///
125    /// A filled tonal button is an alternative middle ground between
126    /// [`FilledButton`] and `OutlinedButton`. They’re useful in contexts where
127    /// a lower-priority button requires slightly more emphasis than an
128    /// outline would give, such as "Next" in an onboarding flow.
129    #[cfg_attr(debug_assertions, track_caller)]
130    pub fn tonal<K>(
131        on_pressed: Option<Listener>,
132        child: Option<impl IntoWidget<K>>,
133    ) -> FilledButton {
134        FilledButton::with_child(
135            FilledButtonVariant::Tonal,
136            on_pressed,
137            match child {
138                Some(child) => Some(child.into_widget()),
139                None => None,
140            },
141        )
142    }
143
144    /// Create a filled tonal button from [`icon`](FilledButtonIcon::icon) and `label`.
145    ///
146    /// The [`icon`](FilledButtonIcon::icon) and `label` are arranged in a row with padding
147    /// at the start and end and a gap between them.
148    ///
149    /// If [`icon`](FilledButtonIcon::icon) is null, this constructor will create a
150    /// [`FilledButton`] that doesn't display an icon.
151    #[cfg_attr(debug_assertions, track_caller)]
152    pub fn tonal_icon<K>(
153        on_pressed: Option<Listener>,
154        label: impl IntoWidget<K>,
155    ) -> FilledButtonIcon {
156        FilledButtonIcon::new(FilledButtonVariant::Tonal, on_pressed, label.into_widget())
157    }
158
159    /// The initializer list of the constructors without an icon.
160    fn with_child(
161        variant: FilledButtonVariant,
162        on_pressed: Option<Listener>,
163        child: Option<WidgetRef>,
164    ) -> FilledButton {
165        let mut button_style_button = ButtonStyleButtonData::new(on_pressed, child);
166        button_style_button.clip_behavior = Some(Clip::None);
167        FilledButton {
168            button_style_button,
169            variant,
170            add_padding: false,
171        }
172    }
173
174    crate::button_style_button_setters!(
175        FilledButton;
176        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
177        clip_behavior, states_controller,
178    );
179
180    /// A static convenience method that constructs a filled button
181    /// [`ButtonStyle`] given simple values.
182    ///
183    /// The `foreground_color` and `disabled_foreground_color` colors are used
184    /// to create a [`WidgetStateProperty`] [`ButtonStyle::foreground_color`], and
185    /// a derived [`ButtonStyle::overlay_color`] if `overlay_color` isn't specified.
186    ///
187    /// If `overlay_color` is specified and its value is `Colors::TRANSPARENT`
188    /// then the pressed/focused/hovered highlights are effectively defeated.
189    /// Otherwise a [`WidgetStateProperty`] with the same opacities as the
190    /// default is created.
191    ///
192    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
193    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
194    ///
195    /// The `icon_color`, `disabled_icon_color` are used to construct
196    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
197    /// [`ButtonStyle::icon_size`].
198    ///
199    /// If `icon_color` is null, the button icon will use `foreground_color`. If
200    /// `foreground_color` is also null, the button icon will use the default icon color.
201    ///
202    /// The button's elevations are defined relative to the `elevation`
203    /// parameter. The disabled elevation is the same as the parameter
204    /// value, `elevation` + 2 is used when the button is hovered
205    /// or focused, and elevation + 6 is used when the button is pressed.
206    ///
207    /// All of the other parameters are either used directly or used to
208    /// create a [`WidgetStateProperty`] with a single value for all
209    /// states.
210    ///
211    /// All parameters default to null, by default this method returns
212    /// a [`ButtonStyle`] that doesn't override anything.
213    ///
214    /// For example, to override the default text and icon colors for a
215    /// [`FilledButton`], as well as its overlay color, with all of the
216    /// standard opacity adjustments for the pressed, focused, and
217    /// hovered states, one could write:
218    ///
219    /// ```text
220    /// FilledButton::new(on_pressed, Text::new("Filled button"))
221    ///     .style(FilledButton::style_from().foreground_color(Colors::GREEN.primary()).build())
222    /// ```
223    ///
224    /// or for a Filled tonal variant:
225    ///
226    /// ```text
227    /// FilledButton::tonal(on_pressed, Text::new("Filled tonal button"))
228    ///     .style(FilledButton::style_from().foreground_color(Colors::GREEN.primary()).build())
229    /// ```
230    pub fn style_from() -> FilledButtonStyleFromBuilder {
231        FilledButtonStyleFromBuilder::default()
232    }
233}
234
235impl ButtonStyleButton for FilledButton {
236    crate::button_style_button_accessors!();
237
238    /// Defines the button's default appearance.
239    ///
240    /// The button `child`'s `Text` and `Icon` widgets are rendered with
241    /// the [`ButtonStyle`]'s foreground color. The button's `InkWell` adds
242    /// the style's overlay color when the button is focused, hovered
243    /// or pressed. The button's background color becomes its `Material`
244    /// color.
245    ///
246    /// All of the ButtonStyle's defaults appear below. In this list
247    /// "Theme.foo" is shorthand for `Theme::of(context).foo`. Color
248    /// scheme values like "onSurface(0.38)" are shorthand for
249    /// `on_surface.with_opacity(0.38)`. [`WidgetStateProperty`] valued
250    /// properties that are not followed by a sublist have the same
251    /// value for all states, otherwise the values are as specified for
252    /// each state, and "others" means all other states.
253    ///
254    /// The "default font size" below refers to the font size specified in the
255    /// [`default_style_of`](ButtonStyleButton::default_style_of) method (or 14.0 if
256    /// unspecified), scaled by the `MediaQuery::text_scaler_of(context).scale` method. The
257    /// names of the EdgeInsets constructors and `EdgeInsetsGeometry::lerp` have been
258    /// abbreviated for readability.
259    ///
260    /// The color of the [`ButtonStyle::text_style`] is not used, the
261    /// [`ButtonStyle::foreground_color`] color is used instead.
262    ///
263    /// * `text_style` - Theme.textTheme.labelLarge
264    /// * `background_color`
265    ///   * disabled - Theme.colorScheme.onSurface(0.12)
266    ///   * others - Theme.colorScheme.secondaryContainer
267    /// * `foreground_color`
268    ///   * disabled - Theme.colorScheme.onSurface(0.38)
269    ///   * others - Theme.colorScheme.onSecondaryContainer
270    /// * `overlay_color`
271    ///   * hovered - Theme.colorScheme.onSecondaryContainer(0.08)
272    ///   * focused or pressed - Theme.colorScheme.onSecondaryContainer(0.12)
273    /// * `shadow_color` - Theme.colorScheme.shadow
274    /// * `surface_tint_color` - null
275    /// * `elevation`
276    ///   * disabled - 0
277    ///   * default - 0
278    ///   * hovered - 1
279    ///   * focused or pressed - 0
280    /// * `padding`
281    ///   * `default font size <= 14` - horizontal(16)
282    ///   * `14 < default font size <= 28` - lerp(horizontal(16), horizontal(8))
283    ///   * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
284    ///   * `36 < default font size` - horizontal(4)
285    /// * `minimum_size` - Size(64, 40)
286    /// * `fixed_size` - null
287    /// * `maximum_size` - Size.infinite
288    /// * `side` - null
289    /// * `shape` - StadiumBorder()
290    /// * `mouse_cursor` - WidgetStateMouseCursor.adaptiveClickable
291    /// * `visual_density` - Theme.visualDensity
292    /// * `tap_target_size` - Theme.materialTapTargetSize
293    /// * `animation_duration` - kThemeChangeDuration
294    /// * `enable_feedback` - true
295    /// * `alignment` - Alignment.center
296    /// * `splash_factory` - Theme.splashFactory
297    ///
298    /// The default padding values for the [`FilledButton::icon`] factory are slightly
299    /// different:
300    ///
301    /// * `padding`
302    ///   * `default font size <= 14` - start(12) end(16)
303    ///   * `14 < default font size <= 28` - lerp(start(12) end(16), horizontal(8))
304    ///   * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
305    ///   * `36 < default font size` - horizontal(4)
306    ///
307    /// The default value for `side`, which defines the appearance of the button's
308    /// outline, is null. That means that the outline is defined by the button
309    /// shape's `OutlinedBorder::side`. Typically the default value of an
310    /// [`OutlinedBorder`]'s side is [`BorderSide::NONE`], so an outline is not drawn.
311    ///
312    /// ## Material 3 defaults
313    ///
314    /// If `ThemeData::use_material3` is set to true the following defaults will
315    /// be used:
316    ///
317    /// * `text_style` - Theme.textTheme.labelLarge
318    /// * `background_color`
319    ///   * disabled - Theme.colorScheme.onSurface(0.12)
320    ///   * others
321    ///     - Theme.colorScheme.primary in `FilledButton`
322    ///     - Theme.colorScheme.secondaryContainer in `FilledButton.tonal`
323    /// * `foreground_color`
324    ///   * disabled - Theme.colorScheme.onSurface(0.38)
325    ///   * others
326    ///     - Theme.colorScheme.onPrimary in `FilledButton`
327    ///     - Theme.colorScheme.onSecondaryContainer in `FilledButton.tonal`
328    /// * `overlay_color`
329    ///   * hovered
330    ///     - Theme.colorScheme.onPrimary(0.08) in `FilledButton`
331    ///     - Theme.colorScheme.onSecondaryContainer(0.08) in `FilledButton.tonal`
332    ///   * focused or pressed
333    ///     - Theme.colorScheme.onPrimary(0.1) in `FilledButton`
334    ///     - Theme.colorScheme.onSecondaryContainer(0.1) in `FilledButton.tonal`
335    /// * `shadow_color` - Theme.colorScheme.shadow
336    /// * `surface_tint_color` - Colors.transparent
337    /// * `elevation`
338    ///   * disabled - 0
339    ///   * default - 1
340    ///   * hovered - 3
341    ///   * focused or pressed - 1
342    /// * `padding`
343    ///   * `default font size <= 14` - horizontal(24)
344    ///   * `14 < default font size <= 28` - lerp(horizontal(24), horizontal(12))
345    ///   * `28 < default font size <= 36` - lerp(horizontal(12), horizontal(6))
346    ///   * `36 < default font size` - horizontal(6)
347    /// * `minimum_size` - Size(64, 40)
348    /// * `fixed_size` - null
349    /// * `maximum_size` - Size.infinite
350    /// * `side` - null
351    /// * `shape` - StadiumBorder()
352    /// * `mouse_cursor` - WidgetStateMouseCursor.adaptiveClickable
353    /// * `visual_density` - Theme.visualDensity
354    /// * `tap_target_size` - Theme.materialTapTargetSize
355    /// * `animation_duration` - kThemeChangeDuration
356    /// * `enable_feedback` - true
357    /// * `alignment` - Alignment.center
358    /// * `splash_factory` - Theme.splashFactory
359    ///
360    /// For the [`FilledButton::icon`] factory, the start (generally the left) value of
361    /// [`ButtonStyle::padding`] is reduced from 24 to 16.
362    fn default_style_of(
363        &self,
364        app: &mut App,
365        context: BuildContext,
366    ) -> Box<dyn ButtonStyleGetters> {
367        let button_style: Box<dyn ButtonStyleGetters> = match self.variant {
368            FilledButtonVariant::Filled => Box::new(FilledButtonDefaultsM3::new(context)),
369            FilledButtonVariant::Tonal => Box::new(FilledTonalButtonDefaultsM3::new(context)),
370        };
371
372        if self.add_padding {
373            let use_material3 = Theme::of(app, context).use_material3;
374            let default_font_size = button_style
375                .text_style(app)
376                .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
377                .and_then(|text_style| text_style.font_size)
378                .unwrap_or(14.0);
379            let effective_text_scale =
380                MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
381
382            let scaled_padding = if use_material3 {
383                <dyn ButtonStyleButton>::scaled_padding(
384                    EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0),
385                    EdgeInsetsGeometry::from_steb(8.0, 0.0, 12.0, 0.0),
386                    EdgeInsetsGeometry::from_steb(4.0, 0.0, 6.0, 0.0),
387                    effective_text_scale,
388                )
389            } else {
390                <dyn ButtonStyleButton>::scaled_padding(
391                    EdgeInsetsGeometry::from_steb(12.0, 0.0, 16.0, 0.0),
392                    EdgeInsetsGeometry::symmetric(0.0, 8.0),
393                    EdgeInsetsGeometry::from_steb(8.0, 0.0, 4.0, 0.0),
394                    effective_text_scale,
395                )
396            };
397            return Box::new(
398                button_style
399                    .copy_with(app)
400                    .padding(Rc::new(MaterialStatePropertyAll::new(Some(scaled_padding)))),
401            );
402        }
403
404        button_style
405    }
406
407    /// Returns the `FilledButtonThemeData::style` of the closest
408    /// [`FilledButtonTheme`] ancestor.
409    fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> {
410        FilledButtonTheme::of(app, context).style
411    }
412}
413
414impl StatefulWidget for FilledButton {
415    type State = ButtonStyleState<FilledButton>;
416
417    fn key(&self) -> Option<&KeyRef> {
418        self.button_style_button.key.as_ref()
419    }
420
421    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
422        self.button_style_button
423            .debug_fill_properties(app, properties);
424    }
425
426    fn create_state(&self) -> ButtonStyleState<FilledButton> {
427        ButtonStyleState::new()
428    }
429}
430
431impl Debug for FilledButton {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        Debug::fmt(&self.button_style_button, f)
434    }
435}
436
437/// Dart's `FilledButton.styleFrom`, collecting its arguments; [`build`](Self::build) is the
438/// call.
439#[derive(Clone, Default)]
440pub struct FilledButtonStyleFromBuilder {
441    foreground_color: Option<Color>,
442    background_color: Option<Color>,
443    disabled_foreground_color: Option<Color>,
444    disabled_background_color: Option<Color>,
445    shadow_color: Option<Color>,
446    surface_tint_color: Option<Color>,
447    icon_color: Option<Color>,
448    icon_size: Option<f64>,
449    icon_alignment: Option<IconAlignment>,
450    disabled_icon_color: Option<Color>,
451    overlay_color: Option<Color>,
452    elevation: Option<f64>,
453    text_style: Option<TextStyle>,
454    padding: Option<EdgeInsetsGeometry>,
455    minimum_size: Option<Size>,
456    fixed_size: Option<Size>,
457    maximum_size: Option<Size>,
458    side: Option<BorderSide>,
459    shape: Option<OutlinedBorderRef>,
460    enabled_mouse_cursor: Option<MouseCursorRef>,
461    disabled_mouse_cursor: Option<MouseCursorRef>,
462    visual_density: Option<VisualDensity>,
463    tap_target_size: Option<MaterialTapTargetSize>,
464    animation_duration: Option<Duration>,
465    enable_feedback: Option<bool>,
466    alignment: Option<AlignmentGeometry>,
467    splash_factory: Option<InteractiveInkFeatureFactoryRef>,
468    background_builder: Option<ButtonLayerBuilder>,
469    foreground_builder: Option<ButtonLayerBuilder>,
470}
471
472/// The setters of `styleFrom`'s named arguments.
473macro_rules! style_from_setters {
474    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
475        $(
476            #[doc = concat!("Dart `FilledButton.styleFrom(", $dart, ":)`.")]
477            pub fn $field(mut self, $field: $ty) -> FilledButtonStyleFromBuilder {
478                self.$field = Some($field);
479                self
480            }
481        )*
482    };
483}
484
485impl FilledButtonStyleFromBuilder {
486    style_from_setters!(
487        foreground_color: Color => "foregroundColor",
488        background_color: Color => "backgroundColor",
489        disabled_foreground_color: Color => "disabledForegroundColor",
490        disabled_background_color: Color => "disabledBackgroundColor",
491        shadow_color: Color => "shadowColor",
492        surface_tint_color: Color => "surfaceTintColor",
493        icon_color: Color => "iconColor",
494        icon_size: f64 => "iconSize",
495        icon_alignment: IconAlignment => "iconAlignment",
496        disabled_icon_color: Color => "disabledIconColor",
497        overlay_color: Color => "overlayColor",
498        elevation: f64 => "elevation",
499        text_style: TextStyle => "textStyle",
500        padding: EdgeInsetsGeometry => "padding",
501        minimum_size: Size => "minimumSize",
502        fixed_size: Size => "fixedSize",
503        maximum_size: Size => "maximumSize",
504        side: BorderSide => "side",
505        enabled_mouse_cursor: MouseCursorRef => "enabledMouseCursor",
506        disabled_mouse_cursor: MouseCursorRef => "disabledMouseCursor",
507        visual_density: VisualDensity => "visualDensity",
508        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
509        animation_duration: Duration => "animationDuration",
510        enable_feedback: bool => "enableFeedback",
511        alignment: AlignmentGeometry => "alignment",
512        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
513        background_builder: ButtonLayerBuilder => "backgroundBuilder",
514        foreground_builder: ButtonLayerBuilder => "foregroundBuilder",
515    );
516
517    /// Dart `FilledButton.styleFrom(shape:)`.
518    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> FilledButtonStyleFromBuilder {
519        self.shape = Some(shape.into());
520        self
521    }
522
523    /// The [`ButtonStyle`] `FilledButton.styleFrom` returns for the arguments given.
524    pub fn build(self) -> ButtonStyle {
525        let overlay_color_prop: Option<WidgetStatePropertyRef<Option<Color>>> =
526            match (self.foreground_color, self.overlay_color) {
527                (None, None) => None,
528                (_, Some(overlay_color)) if overlay_color.a == 0.0 => {
529                    Some(Rc::new(MaterialStatePropertyAll::new(Some(overlay_color))))
530                }
531                (_, Some(color)) | (Some(color), None) => {
532                    Some(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
533                        (WidgetState::Pressed.into(), Some(color.with_opacity(0.1))),
534                        (WidgetState::Hovered.into(), Some(color.with_opacity(0.08))),
535                        (WidgetState::Focused.into(), Some(color.with_opacity(0.1))),
536                        (WidgetState::any(), None),
537                    ]))
538                }
539            };
540
541        ButtonStyle {
542            text_style: Some(Rc::new(MaterialStatePropertyAll::new(self.text_style))),
543            background_color: <dyn ButtonStyleButton>::default_color(
544                self.background_color,
545                self.disabled_background_color,
546            ),
547            foreground_color: <dyn ButtonStyleButton>::default_color(
548                self.foreground_color,
549                self.disabled_foreground_color,
550            ),
551            overlay_color: overlay_color_prop,
552            shadow_color: <dyn ButtonStyleButton>::all_or_null(self.shadow_color),
553            surface_tint_color: <dyn ButtonStyleButton>::all_or_null(self.surface_tint_color),
554            icon_color: <dyn ButtonStyleButton>::default_color(
555                self.icon_color,
556                self.disabled_icon_color,
557            ),
558            icon_size: <dyn ButtonStyleButton>::all_or_null(self.icon_size),
559            icon_alignment: self.icon_alignment,
560            elevation: <dyn ButtonStyleButton>::all_or_null(self.elevation),
561            padding: <dyn ButtonStyleButton>::all_or_null(self.padding),
562            minimum_size: <dyn ButtonStyleButton>::all_or_null(self.minimum_size),
563            fixed_size: <dyn ButtonStyleButton>::all_or_null(self.fixed_size),
564            maximum_size: <dyn ButtonStyleButton>::all_or_null(self.maximum_size),
565            side: <dyn ButtonStyleButton>::all_or_null(self.side),
566            shape: <dyn ButtonStyleButton>::all_or_null(self.shape),
567            mouse_cursor: Some(<dyn WidgetStateProperty<Option<MouseCursorRef>>>::from_map(
568                vec![
569                    (WidgetState::Disabled.into(), self.disabled_mouse_cursor),
570                    (WidgetState::any(), self.enabled_mouse_cursor),
571                ],
572            )),
573            visual_density: self.visual_density,
574            tap_target_size: self.tap_target_size,
575            animation_duration: self.animation_duration,
576            enable_feedback: self.enable_feedback,
577            alignment: self.alignment,
578            splash_factory: self.splash_factory,
579            background_builder: self.background_builder,
580            foreground_builder: self.foreground_builder,
581            size_variant: None,
582            icon_button_width: None,
583            shape_variant: None,
584        }
585    }
586}
587
588/// Dart's `_scaledPadding`: the default padding for the default font size, scaled by the
589/// ambient text scaler.
590pub(crate) fn scaled_padding(app: &mut App, context: BuildContext) -> EdgeInsetsGeometry {
591    let theme = Theme::of(app, context);
592    let default_font_size = theme
593        .text_theme
594        .label_large
595        .as_ref()
596        .and_then(|label_large| label_large.font_size)
597        .unwrap_or(14.0);
598    let effective_text_scale =
599        MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
600    let padding1x = if theme.use_material3 { 24.0 } else { 16.0 };
601    <dyn ButtonStyleButton>::scaled_padding(
602        EdgeInsetsGeometry::symmetric(0.0, padding1x),
603        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0),
604        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0 / 2.0),
605        effective_text_scale,
606    )
607}
608
609/// Dart's private `_FilledButtonWithIconChild`.
610#[derive(Debug)]
611struct FilledButtonWithIconChild {
612    label: WidgetRef,
613    icon: WidgetRef,
614    button_style: Option<ButtonStyle>,
615    icon_alignment: Option<IconAlignment>,
616}
617
618impl StatelessWidget for FilledButtonWithIconChild {
619    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
620        let default_font_size = self
621            .button_style
622            .as_ref()
623            .and_then(|style| style.text_style.as_ref())
624            .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
625            .and_then(|text_style| text_style.font_size)
626            .unwrap_or(14.0);
627        let scale = clamp_double(
628            MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0,
629            1.0,
630            2.0,
631        ) - 1.0;
632
633        let filled_button_theme = FilledButtonTheme::of(app, context);
634        let effective_icon_alignment = self
635            .icon_alignment
636            .or_else(|| {
637                filled_button_theme
638                    .style
639                    .as_ref()
640                    .and_then(|style| style.icon_alignment)
641            })
642            .or_else(|| {
643                self.button_style
644                    .as_ref()
645                    .and_then(|style| style.icon_alignment)
646            })
647            .unwrap_or(IconAlignment::Start);
648        Row::new()
649            .main_axis_size(MainAxisSize::Min)
650            .spacing(lerp_double(Some(8.0), Some(4.0), scale).expect("both ends"))
651            .children(if effective_icon_alignment == IconAlignment::Start {
652                vec![
653                    self.icon.clone(),
654                    Flexible::new(self.label.clone()).into_widget(),
655                ]
656            } else {
657                vec![
658                    Flexible::new(self.label.clone()).into_widget(),
659                    self.icon.clone(),
660                ]
661            })
662            .into_widget()
663    }
664}
665
666/// Dart's `FilledButton.icon(..)` and `FilledButton.tonalIcon(..)` arguments; the value
667/// converts to the [`FilledButton`].
668pub struct FilledButtonIcon {
669    button_style_button: ButtonStyleButtonData,
670    variant: FilledButtonVariant,
671    icon: Option<WidgetRef>,
672    label: WidgetRef,
673    icon_alignment: Option<IconAlignment>,
674}
675
676impl FilledButtonIcon {
677    /// The arguments of the constructor of `variant`, before its setters.
678    fn new(
679        variant: FilledButtonVariant,
680        on_pressed: Option<Listener>,
681        label: WidgetRef,
682    ) -> FilledButtonIcon {
683        let mut button_style_button = ButtonStyleButtonData::new(on_pressed, None);
684        button_style_button.clip_behavior = Some(Clip::None);
685        FilledButtonIcon {
686            button_style_button,
687            variant,
688            icon: None,
689            label,
690            icon_alignment: None,
691        }
692    }
693
694    crate::button_style_button_setters!(
695        FilledButtonIcon;
696        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
697        clip_behavior, states_controller,
698    );
699
700    /// Dart `FilledButton.icon(icon:)` and `FilledButton.tonalIcon(icon:)`.
701    #[cfg_attr(debug_assertions, track_caller)]
702    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> FilledButtonIcon {
703        self.icon = Some(icon.into_widget());
704        self
705    }
706
707    /// Dart `FilledButton.icon(iconAlignment:)` and `FilledButton.tonalIcon(iconAlignment:)`.
708    pub fn icon_alignment(mut self, icon_alignment: IconAlignment) -> FilledButtonIcon {
709        self.icon_alignment = Some(icon_alignment);
710        self
711    }
712
713    /// The [`FilledButton`] these arguments describe.
714    #[cfg_attr(debug_assertions, track_caller)]
715    pub fn build(self) -> FilledButton {
716        let mut button_style_button = self.button_style_button;
717        let add_padding = self.icon.is_some();
718        button_style_button.child = Some(match self.icon {
719            Some(icon) => FilledButtonWithIconChild {
720                label: self.label,
721                icon,
722                button_style: button_style_button.style.clone(),
723                icon_alignment: self.icon_alignment,
724            }
725            .into_widget(),
726            None => self.label,
727        });
728        FilledButton {
729            button_style_button,
730            variant: self.variant,
731            add_padding,
732        }
733    }
734}
735
736impl IntoWidget<StatefulKind> for FilledButtonIcon {
737    #[cfg_attr(debug_assertions, track_caller)]
738    fn into_widget(self) -> WidgetRef {
739        self.build().into_widget()
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use std::cell::{Cell, RefCell};
746    use waft_widgets::Text;
747    use waft_widgets::testing::assert_f32_equals;
748
749    use waft_embedder::{FontWeight, Offset, Rect, TextDirection};
750    use waft_embedder::{PointerChange, RRect, Radius};
751    use waft_foundation::{K_IS_WEB, Listenable};
752    use waft_painting::{Alignment, StadiumBorder};
753    use waft_painting::{BorderRadius, RoundedRectangleBorder};
754    use waft_rendering::{RenderPhysicalModelBase, RenderPhysicalShape};
755    use waft_services::{SystemMouseCursor, SystemMouseCursors};
756    use waft_widgets::{
757        Align, AnyElement, Builder, Center, Column, Directionality, FocusNode, GlobalKey, Icon,
758        IconData, IconTheme, MouseRegion, Padding, SizedBox, downcast_widget,
759    };
760
761    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
762
763    use super::*;
764    use crate::color_scheme::ColorScheme;
765    use crate::filled_button_theme::FilledButtonThemeData;
766    use crate::icons::Icons;
767    use crate::ink_well::InkWell;
768    use crate::material::{Material, MaterialType};
769    use crate::material_state::MaterialStatesController;
770    use crate::test_support::{PaintInspection, material_app};
771    use crate::theme_data::ThemeData;
772    use waft_rendering::testing::RecordedCall;
773    use waft_widgets::FocusNodeRef;
774
775    fn pressed() -> Listener {
776        Listener::new(|_app| {})
777    }
778
779    fn text(text: &str) -> WidgetRef {
780        Text::new(text).into_widget()
781    }
782
783    fn icon() -> WidgetRef {
784        Icon::new(Some(Icons::add())).into_widget()
785    }
786
787    fn states(states: &[WidgetState]) -> WidgetStates {
788        states.iter().copied().collect()
789    }
790
791    fn is_inside<W: 'static>(tester: &WidgetTester, element: AnyElement) -> bool {
792        let ancestors = tester.ancestors(element);
793        let app = tester.cell.borrow();
794        ancestors
795            .into_iter()
796            .any(|ancestor| downcast_widget::<W>(&**ancestor.widget(&app)).is_some())
797    }
798
799    /// The first `W` below a `FilledButton`.
800    fn in_button<W: 'static>(tester: &WidgetTester) -> AnyElement {
801        find::by_type::<W>()
802            .evaluate(tester)
803            .into_iter()
804            .find(|element| is_inside::<FilledButton>(tester, *element))
805            .expect("a descendant of the button")
806    }
807
808    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
809        tester.widget::<Material, R>(in_button::<Material>(tester), read)
810    }
811
812    fn text_color(material: &Material) -> Option<Color> {
813        material
814            .text_style
815            .as_ref()
816            .and_then(|text_style| text_style.color.as_ref())
817            .map(|color| color.color())
818    }
819
820    fn padding(tester: &WidgetTester) -> EdgeInsetsGeometry {
821        tester.widget::<Padding, _>(in_button::<Padding>(tester), |padding| padding.padding)
822    }
823
824    fn material_rect(tester: &WidgetTester) -> Rect {
825        tester.get_rect(in_button::<Material>(tester))
826    }
827
828    fn icon_rect(tester: &WidgetTester) -> Rect {
829        tester.get_rect(find::by_type::<Icon>().evaluate(tester)[0])
830    }
831
832    fn button_center(tester: &WidgetTester) -> Offset {
833        tester.get_center(find::by_type::<FilledButton>().evaluate(tester)[0])
834    }
835
836    fn physical_elevation(tester: &WidgetTester) -> f64 {
837        let shape = tester.first::<RenderPhysicalShape>();
838        shape.elevation(&tester.cell.borrow())
839    }
840
841    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
842        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
843    }
844
845    fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
846        tester
847            .ink_calls()
848            .into_iter()
849            .filter_map(|drawn| match drawn {
850                RecordedCall::Rect { color, .. } => Some(color.value()),
851                _ => None,
852            })
853            .collect()
854    }
855
856    fn check_defaults(tester: &WidgetTester, color: Color, foreground: Color, elevation: f64) {
857        material(tester, |material| {
858            assert_eq!(material.animation_duration, Duration::from_millis(200));
859            assert!(!material.border_on_foreground);
860            assert!(material.border_radius.is_none());
861            assert_eq!(material.clip_behavior, Clip::None);
862            assert_eq!(material.color, Some(color));
863            assert_eq!(material.elevation, elevation);
864            assert_eq!(material.shadow_color, Some(Color::new(0xff000000)));
865            assert!(
866                material
867                    .shape
868                    .as_ref()
869                    .expect("a shape")
870                    .eq_shape(&StadiumBorder::default())
871            );
872            assert_eq!(text_color(material), Some(foreground));
873            let text_style = material.text_style.as_ref().expect("a text style");
874            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
875            assert_eq!(text_style.font_size, Some(14.0));
876            assert_eq!(text_style.font_weight, Some(FontWeight::W500));
877            assert_eq!(material.r#type, MaterialType::Button);
878        });
879    }
880
881    // filled_button_test.dart 'FilledButton, FilledButton.icon defaults' and
882    // 'FilledButton.tonal, FilledButton.tonalIcon defaults'.
883    #[test]
884    fn the_defaults_of_a_filled_and_a_tonal_button_and_their_icon_variants() {
885        test_widgets(|tester| {
886            let color_scheme = ColorScheme::light();
887            for tonal in [false, true] {
888                let theme = ThemeData::from(color_scheme.clone())
889                    .use_material3(tonal)
890                    .build(&tester.cell.borrow());
891                let (color, foreground) = if tonal {
892                    (
893                        color_scheme.secondary_container(),
894                        color_scheme.on_secondary_container(),
895                    )
896                } else {
897                    (color_scheme.primary(), color_scheme.on_primary())
898                };
899                let plain = |child: WidgetRef, on_pressed: Option<Listener>| {
900                    if tonal {
901                        FilledButton::tonal(on_pressed, Some(child))
902                    } else {
903                        FilledButton::new(on_pressed, Some(child))
904                    }
905                };
906
907                // Enabled FilledButton
908                tester.pump_widget(material_app(
909                    theme.clone(),
910                    Center::new()
911                        .child(plain(text("button"), Some(pressed())))
912                        .into_widget(),
913                ));
914                check_defaults(tester, color, foreground, 0.0);
915                tester.widget::<Align, _>(in_button::<Align>(tester), |align| {
916                    assert!(align.alignment == AlignmentGeometry::from(Alignment::CENTER));
917                });
918
919                let center = button_center(tester);
920                let mut gesture = TestPointer::touch(1);
921                tester.down(&mut gesture, center);
922                tester.pump(); // start the splash animation
923                tester.pump_by(Duration::from_millis(100)); // splash is underway
924                check_defaults(tester, color, foreground, 0.0);
925                tester.up(&gesture);
926                tester.pump_and_settle();
927
928                // Enabled FilledButton.icon
929                let with_icon = if tonal {
930                    FilledButton::tonal_icon(Some(pressed()), text("label")).icon(icon())
931                } else {
932                    FilledButton::icon(Some(pressed()), text("label")).icon(icon())
933                };
934                tester.pump_widget(material_app(
935                    theme.clone(),
936                    Center::new().child(with_icon).into_widget(),
937                ));
938                check_defaults(tester, color, foreground, 0.0);
939
940                // Disabled FilledButton
941                tester.pump_widget(material_app(
942                    theme,
943                    Center::new()
944                        .child(plain(text("button"), None))
945                        .into_widget(),
946                ));
947                // Finish the elevation animation, final background color change.
948                tester.pump_and_settle();
949                check_defaults(
950                    tester,
951                    color_scheme.on_surface().with_opacity(0.12),
952                    color_scheme.on_surface().with_opacity(0.38),
953                    0.0,
954                );
955            }
956        });
957    }
958
959    fn captured_default_style(
960        tester: &mut WidgetTester,
961        theme: ThemeData,
962        button: FilledButton,
963    ) -> ButtonStyle {
964        let style = Rc::new(RefCell::new(None));
965        let button = Rc::new(button);
966        let home = Builder::new({
967            let style = Rc::clone(&style);
968            let button = Rc::clone(&button);
969            move |app, context| {
970                *style.borrow_mut() = Some(button.default_style_of(app, context).copy_with(app));
971                SizedBox::shrink().into_widget()
972            }
973        });
974        tester.pump_widget(material_app(theme, home.into_widget()));
975        style.borrow_mut().take().expect("built")
976    }
977
978    // filled_button_test.dart 'FilledButton.defaultStyle produces a ButtonStyle with
979    // appropriate non-null values' and its 'with an icon' twin.
980    #[test]
981    fn the_default_style_fills_every_property_but_the_overriding_ones() {
982        test_widgets(|tester| {
983            let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
984            for button in [
985                FilledButton::new(Some(pressed()), Some(text("button"))),
986                FilledButton::icon(Some(pressed()), text("button"))
987                    .icon(SizedBox::new())
988                    .build(),
989            ] {
990                let style = captured_default_style(tester, theme.clone(), button);
991                // Properties that must be non-null.
992                assert!(style.text_style.is_some(), "textStyle style");
993                assert!(style.background_color.is_some(), "backgroundColor style");
994                assert!(style.foreground_color.is_some(), "foregroundColor style");
995                assert!(style.overlay_color.is_some(), "overlayColor style");
996                assert!(style.shadow_color.is_some(), "shadowColor style");
997                assert!(style.surface_tint_color.is_some(), "surfaceTintColor style");
998                assert!(style.elevation.is_some(), "elevation style");
999                assert!(style.padding.is_some(), "padding style");
1000                assert!(style.minimum_size.is_some(), "minimumSize style");
1001                assert!(style.maximum_size.is_some(), "maximumSize style");
1002                assert!(style.icon_color.is_some(), "iconColor style");
1003                assert!(style.icon_size.is_some(), "iconSize style");
1004                assert!(style.shape.is_some(), "shape style");
1005                assert!(style.mouse_cursor.is_some(), "mouseCursor style");
1006                assert!(style.visual_density.is_some(), "visualDensity style");
1007                assert!(style.tap_target_size.is_some(), "tapTargetSize style");
1008                assert!(
1009                    style.animation_duration.is_some(),
1010                    "animationDuration style"
1011                );
1012                assert!(style.enable_feedback.is_some(), "enableFeedback style");
1013                assert!(style.alignment.is_some(), "alignment style");
1014                assert!(style.splash_factory.is_some(), "splashFactory style");
1015
1016                // Properties that are expected to be null.
1017                assert!(style.fixed_size.is_none(), "fixedSize style");
1018                assert!(style.side.is_none(), "side style");
1019                assert!(
1020                    style.background_builder.is_none(),
1021                    "backgroundBuilder style"
1022                );
1023                assert!(
1024                    style.foreground_builder.is_none(),
1025                    "foregroundBuilder style"
1026                );
1027            }
1028        });
1029    }
1030
1031    // filled_button_test.dart 'FilledButton.icon produces the correct widgets if icon is null'
1032    // and 'FilledButton.tonalIcon produces the correct widgets if icon is null'.
1033    #[test]
1034    fn an_icon_button_without_an_icon_shows_only_its_label() {
1035        test_widgets(|tester| {
1036            for tonal in [false, true] {
1037                let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
1038                let label_key = GlobalKey::new();
1039                let build = |icon: Option<WidgetRef>| {
1040                    let label = SizedBox::new()
1041                        .width(70.0)
1042                        .height(14.0)
1043                        .key(label_key.clone().into());
1044                    let button = if tonal {
1045                        FilledButton::tonal_icon(Some(pressed()), label)
1046                    } else {
1047                        FilledButton::icon(Some(pressed()), label)
1048                    };
1049                    match icon {
1050                        Some(icon) => button.icon(icon),
1051                        None => button,
1052                    }
1053                };
1054                tester.pump_widget(material_app(
1055                    theme.clone(),
1056                    Center::new().child(build(Some(icon()))).into_widget(),
1057                ));
1058                assert_eq!(find::by_type::<Icon>().evaluate(tester).len(), 1);
1059                assert!(
1060                    label_key
1061                        .current_context(&tester.cell.borrow_mut())
1062                        .is_some()
1063                );
1064
1065                tester.pump_widget(material_app(
1066                    theme,
1067                    // No icon specified.
1068                    Center::new().child(build(None)).into_widget(),
1069                ));
1070                assert!(find::by_type::<Icon>().evaluate(tester).is_empty());
1071                assert!(
1072                    label_key
1073                        .current_context(&tester.cell.borrow_mut())
1074                        .is_some()
1075                );
1076            }
1077        });
1078    }
1079
1080    // filled_button_test.dart 'FilledButton default overlayColor and elevation resolve pressed
1081    // state' and 'FilledButton.tonal default overlayColor and elevation resolve pressed state'.
1082    #[test]
1083    fn the_default_overlay_color_and_elevation_follow_hover_press_and_focus() {
1084        for tonal in [false, true] {
1085            test_widgets(|tester| {
1086                let focus_node = focus_node(tester);
1087                let theme = ThemeData::new(&tester.cell.borrow());
1088                let overlay = if tonal {
1089                    theme.color_scheme.on_secondary_container()
1090                } else {
1091                    theme.color_scheme.on_primary()
1092                };
1093                let button = if tonal {
1094                    FilledButton::tonal(Some(pressed()), Some(text("FilledButton")))
1095                } else {
1096                    FilledButton::new(Some(pressed()), Some(text("FilledButton")))
1097                };
1098                tester.pump_widget(material_app(
1099                    theme,
1100                    Center::new()
1101                        .child(button.focus_node(focus_node.clone()))
1102                        .into_widget(),
1103                ));
1104
1105                // Hovered.
1106                let center = button_center(tester);
1107                let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1108                tester.add_pointer(&mut gesture, Offset::ZERO);
1109                tester.move_to(&mut gesture, center, false);
1110                tester.pump_and_settle();
1111                assert_eq!(physical_elevation(tester), 1.0);
1112                assert_eq!(
1113                    ink_rect_colors(tester),
1114                    vec![overlay.with_opacity(0.08).value()]
1115                );
1116
1117                // Highlighted (pressed).
1118                tester.send(&gesture, waft_embedder::PointerChange::Down);
1119                tester.pump_and_settle();
1120                assert_eq!(physical_elevation(tester), 0.0);
1121                assert_eq!(
1122                    ink_rect_colors(tester)[1],
1123                    overlay.with_opacity(0.1).value()
1124                );
1125                // Remove pressed and hovered states
1126                tester.up(&gesture);
1127                tester.pump_and_settle();
1128                tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
1129                tester.pump_and_settle();
1130
1131                // Focused.
1132                focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1133                tester.pump_and_settle();
1134                assert_eq!(physical_elevation(tester), 0.0);
1135                assert_eq!(
1136                    ink_rect_colors(tester),
1137                    vec![overlay.with_opacity(0.1).value()]
1138                );
1139            });
1140        }
1141    }
1142
1143    // filled_button_test.dart 'FilledButton onPressed and onLongPress callbacks are correctly
1144    // called when non-null'.
1145    #[test]
1146    fn either_callback_enables_the_button_and_reaches_it() {
1147        test_widgets(|tester| {
1148            let was_pressed = Rc::new(Cell::new(0));
1149            let count = || {
1150                let was_pressed = Rc::clone(&was_pressed);
1151                Listener::new(move |_app| was_pressed.set(was_pressed.get() + 1))
1152            };
1153            let build_frame = |on_pressed: Option<Listener>, on_long_press: Option<Listener>| {
1154                let mut button = FilledButton::new(on_pressed, Some(text("button")));
1155                if let Some(on_long_press) = on_long_press {
1156                    button = button.on_long_press(on_long_press);
1157                }
1158                Directionality::new(TextDirection::Ltr, button).into_widget()
1159            };
1160            let enabled = |tester: &WidgetTester| {
1161                let button = find::by_type::<FilledButton>().evaluate(tester)[0];
1162                tester.widget::<FilledButton, _>(button, |button| button.enabled())
1163            };
1164
1165            // onPressed not null, onLongPress null.
1166            tester.pump_widget(build_frame(Some(count()), None));
1167            assert!(enabled(tester));
1168            tester.tap_at(button_center(tester), 1);
1169            assert_eq!(was_pressed.get(), 1);
1170
1171            // onPressed null, onLongPress not null.
1172            tester.pump_widget(build_frame(None, Some(count())));
1173            assert!(enabled(tester));
1174            tester.long_press_at(button_center(tester), 2);
1175            assert_eq!(was_pressed.get(), 2);
1176
1177            // onPressed null, onLongPress null.
1178            tester.pump_widget(build_frame(None, None));
1179            assert!(!enabled(tester));
1180        });
1181    }
1182
1183    // filled_button_test.dart 'Default FilledButton padding for textScaleFactor,
1184    // textDirection'.
1185    #[test]
1186    fn the_material_2_padding_and_icon_gap_scale_with_the_text() {
1187        test_widgets(|tester| {
1188            let text_scale_factor_options = [0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0];
1189            // Expected values for each textScaleFactor.
1190            let padding_without_icon_start = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1191            let padding_without_icon_end = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1192            let padding_with_icon_start = [12.0, 12.0, 11.0, 10.0, 8.0, 8.0, 8.0, 8.0];
1193            let padding_with_icon_end = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1194            let padding_with_icon_gap = [8.0, 8.0, 7.0, 6.0, 4.0, 4.0, 4.0, 4.0];
1195            for (index, text_scale_factor) in text_scale_factor_options.into_iter().enumerate() {
1196                for text_direction in [TextDirection::Ltr, TextDirection::Rtl] {
1197                    for with_icon in [false, true] {
1198                        let button_key = GlobalKey::new();
1199                        let label_key = GlobalKey::new();
1200                        let icon_key = GlobalKey::new();
1201                        let theme = ThemeData::builder()
1202                            .use_material3(false)
1203                            .filled_button_theme(
1204                                FilledButtonThemeData::new().style(
1205                                    FilledButton::style_from()
1206                                        .minimum_size(Size::new(64.0, 36.0))
1207                                        .build(),
1208                                ),
1209                            )
1210                            .build(&tester.cell.borrow());
1211                        let label = Text::new("button").key(label_key.clone().into());
1212                        let button = if with_icon {
1213                            FilledButton::icon(Some(pressed()), label)
1214                                .key(button_key.clone().into())
1215                                .icon(
1216                                    Icon::new(Some(Icons::add()))
1217                                        .size(18.0)
1218                                        .key(icon_key.clone().into()),
1219                                )
1220                                .build()
1221                        } else {
1222                            FilledButton::new(Some(pressed()), Some(label))
1223                                .key(button_key.clone().into())
1224                        };
1225                        // Dart's `Scaffold(body:)` is the `Material` the text sits on.
1226                        tester.pump_widget(material_app(
1227                            theme,
1228                            MediaQuery::with_clamped_text_scaling(
1229                                None,
1230                                text_scale_factor,
1231                                text_scale_factor,
1232                                Directionality::new(
1233                                    text_direction,
1234                                    Material::new().child(Center::new().child(button)),
1235                                ),
1236                            ),
1237                        ));
1238
1239                        let padding_element = in_button::<Padding>(tester);
1240                        assert_eq!(
1241                            Directionality::of(&mut tester.cell.borrow_mut(), padding_element),
1242                            text_direction
1243                        );
1244
1245                        // Compute expected padding, and check.
1246                        let (expected_start, expected_end) = if with_icon {
1247                            (padding_with_icon_start[index], padding_with_icon_end[index])
1248                        } else {
1249                            (
1250                                padding_without_icon_start[index],
1251                                padding_without_icon_end[index],
1252                            )
1253                        };
1254                        let expected_padding =
1255                            EdgeInsetsGeometry::from_steb(expected_start, 0.0, expected_end, 0.0)
1256                                .resolve(Some(text_direction));
1257                        assert_eq!(
1258                            padding(tester).resolve(Some(text_direction)),
1259                            expected_padding,
1260                            "text scale {text_scale_factor}, icon {with_icon}, {text_direction:?}"
1261                        );
1262
1263                        // Measure padding in terms of the difference between the button and
1264                        // its label child and check that.
1265                        let label_bounds = tester.get_rect(&label_key);
1266                        let icon_bounds = with_icon.then(|| tester.get_rect(&icon_key));
1267                        let child_bounds = match icon_bounds {
1268                            Some(icon_bounds) => label_bounds.expand_to_include(icon_bounds),
1269                            None => label_bounds,
1270                        };
1271
1272                        // We measure the `InkResponse` descendant of the button element,
1273                        // because the button has a larger `RenderBox` which accommodates the
1274                        // minimum tap target with a height of 48.
1275                        let button_bounds = tester.get_rect(in_button::<InkWell>(tester));
1276
1277                        // Since there is a requirement of a minimum width of 64 and a minimum
1278                        // height of 36 on material buttons, the visual padding of smaller
1279                        // buttons may not match their settings. Therefore, we only test
1280                        // buttons that are large enough.
1281                        if button_bounds.width() > 64.0 {
1282                            assert_eq!(
1283                                child_bounds.left - button_bounds.left,
1284                                expected_padding.left
1285                            );
1286                            assert_eq!(
1287                                button_bounds.right - child_bounds.right,
1288                                expected_padding.right
1289                            );
1290                        }
1291                        if button_bounds.height() > 36.0 {
1292                            assert_eq!(child_bounds.top - button_bounds.top, expected_padding.top);
1293                            assert_eq!(
1294                                button_bounds.bottom - child_bounds.bottom,
1295                                expected_padding.bottom
1296                            );
1297                        }
1298
1299                        // Check the gap between the icon and the label
1300                        if let Some(icon_bounds) = icon_bounds {
1301                            let gap_width = if text_direction == TextDirection::Ltr {
1302                                label_bounds.left - icon_bounds.right
1303                            } else {
1304                                icon_bounds.left - label_bounds.right
1305                            };
1306                            assert_eq!(gap_width, padding_with_icon_gap[index]);
1307                        }
1308                    }
1309                }
1310            }
1311        });
1312    }
1313
1314    // filled_button_test.dart 'Override FilledButton default padding', 'Override theme
1315    // fontSize changes padding', 'M3 FilledButton has correct padding' and 'M3
1316    // FilledButton.icon has correct padding'.
1317    #[test]
1318    fn the_material_3_padding_follows_the_style_the_font_size_and_the_icon() {
1319        test_widgets(|tester| {
1320            let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
1321            tester.pump_widget(material_app(
1322                theme.clone(),
1323                MediaQuery::with_clamped_text_scaling(
1324                    None,
1325                    2.0,
1326                    2.0,
1327                    Center::new().child(
1328                        FilledButton::new(Some(pressed()), Some(text("FilledButton"))).style(
1329                            FilledButton::style_from()
1330                                .padding(EdgeInsetsGeometry::all(22.0))
1331                                .build(),
1332                        ),
1333                    ),
1334                ),
1335            ));
1336            tester.pump_and_settle();
1337            assert!(padding(tester) == EdgeInsetsGeometry::all(22.0));
1338
1339            let mut text_theme = crate::text_theme::TextTheme::new();
1340            text_theme.label_large = Some(TextStyle::new().font_size(28.0));
1341            let large = ThemeData::from(ColorScheme::light())
1342                .text_theme(text_theme)
1343                .build(&tester.cell.borrow());
1344            tester.pump_widget(material_app(
1345                large,
1346                Center::new()
1347                    .child(FilledButton::new(Some(pressed()), Some(text("text"))))
1348                    .into_widget(),
1349            ));
1350            tester.pump_and_settle();
1351            assert!(padding(tester) == EdgeInsetsGeometry::symmetric(0.0, 12.0));
1352
1353            tester.pump_widget(material_app(
1354                theme.clone(),
1355                Center::new()
1356                    .child(FilledButton::new(
1357                        Some(pressed()),
1358                        Some(text("FilledButton")),
1359                    ))
1360                    .into_widget(),
1361            ));
1362            tester.pump_and_settle();
1363            assert!(padding(tester) == EdgeInsetsGeometry::symmetric(0.0, 24.0));
1364
1365            tester.pump_widget(material_app(
1366                theme,
1367                Center::new()
1368                    .child(FilledButton::icon(Some(pressed()), text("FilledButton")).icon(icon()))
1369                    .into_widget(),
1370            ));
1371            tester.pump_and_settle();
1372            assert!(padding(tester) == EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0));
1373        });
1374    }
1375
1376    // filled_button_test.dart 'FilledButton.icon icon,label layout'.
1377    #[test]
1378    fn an_icon_button_lays_out_icon_gap_and_label_centred() {
1379        test_widgets(|tester| {
1380            let button_key = GlobalKey::new();
1381            let icon_key = GlobalKey::new();
1382            let label_key = GlobalKey::new();
1383            let style = FilledButton::style_from()
1384                .padding(EdgeInsetsGeometry::ZERO)
1385                .visual_density(VisualDensity::STANDARD) // dx=0, dy=0
1386                .build();
1387            let theme = ThemeData::new(&tester.cell.borrow());
1388            let sized = |key: &GlobalKey| {
1389                SizedBox::new()
1390                    .width(50.0)
1391                    .height(100.0)
1392                    .key(key.clone().into())
1393                    .into_widget()
1394            };
1395            tester.pump_widget(material_app(
1396                theme,
1397                // Dart's `Scaffold(body:)` lays its body out loosely at the top left.
1398                Align::new()
1399                    .alignment(AlignmentGeometry::TOP_LEFT)
1400                    .child(
1401                        SizedBox::new().width(200.0).child(
1402                            FilledButton::icon(Some(pressed()), sized(&label_key))
1403                                .icon(sized(&icon_key))
1404                                .key(button_key.clone().into())
1405                                .style(style),
1406                        ),
1407                    )
1408                    .into_widget(),
1409            ));
1410
1411            // The button's label and icon are separated by a gap of 8:
1412            // 46 [icon 50] 8 [label 50] 46
1413            // The overall button width is 200. So:
1414            // icon.x = 46
1415            // label.x = 46 + 50 + 8 = 104
1416            let rect = |key: &GlobalKey| {
1417                let context = key
1418                    .current_context(&tester.cell.borrow_mut())
1419                    .expect("mounted");
1420                tester.get_rect(context)
1421            };
1422            assert_eq!(rect(&button_key), Rect::from_ltrb(0.0, 0.0, 200.0, 100.0));
1423            assert_eq!(rect(&icon_key), Rect::from_ltrb(46.0, 0.0, 96.0, 100.0));
1424            assert_eq!(rect(&label_key), Rect::from_ltrb(104.0, 0.0, 154.0, 100.0));
1425        });
1426    }
1427
1428    // filled_button_test.dart 'Default FilledButton icon alignment', 'FilledButton icon
1429    // alignment can be customized', 'FilledButton icon alignment respects
1430    // ButtonStyle.iconAlignment', 'FilledButton tonal button icon alignment respects
1431    // ButtonStyle.iconAlignment', 'Tonal icon default iconAlignment' and 'Tonal icon
1432    // iconAlignment can be customized'.
1433    #[test]
1434    fn the_icon_sits_at_the_start_or_end_by_its_alignment_and_the_text_direction() {
1435        test_widgets(|tester| {
1436            for tonal in [false, true] {
1437                let build = |tester: &mut WidgetTester,
1438                             text_direction: TextDirection,
1439                             icon_alignment: Option<IconAlignment>,
1440                             style_alignment: Option<IconAlignment>| {
1441                    let mut button = if tonal {
1442                        FilledButton::tonal_icon(Some(pressed()), text("button")).icon(icon())
1443                    } else {
1444                        FilledButton::icon(Some(pressed()), text("button")).icon(icon())
1445                    };
1446                    if let Some(icon_alignment) = icon_alignment {
1447                        button = button.icon_alignment(icon_alignment);
1448                    }
1449                    if let Some(style_alignment) = style_alignment {
1450                        button = button.style(ButtonStyle::new().icon_alignment(style_alignment));
1451                    }
1452                    let theme = ThemeData::new(&tester.cell.borrow());
1453                    tester.pump_widget(material_app(
1454                        theme,
1455                        Directionality::new(text_direction, Center::new().child(button))
1456                            .into_widget(),
1457                    ));
1458                };
1459                // 16.0 - padding between icon and button edge at the start, 24.0 at the end.
1460                build(tester, TextDirection::Ltr, None, None);
1461                assert_eq!(material_rect(tester).left, icon_rect(tester).left - 16.0);
1462                build(tester, TextDirection::Rtl, None, None);
1463                assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 16.0);
1464
1465                build(tester, TextDirection::Ltr, Some(IconAlignment::Start), None);
1466                assert_eq!(material_rect(tester).left, icon_rect(tester).left - 16.0);
1467                build(tester, TextDirection::Ltr, Some(IconAlignment::End), None);
1468                assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 24.0);
1469                build(tester, TextDirection::Rtl, Some(IconAlignment::Start), None);
1470                assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 16.0);
1471                build(tester, TextDirection::Rtl, Some(IconAlignment::End), None);
1472                assert_eq!(material_rect(tester).left, icon_rect(tester).left - 24.0);
1473
1474                build(tester, TextDirection::Ltr, None, Some(IconAlignment::End));
1475                assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 24.0);
1476            }
1477        });
1478    }
1479
1480    // filled_button_test.dart 'FilledButton.styleFrom can be used to set foreground and
1481    // background colors'.
1482    #[test]
1483    fn style_from_turns_each_argument_into_its_property() {
1484        test_widgets(|tester| {
1485            let red = Color::new(0xffff0000);
1486            let blue = Color::new(0xff0000ff);
1487            let none = WidgetStates::new();
1488            let disabled = states(&[WidgetState::Disabled]);
1489            let hovered = states(&[WidgetState::Hovered]);
1490            let style = FilledButton::style_from()
1491                .foreground_color(red)
1492                .background_color(blue)
1493                .icon_color(blue)
1494                .icon_size(32.0)
1495                .elevation(4.0)
1496                .build();
1497            // The elevation is the same in every state, unlike ElevatedButton's.
1498            let elevation = style.elevation.as_ref().expect("an elevation");
1499            assert_eq!(elevation.resolve(&none), Some(4.0));
1500            assert_eq!(elevation.resolve(&disabled), Some(4.0));
1501            assert_eq!(elevation.resolve(&hovered), Some(4.0));
1502            assert_eq!(
1503                style
1504                    .overlay_color
1505                    .as_ref()
1506                    .and_then(|overlay| overlay.resolve(&hovered)),
1507                Some(red.with_opacity(0.08))
1508            );
1509            assert_eq!(style.size_variant, None);
1510            assert_eq!(style.shape_variant, None);
1511
1512            let icon_seen = Rc::new(Cell::new((None, None)));
1513            let probe = Builder::new({
1514                let icon_seen = Rc::clone(&icon_seen);
1515                move |app, context| {
1516                    let icon_theme = IconTheme::of(app, context);
1517                    icon_seen.set((icon_theme.color.map(|color| color.color()), icon_theme.size));
1518                    SizedBox::new().width(18.0).height(18.0).into_widget()
1519                }
1520            });
1521            let theme = ThemeData::new(&tester.cell.borrow());
1522            tester.pump_widget(material_app(
1523                theme,
1524                Center::new()
1525                    .child(
1526                        FilledButton::icon(Some(pressed()), text("button"))
1527                            .icon(probe)
1528                            .style(style),
1529                    )
1530                    .into_widget(),
1531            ));
1532            material(tester, |material| {
1533                assert_eq!(material.color, Some(blue));
1534                assert_eq!(text_color(material), Some(red));
1535            });
1536            assert_eq!(icon_seen.get(), (Some(blue), Some(32.0)));
1537        });
1538    }
1539
1540    // filled_button_test.dart 'FilledButton.icon does not lose focus when icon is nullified'
1541    // and 'FilledButton.tonalIcon does not lose focus when icon is nullified'.
1542    #[test]
1543    fn an_icon_button_keeps_its_focus_when_its_icon_goes() {
1544        for tonal in [false, true] {
1545            test_widgets(|tester| {
1546                let focus_node = focus_node(tester);
1547                let build = |tester: &mut WidgetTester, icon: Option<WidgetRef>| {
1548                    let button = if tonal {
1549                        FilledButton::tonal_icon(Some(pressed()), text("button"))
1550                    } else {
1551                        FilledButton::icon(Some(pressed()), text("button"))
1552                    };
1553                    let button = match icon {
1554                        Some(icon) => button.icon(icon),
1555                        None => button,
1556                    };
1557                    let theme = ThemeData::new(&tester.cell.borrow());
1558                    tester.pump_widget(material_app(
1559                        theme,
1560                        Center::new()
1561                            .child(button.focus_node(focus_node.clone()).autofocus(true))
1562                            .into_widget(),
1563                    ));
1564                };
1565                build(tester, Some(self::icon()));
1566                tester.pump_and_settle();
1567                assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
1568                build(tester, None);
1569                tester.pump_and_settle();
1570                assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
1571            });
1572        }
1573    }
1574
1575    // Dart's `super.clipBehavior = Clip.none` on every FilledButton constructor: with a layer
1576    // builder, which makes a button without a clip behavior clip, the button still does not.
1577    #[test]
1578    fn every_filled_constructor_defaults_to_no_clip() {
1579        let builder =
1580            crate::button_style::ButtonLayerBuilder::new(|_app, _context, _states, child| {
1581                child.expect("a child")
1582            });
1583        for button in [
1584            FilledButton::new(Some(pressed()), Some(text("a"))),
1585            FilledButton::icon(Some(pressed()), text("a"))
1586                .icon(icon())
1587                .build(),
1588            FilledButton::tonal(Some(pressed()), Some(text("a"))),
1589            FilledButton::tonal_icon(Some(pressed()), text("a"))
1590                .icon(icon())
1591                .build(),
1592        ] {
1593            let button = button.style(ButtonStyle::new().background_builder(builder.clone()));
1594            assert_eq!(button.button_style_button.clip_behavior, Some(Clip::None));
1595        }
1596    }
1597
1598    /// The colour of the glyph of the `Icon` showing `icon`.
1599    fn glyph_color(tester: &WidgetTester, icon: &IconData) -> Option<Color> {
1600        tester
1601            .glyph_style(tester.element(find::by_icon(icon).first()))
1602            .color
1603            .map(|color| color.color())
1604    }
1605
1606    // filled_button_test.dart 'FilledButton.icon responds to applied padding'.
1607    #[test]
1608    fn an_icon_button_puts_its_padding_around_the_icon_and_label() {
1609        test_widgets(|tester| {
1610            let label_key = GlobalKey::new();
1611            tester.pump_widget(
1612                // When textDirection is set to TextDirection.ltr, the label appears on the
1613                // right side of the icon. This is important in determining whether the
1614                // horizontal padding is applied correctly later on
1615                Directionality::new(
1616                    TextDirection::Ltr,
1617                    Center::new().child(
1618                        FilledButton::icon(
1619                            Some(pressed()),
1620                            // 'Hello' at the label style's 14 pixels and 1.43 line height, whose line
1621                            // is 20 pixels high.
1622                            SizedBox::new()
1623                                .width(70.0)
1624                                .height(20.0)
1625                                .key(label_key.clone().into()),
1626                        )
1627                        .style(
1628                            ButtonStyle::new().padding(Rc::new(MaterialStatePropertyAll::new(
1629                                Some(EdgeInsetsGeometry::from_ltrb(16.0, 5.0, 10.0, 12.0)),
1630                            ))),
1631                        )
1632                        .icon(icon()),
1633                    ),
1634                )
1635                .into_widget(),
1636            );
1637
1638            let padding_rect = tester.get_rect(in_button::<Padding>(tester));
1639            let label = label_key
1640                .current_context(&tester.cell.borrow_mut())
1641                .expect("mounted");
1642            let label_rect = tester.get_rect(label);
1643            let icon_rect = icon_rect(tester);
1644
1645            // The right padding should be applied on the right of the label, whereas the
1646            // left padding should be applied on the left side of the icon.
1647            assert_eq!(padding_rect.right, label_rect.right + 10.0);
1648            assert_eq!(padding_rect.left, icon_rect.left - 16.0);
1649            // Use the taller widget to check the top and bottom padding.
1650            let taller_widget = if icon_rect.height() > label_rect.height() {
1651                icon_rect
1652            } else {
1653                label_rect
1654            };
1655            assert_eq!(padding_rect.top, taller_widget.top - 6.5);
1656            assert_eq!(padding_rect.bottom, taller_widget.bottom + 13.5);
1657        });
1658    }
1659
1660    // filled_button_test.dart 'By default, FilledButton shape outline is defined by
1661    // shape.side'.
1662    #[test]
1663    fn by_default_the_shape_side_is_the_outline() {
1664        test_widgets(|tester| {
1665            let border_color = Color::new(0xff4caf50);
1666            let theme = ThemeData::builder()
1667                .use_material3(false)
1668                .build(&tester.cell.borrow());
1669            tester.pump_widget(material_app(
1670                theme,
1671                Center::new()
1672                    .child(
1673                        FilledButton::new(Some(pressed()), Some(text("button"))).style(
1674                            FilledButton::style_from()
1675                                .shape(RoundedRectangleBorder::new(
1676                                    BorderSide {
1677                                        width: 10.0,
1678                                        color: border_color,
1679                                        ..BorderSide::default()
1680                                    },
1681                                    BorderRadius::all(Radius::circular(16.0)).into(),
1682                                ))
1683                                .minimum_size(Size::new(64.0, 36.0))
1684                                .build(),
1685                        ),
1686                    )
1687                    .into_widget(),
1688            ));
1689
1690            let button = tester.render_object(find::by_type::<FilledButton>().evaluate(tester)[0]);
1691            waft_rendering::testing::assert_paints(
1692                &tester.painted_ops(button),
1693                &[waft_rendering::testing::PaintCall::drrect_between(
1694                    // Outer and inner rect that give the outline a width of 10.
1695                    RRect::from_ltrbr(0.0, 0.0, 116.0, 36.0, Radius::circular(16.0)),
1696                    RRect::from_ltrbr(10.0, 10.0, 106.0, 26.0, Radius::circular(16.0 - 10.0)),
1697                    Some(border_color),
1698                )],
1699            );
1700        });
1701    }
1702
1703    // filled_button_test.dart 'FilledButton changes mouse cursor when hovered'.
1704    #[test]
1705    fn style_from_cursors_show_while_hovered_and_the_default_is_basic() {
1706        test_widgets(|tester| {
1707            let frame = |on_pressed: Option<Listener>, custom: bool| {
1708                let mut button = FilledButton::new(on_pressed, Some(text("button")));
1709                if custom {
1710                    button = button.style(
1711                        FilledButton::style_from()
1712                            .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
1713                            .disabled_mouse_cursor(SystemMouseCursors::GRAB.into())
1714                            .build(),
1715                    );
1716                }
1717                Directionality::new(
1718                    TextDirection::Ltr,
1719                    MouseRegion::new()
1720                        .cursor(SystemMouseCursors::FORBIDDEN.into())
1721                        .child(button),
1722                )
1723                .into_widget()
1724            };
1725            let is = |tester: &WidgetTester, cursor: SystemMouseCursor| {
1726                tester.active_cursor(1) == MouseCursorRef::from(cursor)
1727            };
1728
1729            tester.pump_widget(frame(Some(pressed()), true));
1730            let mut gesture = TestPointer::mouse(1, 0);
1731            tester.add_pointer(&mut gesture, Offset::ZERO);
1732            tester.pump();
1733            assert!(is(tester, SystemMouseCursors::TEXT));
1734
1735            // Test cursor when disabled
1736            tester.pump_widget(frame(None, true));
1737            assert!(is(tester, SystemMouseCursors::GRAB));
1738
1739            // Test default cursor
1740            tester.pump_widget(frame(Some(pressed()), false));
1741            assert!(is(
1742                tester,
1743                if K_IS_WEB {
1744                    SystemMouseCursors::CLICK
1745                } else {
1746                    SystemMouseCursors::BASIC
1747                }
1748            ));
1749
1750            // Test default cursor when disabled
1751            tester.pump_widget(frame(None, false));
1752            assert!(is(tester, SystemMouseCursors::BASIC));
1753        });
1754    }
1755
1756    // filled_button_test.dart 'FilledButton.icon statesController'; the plain button's case is
1757    // button_style_button.rs's.
1758    #[test]
1759    fn an_icon_buttons_states_controller_follows_hover_press_and_disable() {
1760        test_widgets(|tester| {
1761            let count = Rc::new(Cell::new(0));
1762            let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
1763            controller.add_listener(&mut tester.cell.borrow_mut(), {
1764                let count = Rc::clone(&count);
1765                Listener::new(move |_app| count.set(count.get() + 1))
1766            });
1767            let label_key = GlobalKey::new();
1768            let frame = |tester: &WidgetTester, enabled: bool| {
1769                let theme = ThemeData::new(&tester.cell.borrow());
1770                material_app(
1771                    theme,
1772                    Center::new()
1773                        .child(
1774                            FilledButton::icon(
1775                                enabled.then(pressed),
1776                                Text::new("button").key(label_key.clone().into()),
1777                            )
1778                            .states_controller(controller.clone())
1779                            .icon(icon()),
1780                        )
1781                        .into_widget(),
1782                )
1783            };
1784            let value =
1785                |tester: &WidgetTester| tester.cell.borrow().get(&controller).value().clone();
1786
1787            let first = frame(tester, true);
1788            tester.pump_widget(first);
1789            assert_eq!(value(tester), states(&[]));
1790            assert_eq!(count.get(), 0);
1791
1792            let center = tester.get_center(&label_key);
1793            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1794            tester.add_pointer(&mut gesture, Offset::ZERO);
1795            tester.move_to(&mut gesture, center, false);
1796            tester.pump_and_settle();
1797            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
1798            assert_eq!(count.get(), 1);
1799
1800            tester.move_to(&mut gesture, Offset::ZERO, false);
1801            tester.pump_and_settle();
1802            assert_eq!(value(tester), states(&[]));
1803            assert_eq!(count.get(), 2);
1804
1805            tester.move_to(&mut gesture, center, false);
1806            tester.pump_and_settle();
1807            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
1808            assert_eq!(count.get(), 3);
1809
1810            tester.send(&gesture, PointerChange::Down);
1811            tester.pump_and_settle();
1812            assert_eq!(
1813                value(tester),
1814                states(&[WidgetState::Hovered, WidgetState::Pressed])
1815            );
1816            assert_eq!(count.get(), 4);
1817
1818            tester.up(&gesture);
1819            tester.pump_and_settle();
1820            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
1821            assert_eq!(count.get(), 5);
1822
1823            tester.move_to(&mut gesture, Offset::ZERO, false);
1824            tester.pump_and_settle();
1825            assert_eq!(value(tester), states(&[]));
1826            assert_eq!(count.get(), 6);
1827
1828            tester.down(&mut gesture, center);
1829            tester.pump_and_settle();
1830            assert_eq!(
1831                value(tester),
1832                states(&[WidgetState::Hovered, WidgetState::Pressed])
1833            );
1834            assert_eq!(count.get(), 8); // adds hovered and pressed - two changes
1835
1836            // If the button is rebuilt disabled, then the pressed state is
1837            // removed.
1838            let disabled = frame(tester, false);
1839            tester.pump_widget(disabled);
1840            tester.pump_and_settle();
1841            assert_eq!(
1842                value(tester),
1843                states(&[WidgetState::Hovered, WidgetState::Disabled])
1844            );
1845            assert_eq!(count.get(), 10); // removes pressed and adds disabled - two changes
1846            tester.move_to(&mut gesture, Offset::ZERO, true);
1847            tester.pump_and_settle();
1848            assert_eq!(value(tester), states(&[WidgetState::Disabled]));
1849            assert_eq!(count.get(), 11);
1850        });
1851    }
1852
1853    // filled_button_test.dart 'FilledButton.styleFrom can customize the button icon'.
1854    #[test]
1855    fn style_from_can_customize_the_button_icon() {
1856        test_widgets(|tester| {
1857            let icon_color = Color::new(0xFFF000FF);
1858            let icon_size = 32.0;
1859            let disabled_icon_color = Color::new(0xFFFFF000);
1860            let build_button = |tester: &WidgetTester, enabled: bool| {
1861                let theme = ThemeData::new(&tester.cell.borrow());
1862                material_app(
1863                    theme,
1864                    Material::new()
1865                        .child(
1866                            Center::new().child(
1867                                FilledButton::icon(enabled.then(pressed), text("Button"))
1868                                    .style(
1869                                        FilledButton::style_from()
1870                                            .icon_color(icon_color)
1871                                            .icon_size(icon_size)
1872                                            .icon_alignment(IconAlignment::End)
1873                                            .disabled_icon_color(disabled_icon_color)
1874                                            .build(),
1875                                    )
1876                                    .icon(icon()),
1877                            ),
1878                        )
1879                        .into_widget(),
1880                )
1881            };
1882
1883            // Test enabled button.
1884            let enabled = build_button(tester, true);
1885            tester.pump_widget(enabled);
1886            assert_eq!(icon_rect(tester).size(), Size::new(icon_size, icon_size));
1887            assert_eq!(glyph_color(tester, &Icons::add()), Some(icon_color));
1888
1889            // Test disabled button.
1890            let disabled = build_button(tester, false);
1891            tester.pump_widget(disabled);
1892            tester.pump_and_settle();
1893            assert_eq!(
1894                glyph_color(tester, &Icons::add()),
1895                Some(disabled_icon_color)
1896            );
1897
1898            let button_top_right = material_rect(tester).top_right();
1899            let icon_top_right = icon_rect(tester).top_right();
1900            assert_f32_equals(button_top_right.dx(), icon_top_right.dx() + 24.0);
1901        });
1902    }
1903
1904    // filled_button_test.dart 'FilledButton icon uses provided foregroundColor over default icon
1905    // color'.
1906    #[test]
1907    fn an_icon_takes_the_style_foreground_color_over_the_default_icon_color() {
1908        test_widgets(|tester| {
1909            let foreground_color = Color::new(0xFFFF1234);
1910            let theme = ThemeData::new(&tester.cell.borrow());
1911            tester.pump_widget(material_app(
1912                theme,
1913                Material::new()
1914                    .child(Center::new().child(Column::new().children(vec![
1915                            FilledButton::icon(Some(pressed()), text("Button"))
1916                                .style(
1917                                    FilledButton::style_from()
1918                                        .foreground_color(foreground_color)
1919                                        .build(),
1920                                )
1921                                .icon(Icon::new(Some(Icons::add())))
1922                                .into_widget(),
1923                            FilledButton::tonal_icon(Some(pressed()), text("Button"))
1924                                .style(
1925                                    FilledButton::style_from()
1926                                        .foreground_color(foreground_color)
1927                                        .build(),
1928                                )
1929                                .icon(Icon::new(Some(Icons::mail())))
1930                                .into_widget(),
1931                        ])))
1932                    .into_widget(),
1933            ));
1934            assert_eq!(glyph_color(tester, &Icons::add()), Some(foreground_color));
1935            assert_eq!(glyph_color(tester, &Icons::mail()), Some(foreground_color));
1936        });
1937    }
1938}