Skip to main content

waft_material/
elevated_button.rs

1//! Flutter counterpart: material_ui's `elevated_button.dart`, with its parts
2//! `generated/elevated_button_defaults_m3.g.dart` and
3//! `generated/elevated_button_defaults_m3e.g.dart`.
4//!
5//! Dart's `ElevatedButton.icon` and `ElevatedButton.styleFrom` take named arguments the body
6//! combines (the icon child reads `style`; `styleFrom` derives its overlay color from two of
7//! them), so each is a value collecting them, [`ElevatedButtonIcon`] and
8//! [`ElevatedButtonStyleFromBuilder`], 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, Radius, Size, clamp_double, lerp_double};
16use waft_foundation::{App, DiagnosticPropertiesBuilder, K_IS_WEB, Listener};
17use waft_painting::{
18    AlignmentGeometry, BorderRadius, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef,
19    RoundedRectangleBorder, TextStyle,
20};
21use waft_services::{MouseCursorRef, SystemMouseCursors};
22use waft_widgets::{
23    BuildContext, Flexible, IntoWidget, KeyRef, MainAxisSize, MediaQuery, Row, StatefulKind,
24    StatefulWidget, StatelessWidget, WidgetRef, WidgetState, WidgetStateProperty,
25    WidgetStatePropertyRef, WidgetStates,
26};
27
28use crate::button_style::ButtonStyleGetters;
29use crate::button_style::{ButtonLayerBuilder, ButtonShapeVariant, ButtonSizeVariant, ButtonStyle};
30use crate::button_style_button::{
31    ButtonStyleButton, ButtonStyleButtonData, ButtonStyleState, IconAlignment,
32};
33use crate::constants::K_THEME_CHANGE_DURATION;
34use crate::elevated_button_theme::ElevatedButtonTheme;
35use crate::generated::elevated_button_defaults_m3::ElevatedButtonDefaultsM3;
36use crate::generated::elevated_button_defaults_m3e::{ElevatedButtonDefaultsM3E, icon_label_space};
37use crate::ink_ripple::InkRipple;
38use crate::ink_well::InteractiveInkFeatureFactoryRef;
39use crate::material_state::MaterialStatePropertyAll;
40use crate::theme::Theme;
41use crate::theme_data::{MaterialTapTargetSize, StyleVariant, VisualDensity};
42
43/// A Material Design "elevated button".
44///
45/// Use elevated buttons to add dimension to otherwise mostly flat
46/// layouts, e.g. in long busy lists of content, or in wide
47/// spaces. Avoid using elevated buttons on already-elevated content
48/// such as dialogs or cards.
49///
50/// An elevated button is a label `child` displayed on a `Material`
51/// widget whose `Material::elevation` increases when the button is
52/// pressed. The label's `Text` and `Icon` widgets are displayed in
53/// `style`'s [`ButtonStyle::foreground_color`] and the button's filled
54/// background is the [`ButtonStyle::background_color`].
55///
56/// The elevated button's default style is defined by
57/// [`default_style_of`](ButtonStyleButton::default_style_of). The style of this elevated
58/// button can be overridden with its `style` parameter. The style of all elevated
59/// buttons in a subtree can be overridden with the
60/// [`ElevatedButtonTheme`], and the style of all of the elevated
61/// buttons in an app can be overridden with the `Theme`'s
62/// `ThemeData::elevated_button_theme` property.
63///
64/// The static [`style_from`](Self::style_from) method is a convenient way to create a
65/// elevated button [`ButtonStyle`] from simple values.
66///
67/// If `on_pressed` and `on_long_press` callbacks are null, then the
68/// button will be disabled.
69///
70/// To use the Material 3 Expressive style, set
71/// `ElevatedButtonThemeData::variant` to [`StyleVariant::Material3Expressive`].
72/// The Expressive size and shape variants can then be selected with
73/// [`ButtonStyle::size_variant`] and [`ButtonStyle::shape_variant`], and the button
74/// becomes a toggle button when `is_selected` is non-null.
75///
76/// With the Material 3 style, `is_selected` updates [`WidgetState::Selected`] and
77/// the button's semantics, but the default style doesn't change the button's
78/// appearance when it's selected. To show the selected state, use a `style`
79/// that resolves [`WidgetState::Selected`].
80///
81/// See also:
82///
83///  * `FilledButton`, a filled button that doesn't elevate when pressed.
84///  * `FilledButton::tonal`, a filled button variant that uses a secondary fill color.
85///  * `OutlinedButton`, a button with an outlined border and no fill color.
86///  * `TextButton`, a button with no outline or fill color.
87///  * <https://material.io/design/components/buttons.html>
88///  * <https://m3.material.io/components/buttons>
89pub struct ElevatedButton {
90    button_style_button: ButtonStyleButtonData,
91    add_padding: bool,
92}
93
94impl ElevatedButton {
95    /// Create an ElevatedButton.
96    #[cfg_attr(debug_assertions, track_caller)]
97    pub fn new<K>(
98        on_pressed: Option<Listener>,
99        child: Option<impl IntoWidget<K>>,
100    ) -> ElevatedButton {
101        ElevatedButton {
102            button_style_button: ButtonStyleButtonData::new(
103                on_pressed,
104                match child {
105                    Some(child) => Some(child.into_widget()),
106                    None => None,
107                },
108            ),
109            add_padding: false,
110        }
111    }
112
113    /// Create an elevated button from a pair of widgets that serve as the button's
114    /// [`icon`](ElevatedButtonIcon::icon) and `label`.
115    ///
116    /// The icon and label are arranged in a row and padded by 12 logical pixels
117    /// at the start, and 16 at the end, with an 8 pixel gap in between.
118    ///
119    /// With the Material 3 Expressive style, the padding and the gap between the
120    /// icon and the label depend on [`ButtonStyle::size_variant`]. See
121    /// [`default_style_of`](ButtonStyleButton::default_style_of).
122    ///
123    /// If [`icon`](ElevatedButtonIcon::icon) is null, this constructor will create an
124    /// [`ElevatedButton`] that doesn't display an icon.
125    ///
126    /// The alignment of the icon within the button is set by
127    /// [`icon_alignment`](ElevatedButtonIcon::icon_alignment); see [`IconAlignment`].
128    #[cfg_attr(debug_assertions, track_caller)]
129    pub fn icon<K>(on_pressed: Option<Listener>, label: impl IntoWidget<K>) -> ElevatedButtonIcon {
130        let mut button_style_button = ButtonStyleButtonData::new(on_pressed, None);
131        button_style_button.clip_behavior = Some(Clip::None);
132        ElevatedButtonIcon {
133            button_style_button,
134            icon: None,
135            label: label.into_widget(),
136            icon_alignment: None,
137        }
138    }
139
140    crate::button_style_button_setters!(
141        ElevatedButton;
142        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
143        clip_behavior, states_controller, is_selected,
144    );
145
146    /// A static convenience method that constructs an elevated button
147    /// [`ButtonStyle`] given simple values.
148    ///
149    /// The `foreground_color` and `disabled_foreground_color` colors are used
150    /// to create a [`WidgetStateProperty`] [`ButtonStyle::foreground_color`], and
151    /// a derived [`ButtonStyle::overlay_color`] if `overlay_color` isn't specified.
152    ///
153    /// If `overlay_color` is specified and its value is `Colors::TRANSPARENT`
154    /// then the pressed/focused/hovered highlights are effectively defeated.
155    /// Otherwise a [`WidgetStateProperty`] with the same opacities as the
156    /// default is created.
157    ///
158    /// The `background_color` and `disabled_background_color` colors are
159    /// used to create a [`WidgetStateProperty`] [`ButtonStyle::background_color`].
160    ///
161    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
162    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
163    ///
164    /// The `icon_color`, `disabled_icon_color` are used to construct
165    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
166    /// [`ButtonStyle::icon_size`].
167    ///
168    /// If `icon_color` is null, the button icon will use `foreground_color`. If
169    /// `foreground_color` is also null, the button icon will use the default icon color.
170    ///
171    /// The button's elevations are defined relative to the `elevation`
172    /// parameter. The disabled elevation is the same as the parameter
173    /// value, `elevation` + 2 is used when the button is hovered
174    /// or focused, and elevation + 6 is used when the button is pressed.
175    ///
176    /// All of the other parameters are either used directly or used to
177    /// create a [`WidgetStateProperty`] with a single value for all
178    /// states.
179    ///
180    /// The `size_variant` and `shape_variant` parameters are Material 3 Expressive
181    /// options. They provide extra-small through extra-large sizes and round or
182    /// square shapes through [`ButtonStyle::size_variant`] and
183    /// [`ButtonStyle::shape_variant`].
184    ///
185    /// When `ElevatedButtonThemeData::variant` is
186    /// [`StyleVariant::Material3Expressive`] and these properties are null,
187    /// Material 3 Expressive [`ElevatedButton`] defaults use
188    /// [`ButtonSizeVariant::Small`] and [`ButtonShapeVariant::Round`].
189    ///
190    /// All parameters default to null, by default this method returns
191    /// a [`ButtonStyle`] that doesn't override anything.
192    ///
193    /// For example, to override the default text and icon colors for an
194    /// [`ElevatedButton`], as well as its overlay color, with all of the
195    /// standard opacity adjustments for the pressed, focused, and
196    /// hovered states, one could write:
197    ///
198    /// ```text
199    /// ElevatedButton::new(on_pressed, Text::new("Jump"))
200    ///     .style(ElevatedButton::style_from().foreground_color(Colors::GREEN.primary()).build())
201    /// ```
202    ///
203    /// And to change the fill color:
204    ///
205    /// ```text
206    /// ElevatedButton::new(on_pressed, Text::new("Meow"))
207    ///     .style(ElevatedButton::style_from().background_color(Colors::GREEN.primary()).build())
208    /// ```
209    pub fn style_from() -> ElevatedButtonStyleFromBuilder {
210        ElevatedButtonStyleFromBuilder::default()
211    }
212}
213
214impl ButtonStyleButton for ElevatedButton {
215    crate::button_style_button_accessors!();
216
217    /// Defines the button's default appearance.
218    ///
219    /// The button `child`'s `Text` and `Icon` widgets are rendered with
220    /// the [`ButtonStyle`]'s foreground color. The button's `InkWell` adds
221    /// the style's overlay color when the button is focused, hovered
222    /// or pressed. The button's background color becomes its `Material`
223    /// color.
224    ///
225    /// All of the ButtonStyle's defaults appear below. In this list
226    /// "Theme.foo" is shorthand for `Theme::of(context).foo`. Color
227    /// scheme values like "onSurface(0.38)" are shorthand for
228    /// `on_surface.with_opacity(0.38)`. [`WidgetStateProperty`] valued
229    /// properties that are not followed by a sublist have the same
230    /// value for all states, otherwise the values are as specified for
231    /// each state, and "others" means all other states.
232    ///
233    /// The "default font size" below refers to the font size specified in the
234    /// [`default_style_of`](ButtonStyleButton::default_style_of) method (or 14.0 if
235    /// unspecified), scaled by the `MediaQuery::text_scaler_of(context).scale` method. The
236    /// names of the EdgeInsets constructors and `EdgeInsetsGeometry::lerp` have been
237    /// abbreviated for readability.
238    ///
239    /// The color of the [`ButtonStyle::text_style`] is not used, the
240    /// [`ButtonStyle::foreground_color`] color is used instead.
241    ///
242    /// ## Material 2 defaults
243    ///
244    /// * `text_style` - Theme.textTheme.button
245    /// * `background_color`
246    ///   * disabled - Theme.colorScheme.onSurface(0.12)
247    ///   * others - Theme.colorScheme.primary
248    /// * `foreground_color`
249    ///   * disabled - Theme.colorScheme.onSurface(0.38)
250    ///   * others - Theme.colorScheme.onPrimary
251    /// * `overlay_color`
252    ///   * hovered - Theme.colorScheme.onPrimary(0.08)
253    ///   * focused or pressed - Theme.colorScheme.onPrimary(0.12)
254    /// * `shadow_color` - Theme.shadowColor
255    /// * `elevation`
256    ///   * disabled - 0
257    ///   * default - 2
258    ///   * hovered or focused - 4
259    ///   * pressed - 8
260    /// * `padding`
261    ///   * `default font size <= 14` - horizontal(16)
262    ///   * `14 < default font size <= 28` - lerp(horizontal(16), horizontal(8))
263    ///   * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
264    ///   * `36 < default font size` - horizontal(4)
265    /// * `minimum_size` - Size(64, 36)
266    /// * `fixed_size` - null
267    /// * `maximum_size` - Size.infinite
268    /// * `side` - null
269    /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
270    /// * `mouse_cursor` - WidgetStateMouseCursor.adaptiveClickable
271    /// * `visual_density` - theme.visualDensity
272    /// * `tap_target_size` - theme.materialTapTargetSize
273    /// * `animation_duration` - kThemeChangeDuration
274    /// * `enable_feedback` - true
275    /// * `alignment` - Alignment.center
276    /// * `splash_factory` - InkRipple.splashFactory
277    ///
278    /// The default padding values for the [`ElevatedButton::icon`] factory are slightly
279    /// different:
280    ///
281    /// * `padding`
282    ///   * `default font size <= 14` - start(12) end(16)
283    ///   * `14 < default font size <= 28` - lerp(start(12) end(16), horizontal(8))
284    ///   * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
285    ///   * `36 < default font size` - horizontal(4)
286    ///
287    /// The default value for `side`, which defines the appearance of the button's
288    /// outline, is null. That means that the outline is defined by the button
289    /// shape's `OutlinedBorder::side`. Typically the default value of an
290    /// [`OutlinedBorder`]'s side is [`BorderSide::NONE`], so an outline is not drawn.
291    ///
292    /// ## Material 3 defaults
293    ///
294    /// If `ThemeData::use_material3` is set to true the following defaults will
295    /// be used:
296    ///
297    /// * `text_style` - Theme.textTheme.labelLarge
298    /// * `background_color`
299    ///   * disabled - Theme.colorScheme.onSurface(0.12)
300    ///   * others - Theme.colorScheme.surfaceContainerLow
301    /// * `foreground_color`
302    ///   * disabled - Theme.colorScheme.onSurface(0.38)
303    ///   * others - Theme.colorScheme.primary
304    /// * `overlay_color`
305    ///   * hovered - Theme.colorScheme.primary(0.08)
306    ///   * focused or pressed - Theme.colorScheme.primary(0.1)
307    /// * `shadow_color` - Theme.colorScheme.shadow
308    /// * `surface_tint_color` - Colors.transparent
309    /// * `elevation`
310    ///   * disabled - 0
311    ///   * default - 1
312    ///   * hovered - 3
313    ///   * focused or pressed - 1
314    /// * `padding`
315    ///   * `default font size <= 14` - horizontal(24)
316    ///   * `14 < default font size <= 28` - lerp(horizontal(24), horizontal(12))
317    ///   * `28 < default font size <= 36` - lerp(horizontal(12), horizontal(6))
318    ///   * `36 < default font size` - horizontal(6)
319    /// * `minimum_size` - Size(64, 40)
320    /// * `fixed_size` - null
321    /// * `maximum_size` - Size.infinite
322    /// * `side` - null
323    /// * `shape` - StadiumBorder()
324    /// * `mouse_cursor` - WidgetStateMouseCursor.adaptiveClickable
325    /// * `visual_density` - Theme.visualDensity
326    /// * `tap_target_size` - Theme.materialTapTargetSize
327    /// * `animation_duration` - kThemeChangeDuration
328    /// * `enable_feedback` - true
329    /// * `alignment` - Alignment.center
330    /// * `splash_factory` - Theme.splashFactory
331    ///
332    /// For the [`ElevatedButton::icon`] factory, the start (generally the left) value of
333    /// [`ButtonStyle::padding`] is reduced from 24 to 16.
334    ///
335    /// ## Material 3 Expressive defaults
336    ///
337    /// If `ThemeData::use_material3` is true and `ElevatedButtonThemeData::variant`
338    /// is [`StyleVariant::Material3Expressive`], the following defaults will be
339    /// used. Values listed per size are for [`ButtonSizeVariant::XSmall`],
340    /// [`ButtonSizeVariant::Small`], [`ButtonSizeVariant::Medium`],
341    /// [`ButtonSizeVariant::Large`], and [`ButtonSizeVariant::XLarge`] respectively.
342    /// The selected values only apply when `is_selected` is non-null.
343    ///
344    /// * `text_style` - based on [`ButtonStyle::size_variant`]
345    ///   * xSmall or small - Theme.textTheme.labelLarge
346    ///   * medium - Theme.textTheme.titleMedium
347    ///   * large - Theme.textTheme.headlineSmall
348    ///   * xLarge - Theme.textTheme.headlineLarge
349    /// * `background_color`
350    ///   * disabled - Theme.colorScheme.onSurface(0.1)
351    ///   * selected - Theme.colorScheme.primary
352    ///   * others - Theme.colorScheme.surfaceContainerLow
353    /// * `foreground_color`
354    ///   * disabled - Theme.colorScheme.onSurface(0.38)
355    ///   * selected - Theme.colorScheme.onPrimary
356    ///   * others - Theme.colorScheme.primary
357    /// * `overlay_color`
358    ///   * selected
359    ///     * hovered - Theme.colorScheme.onPrimary(0.08)
360    ///     * focused or pressed - Theme.colorScheme.onPrimary(0.1)
361    ///   * hovered - Theme.colorScheme.primary(0.08)
362    ///   * focused or pressed - Theme.colorScheme.primary(0.1)
363    /// * `shadow_color` - Theme.colorScheme.shadow
364    /// * `surface_tint_color` - Colors.transparent
365    /// * `elevation`
366    ///   * disabled - 0
367    ///   * others - 1
368    /// * `padding` - based on [`ButtonStyle::size_variant`]; horizontal(12),
369    ///   horizontal(16), horizontal(24), horizontal(48), horizontal(64)
370    /// * `minimum_size` - based on [`ButtonStyle::size_variant`]; Size(64, 32),
371    ///   Size(64, 40), Size(64, 56), Size(64, 96), Size(64, 136)
372    /// * `fixed_size` - null
373    /// * `maximum_size` - Size.infinite
374    /// * `icon_size` - based on [`ButtonStyle::size_variant`]; 20, 20, 24, 32, 40
375    /// * `icon_color` - same as `foreground_color`
376    /// * `side` - null
377    /// * `shape` - based on [`ButtonStyle::size_variant`], [`ButtonStyle::shape_variant`],
378    ///   and state
379    ///   * pressed - RoundedRectangleBorder with radius 8, 8, 12, 16, 16
380    ///   * selected
381    ///     * round - RoundedRectangleBorder with radius 12, 12, 16, 28, 28
382    ///     * square - StadiumBorder()
383    ///   * others
384    ///     * round - StadiumBorder()
385    ///     * square - RoundedRectangleBorder with radius 12, 12, 16, 28, 28
386    /// * `mouse_cursor` - WidgetStateMouseCursor.adaptiveClickable
387    /// * `visual_density` - VisualDensity.standard
388    /// * `tap_target_size` - MaterialTapTargetSize.padded
389    /// * `animation_duration` - kThemeChangeDuration
390    /// * `enable_feedback` - true
391    /// * `alignment` - Alignment.center
392    /// * `splash_factory` - Theme.splashFactory
393    /// * `size_variant` - ButtonSizeVariant.small
394    /// * `shape_variant` - ButtonShapeVariant.round
395    ///
396    /// For the [`ElevatedButton::icon`] factory, the padding is the same, and the
397    /// gap between the icon and the label is 4, 8, 8, 12, or 16 based on
398    /// [`ButtonStyle::size_variant`].
399    fn default_style_of(
400        &self,
401        app: &mut App,
402        context: BuildContext,
403    ) -> Box<dyn ButtonStyleGetters> {
404        let theme = Theme::of(app, context);
405        let color_scheme = &theme.color_scheme;
406        let elevated_button_theme = ElevatedButtonTheme::of(app, context);
407        let effective_variant = ElevatedButtonTheme::variant_of(app, context);
408        let style = self.button_style_button.style.as_ref();
409        let effective_size = style.and_then(|style| style.size_variant).or_else(|| {
410            elevated_button_theme
411                .style
412                .as_ref()
413                .and_then(|style| style.size_variant)
414        });
415        let effective_shape = style.and_then(|style| style.shape_variant).or_else(|| {
416            elevated_button_theme
417                .style
418                .as_ref()
419                .and_then(|style| style.shape_variant)
420        });
421        let use_expressive =
422            theme.use_material3 && effective_variant == StyleVariant::Material3Expressive;
423        let button_style: Box<dyn ButtonStyleGetters> = if theme.use_material3 {
424            match effective_variant {
425                StyleVariant::Material3 => Box::new(ElevatedButtonDefaultsM3::new(context)),
426                StyleVariant::Material3Expressive => Box::new(ElevatedButtonDefaultsM3E::new(
427                    context,
428                    self.button_style_button.is_selected.is_some(),
429                    effective_size,
430                    effective_shape,
431                )),
432            }
433        } else {
434            let mut style_from = ElevatedButton::style_from()
435                .background_color(color_scheme.primary())
436                .foreground_color(color_scheme.on_primary())
437                .disabled_background_color(color_scheme.on_surface().with_opacity(0.12))
438                .disabled_foreground_color(color_scheme.on_surface().with_opacity(0.38))
439                .shadow_color(theme.shadow_color)
440                .elevation(2.0);
441            if let Some(text_style) = theme.text_theme.label_large.clone() {
442                style_from = style_from.text_style(text_style);
443            }
444            let style_from = style_from
445                .padding(scaled_padding(app, context))
446                .minimum_size(Size::new(64.0, 36.0))
447                .maximum_size(Size::INFINITE)
448                .shape(RoundedRectangleBorder::new(
449                    BorderSide::NONE,
450                    BorderRadius::all(Radius::circular(4.0)).into(),
451                ))
452                .enabled_mouse_cursor(if K_IS_WEB {
453                    SystemMouseCursors::CLICK.into()
454                } else {
455                    SystemMouseCursors::BASIC.into()
456                })
457                .disabled_mouse_cursor(SystemMouseCursors::BASIC.into())
458                .visual_density(theme.visual_density)
459                .tap_target_size(theme.material_tap_target_size)
460                .animation_duration(K_THEME_CHANGE_DURATION)
461                .enable_feedback(true)
462                .alignment(AlignmentGeometry::CENTER)
463                .splash_factory(InkRipple::splash_factory())
464                .build();
465            Box::new(style_from)
466        };
467
468        // The Material 3 Expressive defaults use the same padding with or without
469        // an icon.
470        if use_expressive {
471            return button_style;
472        }
473
474        // Only apply padding when the ElevatedButton has an Icon.
475        if self.add_padding {
476            let default_font_size = button_style
477                .text_style(app)
478                .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
479                .and_then(|text_style| text_style.font_size)
480                .unwrap_or(14.0);
481            let effective_text_scale =
482                MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
483
484            let scaled_padding = if theme.use_material3 {
485                <dyn ButtonStyleButton>::scaled_padding(
486                    EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0),
487                    EdgeInsetsGeometry::from_steb(8.0, 0.0, 12.0, 0.0),
488                    EdgeInsetsGeometry::from_steb(4.0, 0.0, 6.0, 0.0),
489                    effective_text_scale,
490                )
491            } else {
492                <dyn ButtonStyleButton>::scaled_padding(
493                    EdgeInsetsGeometry::from_steb(12.0, 0.0, 16.0, 0.0),
494                    EdgeInsetsGeometry::symmetric(0.0, 8.0),
495                    EdgeInsetsGeometry::from_steb(8.0, 0.0, 4.0, 0.0),
496                    effective_text_scale,
497                )
498            };
499            return Box::new(
500                button_style
501                    .copy_with(app)
502                    .padding(Rc::new(MaterialStatePropertyAll::new(Some(scaled_padding)))),
503            );
504        }
505
506        button_style
507    }
508
509    /// Returns the `ElevatedButtonThemeData::style` of the closest
510    /// [`ElevatedButtonTheme`] ancestor.
511    fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> {
512        ElevatedButtonTheme::of(app, context).style
513    }
514}
515
516impl StatefulWidget for ElevatedButton {
517    type State = ButtonStyleState<ElevatedButton>;
518
519    fn key(&self) -> Option<&KeyRef> {
520        self.button_style_button.key.as_ref()
521    }
522
523    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
524        self.button_style_button
525            .debug_fill_properties(app, properties);
526    }
527
528    fn create_state(&self) -> ButtonStyleState<ElevatedButton> {
529        ButtonStyleState::new()
530    }
531}
532
533impl Debug for ElevatedButton {
534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535        Debug::fmt(&self.button_style_button, f)
536    }
537}
538
539/// Dart's `ElevatedButton.styleFrom`, collecting its arguments; [`build`](Self::build) is the
540/// call.
541#[derive(Clone, Default)]
542pub struct ElevatedButtonStyleFromBuilder {
543    foreground_color: Option<Color>,
544    background_color: Option<Color>,
545    disabled_foreground_color: Option<Color>,
546    disabled_background_color: Option<Color>,
547    shadow_color: Option<Color>,
548    surface_tint_color: Option<Color>,
549    icon_color: Option<Color>,
550    icon_size: Option<f64>,
551    icon_alignment: Option<IconAlignment>,
552    disabled_icon_color: Option<Color>,
553    overlay_color: Option<Color>,
554    elevation: Option<f64>,
555    text_style: Option<TextStyle>,
556    padding: Option<EdgeInsetsGeometry>,
557    minimum_size: Option<Size>,
558    fixed_size: Option<Size>,
559    maximum_size: Option<Size>,
560    side: Option<BorderSide>,
561    shape: Option<OutlinedBorderRef>,
562    enabled_mouse_cursor: Option<MouseCursorRef>,
563    disabled_mouse_cursor: Option<MouseCursorRef>,
564    visual_density: Option<VisualDensity>,
565    tap_target_size: Option<MaterialTapTargetSize>,
566    animation_duration: Option<Duration>,
567    enable_feedback: Option<bool>,
568    alignment: Option<AlignmentGeometry>,
569    splash_factory: Option<InteractiveInkFeatureFactoryRef>,
570    background_builder: Option<ButtonLayerBuilder>,
571    foreground_builder: Option<ButtonLayerBuilder>,
572    size_variant: Option<ButtonSizeVariant>,
573    shape_variant: Option<ButtonShapeVariant>,
574}
575
576/// The setters of `styleFrom`'s named arguments.
577macro_rules! style_from_setters {
578    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
579        $(
580            #[doc = concat!("Dart `ElevatedButton.styleFrom(", $dart, ":)`.")]
581            pub fn $field(mut self, $field: $ty) -> ElevatedButtonStyleFromBuilder {
582                self.$field = Some($field);
583                self
584            }
585        )*
586    };
587}
588
589impl ElevatedButtonStyleFromBuilder {
590    style_from_setters!(
591        foreground_color: Color => "foregroundColor",
592        background_color: Color => "backgroundColor",
593        disabled_foreground_color: Color => "disabledForegroundColor",
594        disabled_background_color: Color => "disabledBackgroundColor",
595        shadow_color: Color => "shadowColor",
596        surface_tint_color: Color => "surfaceTintColor",
597        icon_color: Color => "iconColor",
598        icon_size: f64 => "iconSize",
599        icon_alignment: IconAlignment => "iconAlignment",
600        disabled_icon_color: Color => "disabledIconColor",
601        overlay_color: Color => "overlayColor",
602        elevation: f64 => "elevation",
603        text_style: TextStyle => "textStyle",
604        padding: EdgeInsetsGeometry => "padding",
605        minimum_size: Size => "minimumSize",
606        fixed_size: Size => "fixedSize",
607        maximum_size: Size => "maximumSize",
608        side: BorderSide => "side",
609        enabled_mouse_cursor: MouseCursorRef => "enabledMouseCursor",
610        disabled_mouse_cursor: MouseCursorRef => "disabledMouseCursor",
611        visual_density: VisualDensity => "visualDensity",
612        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
613        animation_duration: Duration => "animationDuration",
614        enable_feedback: bool => "enableFeedback",
615        alignment: AlignmentGeometry => "alignment",
616        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
617        background_builder: ButtonLayerBuilder => "backgroundBuilder",
618        foreground_builder: ButtonLayerBuilder => "foregroundBuilder",
619        size_variant: ButtonSizeVariant => "sizeVariant",
620        shape_variant: ButtonShapeVariant => "shapeVariant",
621    );
622
623    /// Dart `ElevatedButton.styleFrom(shape:)`.
624    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> ElevatedButtonStyleFromBuilder {
625        self.shape = Some(shape.into());
626        self
627    }
628
629    /// The [`ButtonStyle`] `ElevatedButton.styleFrom` returns for the arguments given.
630    pub fn build(self) -> ButtonStyle {
631        let overlay_color_prop: Option<WidgetStatePropertyRef<Option<Color>>> =
632            match (self.foreground_color, self.overlay_color) {
633                (None, None) => None,
634                (_, Some(overlay_color)) if overlay_color.a == 0.0 => {
635                    Some(Rc::new(MaterialStatePropertyAll::new(Some(overlay_color))))
636                }
637                (_, Some(color)) | (Some(color), None) => {
638                    Some(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
639                        (WidgetState::Pressed.into(), Some(color.with_opacity(0.1))),
640                        (WidgetState::Hovered.into(), Some(color.with_opacity(0.08))),
641                        (WidgetState::Focused.into(), Some(color.with_opacity(0.1))),
642                        (WidgetState::any(), None),
643                    ]))
644                }
645            };
646
647        let mut elevation_value: Option<WidgetStatePropertyRef<Option<f64>>> = None;
648        if let Some(elevation) = self.elevation {
649            elevation_value = Some(<dyn WidgetStateProperty<Option<f64>>>::from_map(vec![
650                (WidgetState::Disabled.into(), Some(0.0)),
651                (WidgetState::Pressed.into(), Some(elevation + 6.0)),
652                (WidgetState::Hovered.into(), Some(elevation + 2.0)),
653                (WidgetState::Focused.into(), Some(elevation + 2.0)),
654                (WidgetState::any(), Some(elevation)),
655            ]));
656        }
657
658        ButtonStyle {
659            text_style: Some(Rc::new(MaterialStatePropertyAll::new(self.text_style))),
660            background_color: <dyn ButtonStyleButton>::default_color(
661                self.background_color,
662                self.disabled_background_color,
663            ),
664            foreground_color: <dyn ButtonStyleButton>::default_color(
665                self.foreground_color,
666                self.disabled_foreground_color,
667            ),
668            overlay_color: overlay_color_prop,
669            shadow_color: <dyn ButtonStyleButton>::all_or_null(self.shadow_color),
670            surface_tint_color: <dyn ButtonStyleButton>::all_or_null(self.surface_tint_color),
671            icon_color: <dyn ButtonStyleButton>::default_color(
672                self.icon_color,
673                self.disabled_icon_color,
674            ),
675            icon_size: <dyn ButtonStyleButton>::all_or_null(self.icon_size),
676            icon_alignment: self.icon_alignment,
677            elevation: elevation_value,
678            padding: <dyn ButtonStyleButton>::all_or_null(self.padding),
679            minimum_size: <dyn ButtonStyleButton>::all_or_null(self.minimum_size),
680            fixed_size: <dyn ButtonStyleButton>::all_or_null(self.fixed_size),
681            maximum_size: <dyn ButtonStyleButton>::all_or_null(self.maximum_size),
682            side: <dyn ButtonStyleButton>::all_or_null(self.side),
683            shape: <dyn ButtonStyleButton>::all_or_null(self.shape),
684            mouse_cursor: Some(<dyn WidgetStateProperty<Option<MouseCursorRef>>>::from_map(
685                vec![
686                    (WidgetState::Disabled.into(), self.disabled_mouse_cursor),
687                    (WidgetState::any(), self.enabled_mouse_cursor),
688                ],
689            )),
690            visual_density: self.visual_density,
691            tap_target_size: self.tap_target_size,
692            animation_duration: self.animation_duration,
693            enable_feedback: self.enable_feedback,
694            alignment: self.alignment,
695            splash_factory: self.splash_factory,
696            background_builder: self.background_builder,
697            foreground_builder: self.foreground_builder,
698            size_variant: self.size_variant,
699            icon_button_width: None,
700            shape_variant: self.shape_variant,
701        }
702    }
703}
704
705/// Dart's `_scaledPadding`: the default padding for the default font size, scaled by the
706/// ambient text scaler.
707pub(crate) fn scaled_padding(app: &mut App, context: BuildContext) -> EdgeInsetsGeometry {
708    let theme = Theme::of(app, context);
709    let padding1x = if theme.use_material3 { 24.0 } else { 16.0 };
710    let default_font_size = theme
711        .text_theme
712        .label_large
713        .as_ref()
714        .and_then(|label_large| label_large.font_size)
715        .unwrap_or(14.0);
716    let effective_text_scale =
717        MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
718
719    <dyn ButtonStyleButton>::scaled_padding(
720        EdgeInsetsGeometry::symmetric(0.0, padding1x),
721        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0),
722        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0 / 2.0),
723        effective_text_scale,
724    )
725}
726
727/// Dart's private `_ElevatedButtonWithIconChild`.
728#[derive(Debug)]
729struct ElevatedButtonWithIconChild {
730    label: WidgetRef,
731    icon: WidgetRef,
732    button_style: Option<ButtonStyle>,
733    icon_alignment: Option<IconAlignment>,
734}
735
736impl StatelessWidget for ElevatedButtonWithIconChild {
737    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
738        let elevated_button_theme = ElevatedButtonTheme::of(app, context);
739        let use_expressive = Theme::of(app, context).use_material3
740            && ElevatedButtonTheme::variant_of(app, context) == StyleVariant::Material3Expressive;
741        let spacing = if use_expressive {
742            let effective_size = self
743                .button_style
744                .as_ref()
745                .and_then(|style| style.size_variant)
746                .or_else(|| {
747                    elevated_button_theme
748                        .style
749                        .as_ref()
750                        .and_then(|style| style.size_variant)
751                })
752                .unwrap_or(ButtonSizeVariant::Small);
753            icon_label_space(effective_size)
754        } else {
755            let default_font_size = self
756                .button_style
757                .as_ref()
758                .and_then(|style| style.text_style.as_ref())
759                .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
760                .and_then(|text_style| text_style.font_size)
761                .unwrap_or(14.0);
762            let scale = clamp_double(
763                MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0,
764                1.0,
765                2.0,
766            ) - 1.0;
767            lerp_double(Some(8.0), Some(4.0), scale).expect("both ends")
768        };
769        let effective_icon_alignment = self
770            .icon_alignment
771            .or_else(|| {
772                elevated_button_theme
773                    .style
774                    .as_ref()
775                    .and_then(|style| style.icon_alignment)
776            })
777            .or_else(|| {
778                self.button_style
779                    .as_ref()
780                    .and_then(|style| style.icon_alignment)
781            })
782            .unwrap_or(IconAlignment::Start);
783        Row::new()
784            .main_axis_size(MainAxisSize::Min)
785            .spacing(spacing)
786            .children(if effective_icon_alignment == IconAlignment::Start {
787                vec![
788                    self.icon.clone(),
789                    Flexible::new(self.label.clone()).into_widget(),
790                ]
791            } else {
792                vec![
793                    Flexible::new(self.label.clone()).into_widget(),
794                    self.icon.clone(),
795                ]
796            })
797            .into_widget()
798    }
799}
800
801/// Dart's `ElevatedButton.icon(..)` arguments; the value converts to the [`ElevatedButton`].
802pub struct ElevatedButtonIcon {
803    button_style_button: ButtonStyleButtonData,
804    icon: Option<WidgetRef>,
805    label: WidgetRef,
806    icon_alignment: Option<IconAlignment>,
807}
808
809impl ElevatedButtonIcon {
810    crate::button_style_button_setters!(
811        ElevatedButtonIcon;
812        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
813        clip_behavior, states_controller, is_selected,
814    );
815
816    /// Dart `ElevatedButton.icon(icon:)`.
817    #[cfg_attr(debug_assertions, track_caller)]
818    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> ElevatedButtonIcon {
819        self.icon = Some(icon.into_widget());
820        self
821    }
822
823    /// Dart `ElevatedButton.icon(iconAlignment:)`.
824    pub fn icon_alignment(mut self, icon_alignment: IconAlignment) -> ElevatedButtonIcon {
825        self.icon_alignment = Some(icon_alignment);
826        self
827    }
828
829    /// The [`ElevatedButton`] these arguments describe.
830    #[cfg_attr(debug_assertions, track_caller)]
831    pub fn build(self) -> ElevatedButton {
832        let mut button_style_button = self.button_style_button;
833        let add_padding = self.icon.is_some();
834        button_style_button.child = Some(match self.icon {
835            Some(icon) => ElevatedButtonWithIconChild {
836                label: self.label,
837                icon,
838                button_style: button_style_button.style.clone(),
839                icon_alignment: self.icon_alignment,
840            }
841            .into_widget(),
842            None => self.label,
843        });
844        ElevatedButton {
845            button_style_button,
846            add_padding,
847        }
848    }
849}
850
851impl IntoWidget<StatefulKind> for ElevatedButtonIcon {
852    #[cfg_attr(debug_assertions, track_caller)]
853    fn into_widget(self) -> WidgetRef {
854        self.build().into_widget()
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use std::cell::{Cell, RefCell};
861    use waft_widgets::testing::assert_f32_equals;
862
863    use waft_embedder::{
864        FontWeight, Offset, PointerChange, RRect, Rect, TargetPlatform, TextDirection,
865    };
866    use waft_foundation::Listenable;
867    use waft_painting::{Alignment, StadiumBorder};
868    use waft_rendering::{
869        RenderFlex, RenderFlexMixin, RenderPhysicalModelBase, RenderPhysicalShape,
870    };
871    use waft_services::{SystemMouseCursor, SystemMouseCursors};
872    use waft_widgets::{
873        AnyElement, Builder, Center, DefaultTextStyle, Directionality, FocusHighlightStrategy,
874        FocusManager, FocusNode, GlobalKey, Icon, IconTheme, MouseRegion, Padding, SizedBox, Text,
875        UnfocusDisposition, WidgetStatesController, downcast_widget,
876    };
877
878    use waft_widgets::testing::{
879        TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
880    };
881
882    use super::*;
883    use crate::color_scheme::ColorScheme;
884    use crate::colors::Colors;
885    use crate::elevated_button_theme::ElevatedButtonThemeData;
886    use crate::icons::Icons;
887    use crate::ink_well::InkWell;
888    use crate::material::{Material, MaterialType};
889    use crate::no_splash::NoSplash;
890    use crate::test_support::{PaintInspection, material_app, path_like};
891    use crate::theme_data::ThemeData;
892    use waft_rendering::testing::RecordedCall;
893    use waft_widgets::FocusNodeRef;
894
895    fn pressed() -> Listener {
896        Listener::new(|_app| {})
897    }
898
899    fn counter(count: &Rc<Cell<usize>>) -> Listener {
900        let count = Rc::clone(count);
901        Listener::new(move |_app| count.set(count.get() + 1))
902    }
903
904    fn text(text: &str) -> WidgetRef {
905        Text::new(text).into_widget()
906    }
907
908    fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
909        Rc::new(MaterialStatePropertyAll::new(Some(value)))
910    }
911
912    fn states(states: &[WidgetState]) -> WidgetStates {
913        states.iter().copied().collect()
914    }
915
916    fn icon() -> WidgetRef {
917        Icon::new(Some(Icons::add())).into_widget()
918    }
919
920    fn m3e_theme(tester: &WidgetTester, style: Option<ButtonStyle>) -> ThemeData {
921        let mut data = ElevatedButtonThemeData::new().variant(StyleVariant::Material3Expressive);
922        data.style = style;
923        ThemeData::builder()
924            .elevated_button_theme(data)
925            .build(&tester.cell.borrow())
926    }
927
928    fn is_inside<W: 'static>(tester: &WidgetTester, element: AnyElement) -> bool {
929        let ancestors = tester.ancestors(element);
930        let app = tester.cell.borrow();
931        ancestors
932            .into_iter()
933            .any(|ancestor| downcast_widget::<W>(&**ancestor.widget(&app)).is_some())
934    }
935
936    /// Dart's `find.descendant(of: find.byType(ElevatedButton), matching: find.byType(W))`,
937    /// first match.
938    fn in_button<W: 'static>(tester: &WidgetTester) -> AnyElement {
939        find::by_type::<W>()
940            .evaluate(tester)
941            .into_iter()
942            .find(|element| is_inside::<ElevatedButton>(tester, *element))
943            .expect("a descendant of the button")
944    }
945
946    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
947        tester.widget::<Material, R>(in_button::<Material>(tester), read)
948    }
949
950    fn padding(tester: &WidgetTester) -> EdgeInsetsGeometry {
951        tester.widget::<Padding, _>(in_button::<Padding>(tester), |padding| padding.padding)
952    }
953
954    fn row_spacing(tester: &WidgetTester) -> f64 {
955        tester.widget::<Row, _>(in_button::<Row>(tester), |row| row.spacing)
956    }
957
958    fn button_size(tester: &WidgetTester) -> Size {
959        let button = find::by_type::<ElevatedButton>().evaluate(tester)[0];
960        tester.get_size(button)
961    }
962
963    fn material_rect(tester: &WidgetTester) -> Rect {
964        tester.get_rect(in_button::<Material>(tester))
965    }
966
967    fn icon_rect(tester: &WidgetTester) -> Rect {
968        tester.get_rect(find::by_type::<Icon>().evaluate(tester)[0])
969    }
970
971    fn shape_is(tester: &WidgetTester, expected: &dyn waft_painting::ShapeBorder) -> bool {
972        material(tester, |material| {
973            material
974                .shape
975                .as_ref()
976                .is_some_and(|shape| shape.eq_shape(expected))
977        })
978    }
979
980    fn rounded(radius: f64) -> RoundedRectangleBorder {
981        RoundedRectangleBorder::new(
982            BorderSide::NONE,
983            BorderRadius::all(Radius::circular(radius)).into(),
984        )
985    }
986
987    fn physical_elevation(tester: &WidgetTester) -> f64 {
988        let shape = tester.first::<RenderPhysicalShape>();
989        shape.elevation(&tester.cell.borrow())
990    }
991
992    fn set_highlight_strategy(tester: &WidgetTester, strategy: FocusHighlightStrategy) {
993        let mut app = tester.cell.borrow_mut();
994        FocusManager::instance(&mut app).set_highlight_strategy(&mut app, strategy);
995    }
996
997    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
998        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
999    }
1000
1001    /// The colours of the rects the button's ink features draw.
1002    fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
1003        tester
1004            .ink_calls()
1005            .into_iter()
1006            .filter_map(|drawn| match drawn {
1007                RecordedCall::Rect { color, .. } => Some(color.value()),
1008                _ => None,
1009            })
1010            .collect()
1011    }
1012
1013    fn argb(color: Color) -> u32 {
1014        color.value()
1015    }
1016
1017    /// The colours and font size a probe in the button's child reads: the ambient icon
1018    /// theme's colour and size, and the default text style's colour and font size.
1019    #[derive(Clone, Copy, Debug, Default, PartialEq)]
1020    struct Ambient {
1021        icon_color: Option<Color>,
1022        icon_size: Option<f64>,
1023        text_color: Option<Color>,
1024        font_size: Option<f64>,
1025    }
1026
1027    fn probe(seen: &Rc<RefCell<Ambient>>, size: Size) -> WidgetRef {
1028        let seen = Rc::clone(seen);
1029        Builder::new(move |app, context| {
1030            let icon_theme = IconTheme::of(app, context);
1031            let text_style = DefaultTextStyle::of(app, context).style;
1032            *seen.borrow_mut() = Ambient {
1033                icon_color: icon_theme.color.map(|color| color.color()),
1034                icon_size: icon_theme.size,
1035                text_color: text_style.color.map(|color| color.color()),
1036                font_size: text_style.font_size,
1037            };
1038            SizedBox::new()
1039                .width(size.width())
1040                .height(size.height())
1041                .into_widget()
1042        })
1043        .into_widget()
1044    }
1045
1046    fn mouse_over(tester: &mut WidgetTester, at: Offset) -> TestPointer {
1047        let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1048        tester.add_pointer(&mut gesture, Offset::ZERO);
1049        tester.move_to(&mut gesture, at, false);
1050        gesture
1051    }
1052
1053    fn button_center(tester: &WidgetTester) -> Offset {
1054        tester.get_center(find::by_type::<ElevatedButton>().evaluate(tester)[0])
1055    }
1056
1057    // elevated_button_test.dart 'ElevatedButton, ElevatedButton.icon defaults'.
1058    #[test]
1059    fn the_material_3_defaults_of_an_elevated_button_and_its_icon_variant() {
1060        test_widgets(|tester| {
1061            let color_scheme = ColorScheme::light();
1062            let theme = ThemeData::from(color_scheme.clone()).build(&tester.cell.borrow());
1063            assert!(theme.use_material3);
1064
1065            let check = |tester: &WidgetTester, elevation: f64| {
1066                material(tester, |material| {
1067                    assert_eq!(material.animation_duration, Duration::from_millis(200));
1068                    assert!(!material.border_on_foreground);
1069                    assert!(material.border_radius.is_none());
1070                    assert_eq!(material.clip_behavior, Clip::None);
1071                    assert_eq!(material.color, Some(color_scheme.on_primary()));
1072                    assert_eq!(material.elevation, elevation);
1073                    assert_eq!(material.shadow_color, Some(Color::new(0xff000000)));
1074                    assert!(
1075                        material
1076                            .shape
1077                            .as_ref()
1078                            .expect("a shape")
1079                            .eq_shape(&StadiumBorder::default())
1080                    );
1081                    let text_style = material.text_style.as_ref().expect("a text style");
1082                    assert_eq!(
1083                        text_style.color.as_ref().map(|color| color.color()),
1084                        Some(color_scheme.primary())
1085                    );
1086                    assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
1087                    assert_eq!(text_style.font_size, Some(14.0));
1088                    assert_eq!(text_style.font_weight, Some(FontWeight::W500));
1089                    assert_eq!(material.r#type, MaterialType::Button);
1090                });
1091            };
1092
1093            // Enabled ElevatedButton
1094            tester.pump_widget(material_app(
1095                theme.clone(),
1096                Center::new()
1097                    .child(ElevatedButton::new(Some(pressed()), Some(text("button"))))
1098                    .into_widget(),
1099            ));
1100            check(tester, 1.0);
1101            let align = in_button::<waft_widgets::Align>(tester);
1102            tester.widget::<waft_widgets::Align, _>(align, |align| {
1103                assert!(align.alignment == AlignmentGeometry::from(Alignment::CENTER));
1104            });
1105
1106            let center = button_center(tester);
1107            let mut gesture = TestPointer::touch(1);
1108            tester.down(&mut gesture, center);
1109            tester.pump(); // start the splash animation
1110            tester.pump_by(Duration::from_millis(100)); // splash is underway
1111
1112            // Only elevation changes when enabled and pressed.
1113            check(tester, 1.0);
1114            tester.up(&gesture);
1115            tester.pump_and_settle();
1116
1117            // Enabled ElevatedButton.icon
1118            tester.pump_widget(material_app(
1119                theme.clone(),
1120                Center::new()
1121                    .child(ElevatedButton::icon(Some(pressed()), text("label")).icon(icon()))
1122                    .into_widget(),
1123            ));
1124            check(tester, 1.0);
1125
1126            // Disabled ElevatedButton
1127            tester.pump_widget(material_app(
1128                theme,
1129                Center::new()
1130                    .child(ElevatedButton::new(None, Some(text("button"))))
1131                    .into_widget(),
1132            ));
1133            // Finish the elevation animation, final background color change.
1134            tester.pump_and_settle();
1135            material(tester, |material| {
1136                assert_eq!(
1137                    material.color,
1138                    Some(color_scheme.on_surface().with_opacity(0.12))
1139                );
1140                assert_eq!(material.elevation, 0.0);
1141                let text_style = material.text_style.as_ref().expect("a text style");
1142                assert_eq!(
1143                    text_style.color.as_ref().map(|color| color.color()),
1144                    Some(color_scheme.on_surface().with_opacity(0.38))
1145                );
1146                assert_eq!(material.r#type, MaterialType::Button);
1147            });
1148        });
1149    }
1150
1151    fn captured_default_style(
1152        tester: &mut WidgetTester,
1153        theme: ThemeData,
1154        button: ElevatedButton,
1155    ) -> ButtonStyle {
1156        let style = Rc::new(RefCell::new(None));
1157        let button = Rc::new(button);
1158        let home = Builder::new({
1159            let style = Rc::clone(&style);
1160            let button = Rc::clone(&button);
1161            move |app, context| {
1162                *style.borrow_mut() = Some(button.default_style_of(app, context).copy_with(app));
1163                SizedBox::shrink().into_widget()
1164            }
1165        });
1166        tester.pump_widget(material_app(theme, home.into_widget()));
1167        style.borrow_mut().take().expect("built")
1168    }
1169
1170    fn assert_complete(style: &ButtonStyle) {
1171        // Properties that must be non-null.
1172        assert!(style.text_style.is_some(), "textStyle style");
1173        assert!(style.background_color.is_some(), "backgroundColor style");
1174        assert!(style.foreground_color.is_some(), "foregroundColor style");
1175        assert!(style.overlay_color.is_some(), "overlayColor style");
1176        assert!(style.shadow_color.is_some(), "shadowColor style");
1177        assert!(style.surface_tint_color.is_some(), "surfaceTintColor style");
1178        assert!(style.elevation.is_some(), "elevation style");
1179        assert!(style.padding.is_some(), "padding style");
1180        assert!(style.minimum_size.is_some(), "minimumSize style");
1181        assert!(style.maximum_size.is_some(), "maximumSize style");
1182        assert!(style.icon_color.is_some(), "iconColor style");
1183        assert!(style.icon_size.is_some(), "iconSize style");
1184        assert!(style.shape.is_some(), "shape style");
1185        assert!(style.mouse_cursor.is_some(), "mouseCursor style");
1186        assert!(style.visual_density.is_some(), "visualDensity style");
1187        assert!(style.tap_target_size.is_some(), "tapTargetSize style");
1188        assert!(
1189            style.animation_duration.is_some(),
1190            "animationDuration style"
1191        );
1192        assert!(style.enable_feedback.is_some(), "enableFeedback style");
1193        assert!(style.alignment.is_some(), "alignment style");
1194        assert!(style.splash_factory.is_some(), "splashFactory style");
1195
1196        // Properties that are expected to be null.
1197        assert!(style.fixed_size.is_none(), "fixedSize style");
1198        assert!(style.side.is_none(), "side style");
1199        assert!(
1200            style.background_builder.is_none(),
1201            "backgroundBuilder style"
1202        );
1203        assert!(
1204            style.foreground_builder.is_none(),
1205            "foregroundBuilder style"
1206        );
1207    }
1208
1209    // elevated_button_test.dart 'ElevatedButton.defaultStyle produces a ButtonStyle with
1210    // appropriate non-null values' and its 'with an icon' twin.
1211    #[test]
1212    fn the_default_style_fills_every_property_but_the_overriding_ones() {
1213        test_widgets(|tester| {
1214            let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
1215            let style = captured_default_style(
1216                tester,
1217                theme.clone(),
1218                ElevatedButton::new(Some(pressed()), Some(text("button"))),
1219            );
1220            assert_complete(&style);
1221            let style = captured_default_style(
1222                tester,
1223                theme,
1224                ElevatedButton::icon(Some(pressed()), text("button"))
1225                    .icon(SizedBox::new())
1226                    .build(),
1227            );
1228            assert_complete(&style);
1229        });
1230    }
1231
1232    // elevated_button_test.dart 'ElevatedButton.icon produces the correct widgets if icon is
1233    // null'.
1234    #[test]
1235    fn an_icon_button_without_an_icon_shows_only_its_label() {
1236        test_widgets(|tester| {
1237            let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
1238            let label_key = GlobalKey::new();
1239            let label = || {
1240                SizedBox::new()
1241                    .width(70.0)
1242                    .height(14.0)
1243                    .key(label_key.clone().into())
1244                    .into_widget()
1245            };
1246            tester.pump_widget(material_app(
1247                theme.clone(),
1248                Center::new()
1249                    .child(ElevatedButton::icon(Some(pressed()), label()).icon(icon()))
1250                    .into_widget(),
1251            ));
1252            assert_eq!(find::by_type::<Icon>().evaluate(tester).len(), 1);
1253            assert!(
1254                label_key
1255                    .current_context(&tester.cell.borrow_mut())
1256                    .is_some()
1257            );
1258
1259            tester.pump_widget(material_app(
1260                theme,
1261                Center::new()
1262                    // No icon specified.
1263                    .child(ElevatedButton::icon(Some(pressed()), label()))
1264                    .into_widget(),
1265            ));
1266            assert!(find::by_type::<Icon>().evaluate(tester).is_empty());
1267            assert!(
1268                label_key
1269                    .current_context(&tester.cell.borrow_mut())
1270                    .is_some()
1271            );
1272            assert!(find::by_type::<Row>().evaluate(tester).is_empty());
1273        });
1274    }
1275
1276    // elevated_button_test.dart 'ElevatedButton default overlayColor and elevation resolve
1277    // pressed state'.
1278    #[test]
1279    fn the_default_overlay_color_and_elevation_follow_hover_press_and_focus() {
1280        test_widgets(|tester| {
1281            let focus_node = focus_node(tester);
1282            let theme = ThemeData::new(&tester.cell.borrow());
1283            let primary = theme.color_scheme.primary();
1284            tester.pump_widget(material_app(
1285                theme,
1286                Center::new()
1287                    .child(
1288                        ElevatedButton::new(Some(pressed()), Some(text("ElevatedButton")))
1289                            .focus_node(focus_node.clone()),
1290                    )
1291                    .into_widget(),
1292            ));
1293
1294            // Hovered.
1295            let center = button_center(tester);
1296            let mut gesture = mouse_over(tester, center);
1297            tester.pump_and_settle();
1298            assert_eq!(physical_elevation(tester), 3.0);
1299            assert_eq!(
1300                ink_rect_colors(tester),
1301                vec![argb(primary.with_opacity(0.08))]
1302            );
1303
1304            // Highlighted (pressed).
1305            tester.send(&gesture, waft_embedder::PointerChange::Down);
1306            tester.pump_and_settle();
1307            assert_eq!(physical_elevation(tester), 1.0);
1308            assert_eq!(ink_rect_colors(tester)[1], argb(primary.with_opacity(0.1)));
1309            // Remove pressed and hovered states
1310            tester.up(&gesture);
1311            tester.pump_and_settle();
1312            tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
1313            tester.pump_and_settle();
1314
1315            // Focused.
1316            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1317            tester.pump_and_settle();
1318            assert_eq!(physical_elevation(tester), 1.0);
1319            assert_eq!(
1320                ink_rect_colors(tester),
1321                vec![argb(primary.with_opacity(0.1))]
1322            );
1323        });
1324    }
1325
1326    fn state_color(states: &WidgetStates) -> Option<Color> {
1327        if states.contains(&WidgetState::Pressed) {
1328            return Some(Color::new(0x00000001));
1329        }
1330        if states.contains(&WidgetState::Hovered) {
1331            return Some(Color::new(0x00000002));
1332        }
1333        if states.contains(&WidgetState::Focused) {
1334            return Some(Color::new(0x00000003));
1335        }
1336        Some(Color::new(0x00000004))
1337    }
1338
1339    // elevated_button_test.dart 'ElevatedButton uses stateful color for text color in
1340    // different states' and 'ElevatedButton uses stateful color for icon color in different
1341    // states'.
1342    #[test]
1343    fn a_theme_foreground_and_icon_color_resolve_per_state() {
1344        for with_icon in [false, true] {
1345            test_widgets(|tester| {
1346                let focus_node = focus_node(tester);
1347                let seen = Rc::new(RefCell::new(Ambient::default()));
1348                let child = probe(&seen, Size::new(196.0, 14.0));
1349                let button = if with_icon {
1350                    ElevatedButton::icon(Some(pressed()), text("ElevatedButton"))
1351                        .icon(child)
1352                        .build()
1353                } else {
1354                    ElevatedButton::new(Some(pressed()), Some(child))
1355                };
1356                let theme = ThemeData::new(&tester.cell.borrow());
1357                tester.pump_widget(material_app(
1358                    theme,
1359                    Center::new()
1360                        .child(ElevatedButtonTheme::new(
1361                            ElevatedButtonThemeData::new().style(
1362                                ButtonStyle::new()
1363                                    .foreground_color(<dyn WidgetStateProperty<_>>::resolve_with(
1364                                        state_color,
1365                                    ))
1366                                    .icon_color(<dyn WidgetStateProperty<_>>::resolve_with(
1367                                        state_color,
1368                                    )),
1369                            ),
1370                            button.focus_node(focus_node.clone()),
1371                        ))
1372                        .into_widget(),
1373                ));
1374                let color = |tester: &WidgetTester| {
1375                    let ambient = *seen.borrow();
1376                    let _ = tester;
1377                    if with_icon {
1378                        ambient.icon_color
1379                    } else {
1380                        ambient.text_color
1381                    }
1382                };
1383
1384                // Default, not disabled.
1385                assert_eq!(color(tester), Some(Color::new(0x00000004)));
1386
1387                // Focused.
1388                focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1389                tester.pump_and_settle();
1390                assert_eq!(color(tester), Some(Color::new(0x00000003)));
1391
1392                // Hovered.
1393                let center = button_center(tester);
1394                let gesture = mouse_over(tester, center);
1395                tester.pump_and_settle();
1396                assert_eq!(color(tester), Some(Color::new(0x00000002)));
1397
1398                // Highlighted (pressed).
1399                tester.send(&gesture, waft_embedder::PointerChange::Down);
1400                tester.pump(); // Start the splash and highlight animations.
1401                // Wait for splash and highlight to be well under way.
1402                tester.pump_by(Duration::from_millis(800));
1403                assert_eq!(color(tester), Some(Color::new(0x00000001)));
1404            });
1405        }
1406    }
1407
1408    // elevated_button_test.dart 'ElevatedButton onPressed and onLongPress callbacks are
1409    // correctly called when non-null'.
1410    #[test]
1411    fn either_callback_enables_the_button_and_reaches_it() {
1412        test_widgets(|tester| {
1413            let was_pressed = Rc::new(Cell::new(0));
1414            let build_frame = |on_pressed: Option<Listener>, on_long_press: Option<Listener>| {
1415                let mut button = ElevatedButton::new(on_pressed, Some(text("button")));
1416                if let Some(on_long_press) = on_long_press {
1417                    button = button.on_long_press(on_long_press);
1418                }
1419                Directionality::new(TextDirection::Ltr, button).into_widget()
1420            };
1421            let enabled = |tester: &WidgetTester| {
1422                let button = find::by_type::<ElevatedButton>().evaluate(tester)[0];
1423                tester.widget::<ElevatedButton, _>(button, |button| button.enabled())
1424            };
1425
1426            // onPressed not null, onLongPress null.
1427            tester.pump_widget(build_frame(Some(counter(&was_pressed)), None));
1428            assert!(enabled(tester));
1429            tester.tap_at(button_center(tester), 1);
1430            assert_eq!(was_pressed.get(), 1);
1431
1432            // onPressed null, onLongPress not null.
1433            tester.pump_widget(build_frame(None, Some(counter(&was_pressed))));
1434            assert!(enabled(tester));
1435            tester.long_press_at(button_center(tester), 2);
1436            assert_eq!(was_pressed.get(), 2);
1437
1438            // onPressed null, onLongPress null.
1439            tester.pump_widget(build_frame(None, None));
1440            assert!(!enabled(tester));
1441        });
1442    }
1443
1444    // elevated_button_test.dart "ElevatedButton response doesn't hover when disabled".
1445    #[test]
1446    fn a_disabled_button_gives_up_its_focus() {
1447        test_widgets(|tester| {
1448            set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTouch);
1449            let focus_node = focus_node(tester);
1450            let hovering = Rc::new(Cell::new(false));
1451            let child_key = GlobalKey::new();
1452            let on_hover = || -> waft_foundation::ValueChanged<bool> {
1453                let hovering = Rc::clone(&hovering);
1454                Rc::new(move |_app, value| hovering.set(value))
1455            };
1456            let frame = |button: ElevatedButton| {
1457                Directionality::new(
1458                    TextDirection::Ltr,
1459                    SizedBox::square(Some(100.0)).child(button.focus_node(focus_node.clone())),
1460                )
1461                .into_widget()
1462            };
1463            tester.pump_widget(frame(
1464                ElevatedButton::new(
1465                    Some(pressed()),
1466                    Some(SizedBox::new().key(child_key.clone().into())),
1467                )
1468                .autofocus(true)
1469                .on_long_press(pressed())
1470                .on_hover(on_hover()),
1471            ));
1472            tester.pump_and_settle();
1473            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1474            let center = tester.get_center(&child_key);
1475            mouse_over(tester, center);
1476            tester.pump_and_settle();
1477            assert!(hovering.get());
1478
1479            tester.pump_widget(frame(
1480                ElevatedButton::new(None, Some(SizedBox::new().key(child_key.clone().into())))
1481                    .on_hover(on_hover()),
1482            ));
1483            tester.pump_and_settle();
1484            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
1485        });
1486    }
1487
1488    // elevated_button_test.dart 'disabled and hovered ElevatedButton responds to mouse-exit'.
1489    #[test]
1490    fn a_disabled_hovered_button_still_reports_the_mouse_leaving() {
1491        test_widgets(|tester| {
1492            let on_hover_count = Rc::new(Cell::new(0));
1493            let hover = Rc::new(Cell::new(false));
1494            let build_frame = |enabled: bool| {
1495                let on_hover_count = Rc::clone(&on_hover_count);
1496                let hover = Rc::clone(&hover);
1497                Directionality::new(
1498                    TextDirection::Ltr,
1499                    Center::new().child(
1500                        SizedBox::square(Some(100.0)).child(
1501                            ElevatedButton::new(
1502                                enabled.then(pressed),
1503                                Some(text("ElevatedButton")),
1504                            )
1505                            .on_hover(Rc::new(move |_app, value| {
1506                                on_hover_count.set(on_hover_count.get() + 1);
1507                                hover.set(value);
1508                            })),
1509                        ),
1510                    ),
1511                )
1512                .into_widget()
1513            };
1514
1515            tester.pump_widget(build_frame(true));
1516            let center = button_center(tester);
1517            let mut gesture = mouse_over(tester, center);
1518            tester.pump_and_settle();
1519            assert_eq!(on_hover_count.get(), 1);
1520            assert!(hover.get());
1521
1522            tester.pump_widget(build_frame(false));
1523            tester.pump_and_settle();
1524            tester.move_to(&mut gesture, Offset::ZERO, false);
1525            // Even though the ElevatedButton has been disabled, the mouse-exit still
1526            // causes onHover(false) to be called.
1527            assert_eq!(on_hover_count.get(), 2);
1528            assert!(!hover.get());
1529
1530            tester.move_to(&mut gesture, center, false);
1531            tester.pump_and_settle();
1532            // We no longer see hover events because the ElevatedButton is disabled
1533            // and it's no longer in the "hovering" state.
1534            assert_eq!(on_hover_count.get(), 2);
1535            assert!(!hover.get());
1536
1537            tester.pump_widget(build_frame(true));
1538            tester.pump_and_settle();
1539            // The ElevatedButton was enabled while it contained the mouse, however
1540            // we do not call onHover() because it may call setState().
1541            assert_eq!(on_hover_count.get(), 2);
1542            assert!(!hover.get());
1543
1544            tester.move_to(&mut gesture, center - Offset::new(1.0, 1.0), false);
1545            tester.pump_and_settle();
1546            // Moving the mouse a little within the ElevatedButton doesn't change anything.
1547            assert_eq!(on_hover_count.get(), 2);
1548            assert!(!hover.get());
1549        });
1550    }
1551
1552    // elevated_button_test.dart 'Can set ElevatedButton focus and Can set unFocus.' and 'When
1553    // ElevatedButton disable, Can not set ElevatedButton focus.'.
1554    #[test]
1555    fn on_focus_change_reports_focus_of_an_enabled_button_only() {
1556        test_widgets(|tester| {
1557            for enabled in [true, false] {
1558                let node = focus_node(tester);
1559                let got_focus = Rc::new(Cell::new(false));
1560                let on_focus_change: waft_foundation::ValueChanged<bool> = {
1561                    let got_focus = Rc::clone(&got_focus);
1562                    Rc::new(move |_app, focused| got_focus.set(focused))
1563                };
1564                tester.pump_widget(
1565                    Directionality::new(
1566                        TextDirection::Ltr,
1567                        ElevatedButton::new(enabled.then(pressed), Some(SizedBox::new()))
1568                            .focus_node(node.clone())
1569                            .on_focus_change(on_focus_change),
1570                    )
1571                    .into_widget(),
1572                );
1573
1574                node.request_focus(&mut tester.cell.borrow_mut(), None);
1575                tester.pump();
1576                assert_eq!(got_focus.get(), enabled);
1577                assert_eq!(node.has_focus(&tester.cell.borrow_mut()), enabled);
1578
1579                if enabled {
1580                    node.unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
1581                    tester.pump();
1582                    assert!(!got_focus.get());
1583                    assert!(!node.has_focus(&tester.cell.borrow_mut()));
1584                }
1585            }
1586        });
1587    }
1588
1589    // elevated_button_test.dart 'Does ElevatedButton work with hover', '... with focus' and
1590    // '... with autofocus'.
1591    #[test]
1592    fn a_style_overlay_color_shows_on_hover_focus_and_autofocus() {
1593        test_widgets(|tester| {
1594            let color = Color::new(0xff001122);
1595            let overlay = |state: WidgetState| {
1596                ButtonStyle::new().overlay_color(<dyn WidgetStateProperty<_>>::resolve_with(
1597                    move |states| states.contains(&state).then_some(color),
1598                ))
1599            };
1600            let ltr = |button: ElevatedButton| {
1601                Directionality::new(TextDirection::Ltr, button).into_widget()
1602            };
1603
1604            tester.pump_widget(ltr(ElevatedButton::new(
1605                Some(pressed()),
1606                Some(text("button")),
1607            )
1608            .style(overlay(WidgetState::Hovered))));
1609            let center = button_center(tester);
1610            mouse_over(tester, center);
1611            tester.pump_and_settle();
1612            assert!(ink_rect_colors(tester).contains(&argb(color)));
1613
1614            let node = focus_node(tester);
1615            tester.pump_widget(ltr(ElevatedButton::new(
1616                Some(pressed()),
1617                Some(text("button")),
1618            )
1619            .style(overlay(WidgetState::Focused))
1620            .focus_node(node.clone())));
1621            set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
1622            node.request_focus(&mut tester.cell.borrow_mut(), None);
1623            tester.pump_and_settle();
1624            assert!(ink_rect_colors(tester).contains(&argb(color)));
1625
1626            let node = focus_node(tester);
1627            tester.pump_widget(ltr(ElevatedButton::new(
1628                Some(pressed()),
1629                Some(text("button")),
1630            )
1631            .autofocus(true)
1632            .style(overlay(WidgetState::Focused))
1633            .focus_node(node)));
1634            set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
1635            tester.pump_and_settle();
1636            assert!(ink_rect_colors(tester).contains(&argb(color)));
1637        });
1638    }
1639
1640    // elevated_button_test.dart 'ElevatedButton.icon responds to applied padding'.
1641    #[test]
1642    fn an_icon_button_puts_its_padding_around_the_icon_and_label() {
1643        test_widgets(|tester| {
1644            let label_key = GlobalKey::new();
1645            tester.pump_widget(
1646                Directionality::new(
1647                    TextDirection::Ltr,
1648                    Center::new().child(
1649                        ElevatedButton::icon(
1650                            Some(pressed()),
1651                            // 'Hello' at the label style's 14 pixels and 1.43 line height, whose line
1652                            // is 20 pixels high.
1653                            SizedBox::new()
1654                                .width(70.0)
1655                                .height(20.0)
1656                                .key(label_key.clone().into()),
1657                        )
1658                        .icon(icon())
1659                        .style(
1660                            ButtonStyle::new()
1661                                .padding(all(EdgeInsetsGeometry::from_ltrb(16.0, 5.0, 10.0, 12.0))),
1662                        ),
1663                    ),
1664                )
1665                .into_widget(),
1666            );
1667
1668            let padding_rect = tester.get_rect(in_button::<Padding>(tester));
1669            let label = label_key
1670                .current_context(&tester.cell.borrow_mut())
1671                .expect("mounted");
1672            let label_rect = tester.get_rect(label);
1673            let icon_rect = icon_rect(tester);
1674
1675            // The right padding should be applied on the right of the label, whereas the
1676            // left padding should be applied on the left side of the icon.
1677            assert_eq!(padding_rect.right, label_rect.right + 10.0);
1678            assert_eq!(padding_rect.left, icon_rect.left - 16.0);
1679            // Use the taller widget to check the top and bottom padding.
1680            let taller_widget = if icon_rect.height() > label_rect.height() {
1681                icon_rect
1682            } else {
1683                label_rect
1684            };
1685            assert_eq!(padding_rect.top, taller_widget.top - 6.5);
1686            assert_eq!(padding_rect.bottom, taller_widget.bottom + 13.5);
1687        });
1688    }
1689
1690    // elevated_button_test.dart 'Default ElevatedButton padding for textScaleFactor,
1691    // textDirection'.
1692    #[test]
1693    fn the_material_2_padding_and_icon_gap_scale_with_the_text() {
1694        test_widgets(|tester| {
1695            let text_scale_factor_options = [0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0];
1696            // Expected values for each textScaleFactor.
1697            let padding_without_icon_start = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1698            let padding_without_icon_end = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1699            let padding_with_icon_start = [12.0, 12.0, 11.0, 10.0, 8.0, 8.0, 8.0, 8.0];
1700            let padding_with_icon_end = [16.0, 16.0, 14.0, 12.0, 8.0, 6.0, 4.0, 4.0];
1701            let padding_with_icon_gap = [8.0, 8.0, 7.0, 6.0, 4.0, 4.0, 4.0, 4.0];
1702            for (index, text_scale_factor) in text_scale_factor_options.into_iter().enumerate() {
1703                for text_direction in [TextDirection::Ltr, TextDirection::Rtl] {
1704                    for with_icon in [false, true] {
1705                        let button_key = GlobalKey::new();
1706                        let label_key = GlobalKey::new();
1707                        let icon_key = GlobalKey::new();
1708                        let theme = ThemeData::builder()
1709                            .use_material3(false)
1710                            .color_scheme(ColorScheme::light())
1711                            .elevated_button_theme(
1712                                ElevatedButtonThemeData::new().style(
1713                                    ElevatedButton::style_from()
1714                                        .minimum_size(Size::new(64.0, 36.0))
1715                                        .build(),
1716                                ),
1717                            )
1718                            .build(&tester.cell.borrow());
1719                        let label = Text::new("button").key(label_key.clone().into());
1720                        let button = if with_icon {
1721                            ElevatedButton::icon(Some(pressed()), label)
1722                                .key(button_key.clone().into())
1723                                .icon(
1724                                    Icon::new(Some(Icons::add()))
1725                                        .size(18.0)
1726                                        .key(icon_key.clone().into()),
1727                                )
1728                                .build()
1729                        } else {
1730                            ElevatedButton::new(Some(pressed()), Some(label))
1731                                .key(button_key.clone().into())
1732                        };
1733                        // Dart's `Scaffold(body:)` is the `Material` the text sits on.
1734                        tester.pump_widget(material_app(
1735                            theme,
1736                            MediaQuery::with_clamped_text_scaling(
1737                                None,
1738                                text_scale_factor,
1739                                text_scale_factor,
1740                                Directionality::new(
1741                                    text_direction,
1742                                    Material::new().child(Center::new().child(button)),
1743                                ),
1744                            ),
1745                        ));
1746
1747                        let padding_element = in_button::<Padding>(tester);
1748                        assert_eq!(
1749                            Directionality::of(&mut tester.cell.borrow_mut(), padding_element),
1750                            text_direction
1751                        );
1752
1753                        // Compute expected padding, and check.
1754                        let (expected_start, expected_end) = if with_icon {
1755                            (padding_with_icon_start[index], padding_with_icon_end[index])
1756                        } else {
1757                            (
1758                                padding_without_icon_start[index],
1759                                padding_without_icon_end[index],
1760                            )
1761                        };
1762                        let expected_padding =
1763                            EdgeInsetsGeometry::from_steb(expected_start, 0.0, expected_end, 0.0)
1764                                .resolve(Some(text_direction));
1765                        assert_eq!(
1766                            padding(tester).resolve(Some(text_direction)),
1767                            expected_padding,
1768                            "text scale {text_scale_factor}, icon {with_icon}, {text_direction:?}"
1769                        );
1770
1771                        // Measure padding in terms of the difference between the button and
1772                        // its label child and check that.
1773                        let label_bounds = tester.get_rect(&label_key);
1774                        let icon_bounds = with_icon.then(|| tester.get_rect(&icon_key));
1775                        let child_bounds = match icon_bounds {
1776                            Some(icon_bounds) => label_bounds.expand_to_include(icon_bounds),
1777                            None => label_bounds,
1778                        };
1779
1780                        // We measure the `InkResponse` descendant of the button element,
1781                        // because the button has a larger `RenderBox` which accommodates the
1782                        // minimum tap target with a height of 48.
1783                        let button_bounds = tester.get_rect(in_button::<InkWell>(tester));
1784
1785                        // Since there is a requirement of a minimum width of 64 and a minimum
1786                        // height of 36 on material buttons, the visual padding of smaller
1787                        // buttons may not match their settings. Therefore, we only test
1788                        // buttons that are large enough.
1789                        if button_bounds.width() > 64.0 {
1790                            assert_eq!(
1791                                child_bounds.left - button_bounds.left,
1792                                expected_padding.left
1793                            );
1794                            assert_eq!(
1795                                button_bounds.right - child_bounds.right,
1796                                expected_padding.right
1797                            );
1798                        }
1799                        if button_bounds.height() > 36.0 {
1800                            assert_eq!(child_bounds.top - button_bounds.top, expected_padding.top);
1801                            assert_eq!(
1802                                button_bounds.bottom - child_bounds.bottom,
1803                                expected_padding.bottom
1804                            );
1805                        }
1806
1807                        // Check the gap between the icon and the label
1808                        if let Some(icon_bounds) = icon_bounds {
1809                            let gap_width = if text_direction == TextDirection::Ltr {
1810                                label_bounds.left - icon_bounds.right
1811                            } else {
1812                                icon_bounds.left - label_bounds.right
1813                            };
1814                            assert_eq!(gap_width, padding_with_icon_gap[index]);
1815                        }
1816                    }
1817                }
1818            }
1819        });
1820    }
1821
1822    // elevated_button_test.dart 'Override theme fontSize changes padding', 'Override
1823    // ElevatedButton default padding', 'M3 ElevatedButton has correct padding' and 'M3
1824    // ElevatedButton.icon has correct padding'.
1825    #[test]
1826    fn the_material_3_padding_follows_the_font_size_the_style_and_the_icon() {
1827        test_widgets(|tester| {
1828            let mut text_theme = crate::text_theme::TextTheme::new();
1829            text_theme.label_large = Some(TextStyle::new().font_size(28.0));
1830            let theme = ThemeData::from(ColorScheme::light())
1831                .text_theme(text_theme)
1832                .build(&tester.cell.borrow());
1833            tester.pump_widget(material_app(
1834                theme,
1835                Center::new()
1836                    .child(ElevatedButton::new(Some(pressed()), Some(text("text"))))
1837                    .into_widget(),
1838            ));
1839            tester.pump_and_settle();
1840            assert!(padding(tester) == EdgeInsetsGeometry::symmetric(0.0, 12.0));
1841
1842            let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
1843            tester.pump_widget(material_app(
1844                theme.clone(),
1845                MediaQuery::with_clamped_text_scaling(
1846                    None,
1847                    2.0,
1848                    2.0,
1849                    Center::new().child(
1850                        ElevatedButton::new(Some(pressed()), Some(text("ElevatedButton"))).style(
1851                            ElevatedButton::style_from()
1852                                .padding(EdgeInsetsGeometry::all(22.0))
1853                                .build(),
1854                        ),
1855                    ),
1856                ),
1857            ));
1858            tester.pump_and_settle();
1859            assert!(padding(tester) == EdgeInsetsGeometry::all(22.0));
1860
1861            tester.pump_widget(material_app(
1862                theme.clone(),
1863                Center::new()
1864                    .child(ElevatedButton::new(
1865                        Some(pressed()),
1866                        Some(text("ElevatedButton")),
1867                    ))
1868                    .into_widget(),
1869            ));
1870            tester.pump_and_settle();
1871            assert!(padding(tester) == EdgeInsetsGeometry::symmetric(0.0, 24.0));
1872
1873            tester.pump_widget(material_app(
1874                theme,
1875                Center::new()
1876                    .child(
1877                        ElevatedButton::icon(Some(pressed()), text("ElevatedButton")).icon(icon()),
1878                    )
1879                    .into_widget(),
1880            ));
1881            tester.pump_and_settle();
1882            assert!(padding(tester) == EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0));
1883        });
1884    }
1885
1886    // elevated_button_test.dart 'ElevatedButton with NoSplash splashFactory paints nothing'.
1887    #[test]
1888    fn a_no_splash_factory_draws_no_splash_and_a_ripple_draws_one() {
1889        test_widgets(|tester| {
1890            for (splash_factory, circles) in [
1891                (NoSplash::splash_factory(), 0),
1892                (InkRipple::splash_factory(), 1),
1893            ] {
1894                let theme = ThemeData::new(&tester.cell.borrow());
1895                tester.pump_widget(material_app(
1896                    theme,
1897                    Center::new()
1898                        .child(
1899                            ElevatedButton::new(Some(pressed()), Some(text("test"))).style(
1900                                ElevatedButton::style_from()
1901                                    .splash_factory(splash_factory)
1902                                    .build(),
1903                            ),
1904                        )
1905                        .into_widget(),
1906                ));
1907                let center = button_center(tester);
1908                let mut gesture = TestPointer::touch(1);
1909                tester.down(&mut gesture, center);
1910                // No circle is recorded on the frame the ripple's fade-in starts at alpha 0,
1911                // where Dart's matcher counts that call, so the splash starts a frame earlier.
1912                tester.pump();
1913                tester.pump_by(Duration::from_millis(200));
1914                let drawn = tester
1915                    .ink_calls()
1916                    .into_iter()
1917                    .filter(|drawn| path_like(drawn).is_some())
1918                    .count();
1919                assert_eq!(drawn, circles);
1920                tester.up(&gesture);
1921                tester.pump_and_settle();
1922            }
1923        });
1924    }
1925
1926    // elevated_button_test.dart 'ElevatedButton uses InkRipple when useMaterial3 is false',
1927    // under every platform it names.
1928    #[test]
1929    fn a_material_2_button_splashes_with_ripples_on_every_platform() {
1930        test_widgets(|_| {
1931            for platform in [
1932                TargetPlatform::Android,
1933                TargetPlatform::Fuchsia,
1934                TargetPlatform::IOS,
1935                TargetPlatform::Linux,
1936                TargetPlatform::MacOS,
1937                TargetPlatform::Windows,
1938            ] {
1939                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1940                    let theme = ThemeData::builder()
1941                        .use_material3(false)
1942                        .build(&tester.cell.borrow());
1943                    tester.pump_widget(material_app(
1944                        theme,
1945                        Center::new()
1946                            .child(ElevatedButton::new(Some(pressed()), Some(text("button"))))
1947                            .into_widget(),
1948                    ));
1949                    let splash_factory = tester
1950                        .widget::<InkWell, _>(in_button::<InkWell>(tester), |ink_well| {
1951                            ink_well.ink_response.splash_factory.clone()
1952                        });
1953                    assert!(Rc::ptr_eq(
1954                        &splash_factory.expect("a splash factory"),
1955                        &InkRipple::splash_factory()
1956                    ));
1957                });
1958            }
1959        });
1960    }
1961
1962    // elevated_button_test.dart 'ElevatedButton.icon icon,label layout'.
1963    #[test]
1964    fn an_icon_button_lays_out_icon_gap_and_label_centred() {
1965        test_widgets(|tester| {
1966            let button_key = GlobalKey::new();
1967            let icon_key = GlobalKey::new();
1968            let label_key = GlobalKey::new();
1969            let style = ElevatedButton::style_from()
1970                .padding(EdgeInsetsGeometry::ZERO)
1971                .visual_density(VisualDensity::STANDARD) // dx=0, dy=0
1972                .build();
1973            let theme = ThemeData::new(&tester.cell.borrow());
1974            tester.pump_widget(material_app(
1975                theme,
1976                // Dart's `Scaffold(body:)` lays its body out loosely at the top left.
1977                waft_widgets::Align::new()
1978                    .alignment(AlignmentGeometry::TOP_LEFT)
1979                    .child(
1980                        SizedBox::new().width(200.0).child(
1981                            ElevatedButton::icon(
1982                                Some(pressed()),
1983                                SizedBox::new()
1984                                    .width(50.0)
1985                                    .height(100.0)
1986                                    .key(label_key.clone().into()),
1987                            )
1988                            .icon(
1989                                SizedBox::new()
1990                                    .width(50.0)
1991                                    .height(100.0)
1992                                    .key(icon_key.clone().into())
1993                                    .into_widget(),
1994                            )
1995                            .key(button_key.clone().into())
1996                            .style(style),
1997                        ),
1998                    )
1999                    .into_widget(),
2000            ));
2001
2002            // The button's label and icon are separated by a gap of 8:
2003            // 46 [icon 50] 8 [label 50] 46
2004            // The overall button width is 200. So:
2005            // icon.x = 46
2006            // label.x = 46 + 50 + 8 = 104
2007            let rect = |key: &GlobalKey| {
2008                let context = key
2009                    .current_context(&tester.cell.borrow_mut())
2010                    .expect("mounted");
2011                tester.get_rect(context)
2012            };
2013            assert_eq!(rect(&button_key), Rect::from_ltrb(0.0, 0.0, 200.0, 100.0));
2014            assert_eq!(rect(&icon_key), Rect::from_ltrb(46.0, 0.0, 96.0, 100.0));
2015            assert_eq!(rect(&label_key), Rect::from_ltrb(104.0, 0.0, 154.0, 100.0));
2016        });
2017    }
2018
2019    // elevated_button_test.dart 'Default ElevatedButton icon alignment', 'ElevatedButton
2020    // icon alignment can be customized' and 'ElevatedButton icon alignment respects
2021    // ButtonStyle.iconAlignment'.
2022    #[test]
2023    fn the_icon_sits_at_the_start_or_end_by_its_alignment_and_the_text_direction() {
2024        test_widgets(|tester| {
2025            let build = |tester: &mut WidgetTester,
2026                         text_direction: TextDirection,
2027                         icon_alignment: Option<IconAlignment>,
2028                         style_alignment: Option<IconAlignment>| {
2029                let mut button = ElevatedButton::icon(Some(pressed()), text("button")).icon(icon());
2030                if let Some(icon_alignment) = icon_alignment {
2031                    button = button.icon_alignment(icon_alignment);
2032                }
2033                if let Some(style_alignment) = style_alignment {
2034                    button = button.style(ButtonStyle::new().icon_alignment(style_alignment));
2035                }
2036                let theme = ThemeData::new(&tester.cell.borrow());
2037                tester.pump_widget(material_app(
2038                    theme,
2039                    Directionality::new(text_direction, Center::new().child(button)).into_widget(),
2040                ));
2041            };
2042            // 16.0 - padding between icon and button edge at the start, 24.0 at the end.
2043            build(tester, TextDirection::Ltr, None, None);
2044            assert_eq!(material_rect(tester).left, icon_rect(tester).left - 16.0);
2045            build(tester, TextDirection::Rtl, None, None);
2046            assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 16.0);
2047
2048            build(tester, TextDirection::Ltr, Some(IconAlignment::Start), None);
2049            assert_eq!(material_rect(tester).left, icon_rect(tester).left - 16.0);
2050            build(tester, TextDirection::Ltr, Some(IconAlignment::End), None);
2051            assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 24.0);
2052            build(tester, TextDirection::Rtl, Some(IconAlignment::Start), None);
2053            assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 16.0);
2054            build(tester, TextDirection::Rtl, Some(IconAlignment::End), None);
2055            assert_eq!(material_rect(tester).left, icon_rect(tester).left - 24.0);
2056
2057            build(tester, TextDirection::Ltr, None, Some(IconAlignment::End));
2058            assert_f32_equals(material_rect(tester).right, icon_rect(tester).right + 24.0);
2059        });
2060    }
2061
2062    // elevated_button_test.dart 'ElevatedButton.styleFrom can be used to set foreground and
2063    // background colors' and 'ElevatedButton.styleFrom can customize the button icon'.
2064    #[test]
2065    fn style_from_turns_each_argument_into_its_property() {
2066        let red = Color::new(0xffff0000);
2067        let green = Color::new(0xff00ff00);
2068        let blue = Color::new(0xff0000ff);
2069        let none = WidgetStates::new();
2070        let disabled = states(&[WidgetState::Disabled]);
2071        let hovered = states(&[WidgetState::Hovered]);
2072        let focused = states(&[WidgetState::Focused]);
2073        let pressed = states(&[WidgetState::Pressed]);
2074        let style = ElevatedButton::style_from()
2075            .foreground_color(red)
2076            .disabled_foreground_color(green)
2077            .background_color(blue)
2078            .disabled_background_color(red)
2079            .icon_color(green)
2080            .disabled_icon_color(blue)
2081            .icon_size(32.0)
2082            .icon_alignment(IconAlignment::End)
2083            .elevation(4.0)
2084            .shadow_color(green)
2085            .surface_tint_color(blue)
2086            .size_variant(ButtonSizeVariant::Large)
2087            .shape_variant(ButtonShapeVariant::Square)
2088            .build();
2089        let resolve = |property: &Option<WidgetStatePropertyRef<Option<Color>>>,
2090                       states: &WidgetStates| {
2091            property
2092                .as_ref()
2093                .and_then(|property| property.resolve(states))
2094        };
2095        assert_eq!(resolve(&style.foreground_color, &none), Some(red));
2096        assert_eq!(resolve(&style.foreground_color, &disabled), Some(green));
2097        assert_eq!(resolve(&style.background_color, &none), Some(blue));
2098        assert_eq!(resolve(&style.background_color, &disabled), Some(red));
2099        assert_eq!(resolve(&style.icon_color, &none), Some(green));
2100        assert_eq!(resolve(&style.icon_color, &disabled), Some(blue));
2101        assert_eq!(resolve(&style.shadow_color, &none), Some(green));
2102        assert_eq!(resolve(&style.surface_tint_color, &none), Some(blue));
2103        // The overlay is the foreground color at the default opacities.
2104        assert_eq!(resolve(&style.overlay_color, &none), None);
2105        assert_eq!(
2106            resolve(&style.overlay_color, &hovered),
2107            Some(red.with_opacity(0.08))
2108        );
2109        assert_eq!(
2110            resolve(&style.overlay_color, &focused),
2111            Some(red.with_opacity(0.1))
2112        );
2113        assert_eq!(
2114            resolve(&style.overlay_color, &pressed),
2115            Some(red.with_opacity(0.1))
2116        );
2117        let elevation = style.elevation.as_ref().expect("an elevation");
2118        assert_eq!(elevation.resolve(&none), Some(4.0));
2119        assert_eq!(elevation.resolve(&disabled), Some(0.0));
2120        assert_eq!(elevation.resolve(&hovered), Some(6.0));
2121        assert_eq!(elevation.resolve(&focused), Some(6.0));
2122        assert_eq!(elevation.resolve(&pressed), Some(10.0));
2123        assert_eq!(
2124            style
2125                .icon_size
2126                .as_ref()
2127                .and_then(|size| size.resolve(&none)),
2128            Some(32.0)
2129        );
2130        assert_eq!(style.icon_alignment, Some(IconAlignment::End));
2131        assert_eq!(style.size_variant, Some(ButtonSizeVariant::Large));
2132        assert_eq!(style.shape_variant, Some(ButtonShapeVariant::Square));
2133        // The text style property is always given, null when no style is.
2134        assert_eq!(
2135            style
2136                .text_style
2137                .as_ref()
2138                .map(|text_style| text_style.resolve(&none)),
2139            Some(None)
2140        );
2141
2142        // A transparent overlay color defeats the highlights; an opaque one replaces the
2143        // foreground's.
2144        let transparent = ElevatedButton::style_from()
2145            .foreground_color(red)
2146            .overlay_color(Color::new(0x00000000))
2147            .build();
2148        assert_eq!(
2149            resolve(&transparent.overlay_color, &hovered),
2150            Some(Color::new(0x00000000))
2151        );
2152        assert_eq!(
2153            resolve(&transparent.overlay_color, &none),
2154            Some(Color::new(0x00000000))
2155        );
2156        let overlay = ElevatedButton::style_from()
2157            .foreground_color(red)
2158            .overlay_color(blue)
2159            .build();
2160        assert_eq!(
2161            resolve(&overlay.overlay_color, &hovered),
2162            Some(blue.with_opacity(0.08))
2163        );
2164
2165        // Nothing given overrides nothing but the two always-given properties.
2166        let empty = ElevatedButton::style_from().build();
2167        assert!(empty.background_color.is_none());
2168        assert!(empty.foreground_color.is_none());
2169        assert!(empty.overlay_color.is_none());
2170        assert!(empty.elevation.is_none());
2171        assert!(empty.padding.is_none());
2172        assert!(empty.shape.is_none());
2173        assert!(empty.text_style.is_some());
2174        let cursor = empty.mouse_cursor.as_ref().expect("a mouse cursor");
2175        assert!(cursor.resolve(&none).is_none());
2176        assert!(cursor.resolve(&disabled).is_none());
2177    }
2178
2179    // elevated_button_test.dart 'ElevatedButton.styleFrom can be used to set foreground and
2180    // background colors', on a built button.
2181    #[test]
2182    fn a_style_from_button_shows_its_colors_and_icon_color() {
2183        test_widgets(|tester| {
2184            let seen = Rc::new(RefCell::new(Ambient::default()));
2185            let theme = ThemeData::new(&tester.cell.borrow());
2186            tester.pump_widget(material_app(
2187                theme,
2188                Center::new()
2189                    .child(
2190                        ElevatedButton::icon(Some(pressed()), text("button"))
2191                            .icon(probe(&seen, Size::new(18.0, 18.0)))
2192                            .style(
2193                                ElevatedButton::style_from()
2194                                    .foreground_color(Color::new(0xffffffff))
2195                                    .background_color(Color::new(0xff000000))
2196                                    .icon_color(Color::new(0xffff0000))
2197                                    .icon_size(32.0)
2198                                    .build(),
2199                            ),
2200                    )
2201                    .into_widget(),
2202            ));
2203            material(tester, |material| {
2204                assert_eq!(material.color, Some(Color::new(0xff000000)));
2205                assert_eq!(
2206                    material
2207                        .text_style
2208                        .as_ref()
2209                        .and_then(|text_style| text_style.color.as_ref())
2210                        .map(|color| color.color()),
2211                    Some(Color::new(0xffffffff))
2212                );
2213            });
2214            assert_eq!(seen.borrow().icon_color, Some(Color::new(0xffff0000)));
2215            assert_eq!(seen.borrow().icon_size, Some(32.0));
2216        });
2217    }
2218
2219    // elevated_button_test.dart 'ElevatedButton.icon does not lose focus when icon is
2220    // nullified'.
2221    #[test]
2222    fn an_icon_button_keeps_its_focus_when_its_icon_goes() {
2223        test_widgets(|tester| {
2224            let focus_node = focus_node(tester);
2225            let build = |tester: &mut WidgetTester, icon: Option<WidgetRef>| {
2226                let button = ElevatedButton::icon(Some(pressed()), text("button"));
2227                let button = match icon {
2228                    Some(icon) => button.icon(icon),
2229                    None => button,
2230                };
2231                let theme = ThemeData::new(&tester.cell.borrow());
2232                tester.pump_widget(material_app(
2233                    theme,
2234                    Center::new()
2235                        .child(button.focus_node(focus_node.clone()).autofocus(true))
2236                        .into_widget(),
2237                ));
2238            };
2239            build(tester, Some(self::icon()));
2240            tester.pump_and_settle();
2241            assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
2242            build(tester, None);
2243            tester.pump_and_settle();
2244            assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
2245        });
2246    }
2247
2248    // elevated_button_test.dart 'M3E ElevatedButton resolves selected and unselected colors'.
2249    #[test]
2250    fn an_expressive_toggle_button_fills_with_primary_when_selected() {
2251        test_widgets(|tester| {
2252            let theme = m3e_theme(tester, None);
2253            let colors = theme.color_scheme.clone();
2254            for (is_selected, color) in [
2255                (false, colors.surface_container_low()),
2256                (true, colors.primary()),
2257            ] {
2258                tester.pump_widget(material_app(
2259                    theme.clone(),
2260                    Center::new()
2261                        .child(
2262                            ElevatedButton::new(Some(pressed()), Some(text("Button")))
2263                                .is_selected(is_selected),
2264                        )
2265                        .into_widget(),
2266                ));
2267                tester.pump_and_settle();
2268                assert_eq!(material(tester, |material| material.color), Some(color));
2269            }
2270        });
2271    }
2272
2273    // elevated_button_test.dart 'M3E ElevatedButton uses size variants', 'M3E ElevatedButton
2274    // keeps size-specific padding when text scales', 'M3E ElevatedButton.icon uses
2275    // size-specific icon-label spacing' and 'ElevatedButton.styleFrom supports M3E size and
2276    // shape variants'.
2277    #[test]
2278    fn an_expressive_button_takes_its_size_padding_gap_and_shape_from_its_variants() {
2279        test_widgets(|tester| {
2280            let theme = m3e_theme(tester, None);
2281            let medium = ButtonStyle::new().size_variant(ButtonSizeVariant::Medium);
2282            tester.pump_widget(material_app(
2283                theme.clone(),
2284                Center::new()
2285                    .child(
2286                        ElevatedButton::new(Some(pressed()), Some(text("Button")))
2287                            .style(medium.clone()),
2288                    )
2289                    .into_widget(),
2290            ));
2291            assert_eq!(button_size(tester).height(), 56.0);
2292
2293            for text_scale_factor in [1.0, 2.0, 3.0] {
2294                for with_icon in [false, true] {
2295                    let button = if with_icon {
2296                        ElevatedButton::icon(Some(pressed()), text("Button"))
2297                            .icon(icon())
2298                            .build()
2299                    } else {
2300                        ElevatedButton::new(Some(pressed()), Some(text("Button")))
2301                    };
2302                    tester.pump_widget(material_app(
2303                        theme.clone(),
2304                        MediaQuery::with_clamped_text_scaling(
2305                            None,
2306                            text_scale_factor,
2307                            text_scale_factor,
2308                            Center::new().child(button.style(medium.clone())),
2309                        ),
2310                    ));
2311                    assert!(padding(tester) == EdgeInsetsGeometry::symmetric(0.0, 24.0));
2312                }
2313            }
2314
2315            tester.pump_widget(material_app(
2316                theme.clone(),
2317                Center::new()
2318                    .child(
2319                        ElevatedButton::icon(Some(pressed()), text("Button"))
2320                            .icon(icon())
2321                            .style(ButtonStyle::new().size_variant(ButtonSizeVariant::Large)),
2322                    )
2323                    .into_widget(),
2324            ));
2325            assert_eq!(row_spacing(tester), 12.0);
2326
2327            let style = ElevatedButton::style_from()
2328                .size_variant(ButtonSizeVariant::Large)
2329                .shape_variant(ButtonShapeVariant::Square)
2330                .build();
2331            assert_eq!(style.size_variant, Some(ButtonSizeVariant::Large));
2332            assert_eq!(style.shape_variant, Some(ButtonShapeVariant::Square));
2333            tester.pump_widget(material_app(
2334                theme,
2335                Center::new()
2336                    .child(ElevatedButton::new(Some(pressed()), Some(text("Button"))).style(style))
2337                    .into_widget(),
2338            ));
2339            tester.pump_and_settle();
2340            assert_eq!(button_size(tester).height(), 96.0);
2341            assert!(shape_is(tester, &rounded(28.0)));
2342        });
2343    }
2344
2345    // elevated_button_test.dart group 'M3E ElevatedButton', 'uses size-specific height, icon
2346    // size, and label font size'.
2347    #[test]
2348    fn each_expressive_size_has_its_height_icon_size_and_font_size() {
2349        test_widgets(|tester| {
2350            let theme = m3e_theme(tester, None);
2351            // Font sizes of labelLarge, titleMedium, headlineSmall, and headlineLarge.
2352            let expectations = [
2353                (ButtonSizeVariant::XSmall, 32.0, 20.0, 14.0),
2354                (ButtonSizeVariant::Small, 40.0, 20.0, 14.0),
2355                (ButtonSizeVariant::Medium, 56.0, 24.0, 16.0),
2356                (ButtonSizeVariant::Large, 96.0, 32.0, 24.0),
2357                (ButtonSizeVariant::XLarge, 136.0, 40.0, 32.0),
2358            ];
2359            for (size_variant, height, icon_size, font_size) in expectations {
2360                let icon_seen = Rc::new(RefCell::new(Ambient::default()));
2361                let label_seen = Rc::new(RefCell::new(Ambient::default()));
2362                tester.pump_widget(material_app(
2363                    theme.clone(),
2364                    Center::new()
2365                        .child(
2366                            ElevatedButton::icon(
2367                                Some(pressed()),
2368                                probe(&label_seen, Size::new(84.0, 14.0)),
2369                            )
2370                            .icon(probe(&icon_seen, Size::new(18.0, 18.0)))
2371                            .style(ButtonStyle::new().size_variant(size_variant)),
2372                        )
2373                        .into_widget(),
2374                ));
2375                // The icon size and text style animate between size variants.
2376                tester.pump_and_settle();
2377
2378                assert_eq!(material_rect(tester).height(), height, "{size_variant:?}");
2379                assert_eq!(
2380                    icon_seen.borrow().icon_size,
2381                    Some(icon_size),
2382                    "{size_variant:?}"
2383                );
2384                assert_eq!(
2385                    label_seen.borrow().font_size,
2386                    Some(font_size),
2387                    "{size_variant:?}"
2388                );
2389            }
2390        });
2391    }
2392
2393    // elevated_button_test.dart group 'M3E ElevatedButton', 'xSmall keeps a 48dp tap target
2394    // when the theme shrink-wraps'.
2395    #[test]
2396    fn an_extra_small_expressive_button_keeps_its_48_tap_target() {
2397        test_widgets(|tester| {
2398            let press_count = Rc::new(Cell::new(0));
2399            let build_app =
2400                |tester: &mut WidgetTester, tap_target_size: Option<MaterialTapTargetSize>| {
2401                    let theme = m3e_theme(tester, None)
2402                        .copy_with()
2403                        .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
2404                        .build();
2405                    let mut style = ButtonStyle::new().size_variant(ButtonSizeVariant::XSmall);
2406                    style.tap_target_size = tap_target_size;
2407                    tester.pump_widget(material_app(
2408                        theme,
2409                        Center::new()
2410                            .child(
2411                                ElevatedButton::new(
2412                                    Some(counter(&press_count)),
2413                                    Some(text("Button")),
2414                                )
2415                                .style(style),
2416                            )
2417                            .into_widget(),
2418                    ));
2419                };
2420
2421            build_app(tester, None);
2422            assert_eq!(material_rect(tester).height(), 32.0);
2423            assert_eq!(button_size(tester).height(), 48.0);
2424
2425            // Taps just above and below the 32dp button still reach it.
2426            let center = button_center(tester);
2427            for (pointer, offset) in [(1, Offset::new(0.0, 23.0)), (2, Offset::new(0.0, -23.0))] {
2428                tester.tap_at(center + offset, pointer);
2429                tester.pump();
2430            }
2431            tester.pump_and_settle();
2432            assert_eq!(press_count.get(), 2);
2433
2434            // An explicit tap target size in the style overrides the default.
2435            build_app(tester, Some(MaterialTapTargetSize::ShrinkWrap));
2436            assert_eq!(button_size(tester).height(), 32.0);
2437        });
2438    }
2439
2440    // elevated_button_test.dart group 'M3E ElevatedButton', 'ignores the theme visual
2441    // density'.
2442    #[test]
2443    fn an_expressive_button_ignores_the_theme_visual_density() {
2444        test_widgets(|tester| {
2445            let build_app = |tester: &mut WidgetTester, visual_density: Option<VisualDensity>| {
2446                // Compact is the default density on desktop platforms.
2447                let theme = m3e_theme(tester, None)
2448                    .copy_with()
2449                    .visual_density(VisualDensity::COMPACT)
2450                    .build();
2451                let mut style = ButtonStyle::new();
2452                style.visual_density = visual_density;
2453                tester.pump_widget(material_app(
2454                    theme,
2455                    Center::new()
2456                        .child(
2457                            ElevatedButton::new(Some(pressed()), Some(text("Button"))).style(style),
2458                        )
2459                        .into_widget(),
2460                ));
2461            };
2462
2463            build_app(tester, None);
2464            assert_eq!(material_rect(tester).height(), 40.0);
2465            assert_eq!(button_size(tester).height(), 48.0);
2466
2467            // An explicit visual density in the style overrides the default.
2468            build_app(tester, Some(VisualDensity::COMPACT));
2469            assert_eq!(material_rect(tester).height(), 32.0);
2470            assert_eq!(button_size(tester).height(), 40.0);
2471        });
2472    }
2473
2474    // elevated_button_test.dart group 'M3E ElevatedButton', 'resolves shapes for shape
2475    // variants and states'.
2476    #[test]
2477    fn the_expressive_shapes_follow_the_shape_variant_and_the_state() {
2478        test_widgets(|tester| {
2479            let selected = states(&[WidgetState::Selected]);
2480            let pressed_states = states(&[WidgetState::Pressed]);
2481            let shape = |style: &ButtonStyle, states: &WidgetStates| {
2482                style
2483                    .shape
2484                    .as_ref()
2485                    .and_then(|shape| shape.resolve(states))
2486                    .expect("a shape")
2487            };
2488            let theme = m3e_theme(tester, None);
2489
2490            let style = captured_default_style(
2491                tester,
2492                theme.clone(),
2493                ElevatedButton::new(Some(pressed()), Some(text("Button")))
2494                    .is_selected(false)
2495                    .style(ButtonStyle::new().size_variant(ButtonSizeVariant::Medium)),
2496            );
2497            assert!(shape(&style, &WidgetStates::new()).eq_shape(&StadiumBorder::default()));
2498            assert!(shape(&style, &selected).eq_shape(&rounded(16.0)));
2499            assert!(shape(&style, &pressed_states).eq_shape(&rounded(12.0)));
2500
2501            let style = captured_default_style(
2502                tester,
2503                theme.clone(),
2504                ElevatedButton::new(Some(pressed()), Some(text("Button")))
2505                    .is_selected(false)
2506                    .style(
2507                        ButtonStyle::new()
2508                            .size_variant(ButtonSizeVariant::Medium)
2509                            .shape_variant(ButtonShapeVariant::Square),
2510                    ),
2511            );
2512            assert!(shape(&style, &WidgetStates::new()).eq_shape(&rounded(16.0)));
2513            assert!(shape(&style, &selected).eq_shape(&StadiumBorder::default()));
2514            assert!(shape(&style, &pressed_states).eq_shape(&rounded(12.0)));
2515
2516            // A button that is not toggleable ignores the selected state.
2517            let style = captured_default_style(
2518                tester,
2519                theme,
2520                ElevatedButton::new(Some(pressed()), Some(text("Button"))),
2521            );
2522            assert!(shape(&style, &selected).eq_shape(&StadiumBorder::default()));
2523        });
2524    }
2525
2526    // elevated_button_test.dart group 'M3E ElevatedButton', 'resolves colors and elevation
2527    // for each state' and 'resolves selected and unselected colors when toggleable'.
2528    #[test]
2529    fn the_expressive_colors_and_elevation_resolve_per_state() {
2530        test_widgets(|tester| {
2531            let theme = m3e_theme(tester, None);
2532            let colors = theme.color_scheme.clone();
2533            let alpha =
2534                |color: Color, alpha: f64| color.with_values(Some(alpha), None, None, None, None);
2535            let resolve = |property: &Option<WidgetStatePropertyRef<Option<Color>>>,
2536                           states: &WidgetStates| {
2537                property
2538                    .as_ref()
2539                    .and_then(|property| property.resolve(states))
2540            };
2541            let none = WidgetStates::new();
2542            let disabled = states(&[WidgetState::Disabled]);
2543            let hovered = states(&[WidgetState::Hovered]);
2544            let focused = states(&[WidgetState::Focused]);
2545            let pressed_states = states(&[WidgetState::Pressed]);
2546            let selected = states(&[WidgetState::Selected]);
2547
2548            let style = captured_default_style(
2549                tester,
2550                theme.clone(),
2551                ElevatedButton::new(Some(pressed()), Some(text("Button"))),
2552            );
2553            assert_eq!(
2554                resolve(&style.background_color, &none),
2555                Some(colors.surface_container_low())
2556            );
2557            assert_eq!(
2558                resolve(&style.background_color, &disabled),
2559                Some(alpha(colors.on_surface(), 0.1))
2560            );
2561            assert_eq!(
2562                resolve(&style.foreground_color, &none),
2563                Some(colors.primary())
2564            );
2565            assert_eq!(
2566                resolve(&style.foreground_color, &disabled),
2567                Some(alpha(colors.on_surface(), 0.38))
2568            );
2569            assert_eq!(resolve(&style.icon_color, &none), Some(colors.primary()));
2570            assert_eq!(
2571                resolve(&style.icon_color, &disabled),
2572                Some(alpha(colors.on_surface(), 0.38))
2573            );
2574            assert_eq!(resolve(&style.overlay_color, &none), None);
2575            assert_eq!(
2576                resolve(&style.overlay_color, &hovered),
2577                Some(alpha(colors.primary(), 0.08))
2578            );
2579            assert_eq!(
2580                resolve(&style.overlay_color, &focused),
2581                Some(alpha(colors.primary(), 0.1))
2582            );
2583            assert_eq!(
2584                resolve(&style.overlay_color, &pressed_states),
2585                Some(alpha(colors.primary(), 0.1))
2586            );
2587            let elevation = style.elevation.as_ref().expect("an elevation");
2588            assert_eq!(elevation.resolve(&none), Some(1.0));
2589            assert_eq!(elevation.resolve(&hovered), Some(1.0));
2590            assert_eq!(elevation.resolve(&focused), Some(1.0));
2591            assert_eq!(elevation.resolve(&pressed_states), Some(1.0));
2592            assert_eq!(elevation.resolve(&disabled), Some(0.0));
2593
2594            let style = captured_default_style(
2595                tester,
2596                theme,
2597                ElevatedButton::new(Some(pressed()), Some(text("Button"))).is_selected(true),
2598            );
2599            assert_eq!(
2600                resolve(&style.background_color, &selected),
2601                Some(colors.primary())
2602            );
2603            assert_eq!(
2604                resolve(&style.foreground_color, &selected),
2605                Some(colors.on_primary())
2606            );
2607            assert_eq!(
2608                resolve(&style.icon_color, &selected),
2609                Some(colors.on_primary())
2610            );
2611            assert_eq!(
2612                resolve(
2613                    &style.overlay_color,
2614                    &states(&[WidgetState::Selected, WidgetState::Hovered])
2615                ),
2616                Some(alpha(colors.on_primary(), 0.08))
2617            );
2618            assert_eq!(
2619                resolve(&style.background_color, &none),
2620                Some(colors.surface_container_low())
2621            );
2622            assert_eq!(
2623                resolve(&style.foreground_color, &none),
2624                Some(colors.primary())
2625            );
2626            assert_eq!(
2627                resolve(
2628                    &style.background_color,
2629                    &states(&[WidgetState::Selected, WidgetState::Disabled])
2630                ),
2631                Some(alpha(colors.on_surface(), 0.1))
2632            );
2633        });
2634    }
2635
2636    // elevated_button_test.dart group 'M3E ElevatedButton', 'uses theme-level size and shape
2637    // variants' and 'ElevatedButton.icon uses theme-level size for icon-label spacing'.
2638    #[test]
2639    fn the_theme_size_and_shape_variants_apply_under_the_widget_style() {
2640        test_widgets(|tester| {
2641            let theme = m3e_theme(
2642                tester,
2643                Some(
2644                    ButtonStyle::new()
2645                        .size_variant(ButtonSizeVariant::Large)
2646                        .shape_variant(ButtonShapeVariant::Square),
2647                ),
2648            );
2649            let build_app = |tester: &mut WidgetTester, style: Option<ButtonStyle>| {
2650                let mut button = ElevatedButton::new(Some(pressed()), Some(text("Button")));
2651                if let Some(style) = style {
2652                    button = button.style(style);
2653                }
2654                tester.pump_widget(material_app(
2655                    theme.clone(),
2656                    Center::new().child(button).into_widget(),
2657                ));
2658                tester.pump_and_settle();
2659            };
2660            build_app(tester, None);
2661            assert_eq!(material_rect(tester).height(), 96.0);
2662            assert!(shape_is(tester, &rounded(28.0)));
2663
2664            // The widget style overrides the theme style.
2665            build_app(
2666                tester,
2667                Some(ButtonStyle::new().size_variant(ButtonSizeVariant::XSmall)),
2668            );
2669            tester.pump_and_settle();
2670            assert_eq!(material_rect(tester).height(), 32.0);
2671            assert!(shape_is(tester, &rounded(12.0)));
2672
2673            let theme = m3e_theme(
2674                tester,
2675                Some(ButtonStyle::new().size_variant(ButtonSizeVariant::XLarge)),
2676            );
2677            tester.pump_widget(material_app(
2678                theme,
2679                Center::new()
2680                    .child(ElevatedButton::icon(Some(pressed()), text("Button")).icon(icon()))
2681                    .into_widget(),
2682            ));
2683            tester.pump_and_settle();
2684            assert_eq!(row_spacing(tester), 16.0);
2685        });
2686    }
2687
2688    // elevated_button_test.dart group 'M3E ElevatedButton', 'variant is ignored when
2689    // useMaterial3 is false'.
2690    #[test]
2691    fn a_material_2_theme_ignores_the_expressive_variant() {
2692        test_widgets(|tester| {
2693            let theme = ThemeData::builder()
2694                .use_material3(false)
2695                .elevated_button_theme(
2696                    ElevatedButtonThemeData::new().variant(StyleVariant::Material3Expressive),
2697                )
2698                .build(&tester.cell.borrow());
2699            tester.pump_widget(material_app(
2700                theme,
2701                Center::new()
2702                    .child(
2703                        ElevatedButton::new(Some(pressed()), Some(text("Button")))
2704                            .style(ButtonStyle::new().size_variant(ButtonSizeVariant::Large)),
2705                    )
2706                    .into_widget(),
2707            ));
2708            assert_eq!(material_rect(tester).height(), 36.0);
2709            assert!(shape_is(tester, &rounded(4.0)));
2710        });
2711    }
2712
2713    // elevated_button_test.dart group 'M3E ElevatedButton', 'does not crash at zero area'.
2714    #[test]
2715    fn an_expressive_button_of_every_size_fits_a_zero_area() {
2716        test_widgets(|tester| {
2717            for size in [
2718                ButtonSizeVariant::XSmall,
2719                ButtonSizeVariant::Small,
2720                ButtonSizeVariant::Medium,
2721                ButtonSizeVariant::Large,
2722                ButtonSizeVariant::XLarge,
2723            ] {
2724                let theme = m3e_theme(tester, Some(ButtonStyle::new().size_variant(size)));
2725                tester.pump_widget(material_app(
2726                    theme,
2727                    Center::new()
2728                        .child(
2729                            SizedBox::shrink().child(
2730                                ElevatedButton::icon(Some(pressed()), text("X"))
2731                                    .icon(icon())
2732                                    .is_selected(true),
2733                            ),
2734                        )
2735                        .into_widget(),
2736                ));
2737                assert_eq!(button_size(tester), Size::ZERO);
2738            }
2739        });
2740    }
2741
2742    // elevated_button_test.dart 'ElevatedButton statesController selected override is
2743    // visual-only until isSelected changes', without its semantics.
2744    #[test]
2745    fn a_controller_selected_state_holds_until_is_selected_changes() {
2746        test_widgets(|tester| {
2747            let controller = WidgetStatesController::new(&mut tester.cell.borrow_mut(), None);
2748            let theme = m3e_theme(tester, None);
2749            let colors = theme.color_scheme.clone();
2750            let build_button = |tester: &mut WidgetTester, is_selected: bool| {
2751                tester.pump_widget(material_app(
2752                    theme.clone(),
2753                    Center::new()
2754                        .child(
2755                            ElevatedButton::new(Some(pressed()), Some(text("Button")))
2756                                .states_controller(controller.clone())
2757                                .is_selected(is_selected),
2758                        )
2759                        .into_widget(),
2760                ));
2761            };
2762            let background_color =
2763                |tester: &WidgetTester| material(tester, |material| material.color);
2764
2765            build_button(tester, false);
2766            assert_eq!(
2767                background_color(tester),
2768                Some(colors.surface_container_low())
2769            );
2770
2771            // Updating the controller changes only the appearance.
2772            controller.update(&mut tester.cell.borrow_mut(), WidgetState::Selected, true);
2773            tester.pump();
2774            assert_eq!(background_color(tester), Some(colors.primary()));
2775
2776            // Rebuilding with the same isSelected keeps the controller's value.
2777            build_button(tester, false);
2778            assert!(
2779                tester
2780                    .cell
2781                    .borrow()
2782                    .get(&controller)
2783                    .value()
2784                    .contains(&WidgetState::Selected)
2785            );
2786            assert_eq!(background_color(tester), Some(colors.primary()));
2787
2788            // Changing isSelected overwrites the controller's value.
2789            build_button(tester, true);
2790            build_button(tester, false);
2791            assert!(
2792                !tester
2793                    .cell
2794                    .borrow()
2795                    .get(&controller)
2796                    .value()
2797                    .contains(&WidgetState::Selected)
2798            );
2799            assert_eq!(
2800                background_color(tester),
2801                Some(colors.surface_container_low())
2802            );
2803        });
2804    }
2805
2806    // elevated_button_test.dart 'ElevatedButton debugFillProperties includes selected'.
2807    #[test]
2808    fn the_debug_description_names_a_selected_button() {
2809        let button = ElevatedButton::new(Some(pressed()), Some(SizedBox::new())).is_selected(true);
2810        assert!(format!("{button:?}").contains("selected"));
2811    }
2812
2813    // An `ElevatedButton::icon` chain gives the same child whatever order its setters run in.
2814    #[test]
2815    fn the_icon_child_sees_the_style_and_alignment_in_any_order() {
2816        let style = ButtonStyle::new().size_variant(ButtonSizeVariant::Large);
2817        let child_of = |button: &ElevatedButton| {
2818            let child = button.button_style_button.child.clone().expect("a child");
2819            let child =
2820                downcast_widget::<ElevatedButtonWithIconChild>(&*child).expect("the icon child");
2821            (
2822                child
2823                    .button_style
2824                    .as_ref()
2825                    .and_then(|style| style.size_variant),
2826                child.icon_alignment,
2827            )
2828        };
2829        let first = ElevatedButton::icon(Some(pressed()), text("a"))
2830            .icon(icon())
2831            .style(style.clone())
2832            .icon_alignment(IconAlignment::End)
2833            .build();
2834        let second = ElevatedButton::icon(Some(pressed()), text("a"))
2835            .icon_alignment(IconAlignment::End)
2836            .style(style)
2837            .icon(icon())
2838            .build();
2839        assert_eq!(
2840            child_of(&first),
2841            (Some(ButtonSizeVariant::Large), Some(IconAlignment::End))
2842        );
2843        assert_eq!(child_of(&first), child_of(&second));
2844    }
2845
2846    // elevated_button_test.dart 'By default, ElevatedButton shape outline is defined by
2847    // shape.side'.
2848    #[test]
2849    fn by_default_the_shape_side_is_the_outline() {
2850        // This is a regression test for https://github.com/flutter/flutter/issues/69544
2851        test_widgets(|tester| {
2852            let border_color = Color::new(0xff4caf50);
2853            let theme = ThemeData::builder()
2854                .color_scheme(ColorScheme::light())
2855                .text_theme(crate::typography::Typography::english_like2014())
2856                .use_material3(false)
2857                .build(&tester.cell.borrow());
2858            tester.pump_widget(material_app(
2859                theme,
2860                Center::new()
2861                    .child(
2862                        ElevatedButton::new(Some(pressed()), Some(text("button"))).style(
2863                            ElevatedButton::style_from()
2864                                .shape(RoundedRectangleBorder::new(
2865                                    BorderSide {
2866                                        width: 10.0,
2867                                        color: border_color,
2868                                        ..BorderSide::default()
2869                                    },
2870                                    BorderRadius::all(Radius::circular(16.0)).into(),
2871                                ))
2872                                .minimum_size(Size::new(64.0, 36.0))
2873                                .build(),
2874                        ),
2875                    )
2876                    .into_widget(),
2877            ));
2878
2879            let button =
2880                tester.render_object(find::by_type::<ElevatedButton>().evaluate(tester)[0]);
2881            waft_rendering::testing::assert_paints(
2882                &tester.painted_ops(button),
2883                &[waft_rendering::testing::PaintCall::drrect_between(
2884                    // Outer and inner rect that give the outline a width of 10.
2885                    RRect::from_ltrbr(0.0, 0.0, 116.0, 36.0, Radius::circular(16.0)),
2886                    RRect::from_ltrbr(10.0, 10.0, 106.0, 26.0, Radius::circular(16.0 - 10.0)),
2887                    Some(border_color),
2888                )],
2889            );
2890        });
2891    }
2892
2893    // elevated_button_test.dart 'ElevatedButton.icon does not overflow'. Dart's
2894    // `tester.takeException()` is the overflow its debug paint reports; Waft paints no overflow
2895    // indicator, so the case reads the overflow of the button's `Row`.
2896    #[test]
2897    fn an_icon_button_with_a_long_label_does_not_overflow() {
2898        // Regression test for https://github.com/flutter/flutter/issues/77815
2899        test_widgets(|tester| {
2900            let theme = ThemeData::new(&tester.cell.borrow());
2901            tester.pump_widget(material_app(
2902                theme,
2903                // Dart's `Scaffold(body:)` lays its body out loosely at the top left.
2904                waft_widgets::Align::new()
2905                    .alignment(AlignmentGeometry::TOP_LEFT)
2906                    .child(
2907                        SizedBox::new().width(200.0).child(
2908                            ElevatedButton::icon(
2909                                Some(pressed()),
2910                                Text::new(
2911                                    // Much wider than 200
2912                                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a euismod nibh. Morbi laoreet purus.",
2913                                ),
2914                            )
2915                            .icon(Icon::new(Some(Icons::add()))),
2916                        ),
2917                    )
2918                    .into_widget(),
2919            ));
2920            let flexes = tester.all::<RenderFlex>();
2921            let app = tester.cell.borrow();
2922            for flex in flexes {
2923                assert!(!flex.has_overflow(&app));
2924            }
2925        });
2926    }
2927
2928    // elevated_button_test.dart 'ElevatedButton maximumSize'.
2929    #[test]
2930    fn the_maximum_size_bounds_the_width_of_a_button_and_of_an_icon_button() {
2931        test_widgets(|tester| {
2932            let key0 = GlobalKey::new();
2933            let key1 = GlobalKey::new();
2934            let theme = ThemeData::builder()
2935                .text_theme(crate::typography::Typography::english_like2014())
2936                .build(&tester.cell.borrow());
2937            tester.pump_widget(material_app(
2938                theme,
2939                Material::new()
2940                    .child(
2941                        Center::new().child(
2942                            waft_widgets::Column::new()
2943                                .main_axis_size(MainAxisSize::Min)
2944                                .children(vec![
2945                                    ElevatedButton::new(
2946                                        Some(pressed()),
2947                                        Some(Text::new("A B C D E F G H I J K L M N O P")),
2948                                    )
2949                                    .key(key0.clone().into())
2950                                    .style(
2951                                        ElevatedButton::style_from()
2952                                            .minimum_size(Size::new(24.0, 36.0))
2953                                            .maximum_size(Size::from_width(64.0))
2954                                            .build(),
2955                                    )
2956                                    .into_widget(),
2957                                    ElevatedButton::icon(
2958                                        Some(pressed()),
2959                                        Text::new("A B C D E F G H I J K L M N O P"),
2960                                    )
2961                                    .key(key1.clone().into())
2962                                    .style(
2963                                        ElevatedButton::style_from()
2964                                            .minimum_size(Size::new(24.0, 36.0))
2965                                            .maximum_size(Size::from_width(104.0))
2966                                            .build(),
2967                                    )
2968                                    .icon(
2969                                        waft_widgets::Container::new()
2970                                            .color(Colors::RED.primary())
2971                                            .width(32.0)
2972                                            .height(32.0),
2973                                    )
2974                                    .into_widget(),
2975                                ]),
2976                        ),
2977                    )
2978                    .into_widget(),
2979            ));
2980
2981            assert_eq!(tester.get_size(&key0), Size::new(64.0, 224.0));
2982            assert_eq!(tester.get_size(&key1), Size::new(104.0, 224.0));
2983        });
2984    }
2985
2986    // elevated_button_test.dart 'ElevatedButton changes mouse cursor when hovered'.
2987    #[test]
2988    fn style_from_cursors_show_while_hovered_and_the_default_is_basic() {
2989        test_widgets(|tester| {
2990            let frame = |on_pressed: Option<Listener>, custom: bool| {
2991                let mut button = ElevatedButton::new(on_pressed, Some(text("button")));
2992                if custom {
2993                    button = button.style(
2994                        ElevatedButton::style_from()
2995                            .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
2996                            .disabled_mouse_cursor(SystemMouseCursors::GRAB.into())
2997                            .build(),
2998                    );
2999                }
3000                Directionality::new(
3001                    TextDirection::Ltr,
3002                    MouseRegion::new()
3003                        .cursor(SystemMouseCursors::FORBIDDEN.into())
3004                        .child(button),
3005                )
3006                .into_widget()
3007            };
3008            let is = |tester: &WidgetTester, cursor: SystemMouseCursor| {
3009                tester.active_cursor(1) == MouseCursorRef::from(cursor)
3010            };
3011
3012            tester.pump_widget(frame(Some(pressed()), true));
3013            let mut gesture = TestPointer::mouse(1, 0);
3014            tester.add_pointer(&mut gesture, Offset::ZERO);
3015            tester.pump();
3016            assert!(is(tester, SystemMouseCursors::TEXT));
3017
3018            // Test cursor when disabled
3019            tester.pump_widget(frame(None, true));
3020            assert!(is(tester, SystemMouseCursors::GRAB));
3021
3022            // Test default cursor
3023            tester.pump_widget(frame(Some(pressed()), false));
3024            assert!(is(
3025                tester,
3026                if K_IS_WEB {
3027                    SystemMouseCursors::CLICK
3028                } else {
3029                    SystemMouseCursors::BASIC
3030                }
3031            ));
3032
3033            // Test default cursor when disabled
3034            tester.pump_widget(frame(None, false));
3035            assert!(is(tester, SystemMouseCursors::BASIC));
3036        });
3037    }
3038
3039    // elevated_button_test.dart 'Ink Response shape matches Material shape'.
3040    #[test]
3041    fn the_ink_response_shape_is_the_material_shape_with_the_style_side() {
3042        // This is a regression test for https://github.com/flutter/flutter/issues/91844
3043        test_widgets(|tester| {
3044            let shape_side = BorderSide {
3045                color: Color::new(0xff0000ff),
3046                width: 0.0,
3047                ..BorderSide::default()
3048            };
3049            let build_frame = |tester: &WidgetTester, side: Option<BorderSide>| {
3050                let mut style_from = ElevatedButton::style_from().shape(
3051                    RoundedRectangleBorder::new(shape_side, BorderRadius::ZERO.into()),
3052                );
3053                if let Some(side) = side {
3054                    style_from = style_from.side(side);
3055                }
3056                let theme = ThemeData::new(&tester.cell.borrow());
3057                material_app(
3058                    theme,
3059                    Material::new()
3060                        .child(
3061                            Center::new().child(
3062                                ElevatedButton::new(Some(pressed()), Some(text("ElevatedButton")))
3063                                    .style(style_from.build()),
3064                            ),
3065                        )
3066                        .into_widget(),
3067                )
3068            };
3069            let custom_border_is = |tester: &WidgetTester, expected: RoundedRectangleBorder| {
3070                tester.widget(in_button::<InkWell>(tester), |ink_well: &InkWell| {
3071                    ink_well
3072                        .ink_response
3073                        .custom_border
3074                        .as_ref()
3075                        .is_some_and(|border| border.eq_shape(&expected))
3076                })
3077            };
3078
3079            let border_side = BorderSide {
3080                width: 10.0,
3081                color: Color::new(0xff00ff00),
3082                ..BorderSide::default()
3083            };
3084            let frame = build_frame(tester, Some(border_side));
3085            tester.pump_widget(frame);
3086            assert!(custom_border_is(
3087                tester,
3088                RoundedRectangleBorder::new(border_side, BorderRadius::ZERO.into())
3089            ));
3090
3091            let frame = build_frame(tester, None);
3092            tester.pump_widget(frame);
3093            tester.pump_and_settle();
3094            assert!(custom_border_is(
3095                tester,
3096                RoundedRectangleBorder::new(shape_side, BorderRadius::ZERO.into())
3097            ));
3098        });
3099    }
3100
3101    // elevated_button_test.dart 'ElevatedButton.icon statesController'; the plain button's case
3102    // is button_style_button.rs's.
3103    #[test]
3104    fn an_icon_buttons_states_controller_follows_hover_press_and_disable() {
3105        test_widgets(|tester| {
3106            let count = Rc::new(Cell::new(0));
3107            let controller = WidgetStatesController::new(&mut tester.cell.borrow_mut(), None);
3108            controller.add_listener(&mut tester.cell.borrow_mut(), {
3109                let count = Rc::clone(&count);
3110                Listener::new(move |_app| count.set(count.get() + 1))
3111            });
3112            let label_key = GlobalKey::new();
3113            let frame = |tester: &WidgetTester, enabled: bool| {
3114                let theme = ThemeData::new(&tester.cell.borrow());
3115                material_app(
3116                    theme,
3117                    Center::new()
3118                        .child(
3119                            ElevatedButton::icon(
3120                                enabled.then(pressed),
3121                                Text::new("button").key(label_key.clone().into()),
3122                            )
3123                            .states_controller(controller.clone())
3124                            .icon(icon()),
3125                        )
3126                        .into_widget(),
3127                )
3128            };
3129            let value =
3130                |tester: &WidgetTester| tester.cell.borrow().get(&controller).value().clone();
3131
3132            let first = frame(tester, true);
3133            tester.pump_widget(first);
3134            assert_eq!(value(tester), states(&[]));
3135            assert_eq!(count.get(), 0);
3136
3137            let center = tester.get_center(&label_key);
3138            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3139            tester.add_pointer(&mut gesture, Offset::ZERO);
3140            tester.move_to(&mut gesture, center, false);
3141            tester.pump_and_settle();
3142            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
3143            assert_eq!(count.get(), 1);
3144
3145            tester.move_to(&mut gesture, Offset::ZERO, false);
3146            tester.pump_and_settle();
3147            assert_eq!(value(tester), states(&[]));
3148            assert_eq!(count.get(), 2);
3149
3150            tester.move_to(&mut gesture, center, false);
3151            tester.pump_and_settle();
3152            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
3153            assert_eq!(count.get(), 3);
3154
3155            tester.send(&gesture, PointerChange::Down);
3156            tester.pump_and_settle();
3157            assert_eq!(
3158                value(tester),
3159                states(&[WidgetState::Hovered, WidgetState::Pressed])
3160            );
3161            assert_eq!(count.get(), 4);
3162
3163            tester.up(&gesture);
3164            tester.pump_and_settle();
3165            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
3166            assert_eq!(count.get(), 5);
3167
3168            tester.move_to(&mut gesture, Offset::ZERO, false);
3169            tester.pump_and_settle();
3170            assert_eq!(value(tester), states(&[]));
3171            assert_eq!(count.get(), 6);
3172
3173            tester.down(&mut gesture, center);
3174            tester.pump_and_settle();
3175            assert_eq!(
3176                value(tester),
3177                states(&[WidgetState::Hovered, WidgetState::Pressed])
3178            );
3179            assert_eq!(count.get(), 8); // adds hovered and pressed - two changes
3180
3181            // If the button is rebuilt disabled, then the pressed state is
3182            // removed.
3183            let disabled = frame(tester, false);
3184            tester.pump_widget(disabled);
3185            tester.pump_and_settle();
3186            assert_eq!(
3187                value(tester),
3188                states(&[WidgetState::Hovered, WidgetState::Disabled])
3189            );
3190            assert_eq!(count.get(), 10); // removes pressed and adds disabled - two changes
3191            tester.move_to(&mut gesture, Offset::ZERO, true);
3192            tester.pump_and_settle();
3193            assert_eq!(value(tester), states(&[WidgetState::Disabled]));
3194            assert_eq!(count.get(), 11);
3195        });
3196    }
3197}