Skip to main content

waft_material/
outlined_button.rs

1//! Flutter counterpart: material_ui's `outlined_button.dart`; its Material 3 defaults, a Dart
2//! `part`, are `generated/outlined_button_defaults_m3.rs`.
3//!
4//! Dart's `OutlinedButton.icon` and `OutlinedButton.styleFrom` take named arguments the body
5//! combines (the icon child reads `style`; `styleFrom` derives its overlay color from two of
6//! them), so each is a value collecting them, [`OutlinedButtonIcon`] and
7//! [`OutlinedButtonStyleFromBuilder`], that converts once every argument is given.
8#![allow(deprecated)]
9
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_embedder::{Color, Radius, Size, clamp_double, lerp_double};
15use waft_foundation::{App, DiagnosticPropertiesBuilder, K_IS_WEB, Listener};
16use waft_painting::{
17    AlignmentGeometry, BorderRadius, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef,
18    RoundedRectangleBorder, TextStyle,
19};
20use waft_services::{MouseCursorRef, SystemMouseCursors};
21use waft_widgets::{
22    BuildContext, Flexible, IntoWidget, KeyRef, MainAxisSize, MediaQuery, Row, StatefulKind,
23    StatefulWidget, StatelessWidget, WidgetRef, WidgetState, WidgetStateProperty,
24    WidgetStatePropertyAll, WidgetStatePropertyRef, WidgetStates,
25};
26
27use crate::button_style::ButtonStyleGetters;
28use crate::button_style::{ButtonLayerBuilder, ButtonStyle};
29use crate::button_style_button::{
30    ButtonStyleButton, ButtonStyleButtonData, ButtonStyleState, IconAlignment,
31};
32use crate::colors::Colors;
33use crate::constants::K_THEME_CHANGE_DURATION;
34use crate::generated::outlined_button_defaults_m3::OutlinedButtonDefaultsM3;
35use crate::ink_ripple::InkRipple;
36use crate::ink_well::InteractiveInkFeatureFactoryRef;
37use crate::material_state::MaterialStatePropertyAll;
38use crate::outlined_button_theme::OutlinedButtonTheme;
39use crate::theme::Theme;
40use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
41
42/// A Material Design "Outlined Button"; essentially a `TextButton`
43/// with an outlined border.
44///
45/// Outlined buttons are medium-emphasis buttons. They contain actions
46/// that are important, but they aren’t the primary action in an app.
47///
48/// An outlined button is a label `child` displayed on a (zero
49/// elevation) `Material` widget. The label's `Text` and `Icon`
50/// widgets are displayed in the `style`'s
51/// [`ButtonStyle::foreground_color`] and the outline's weight and color
52/// are defined by [`ButtonStyle::side`]. The button reacts to touches
53/// by filling with the `style`'s [`ButtonStyle::overlay_color`].
54///
55/// The outlined button's default style is defined by
56/// [`default_style_of`](ButtonStyleButton::default_style_of). The style of this outline button
57/// can be overridden with its `style` parameter. The style of all text buttons in a subtree can
58/// be overridden with the [`OutlinedButtonTheme`] and the style of all of the outlined buttons
59/// in an app can be overridden with the `Theme`'s `ThemeData::outlined_button_theme` property.
60///
61/// Unlike `TextButton` or `ElevatedButton`, outline buttons have a
62/// default [`ButtonStyle::side`] which defines the appearance of the
63/// outline. Because the default `side` is non-null, it
64/// unconditionally overrides the shape's `OutlinedBorder::side`. In
65/// other words, to specify an outlined button's shape _and_ the
66/// appearance of its outline, both the [`ButtonStyle::shape`] and
67/// [`ButtonStyle::side`] properties must be specified.
68///
69/// The static [`style_from`](Self::style_from) method is a convenient way to create a
70/// outlined button [`ButtonStyle`] from simple values.
71///
72/// See also:
73///
74///  * `ElevatedButton`, a filled button whose material elevates when pressed.
75///  * `FilledButton`, a filled button that doesn't elevate when pressed.
76///  * `FilledButton::tonal`, a filled button variant that uses a secondary fill color.
77///  * `TextButton`, a button with no outline or fill color.
78///  * <https://material.io/design/components/buttons.html>
79///  * <https://m3.material.io/components/buttons>
80pub struct OutlinedButton {
81    button_style_button: ButtonStyleButtonData,
82    add_padding: bool,
83}
84
85impl OutlinedButton {
86    /// Create an OutlinedButton.
87    #[cfg_attr(debug_assertions, track_caller)]
88    pub fn new<K>(
89        on_pressed: Option<Listener>,
90        child: Option<impl IntoWidget<K>>,
91    ) -> OutlinedButton {
92        OutlinedButton {
93            button_style_button: ButtonStyleButtonData::new(
94                on_pressed,
95                match child {
96                    Some(child) => Some(child.into_widget()),
97                    None => None,
98                },
99            ),
100            add_padding: false,
101        }
102    }
103
104    crate::button_style_button_setters!(
105        OutlinedButton;
106        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
107        clip_behavior, states_controller,
108    );
109
110    /// Create an outlined button from a pair of widgets that serve as the button's
111    /// [`icon`](OutlinedButtonIcon::icon) and `label`.
112    ///
113    /// The icon and label are arranged in a row and padded by 12 logical pixels
114    /// at the start, and 16 at the end, with an 8 pixel gap in between.
115    ///
116    /// If [`icon`](OutlinedButtonIcon::icon) is null, this constructor will create an outlined
117    /// button that doesn't display an icon.
118    ///
119    /// The alignment of the icon within the button is set by
120    /// [`icon_alignment`](OutlinedButtonIcon::icon_alignment); see [`IconAlignment`].
121    #[cfg_attr(debug_assertions, track_caller)]
122    pub fn icon<K>(on_pressed: Option<Listener>, label: impl IntoWidget<K>) -> OutlinedButtonIcon {
123        OutlinedButtonIcon {
124            button_style_button: ButtonStyleButtonData::new(on_pressed, None),
125            icon: None,
126            label: label.into_widget(),
127            icon_alignment: None,
128        }
129    }
130
131    /// A static convenience method that constructs an outlined button
132    /// [`ButtonStyle`] given simple values.
133    ///
134    /// The `foreground_color` and `disabled_foreground_color` colors are used
135    /// to create a `WidgetStateProperty` [`ButtonStyle::foreground_color`], and
136    /// a derived [`ButtonStyle::overlay_color`] if `overlay_color` isn't specified.
137    ///
138    /// The `background_color` and `disabled_background_color` colors are
139    /// used to create a `WidgetStateProperty` [`ButtonStyle::background_color`].
140    ///
141    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
142    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
143    ///
144    /// The `icon_color`, `disabled_icon_color` are used to construct
145    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
146    /// [`ButtonStyle::icon_size`].
147    ///
148    /// If `icon_color` is null, the button icon will use `foreground_color`. If
149    /// `foreground_color` is also null, the button icon will use the default icon color.
150    ///
151    /// If `overlay_color` is specified and its value is [`Colors::TRANSPARENT`]
152    /// then the pressed/focused/hovered highlights are effectively defeated.
153    /// Otherwise a `WidgetStateProperty` with the same opacities as the
154    /// default is created.
155    ///
156    /// All of the other parameters are either used directly or used to
157    /// create a `WidgetStateProperty` with a single value for all
158    /// states.
159    ///
160    /// All parameters default to null, by default this method returns
161    /// a [`ButtonStyle`] that doesn't override anything.
162    ///
163    /// For example, to override the default shape and outline for an
164    /// [`OutlinedButton`], one could write:
165    ///
166    /// ```text
167    /// OutlinedButton::new(on_pressed, Text::new("Seasons of Love")).style(
168    ///     OutlinedButton::style_from()
169    ///         .shape(StadiumBorder::new(BorderSide::NONE))
170    ///         .side(BorderSide { width: 2.0, color: Colors::GREEN.primary(), ..BorderSide::default() })
171    ///         .build(),
172    /// )
173    /// ```
174    pub fn style_from() -> OutlinedButtonStyleFromBuilder {
175        OutlinedButtonStyleFromBuilder::default()
176    }
177}
178
179impl ButtonStyleButton for OutlinedButton {
180    crate::button_style_button_accessors!();
181
182    /// Defines the button's default appearance.
183    ///
184    /// With the exception of [`ButtonStyle::side`], which defines the
185    /// outline, and [`ButtonStyle::padding`], the returned style is the
186    /// same as for `TextButton`.
187    ///
188    /// The button `child`'s `Text` and `Icon` widgets are rendered with
189    /// the [`ButtonStyle`]'s foreground color. The button's `InkWell` adds
190    /// the style's overlay color when the button is focused, hovered
191    /// or pressed. The button's background color becomes its `Material`
192    /// color and is transparent by default.
193    ///
194    /// All of the ButtonStyle's defaults appear below. In this list
195    /// "Theme.foo" is shorthand for `Theme::of(app, context).foo`. Color
196    /// scheme values like "onSurface(0.38)" are shorthand for
197    /// `on_surface.with_opacity(0.38)`. `WidgetStateProperty` valued
198    /// properties that are not followed by a sublist have the same
199    /// value for all states, otherwise the values are as specified for
200    /// each state and "others" means all other states.
201    ///
202    /// The color of the [`ButtonStyle::text_style`] is not used, the
203    /// [`ButtonStyle::foreground_color`] is used instead.
204    ///
205    /// ## Material 2 defaults
206    ///
207    /// * `textStyle` - Theme.textTheme.button
208    /// * `backgroundColor` - transparent
209    /// * `foregroundColor`
210    ///   * disabled - Theme.colorScheme.onSurface(0.38)
211    ///   * others - Theme.colorScheme.primary
212    /// * `overlayColor`
213    ///   * hovered - Theme.colorScheme.primary(0.08)
214    ///   * focused or pressed - Theme.colorScheme.primary(0.12)
215    /// * `shadowColor` - Theme.shadowColor
216    /// * `elevation` - 0
217    /// * `padding`
218    ///   * `default font size <= 14` - horizontal(16)
219    ///   * `14 < default font size <= 28` - lerp(horizontal(16), horizontal(8))
220    ///   * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
221    ///   * `36 < default font size` - horizontal(4)
222    /// * `minimumSize` - Size(64, 36)
223    /// * `fixedSize` - null
224    /// * `maximumSize` - Size.infinite
225    /// * `side` - BorderSide(width: 1, color: Theme.colorScheme.onSurface(0.12))
226    /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
227    /// * `mouseCursor` - WidgetStateMouseCursor.adaptiveClickable
228    /// * `visualDensity` - theme.visualDensity
229    /// * `tapTargetSize` - theme.materialTapTargetSize
230    /// * `animationDuration` - kThemeChangeDuration
231    /// * `enableFeedback` - true
232    /// * `alignment` - Alignment.center
233    /// * `splashFactory` - InkRipple.splashFactory
234    ///
235    /// ## Material 3 defaults
236    ///
237    /// If `ThemeData::use_material3` is set to true the following defaults will
238    /// be used:
239    ///
240    /// * `textStyle` - Theme.textTheme.labelLarge
241    /// * `backgroundColor` - transparent
242    /// * `foregroundColor`
243    ///   * disabled - Theme.colorScheme.onSurface(0.38)
244    ///   * others - Theme.colorScheme.primary
245    /// * `overlayColor`
246    ///   * hovered - Theme.colorScheme.primary(0.08)
247    ///   * focused or pressed - Theme.colorScheme.primary(0.1)
248    ///   * others - null
249    /// * `shadowColor` - Colors.transparent,
250    /// * `surfaceTintColor` - null
251    /// * `elevation` - 0
252    /// * `padding`
253    ///   * `default font size <= 14` - horizontal(24)
254    ///   * `14 < default font size <= 28` - lerp(horizontal(24), horizontal(12))
255    ///   * `28 < default font size <= 36` - lerp(horizontal(12), horizontal(6))
256    ///   * `36 < default font size` - horizontal(6)
257    /// * `minimumSize` - Size(64, 40)
258    /// * `fixedSize` - null
259    /// * `maximumSize` - Size.infinite
260    /// * `side`
261    ///   * disabled - BorderSide(color: Theme.colorScheme.onSurface(0.12))
262    ///   * others - BorderSide(color: Theme.colorScheme.outline)
263    /// * `shape` - StadiumBorder()
264    /// * `mouseCursor` - WidgetStateMouseCursor.adaptiveClickable
265    /// * `visualDensity` - theme.visualDensity
266    /// * `tapTargetSize` - theme.materialTapTargetSize
267    /// * `animationDuration` - kThemeChangeDuration
268    /// * `enableFeedback` - true
269    /// * `alignment` - Alignment.center
270    /// * `splashFactory` - Theme.splashFactory
271    ///
272    /// For the [`OutlinedButton::icon`] factory, the start (generally the left) value of
273    /// [`ButtonStyle::padding`] is reduced from 24 to 16.
274    fn default_style_of(
275        &self,
276        app: &mut App,
277        context: BuildContext,
278    ) -> Box<dyn ButtonStyleGetters> {
279        let theme = Theme::of(app, context);
280        let color_scheme = &theme.color_scheme;
281        let button_style: Box<dyn ButtonStyleGetters> = if theme.use_material3 {
282            Box::new(OutlinedButtonDefaultsM3::new(context))
283        } else {
284            Box::new(
285                OutlinedButtonStyleFromBuilder {
286                    text_style: theme.text_theme.label_large.clone(),
287                    ..OutlinedButton::style_from()
288                }
289                .foreground_color(color_scheme.primary())
290                .disabled_foreground_color(color_scheme.on_surface().with_opacity(0.38))
291                .background_color(Colors::TRANSPARENT)
292                .disabled_background_color(Colors::TRANSPARENT)
293                .shadow_color(theme.shadow_color)
294                .elevation(0.0)
295                .padding(scaled_padding(app, context))
296                .minimum_size(Size::new(64.0, 36.0))
297                .maximum_size(Size::INFINITE)
298                .side(BorderSide {
299                    color: color_scheme.on_surface().with_opacity(0.12),
300                    ..BorderSide::default()
301                })
302                .shape(RoundedRectangleBorder::new(
303                    BorderSide::NONE,
304                    BorderRadius::all(Radius::circular(4.0)).into(),
305                ))
306                .enabled_mouse_cursor(if K_IS_WEB {
307                    SystemMouseCursors::CLICK.into()
308                } else {
309                    SystemMouseCursors::BASIC.into()
310                })
311                .disabled_mouse_cursor(SystemMouseCursors::BASIC.into())
312                .visual_density(theme.visual_density)
313                .tap_target_size(theme.material_tap_target_size)
314                .animation_duration(K_THEME_CHANGE_DURATION)
315                .enable_feedback(true)
316                .alignment(AlignmentGeometry::CENTER)
317                .splash_factory(InkRipple::splash_factory())
318                .build(),
319            )
320        };
321
322        // Only apply paddings when OutlinedButton has an Icon
323        if self.add_padding && theme.use_material3 {
324            let default_font_size = default_font_size(app, Some(&*button_style));
325            let effective_text_scale =
326                MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
327            let scaled_padding = <dyn ButtonStyleButton>::scaled_padding(
328                EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0),
329                EdgeInsetsGeometry::from_steb(8.0, 0.0, 12.0, 0.0),
330                EdgeInsetsGeometry::from_steb(4.0, 0.0, 6.0, 0.0),
331                effective_text_scale,
332            );
333            let padding = Rc::new(MaterialStatePropertyAll::new(Some(scaled_padding)));
334            return Box::new(button_style.copy_with(app).padding(padding));
335        }
336
337        button_style
338    }
339
340    fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> {
341        OutlinedButtonTheme::of(app, context).style
342    }
343}
344
345impl StatefulWidget for OutlinedButton {
346    type State = ButtonStyleState<OutlinedButton>;
347
348    fn key(&self) -> Option<&KeyRef> {
349        self.button_style_button.key.as_ref()
350    }
351
352    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
353        self.button_style_button
354            .debug_fill_properties(app, properties);
355    }
356
357    fn create_state(&self) -> ButtonStyleState<OutlinedButton> {
358        ButtonStyleState::new()
359    }
360}
361
362impl Debug for OutlinedButton {
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        Debug::fmt(&self.button_style_button, f)
365    }
366}
367
368/// Dart's `_scaledPadding`, which the Material 3 defaults share.
369pub(crate) fn scaled_padding(app: &mut App, context: BuildContext) -> EdgeInsetsGeometry {
370    let theme = Theme::of(app, context);
371    let padding1x = if theme.use_material3 { 24.0 } else { 16.0 };
372    let default_font_size = theme
373        .text_theme
374        .label_large
375        .as_ref()
376        .and_then(|label_large| label_large.font_size)
377        .unwrap_or(14.0);
378    let effective_text_scale =
379        MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
380    <dyn ButtonStyleButton>::scaled_padding(
381        EdgeInsetsGeometry::symmetric(0.0, padding1x),
382        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0),
383        EdgeInsetsGeometry::symmetric(0.0, padding1x / 2.0 / 2.0),
384        effective_text_scale,
385    )
386}
387
388/// The font size of `button_style`'s text style with no state, or 14.
389fn default_font_size(app: &mut App, button_style: Option<&dyn ButtonStyleGetters>) -> f64 {
390    button_style
391        .and_then(|style| style.text_style(app))
392        .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
393        .and_then(|text_style| text_style.font_size)
394        .unwrap_or(14.0)
395}
396
397/// Dart's `_OutlinedButtonWithIconChild`.
398#[derive(Debug)]
399struct OutlinedButtonWithIconChild {
400    label: WidgetRef,
401    icon: WidgetRef,
402    button_style: Option<ButtonStyle>,
403    icon_alignment: Option<IconAlignment>,
404}
405
406impl StatelessWidget for OutlinedButtonWithIconChild {
407    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
408        let default_font_size = default_font_size(
409            app,
410            self.button_style
411                .as_ref()
412                .map(|style| style as &dyn ButtonStyleGetters),
413        );
414        let scale = clamp_double(
415            MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0,
416            1.0,
417            2.0,
418        ) - 1.0;
419
420        let outlined_button_theme = OutlinedButtonTheme::of(app, context);
421        let effective_icon_alignment = self
422            .icon_alignment
423            .or(outlined_button_theme
424                .style
425                .and_then(|style| style.icon_alignment))
426            .or(self
427                .button_style
428                .as_ref()
429                .and_then(|style| style.icon_alignment))
430            .unwrap_or(IconAlignment::Start);
431        Row::new()
432            .main_axis_size(MainAxisSize::Min)
433            .spacing(lerp_double(Some(8.0), Some(4.0), scale).expect("both ends"))
434            .children(if effective_icon_alignment == IconAlignment::Start {
435                vec![
436                    self.icon.clone(),
437                    Flexible::new(self.label.clone()).into_widget(),
438                ]
439            } else {
440                vec![
441                    Flexible::new(self.label.clone()).into_widget(),
442                    self.icon.clone(),
443                ]
444            })
445            .into_widget()
446    }
447}
448
449/// Dart's `OutlinedButton.icon(..)` arguments; the value converts to the [`OutlinedButton`].
450pub struct OutlinedButtonIcon {
451    button_style_button: ButtonStyleButtonData,
452    icon: Option<WidgetRef>,
453    label: WidgetRef,
454    icon_alignment: Option<IconAlignment>,
455}
456
457impl OutlinedButtonIcon {
458    crate::button_style_button_setters!(
459        OutlinedButtonIcon;
460        key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
461        clip_behavior, states_controller,
462    );
463
464    /// Dart `OutlinedButton.icon(icon:)`.
465    #[cfg_attr(debug_assertions, track_caller)]
466    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> OutlinedButtonIcon {
467        self.icon = Some(icon.into_widget());
468        self
469    }
470
471    /// Dart `OutlinedButton.icon(iconAlignment:)`.
472    pub fn icon_alignment(mut self, icon_alignment: IconAlignment) -> OutlinedButtonIcon {
473        self.icon_alignment = Some(icon_alignment);
474        self
475    }
476
477    /// The [`OutlinedButton`] these arguments describe.
478    #[cfg_attr(debug_assertions, track_caller)]
479    pub fn build(self) -> OutlinedButton {
480        let mut button_style_button = self.button_style_button;
481        let add_padding = self.icon.is_some();
482        button_style_button.child = Some(match self.icon {
483            Some(icon) => OutlinedButtonWithIconChild {
484                label: self.label,
485                icon,
486                button_style: button_style_button.style.clone(),
487                icon_alignment: self.icon_alignment,
488            }
489            .into_widget(),
490            None => self.label,
491        });
492        OutlinedButton {
493            button_style_button,
494            add_padding,
495        }
496    }
497}
498
499impl IntoWidget<StatefulKind> for OutlinedButtonIcon {
500    #[cfg_attr(debug_assertions, track_caller)]
501    fn into_widget(self) -> WidgetRef {
502        self.build().into_widget()
503    }
504}
505
506/// Dart's `OutlinedButton.styleFrom(..)` arguments; [`build`](Self::build) makes the
507/// [`ButtonStyle`].
508#[derive(Clone, Default)]
509pub struct OutlinedButtonStyleFromBuilder {
510    foreground_color: Option<Color>,
511    background_color: Option<Color>,
512    disabled_foreground_color: Option<Color>,
513    disabled_background_color: Option<Color>,
514    shadow_color: Option<Color>,
515    surface_tint_color: Option<Color>,
516    icon_color: Option<Color>,
517    icon_size: Option<f64>,
518    icon_alignment: Option<IconAlignment>,
519    disabled_icon_color: Option<Color>,
520    overlay_color: Option<Color>,
521    elevation: Option<f64>,
522    text_style: Option<TextStyle>,
523    padding: Option<EdgeInsetsGeometry>,
524    minimum_size: Option<Size>,
525    fixed_size: Option<Size>,
526    maximum_size: Option<Size>,
527    side: Option<BorderSide>,
528    shape: Option<OutlinedBorderRef>,
529    enabled_mouse_cursor: Option<MouseCursorRef>,
530    disabled_mouse_cursor: Option<MouseCursorRef>,
531    visual_density: Option<VisualDensity>,
532    tap_target_size: Option<MaterialTapTargetSize>,
533    animation_duration: Option<Duration>,
534    enable_feedback: Option<bool>,
535    alignment: Option<AlignmentGeometry>,
536    splash_factory: Option<InteractiveInkFeatureFactoryRef>,
537    background_builder: Option<ButtonLayerBuilder>,
538    foreground_builder: Option<ButtonLayerBuilder>,
539}
540
541/// The fluent setters of Dart's named `styleFrom` arguments.
542macro_rules! style_from_setters {
543    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
544        $(
545            #[doc = concat!("Dart `OutlinedButton.styleFrom(", $dart, ":)`.")]
546            pub fn $field(mut self, $field: $ty) -> OutlinedButtonStyleFromBuilder {
547                self.$field = Some($field);
548                self
549            }
550        )*
551    };
552}
553
554impl OutlinedButtonStyleFromBuilder {
555    style_from_setters!(
556        foreground_color: Color => "foregroundColor",
557        background_color: Color => "backgroundColor",
558        disabled_foreground_color: Color => "disabledForegroundColor",
559        disabled_background_color: Color => "disabledBackgroundColor",
560        shadow_color: Color => "shadowColor",
561        surface_tint_color: Color => "surfaceTintColor",
562        icon_color: Color => "iconColor",
563        icon_size: f64 => "iconSize",
564        icon_alignment: IconAlignment => "iconAlignment",
565        disabled_icon_color: Color => "disabledIconColor",
566        overlay_color: Color => "overlayColor",
567        elevation: f64 => "elevation",
568        text_style: TextStyle => "textStyle",
569        padding: EdgeInsetsGeometry => "padding",
570        minimum_size: Size => "minimumSize",
571        fixed_size: Size => "fixedSize",
572        maximum_size: Size => "maximumSize",
573        side: BorderSide => "side",
574        enabled_mouse_cursor: MouseCursorRef => "enabledMouseCursor",
575        disabled_mouse_cursor: MouseCursorRef => "disabledMouseCursor",
576        visual_density: VisualDensity => "visualDensity",
577        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
578        animation_duration: Duration => "animationDuration",
579        enable_feedback: bool => "enableFeedback",
580        alignment: AlignmentGeometry => "alignment",
581        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
582        background_builder: ButtonLayerBuilder => "backgroundBuilder",
583        foreground_builder: ButtonLayerBuilder => "foregroundBuilder",
584    );
585
586    /// Dart `OutlinedButton.styleFrom(shape:)`.
587    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> OutlinedButtonStyleFromBuilder {
588        self.shape = Some(shape.into());
589        self
590    }
591
592    /// The [`ButtonStyle`] made from these values.
593    pub fn build(self) -> ButtonStyle {
594        let background_color_prop: Option<WidgetStatePropertyRef<Option<Color>>> =
595            match (self.background_color, self.disabled_background_color) {
596                (Some(_), None) => {
597                    Some(Rc::new(WidgetStatePropertyAll::new(self.background_color)))
598                }
599                (_, _) => <dyn ButtonStyleButton>::default_color(
600                    self.background_color,
601                    self.disabled_background_color,
602                ),
603            };
604        let overlay_color_prop: Option<WidgetStatePropertyRef<Option<Color>>> =
605            match (self.foreground_color, self.overlay_color) {
606                (None, None) => None,
607                (_, Some(overlay_color)) if overlay_color.a == 0.0 => {
608                    Some(Rc::new(WidgetStatePropertyAll::new(self.overlay_color)))
609                }
610                (_, Some(color)) | (Some(color), None) => {
611                    Some(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
612                        (WidgetState::Pressed.into(), Some(color.with_opacity(0.1))),
613                        (WidgetState::Hovered.into(), Some(color.with_opacity(0.08))),
614                        (WidgetState::Focused.into(), Some(color.with_opacity(0.1))),
615                        (WidgetState::any(), None),
616                    ]))
617                }
618            };
619
620        ButtonStyle {
621            text_style: <dyn ButtonStyleButton>::all_or_null(self.text_style),
622            foreground_color: <dyn ButtonStyleButton>::default_color(
623                self.foreground_color,
624                self.disabled_foreground_color,
625            ),
626            background_color: background_color_prop,
627            overlay_color: overlay_color_prop,
628            shadow_color: <dyn ButtonStyleButton>::all_or_null(self.shadow_color),
629            surface_tint_color: <dyn ButtonStyleButton>::all_or_null(self.surface_tint_color),
630            icon_color: <dyn ButtonStyleButton>::default_color(
631                self.icon_color,
632                self.disabled_icon_color,
633            ),
634            icon_size: <dyn ButtonStyleButton>::all_or_null(self.icon_size),
635            icon_alignment: self.icon_alignment,
636            elevation: <dyn ButtonStyleButton>::all_or_null(self.elevation),
637            padding: <dyn ButtonStyleButton>::all_or_null(self.padding),
638            minimum_size: <dyn ButtonStyleButton>::all_or_null(self.minimum_size),
639            fixed_size: <dyn ButtonStyleButton>::all_or_null(self.fixed_size),
640            maximum_size: <dyn ButtonStyleButton>::all_or_null(self.maximum_size),
641            side: <dyn ButtonStyleButton>::all_or_null(self.side),
642            shape: <dyn ButtonStyleButton>::all_or_null(self.shape),
643            mouse_cursor: Some(<dyn WidgetStateProperty<Option<MouseCursorRef>>>::from_map(
644                vec![
645                    (WidgetState::Disabled.into(), self.disabled_mouse_cursor),
646                    (WidgetState::any(), self.enabled_mouse_cursor),
647                ],
648            )),
649            visual_density: self.visual_density,
650            tap_target_size: self.tap_target_size,
651            animation_duration: self.animation_duration,
652            enable_feedback: self.enable_feedback,
653            alignment: self.alignment,
654            splash_factory: self.splash_factory,
655            background_builder: self.background_builder,
656            foreground_builder: self.foreground_builder,
657            ..ButtonStyle::new()
658        }
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use std::cell::{Cell, RefCell};
665    use waft_widgets::testing::assert_f32_equals;
666
667    use waft_embedder::{FontWeight, Offset, PointerChange, Rect, TargetPlatform, TextDirection};
668    use waft_painting::{ShapeBorder, ShapeBorderRef, StadiumBorder};
669    use waft_widgets::{
670        Align, Builder, Center, Directionality, FocusHighlightStrategy, FocusNode, GlobalKey, Icon,
671        MouseRegion, Padding, SizedBox, Text, UnfocusDisposition,
672    };
673
674    use waft_foundation::Listenable;
675
676    use waft_widgets::testing::{
677        TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
678    };
679
680    use super::*;
681    use crate::color_scheme::ColorScheme;
682    use crate::icons::Icons;
683    use crate::ink_sparkle::InkSparkle;
684    use crate::ink_well::InkWell;
685    use crate::material::{Material, MaterialType};
686    use crate::material_state::MaterialStatesController;
687    use crate::no_splash::NoSplash;
688    use crate::outlined_button_theme::OutlinedButtonThemeData;
689    use crate::test_support::{PaintInspection, material_app, path_like};
690    use crate::text_theme::TextTheme;
691    use crate::theme_data::ThemeData;
692    use waft_rendering::testing::RecordedCall;
693    use waft_widgets::FocusNodeRef;
694
695    fn pressed() -> Option<Listener> {
696        Some(Listener::new(|_app| {}))
697    }
698
699    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
700        Directionality::new(TextDirection::Ltr, child).into_widget()
701    }
702
703    /// Dart's `ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: ..)`.
704    fn light(tester: &WidgetTester, use_material3: bool) -> ThemeData {
705        ThemeData::from(ColorScheme::light())
706            .use_material3(use_material3)
707            .build(&tester.cell.borrow())
708    }
709
710    /// Dart's `ThemeData()`.
711    fn default_theme(tester: &WidgetTester) -> ThemeData {
712        ThemeData::new(&tester.cell.borrow())
713    }
714
715    /// `MaterialApp(theme: theme, home: Center(child: child))`.
716    fn app_centered<K>(theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
717        material_app(theme, Center::new().child(child).into_widget())
718    }
719
720    fn side(color: Color) -> BorderSide {
721        BorderSide {
722            color,
723            ..BorderSide::default()
724        }
725    }
726
727    fn states(states: &[WidgetState]) -> WidgetStates {
728        states.iter().copied().collect()
729    }
730
731    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
732        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
733    }
734
735    /// Reads the button's `Material`, the last one in the tree: Dart's
736    /// `tester.widget<Material>(find.descendant(of: find.byType(OutlinedButton), matching:
737    /// find.byType(Material)))`.
738    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
739        let element = *find::by_type::<Material>()
740            .evaluate(tester)
741            .last()
742            .expect("the button's Material");
743        tester.widget(element, read)
744    }
745
746    fn material_shape_is(tester: &WidgetTester, expected: &dyn ShapeBorder) -> bool {
747        material(tester, |material| {
748            material
749                .shape
750                .as_deref()
751                .expect("a button gives its Material a shape")
752                .eq_shape(expected)
753        })
754    }
755
756    fn material_side(tester: &WidgetTester) -> BorderSide {
757        material(tester, |material| {
758            material
759                .shape
760                .as_deref()
761                .and_then(|shape| shape.as_outlined_border())
762                .expect("an outlined border")
763                .side()
764        })
765    }
766
767    fn ink_well<R>(tester: &WidgetTester, read: impl FnOnce(&InkWell) -> R) -> R {
768        let element = *find::by_type::<InkWell>()
769            .evaluate(tester)
770            .last()
771            .expect("an InkWell");
772        tester.widget(element, read)
773    }
774
775    fn button_enabled(tester: &WidgetTester) -> bool {
776        let element = *find::by_type::<OutlinedButton>()
777            .evaluate(tester)
778            .first()
779            .expect("an OutlinedButton");
780        tester.widget(element, |button: &OutlinedButton| button.enabled())
781    }
782
783    /// The center of the first `OutlinedButton`: Dart's
784    /// `tester.getCenter(find.byType(OutlinedButton))`.
785    fn button_center(tester: &WidgetTester) -> Offset {
786        let element = *find::by_type::<OutlinedButton>()
787            .evaluate(tester)
788            .first()
789            .expect("an OutlinedButton");
790        tester.get_rect(element).center()
791    }
792
793    fn button_rect(tester: &WidgetTester) -> Rect {
794        let element = *find::by_type::<Material>()
795            .evaluate(tester)
796            .last()
797            .expect("the button's Material");
798        tester.get_rect(element)
799    }
800
801    fn icon_rect(tester: &WidgetTester) -> Rect {
802        let element = *find::by_type::<Icon>()
803            .evaluate(tester)
804            .first()
805            .expect("an Icon");
806        tester.get_rect(element)
807    }
808
809    /// The colors of the rects the button's ink features draw.
810    fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
811        tester
812            .ink_calls()
813            .into_iter()
814            .filter_map(|drawn| match drawn {
815                RecordedCall::Rect { color, .. } => Some(color.value()),
816                _ => None,
817            })
818            .collect()
819    }
820
821    fn ink_circle_count(tester: &WidgetTester) -> usize {
822        tester
823            .ink_calls()
824            .into_iter()
825            .filter(|drawn| path_like(drawn).is_some())
826            .count()
827    }
828
829    fn padding_of_button(tester: &WidgetTester) -> EdgeInsetsGeometry {
830        let button = *find::by_type::<OutlinedButton>()
831            .evaluate(tester)
832            .first()
833            .expect("an OutlinedButton");
834        let padding = find::by_type::<Padding>()
835            .evaluate(tester)
836            .into_iter()
837            .find(|padding| tester.ancestors(*padding).contains(&button))
838            .expect("the button's Padding");
839        tester.widget(padding, |padding: &Padding| padding.padding)
840    }
841
842    fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
843        Rc::new(WidgetStatePropertyAll::new(Some(value)))
844    }
845
846    fn mouse() -> TestPointer {
847        TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON)
848    }
849
850    fn argb(color: Color) -> u32 {
851        color.value()
852    }
853
854    /// Checks the `Material` of a default button; `disabled` picks the disabled colors.
855    fn check_default_material(
856        tester: &WidgetTester,
857        color_scheme: &ColorScheme,
858        material3: bool,
859        disabled: bool,
860    ) {
861        material(tester, |material| {
862            assert_eq!(material.animation_duration, Duration::from_millis(200));
863            assert!(!material.border_on_foreground);
864            assert!(material.border_radius.is_none());
865            assert_eq!(material.clip_behavior, waft_embedder::Clip::None);
866            assert_eq!(material.color, Some(Colors::TRANSPARENT));
867            assert_eq!(material.elevation, 0.0);
868            assert_eq!(
869                material.shadow_color,
870                Some(if material3 {
871                    Colors::TRANSPARENT
872                } else {
873                    Color::new(0xff000000)
874                })
875            );
876            let text_style = material.text_style.as_ref().expect("a text style");
877            assert_eq!(
878                text_style.color.as_deref().copied(),
879                Some(if disabled {
880                    color_scheme.on_surface().with_opacity(0.38)
881                } else {
882                    color_scheme.primary()
883                })
884            );
885            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
886            assert_eq!(text_style.font_size, Some(14.0));
887            assert_eq!(text_style.font_weight, Some(FontWeight::W500));
888            assert_eq!(material.r#type, MaterialType::Button);
889        });
890        let expected: ShapeBorderRef = if material3 {
891            ShapeBorderRef::new(StadiumBorder::new(side(if disabled {
892                color_scheme.on_surface().with_opacity(0.12)
893            } else {
894                color_scheme.outline()
895            })))
896        } else {
897            ShapeBorderRef::new(RoundedRectangleBorder::new(
898                side(color_scheme.on_surface().with_opacity(0.12)),
899                BorderRadius::all(Radius::circular(4.0)).into(),
900            ))
901        };
902        assert!(material_shape_is(tester, &*expected));
903    }
904
905    // 'OutlinedButton, OutlinedButton.icon defaults', which Flutter runs in Material 3; the
906    // Material 2 values are its other branch.
907    fn defaults_case(tester: &mut WidgetTester, material3: bool) {
908        let color_scheme = ColorScheme::light();
909        let theme = light(tester, material3);
910
911        // Enabled OutlinedButton
912        tester.pump_widget(app_centered(
913            theme.clone(),
914            OutlinedButton::new(pressed(), Some(Text::new("button"))),
915        ));
916        check_default_material(tester, &color_scheme, material3, false);
917        let align =
918            tester.element(find::ancestor(find::text("button"), find::by_type::<Align>()).first());
919        tester.widget(align, |align: &Align| {
920            assert!(align.alignment == AlignmentGeometry::CENTER);
921        });
922
923        let mut touch = TestPointer::touch(1);
924        tester.down(&mut touch, button_center(tester));
925        tester.pump(); // start the splash animation
926        tester.pump_by(Duration::from_millis(100)); // splash is underway
927        tester.up(&touch);
928        tester.pump_and_settle();
929        // No change vs enabled and not pressed.
930        check_default_material(tester, &color_scheme, material3, false);
931
932        // Enabled OutlinedButton.icon
933        let icon_button_key = GlobalKey::new();
934        tester.pump_widget(app_centered(
935            theme.clone(),
936            OutlinedButton::icon(pressed(), Text::new("label"))
937                .key(icon_button_key.into())
938                .icon(Icon::new(Some(Icons::add()))),
939        ));
940        check_default_material(tester, &color_scheme, material3, false);
941
942        // Disabled OutlinedButton
943        tester.pump_widget(app_centered(
944            theme,
945            OutlinedButton::new(None, Some(Text::new("button"))),
946        ));
947        check_default_material(tester, &color_scheme, material3, true);
948    }
949
950    #[test]
951    fn material_3_defaults_of_outlined_button_and_its_icon_variant_per_state() {
952        test_widgets(|tester| defaults_case(tester, true));
953    }
954
955    #[test]
956    fn material_2_defaults_of_outlined_button_and_its_icon_variant_per_state() {
957        test_widgets(|tester| defaults_case(tester, false));
958    }
959
960    /// Which of a default style's properties are set, read where `button` builds.
961    fn default_style_fields(
962        tester: &mut WidgetTester,
963        button: OutlinedButton,
964    ) -> (Vec<bool>, Vec<bool>) {
965        let seen = Rc::new(RefCell::new(None));
966        let button = Rc::new(button);
967        let theme = light(tester, true);
968        tester.pump_widget(app_centered(
969            theme,
970            Builder::new({
971                let seen = Rc::clone(&seen);
972                move |app, context| {
973                    let style = button.default_style_of(app, context).copy_with(app);
974                    *seen.borrow_mut() = Some((
975                        vec![
976                            style.text_style.is_some(),
977                            style.background_color.is_some(),
978                            style.foreground_color.is_some(),
979                            style.overlay_color.is_some(),
980                            style.shadow_color.is_some(),
981                            style.surface_tint_color.is_some(),
982                            style.elevation.is_some(),
983                            style.padding.is_some(),
984                            style.minimum_size.is_some(),
985                            style.maximum_size.is_some(),
986                            style.icon_color.is_some(),
987                            style.icon_size.is_some(),
988                            style.shape.is_some(),
989                            style.mouse_cursor.is_some(),
990                            style.visual_density.is_some(),
991                            style.tap_target_size.is_some(),
992                            style.animation_duration.is_some(),
993                            style.enable_feedback.is_some(),
994                            style.alignment.is_some(),
995                            style.splash_factory.is_some(),
996                            style.side.is_some(),
997                        ],
998                        vec![
999                            style.fixed_size.is_some(),
1000                            style.background_builder.is_some(),
1001                            style.foreground_builder.is_some(),
1002                        ],
1003                    ));
1004                    SizedBox::shrink().into_widget()
1005                }
1006            }),
1007        ));
1008        seen.borrow_mut().take().expect("the builder ran")
1009    }
1010
1011    #[test]
1012    fn the_default_style_sets_every_property_but_the_fixed_size_and_the_builders() {
1013        test_widgets(|tester| {
1014            let (set, unset) = default_style_fields(
1015                tester,
1016                OutlinedButton::new(pressed(), Some(Text::new("button"))),
1017            );
1018            assert!(set.iter().all(|set| *set), "{set:?}");
1019            assert!(unset.iter().all(|set| !*set), "{unset:?}");
1020
1021            let (set, unset) = default_style_fields(
1022                tester,
1023                OutlinedButton::icon(pressed(), Text::new("button"))
1024                    .icon(SizedBox::new())
1025                    .build(),
1026            );
1027            assert!(set.iter().all(|set| *set), "{set:?}");
1028            assert!(unset.iter().all(|set| !*set), "{unset:?}");
1029        });
1030    }
1031
1032    #[test]
1033    fn outlined_button_icon_without_an_icon_shows_only_the_label() {
1034        test_widgets(|tester| {
1035            let theme = light(tester, true);
1036            tester.pump_widget(app_centered(
1037                theme.clone(),
1038                OutlinedButton::icon(pressed(), Text::new("label"))
1039                    .icon(Icon::new(Some(Icons::add()))),
1040            ));
1041            assert_eq!(find::by_type::<Icon>().evaluate(tester).len(), 1);
1042            assert_eq!(find::text("label").evaluate(tester).len(), 1);
1043
1044            tester.pump_widget(app_centered(
1045                theme,
1046                // No icon specified.
1047                OutlinedButton::icon(pressed(), Text::new("label")),
1048            ));
1049            assert!(find::by_type::<Icon>().evaluate(tester).is_empty());
1050            assert_eq!(find::text("label").evaluate(tester).len(), 1);
1051        });
1052    }
1053
1054    #[test]
1055    fn the_default_overlay_color_resolves_hovered_pressed_and_focused() {
1056        test_widgets(|tester| {
1057            let focus_node = focus_node(tester);
1058            let theme = default_theme(tester);
1059            let primary = theme.color_scheme.primary();
1060            tester.pump_widget(app_centered(
1061                theme,
1062                OutlinedButton::new(pressed(), Some(Text::new("OutlinedButton")))
1063                    .focus_node(focus_node.clone()),
1064            ));
1065
1066            // Hovered.
1067            let center = button_center(tester);
1068            let mut gesture = mouse();
1069            tester.add_pointer(&mut gesture, Offset::ZERO);
1070            tester.move_to(&mut gesture, center, false);
1071            tester.pump_and_settle();
1072            assert!(ink_rect_colors(tester).contains(&argb(primary.with_opacity(0.08))));
1073
1074            // Highlighted (pressed).
1075            tester.send(&gesture, PointerChange::Down);
1076            tester.pump_and_settle();
1077            let colors = ink_rect_colors(tester);
1078            assert!(
1079                colors[1..].contains(&argb(primary.with_opacity(0.1))),
1080                "{colors:x?}"
1081            );
1082            // Remove pressed and hovered states
1083            tester.up(&gesture);
1084            tester.pump_and_settle();
1085            tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
1086            tester.pump_and_settle();
1087
1088            // Focused.
1089            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1090            tester.pump_and_settle();
1091            assert!(ink_rect_colors(tester).contains(&argb(primary.with_opacity(0.1))));
1092        });
1093    }
1094
1095    #[test]
1096    fn a_style_overlay_color_shows_while_hovered() {
1097        test_widgets(|tester| {
1098            let hover_color = Color::new(0xff001122);
1099            tester.pump_widget(ltr(OutlinedButton::new(
1100                pressed(),
1101                Some(Text::new("button")),
1102            )
1103            .style(ButtonStyle::new().overlay_color(<dyn WidgetStateProperty<
1104                Option<Color>,
1105            >>::resolve_with(
1106                move |states| {
1107                    states
1108                        .contains(&WidgetState::Hovered)
1109                        .then_some(hover_color)
1110                },
1111            )))));
1112
1113            let mut gesture = mouse();
1114            tester.add_pointer(&mut gesture, Offset::ZERO);
1115            tester.move_to(&mut gesture, button_center(tester), false);
1116            tester.pump_and_settle();
1117            assert!(ink_rect_colors(tester).contains(&argb(hover_color)));
1118        });
1119    }
1120
1121    fn focus_case(tester: &mut WidgetTester, autofocus: bool) {
1122        let theme = default_theme(tester);
1123        let primary = theme.color_scheme.primary();
1124        let focus_color = Color::new(0xff001122);
1125        let focus_node = focus_node(tester);
1126        tester.pump_widget(material_app(
1127            theme,
1128            OutlinedButton::new(pressed(), Some(Text::new("button")))
1129                .autofocus(autofocus)
1130                .style(ButtonStyle::new().overlay_color(
1131                    <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
1132                        states
1133                            .contains(&WidgetState::Focused)
1134                            .then_some(focus_color)
1135                    }),
1136                ))
1137                .focus_node(focus_node.clone())
1138                .into_widget(),
1139        ));
1140
1141        tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1142        if !autofocus {
1143            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1144        }
1145        tester.pump_and_settle();
1146
1147        assert!(ink_rect_colors(tester).contains(&argb(focus_color)));
1148        assert!(material_shape_is(
1149            tester,
1150            &StadiumBorder::new(side(primary))
1151        ));
1152    }
1153
1154    #[test]
1155    fn a_style_overlay_color_shows_while_focused_and_the_side_turns_primary() {
1156        test_widgets(|tester| focus_case(tester, false));
1157    }
1158
1159    #[test]
1160    fn an_autofocused_button_shows_its_focused_overlay_and_side() {
1161        test_widgets(|tester| focus_case(tester, true));
1162    }
1163
1164    const PRESSED_COLOR: Color = Color::new(0x00000001);
1165    const HOVER_COLOR: Color = Color::new(0x00000002);
1166    const FOCUSED_COLOR: Color = Color::new(0x00000003);
1167    const DEFAULT_COLOR: Color = Color::new(0x00000004);
1168
1169    fn color_for(states: &WidgetStates) -> Color {
1170        if states.contains(&WidgetState::Pressed) {
1171            return PRESSED_COLOR;
1172        }
1173        if states.contains(&WidgetState::Hovered) {
1174            return HOVER_COLOR;
1175        }
1176        if states.contains(&WidgetState::Focused) {
1177            return FOCUSED_COLOR;
1178        }
1179        DEFAULT_COLOR
1180    }
1181
1182    /// Runs default, focused, hovered and pressed, reading `read` at each.
1183    fn stateful_color_case(
1184        tester: &mut WidgetTester,
1185        button: impl FnOnce(waft_widgets::FocusNodeRef) -> WidgetRef,
1186        read: impl Fn(&WidgetTester) -> Color,
1187        settle_pressed: bool,
1188    ) {
1189        let focus_node = focus_node(tester);
1190        let theme = default_theme(tester);
1191        tester.pump_widget(app_centered(theme, button(focus_node.clone())));
1192
1193        // Default, not disabled.
1194        assert_eq!(read(tester), DEFAULT_COLOR);
1195
1196        // Focused.
1197        focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1198        tester.pump_and_settle();
1199        assert_eq!(read(tester), FOCUSED_COLOR);
1200
1201        // Hovered.
1202        let center = button_center(tester);
1203        let mut gesture = mouse();
1204        tester.add_pointer(&mut gesture, Offset::ZERO);
1205        tester.move_to(&mut gesture, center, false);
1206        tester.pump_and_settle();
1207        assert_eq!(read(tester), HOVER_COLOR);
1208
1209        // Highlighted (pressed).
1210        tester.send(&gesture, PointerChange::Down);
1211        if settle_pressed {
1212            tester.pump_and_settle();
1213        } else {
1214            tester.pump(); // Start the splash and highlight animations.
1215            tester.pump_by(Duration::from_millis(800)); // Wait for splash and highlight to be well under way.
1216        }
1217        assert_eq!(read(tester), PRESSED_COLOR);
1218    }
1219
1220    #[test]
1221    fn a_stateful_foreground_color_colors_the_text_in_each_state() {
1222        test_widgets(|tester| {
1223            stateful_color_case(
1224                tester,
1225                |focus_node| {
1226                    OutlinedButton::new(pressed(), Some(Text::new("OutlinedButton")))
1227                        .style(
1228                            ButtonStyle::new().foreground_color(<dyn WidgetStateProperty<
1229                                Option<Color>,
1230                            >>::resolve_with(
1231                                |states| Some(color_for(states))
1232                            )),
1233                        )
1234                        .focus_node(focus_node.clone())
1235                        .into_widget()
1236                },
1237                |tester| tester.text_color("OutlinedButton"),
1238                false,
1239            );
1240        });
1241    }
1242
1243    #[test]
1244    fn a_stateful_icon_color_colors_the_icon_in_each_state() {
1245        test_widgets(|tester| {
1246            stateful_color_case(
1247                tester,
1248                |focus_node| {
1249                    OutlinedButton::icon(pressed(), Text::new("OutlinedButton"))
1250                        .style(ButtonStyle::new().icon_color(<dyn WidgetStateProperty<
1251                            Option<Color>,
1252                        >>::resolve_with(
1253                            |states| Some(color_for(states))
1254                        )))
1255                        .icon(Icon::new(Some(Icons::add())))
1256                        .focus_node(focus_node.clone())
1257                        .into_widget()
1258                },
1259                |tester| *tester.icon_style().color.expect("an icon color"),
1260                false,
1261            );
1262        });
1263    }
1264
1265    /// The colors of the paths the button's `Material` paints: its outline among them.
1266    fn painted_path_colors(tester: &WidgetTester) -> Vec<u32> {
1267        let element = *find::by_type::<OutlinedButton>()
1268            .evaluate(tester)
1269            .first()
1270            .expect("an OutlinedButton");
1271        let render = tester.render_object(element);
1272        tester
1273            .painted_calls(render)
1274            .into_iter()
1275            .filter_map(|drawn| path_like(&drawn).map(|(color, _)| color.value()))
1276            .collect()
1277    }
1278
1279    /// [`color_for`] made opaque: Valo's canvas drops a draw whose paint is transparent, and
1280    /// Flutter's state colors are.
1281    fn opaque_color_for(states: &WidgetStates) -> Color {
1282        Color::new(color_for(states).value() | 0xff00_0000)
1283    }
1284
1285    #[test]
1286    fn a_stateful_side_paints_the_outline_in_each_state() {
1287        test_widgets(|tester| {
1288            stateful_color_case(
1289                tester,
1290                |focus_node| {
1291                    OutlinedButton::new(pressed(), Some(Text::new("OutlinedButton")))
1292                        .style(
1293                            ButtonStyle::new()
1294                                .side(<dyn WidgetStateProperty<Option<BorderSide>>>::resolve_with(
1295                                    |states| Some(side(opaque_color_for(states))),
1296                                ))
1297                                // Test assumes a rounded rect for the shape
1298                                .shape(all(OutlinedBorderRef::new(RoundedRectangleBorder::new(
1299                                    BorderSide::NONE,
1300                                    BorderRadius::all(Radius::circular(4.0)).into(),
1301                                )))),
1302                        )
1303                        .focus_node(focus_node.clone())
1304                        .into_widget()
1305                },
1306                |tester| {
1307                    let colors = painted_path_colors(tester);
1308                    [PRESSED_COLOR, HOVER_COLOR, FOCUSED_COLOR, DEFAULT_COLOR]
1309                        .into_iter()
1310                        .find(|color| colors.contains(&(argb(*color) | 0xff00_0000)))
1311                        .expect("the outline is painted in a state's color")
1312                },
1313                true,
1314            );
1315        });
1316    }
1317
1318    #[test]
1319    fn on_pressed_or_on_long_press_enables_the_button_and_is_called() {
1320        test_widgets(|tester| {
1321            let was_pressed = Rc::new(Cell::new(false));
1322            let setter = || {
1323                let was_pressed = Rc::clone(&was_pressed);
1324                Listener::new(move |_app| was_pressed.set(true))
1325            };
1326
1327            // onPressed not null, onLongPress null.
1328            tester.pump_widget(ltr(OutlinedButton::new(
1329                Some(setter()),
1330                Some(Text::new("button")),
1331            )));
1332            assert!(button_enabled(tester));
1333            tester.tap_at(button_center(tester), 1);
1334            assert!(was_pressed.get());
1335
1336            // onPressed null, onLongPress not null.
1337            was_pressed.set(false);
1338            tester.pump_widget(ltr(
1339                OutlinedButton::new(None, Some(Text::new("button"))).on_long_press(setter())
1340            ));
1341            assert!(button_enabled(tester));
1342            tester.long_press_at(button_center(tester), 2);
1343            assert!(was_pressed.get());
1344
1345            // onPressed null, onLongPress null.
1346            tester.pump_widget(ltr(OutlinedButton::new(None, Some(Text::new("button")))));
1347            assert!(!button_enabled(tester));
1348        });
1349    }
1350
1351    fn hover_setter(hovering: &Rc<Cell<bool>>) -> waft_foundation::ValueChanged<bool> {
1352        let hovering = Rc::clone(hovering);
1353        Rc::new(move |_app, value| hovering.set(value))
1354    }
1355
1356    fn disabled_drops_focus_case(tester: &mut WidgetTester, icon: bool) {
1357        tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTouch);
1358        let focus_node = focus_node(tester);
1359        let child_key = GlobalKey::new();
1360        let hovering = Rc::new(Cell::new(false));
1361        let frame = |enabled: bool| {
1362            let child = SizedBox::new().key(child_key.clone().into());
1363            let button = if icon {
1364                let mut button =
1365                    OutlinedButton::icon(if enabled { pressed() } else { None }, child)
1366                        .on_hover(hover_setter(&hovering))
1367                        .focus_node(focus_node.clone())
1368                        .icon(Icon::new(Some(Icons::add())));
1369                if enabled {
1370                    button = button
1371                        .autofocus(true)
1372                        .on_long_press(Listener::new(|_app| {}));
1373                }
1374                button.build()
1375            } else {
1376                let mut button =
1377                    OutlinedButton::new(if enabled { pressed() } else { None }, Some(child))
1378                        .on_hover(hover_setter(&hovering))
1379                        .focus_node(focus_node.clone());
1380                if enabled {
1381                    button = button
1382                        .autofocus(true)
1383                        .on_long_press(Listener::new(|_app| {}));
1384                }
1385                button
1386            };
1387            ltr(SizedBox::square(Some(100.0)).child(button))
1388        };
1389        tester.pump_widget(frame(true));
1390        tester.pump_and_settle();
1391        assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1392        let mut gesture = mouse();
1393        tester.add_pointer(&mut gesture, Offset::ZERO);
1394        tester.move_to(&mut gesture, tester.get_center(&child_key), false);
1395        tester.pump_and_settle();
1396        assert!(hovering.get());
1397
1398        tester.pump_widget(frame(false));
1399        tester.pump_and_settle();
1400        assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
1401    }
1402
1403    #[test]
1404    fn a_button_disabled_while_focused_and_hovered_loses_focus() {
1405        test_widgets(|tester| disabled_drops_focus_case(tester, false));
1406    }
1407
1408    #[test]
1409    fn an_icon_button_disabled_while_focused_and_hovered_loses_focus() {
1410        test_widgets(|tester| disabled_drops_focus_case(tester, true));
1411    }
1412
1413    fn mouse_exit_case(tester: &mut WidgetTester, icon: bool) {
1414        let on_hover_count = Rc::new(Cell::new(0));
1415        let hover = Rc::new(Cell::new(false));
1416        let on_hover = || -> waft_foundation::ValueChanged<bool> {
1417            let on_hover_count = Rc::clone(&on_hover_count);
1418            let hover = Rc::clone(&hover);
1419            Rc::new(move |_app, value| {
1420                on_hover_count.set(on_hover_count.get() + 1);
1421                hover.set(value);
1422            })
1423        };
1424        let frame = |enabled: bool| {
1425            let on_pressed = if enabled { pressed() } else { None };
1426            let button = if icon {
1427                OutlinedButton::icon(on_pressed, Text::new("OutlinedButton"))
1428                    .on_hover(on_hover())
1429                    .icon(Icon::new(Some(Icons::add())))
1430                    .build()
1431            } else {
1432                OutlinedButton::new(on_pressed, Some(Text::new("OutlinedButton")))
1433                    .on_hover(on_hover())
1434            };
1435            ltr(Center::new().child(SizedBox::square(Some(100.0)).child(button)))
1436        };
1437
1438        tester.pump_widget(frame(true));
1439        let mut gesture = mouse();
1440        tester.add_pointer(&mut gesture, Offset::ZERO);
1441
1442        tester.move_to(&mut gesture, button_center(tester), false);
1443        tester.pump_and_settle();
1444        assert_eq!(on_hover_count.get(), 1);
1445        assert!(hover.get());
1446
1447        tester.pump_widget(frame(false));
1448        tester.pump_and_settle();
1449        tester.move_to(&mut gesture, Offset::ZERO, false);
1450        // Even though the OutlinedButton has been disabled, the mouse-exit still
1451        // causes onHover(false) to be called.
1452        assert_eq!(on_hover_count.get(), 2);
1453        assert!(!hover.get());
1454
1455        tester.move_to(&mut gesture, button_center(tester), false);
1456        tester.pump_and_settle();
1457        // We no longer see hover events because the OutlinedButton is disabled
1458        // and it's no longer in the "hovering" state.
1459        assert_eq!(on_hover_count.get(), 2);
1460        assert!(!hover.get());
1461
1462        tester.pump_widget(frame(true));
1463        tester.pump_and_settle();
1464        // The OutlinedButton was enabled while it contained the mouse, however
1465        // we do not call onHover() because it may call setState().
1466        assert_eq!(on_hover_count.get(), 2);
1467        assert!(!hover.get());
1468
1469        tester.move_to(
1470            &mut gesture,
1471            button_center(tester) - Offset::new(1.0, 1.0),
1472            false,
1473        );
1474        tester.pump_and_settle();
1475        // Moving the mouse a little within the OutlinedButton doesn't change anything.
1476        assert_eq!(on_hover_count.get(), 2);
1477        assert!(!hover.get());
1478    }
1479
1480    #[test]
1481    fn a_disabled_and_hovered_button_reports_the_mouse_exit() {
1482        test_widgets(|tester| mouse_exit_case(tester, false));
1483    }
1484
1485    #[test]
1486    fn a_disabled_and_hovered_icon_button_reports_the_mouse_exit() {
1487        test_widgets(|tester| mouse_exit_case(tester, true));
1488    }
1489
1490    fn focus_change_case(tester: &mut WidgetTester, icon: bool, enabled: bool) {
1491        let node = focus_node(tester);
1492        let got_focus = Rc::new(Cell::new(false));
1493        let on_focus_change: waft_foundation::ValueChanged<bool> = {
1494            let got_focus = Rc::clone(&got_focus);
1495            Rc::new(move |_app, focused| got_focus.set(focused))
1496        };
1497        let on_pressed = if enabled { pressed() } else { None };
1498        let button = if icon {
1499            OutlinedButton::icon(on_pressed, SizedBox::new())
1500                .focus_node(node.clone())
1501                .on_focus_change(on_focus_change)
1502                .icon(Icon::new(Some(Icons::add())))
1503                .build()
1504        } else {
1505            OutlinedButton::new(on_pressed, Some(SizedBox::new()))
1506                .focus_node(node.clone())
1507                .on_focus_change(on_focus_change)
1508        };
1509        tester.pump_widget(ltr(button));
1510
1511        node.request_focus(&mut tester.cell.borrow_mut(), None);
1512        tester.pump();
1513        assert_eq!(got_focus.get(), enabled);
1514        assert_eq!(node.has_focus(&tester.cell.borrow_mut()), enabled);
1515        if !enabled {
1516            return;
1517        }
1518
1519        node.unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
1520        tester.pump();
1521        assert!(!got_focus.get());
1522        assert!(!node.has_focus(&tester.cell.borrow_mut()));
1523    }
1524
1525    #[test]
1526    fn a_button_can_be_focused_and_unfocused() {
1527        test_widgets(|tester| {
1528            focus_change_case(tester, false, true);
1529            focus_change_case(tester, true, true);
1530        });
1531    }
1532
1533    #[test]
1534    fn a_disabled_button_cannot_be_focused() {
1535        test_widgets(|tester| {
1536            focus_change_case(tester, false, false);
1537            focus_change_case(tester, true, false);
1538        });
1539    }
1540
1541    #[test]
1542    fn a_button_disabled_during_a_gesture_does_not_crash() {
1543        test_widgets(|tester| {
1544            let frame = |tester: &WidgetTester, on_pressed: Option<Listener>| {
1545                let theme = default_theme(tester);
1546                ltr(Theme::new(
1547                    theme,
1548                    Center::new().child(OutlinedButton::new(on_pressed, Some(Text::new("button")))),
1549                ))
1550            };
1551            let first = frame(tester, pressed());
1552            tester.pump_widget(first);
1553            let mut touch = TestPointer::touch(1);
1554            tester.down(&mut touch, button_center(tester));
1555            tester.pump_and_settle();
1556            let second = frame(tester, None);
1557            tester.pump_widget(second);
1558            tester.pump_and_settle();
1559        });
1560    }
1561
1562    #[test]
1563    fn a_shape_and_a_stateful_side_resolve_per_state() {
1564        test_widgets(|tester| {
1565            let fill_color = Color::new(0xFF00FF00);
1566            let disabled_border_side = BorderSide {
1567                color: Color::new(0xFFFF0000),
1568                width: 3.0,
1569                ..BorderSide::default()
1570            };
1571            let enabled_border_side = BorderSide {
1572                color: Color::new(0xFFFF00FF),
1573                width: 4.0,
1574                ..BorderSide::default()
1575            };
1576            let pressed_border_side = BorderSide {
1577                color: Color::new(0xFF0000FF),
1578                width: 5.0,
1579                ..BorderSide::default()
1580            };
1581            let frame = |tester: &WidgetTester, on_pressed: Option<Listener>| {
1582                let theme = ThemeData::builder()
1583                    .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1584                    .build(&tester.cell.borrow());
1585                ltr(Theme::new(
1586                    theme,
1587                    Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
1588                        OutlinedButton::new(on_pressed, Some(Text::new("button")))
1589                            .style(
1590                                OutlinedButton::style_from()
1591                                    .shape(RoundedRectangleBorder::new(
1592                                        BorderSide::NONE,
1593                                        BorderRadius::ZERO.into(),
1594                                    ))
1595                                    // default border radius is 0
1596                                    .background_color(fill_color)
1597                                    .minimum_size(Size::new(64.0, 36.0))
1598                                    .build()
1599                                    .copy_with()
1600                                    .side(
1601                                        <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_with(
1602                                            move |states| {
1603                                                if states.contains(&WidgetState::Disabled) {
1604                                                    return Some(disabled_border_side);
1605                                                }
1606                                                if states.contains(&WidgetState::Pressed) {
1607                                                    return Some(pressed_border_side);
1608                                                }
1609                                                Some(enabled_border_side)
1610                                            },
1611                                        ),
1612                                    ),
1613                            )
1614                            .clip_behavior(waft_embedder::Clip::AntiAlias),
1615                    ),
1616                ))
1617            };
1618
1619            // Pump a button with a null onPressed callback to make it disabled.
1620            let disabled = frame(tester, None);
1621            tester.pump_widget(disabled);
1622
1623            // Expect that the button is disabled and painted with the disabled border color.
1624            assert!(!button_enabled(tester));
1625            assert_eq!(material_side(tester), disabled_border_side);
1626
1627            // Pump a new button with a no-op onPressed callback to make it enabled.
1628            let enabled = frame(tester, pressed());
1629            tester.pump_widget(enabled);
1630
1631            // Wait for the border color to change from disabled to enabled.
1632            tester.pump_and_settle();
1633            assert_eq!(material_side(tester), enabled_border_side);
1634
1635            let mut touch = TestPointer::touch(1);
1636            tester.down(&mut touch, button_center(tester));
1637            tester.pump(); // start gesture
1638
1639            // Wait for the border's color to change to pressed
1640            tester.pump_by(Duration::from_millis(200));
1641            assert_eq!(material_side(tester), pressed_border_side);
1642
1643            // Tap gesture completes, button returns to its initial configuration.
1644            tester.up(&touch);
1645            tester.pump_and_settle();
1646            assert_eq!(material_side(tester), enabled_border_side);
1647        });
1648    }
1649
1650    // 'OutlinedButton scales textScaleFactor'.
1651    #[test]
1652    fn the_text_scale_grows_the_text_and_then_the_button() {
1653        test_widgets(|tester| {
1654            let label_key = GlobalKey::new();
1655            let button_key = GlobalKey::new();
1656            let frame = |tester: &WidgetTester, scale: Option<f64>, minimum_size: bool| {
1657                let theme = ThemeData::builder()
1658                    .use_material3(false)
1659                    .build(&tester.cell.borrow());
1660                let mut button = OutlinedButton::new(
1661                    pressed(),
1662                    Some(Text::new("ABC").key(label_key.clone().into())),
1663                )
1664                .key(button_key.clone().into());
1665                if minimum_size {
1666                    // Specifying minimumSize to mimic the original minimumSize for
1667                    // RaisedButton so that the corresponding button size matches
1668                    // the original version of this test.
1669                    button =
1670                        button.style(ButtonStyle::new().minimum_size(all(Size::new(88.0, 36.0))));
1671                }
1672                let center = Center::new().child(button).into_widget();
1673                let scaled = match scale {
1674                    Some(scale) => {
1675                        MediaQuery::with_clamped_text_scaling(None, scale, scale, center)
1676                    }
1677                    None => {
1678                        MediaQuery::new(waft_widgets::MediaQueryData::new(), center).into_widget()
1679                    }
1680                };
1681                Theme::new(theme, ltr(scaled)).into_widget()
1682            };
1683            let size_of = |tester: &WidgetTester, key: &GlobalKey| {
1684                tester
1685                    .render_object(key)
1686                    .as_box()
1687                    .expect("a box")
1688                    .size(&tester.cell.borrow())
1689            };
1690
1691            let frame1 = frame(tester, None, true);
1692            tester.pump_widget(frame1);
1693            assert_eq!(size_of(tester, &button_key), Size::new(88.0, 48.0));
1694            assert_eq!(size_of(tester, &label_key), Size::new(42.0, 14.0));
1695
1696            // textScaleFactor expands text, but not button.
1697            let frame2 = frame(tester, Some(1.25), true);
1698            tester.pump_widget(frame2);
1699            assert_eq!(size_of(tester, &button_key), Size::new(88.0, 48.0));
1700            assert_eq!(size_of(tester, &label_key), Size::new(52.5, 18.0));
1701
1702            // Set text scale large enough to expand text and button.
1703            let frame3 = frame(tester, Some(3.0), false);
1704            tester.pump_widget(frame3);
1705            assert_eq!(size_of(tester, &button_key), Size::new(134.0, 48.0));
1706            assert_eq!(size_of(tester, &label_key), Size::new(126.0, 42.0));
1707        });
1708    }
1709
1710    // 'Default OutlinedButton padding for textScaleFactor, textDirection': each text scale,
1711    // direction and icon, in Material 2.
1712    #[test]
1713    fn the_default_padding_follows_the_text_scale_in_both_directions() {
1714        test_widgets(|tester| {
1715            const TEXT_SCALE_FACTOR_OPTIONS: [f64; 8] = [0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0];
1716            // Expected values for each textScaleFactor.
1717            let padding_vertical = |_scale: f64| 0.0;
1718            let padding_with_icon_gap = |scale: f64| match scale {
1719                0.5 | 1.0 => 8.0,
1720                1.25 => 7.0,
1721                1.5 => 6.0,
1722                _ => 4.0,
1723            };
1724            let padding_horizontal = |scale: f64| match scale {
1725                0.5 | 1.0 => 16.0,
1726                1.25 => 14.0,
1727                1.5 => 12.0,
1728                2.0 => 8.0,
1729                2.5 => 6.0,
1730                _ => 4.0,
1731            };
1732
1733            for text_scale_factor in TEXT_SCALE_FACTOR_OPTIONS {
1734                for text_direction in [TextDirection::Ltr, TextDirection::Rtl] {
1735                    for with_icon in [false, true] {
1736                        let button_key = GlobalKey::new();
1737                        let label_key = GlobalKey::new();
1738                        let icon_key = GlobalKey::new();
1739                        let theme = ThemeData::builder()
1740                            .use_material3(false)
1741                            .outlined_button_theme(
1742                                OutlinedButtonThemeData::new().style(
1743                                    OutlinedButton::style_from()
1744                                        .minimum_size(Size::new(64.0, 36.0))
1745                                        .build(),
1746                                ),
1747                            )
1748                            .build(&tester.cell.borrow());
1749                        let label = Text::new("button").key(label_key.clone().into());
1750                        let button = if with_icon {
1751                            OutlinedButton::icon(pressed(), label)
1752                                .key(button_key.clone().into())
1753                                .icon(
1754                                    Icon::new(Some(Icons::add()))
1755                                        .size(18.0)
1756                                        .key(icon_key.clone().into()),
1757                                )
1758                                .build()
1759                        } else {
1760                            OutlinedButton::new(pressed(), Some(label))
1761                                .key(button_key.clone().into())
1762                        };
1763                        tester.pump_widget(material_app(
1764                            theme,
1765                            MediaQuery::with_clamped_text_scaling(
1766                                None,
1767                                text_scale_factor,
1768                                text_scale_factor,
1769                                Directionality::new(
1770                                    text_direction,
1771                                    crate::material::Material::new()
1772                                        .child(Center::new().child(button)),
1773                                ),
1774                            ),
1775                        ));
1776
1777                        // Compute expected padding, and check.
1778                        let expected_padding_start = padding_horizontal(text_scale_factor);
1779                        let expected_padding = EdgeInsetsGeometry::from_steb(
1780                            expected_padding_start,
1781                            padding_vertical(text_scale_factor),
1782                            expected_padding_start,
1783                            padding_vertical(text_scale_factor),
1784                        )
1785                        .resolve(Some(text_direction));
1786                        assert_eq!(
1787                            padding_of_button(tester).resolve(Some(text_direction)),
1788                            expected_padding,
1789                            "scale {text_scale_factor}, {text_direction:?}, icon {with_icon}"
1790                        );
1791
1792                        // Measure padding in terms of the difference between the button and
1793                        // its label child and check that.
1794                        let label_bounds = tester.get_rect(&label_key);
1795                        let icon_bounds = with_icon.then(|| tester.get_rect(&icon_key));
1796                        let child_bounds = match icon_bounds {
1797                            Some(icon_bounds) => label_bounds.expand_to_include(icon_bounds),
1798                            None => label_bounds,
1799                        };
1800                        // We measure the `InkResponse` descendant of the button element,
1801                        // because the button has a larger `RenderBox` which accommodates the
1802                        // minimum tap target with a height of 48.
1803                        let ink_well = *find::by_type::<InkWell>()
1804                            .evaluate(tester)
1805                            .last()
1806                            .expect("an InkWell");
1807                        let button_bounds = tester.get_rect(ink_well);
1808
1809                        // Since there is a requirement of a minimum width of 64 and a minimum
1810                        // height of 36 on material buttons, the visual padding of smaller
1811                        // buttons may not match their settings. Therefore, we only test
1812                        // buttons that are large enough.
1813                        if button_bounds.width() > 64.0 {
1814                            assert_eq!(
1815                                child_bounds.left - button_bounds.left,
1816                                expected_padding.left
1817                            );
1818                            assert_eq!(
1819                                button_bounds.right - child_bounds.right,
1820                                expected_padding.right
1821                            );
1822                        }
1823                        if button_bounds.height() > 36.0 {
1824                            assert_eq!(child_bounds.top - button_bounds.top, expected_padding.top);
1825                            assert_eq!(
1826                                button_bounds.bottom - child_bounds.bottom,
1827                                expected_padding.bottom
1828                            );
1829                        }
1830
1831                        // Check the gap between the icon and the label
1832                        if let Some(icon_bounds) = icon_bounds {
1833                            let gap_width = if text_direction == TextDirection::Ltr {
1834                                label_bounds.left - icon_bounds.right
1835                            } else {
1836                                icon_bounds.left - label_bounds.right
1837                            };
1838                            assert_eq!(gap_width, padding_with_icon_gap(text_scale_factor));
1839                        }
1840                    }
1841                }
1842            }
1843        });
1844    }
1845
1846    #[test]
1847    fn a_style_padding_overrides_the_scaled_default() {
1848        test_widgets(|tester| {
1849            let theme = ThemeData::builder()
1850                .use_material3(false)
1851                .build(&tester.cell.borrow());
1852            tester.pump_widget(material_app(
1853                theme,
1854                MediaQuery::with_clamped_text_scaling(
1855                    None,
1856                    2.0,
1857                    2.0,
1858                    Center::new().child(
1859                        OutlinedButton::new(pressed(), Some(Text::new("OutlinedButton"))).style(
1860                            OutlinedButton::style_from()
1861                                .padding(EdgeInsetsGeometry::all(22.0))
1862                                .build(),
1863                        ),
1864                    ),
1865                ),
1866            ));
1867            assert!(padding_of_button(tester) == EdgeInsetsGeometry::all(22.0));
1868        });
1869    }
1870
1871    #[test]
1872    fn a_larger_theme_label_font_size_scales_the_padding_down() {
1873        test_widgets(|tester| {
1874            let theme = ThemeData::from(ColorScheme::light())
1875                .text_theme(TextTheme::new().label_large(TextStyle::new().font_size(28.0)))
1876                .build(&tester.cell.borrow());
1877            tester.pump_widget(app_centered(
1878                theme,
1879                OutlinedButton::new(pressed(), Some(Text::new("text"))),
1880            ));
1881            assert!(padding_of_button(tester) == EdgeInsetsGeometry::symmetric(0.0, 12.0));
1882        });
1883    }
1884
1885    #[test]
1886    fn material_3_padding_of_the_button_and_its_icon_variant() {
1887        test_widgets(|tester| {
1888            let theme = light(tester, true);
1889            tester.pump_widget(app_centered(
1890                theme.clone(),
1891                OutlinedButton::new(pressed(), Some(Text::new("OutlinedButton"))),
1892            ));
1893            assert!(padding_of_button(tester) == EdgeInsetsGeometry::symmetric(0.0, 24.0));
1894
1895            tester.pump_widget(app_centered(
1896                theme,
1897                OutlinedButton::icon(pressed(), Text::new("OutlinedButton"))
1898                    .icon(Icon::new(Some(Icons::favorite()))),
1899            ));
1900            assert!(
1901                padding_of_button(tester) == EdgeInsetsGeometry::from_steb(16.0, 0.0, 24.0, 0.0)
1902            );
1903        });
1904    }
1905
1906    #[test]
1907    fn no_splash_paints_no_splash_and_ink_ripple_one() {
1908        test_widgets(|tester| {
1909            for (splash_factory, circles) in [
1910                (NoSplash::splash_factory(), 0),
1911                (InkRipple::splash_factory(), 1),
1912            ] {
1913                let theme = default_theme(tester);
1914                tester.pump_widget(app_centered(
1915                    theme,
1916                    OutlinedButton::new(pressed(), Some(Text::new("test"))).style(
1917                        OutlinedButton::style_from()
1918                            .splash_factory(splash_factory)
1919                            .build(),
1920                    ),
1921                ));
1922                let mut touch = TestPointer::touch(1);
1923                tester.down(&mut touch, button_center(tester));
1924                // Valo's canvas drops a draw whose paint is transparent, and the splash fades
1925                // in from transparent on the frame after the press: let that frame pass first.
1926                tester.pump();
1927                tester.pump_by(Duration::from_millis(200));
1928                assert_eq!(ink_circle_count(tester), circles);
1929                tester.up(&touch);
1930                tester.pump_and_settle();
1931            }
1932        });
1933    }
1934
1935    // 'OutlinedButton uses InkSparkle only for Android non-web when useMaterial3 is true' and
1936    // 'OutlinedButton uses InkRipple when useMaterial3 is false', on every platform.
1937    #[test]
1938    fn the_splash_factory_is_ink_sparkle_on_android_in_material_3_and_ink_ripple_in_material_2() {
1939        test_widgets(|_| {
1940            for platform in [
1941                TargetPlatform::Android,
1942                TargetPlatform::Fuchsia,
1943                TargetPlatform::IOS,
1944                TargetPlatform::Linux,
1945                TargetPlatform::MacOS,
1946                TargetPlatform::Windows,
1947            ] {
1948                for material3 in [true, false] {
1949                    test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1950                        let theme = ThemeData::builder()
1951                            .use_material3(material3)
1952                            .build(&tester.cell.borrow());
1953                        let sparkles =
1954                            material3 && platform == TargetPlatform::Android && !K_IS_WEB;
1955                        let expected = if sparkles {
1956                            InkSparkle::splash_factory()
1957                        } else {
1958                            InkRipple::splash_factory()
1959                        };
1960                        tester.pump_widget(app_centered(
1961                            theme,
1962                            OutlinedButton::new(pressed(), Some(Text::new("button"))),
1963                        ));
1964                        let splash_factory = ink_well(tester, |ink_well| {
1965                            ink_well.ink_response.splash_factory.clone()
1966                        })
1967                        .expect("the button gives its InkWell a splash factory");
1968                        assert!(Rc::ptr_eq(&splash_factory, &expected), "{platform:?}");
1969                    });
1970                }
1971            }
1972        });
1973    }
1974
1975    #[test]
1976    fn an_icon_button_with_a_long_label_in_a_narrow_box_lays_out() {
1977        // Regression test for https://github.com/flutter/flutter/issues/77815
1978        test_widgets(|tester| {
1979            let theme = default_theme(tester);
1980            tester.pump_widget(material_app(
1981                theme,
1982                SizedBox::new()
1983                    .width(200.0)
1984                    .child(
1985                        OutlinedButton::icon(
1986                            pressed(),
1987                            // Much wider than 200
1988                            Text::new(
1989                                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a \
1990                                 euismod nibh. Morbi laoreet purus.",
1991                            ),
1992                        )
1993                        .icon(Icon::new(Some(Icons::add()))),
1994                    )
1995                    .into_widget(),
1996            ));
1997        });
1998    }
1999
2000    #[test]
2001    fn the_icon_and_label_sit_in_a_row_with_an_eight_pixel_gap() {
2002        test_widgets(|tester| {
2003            let button_key = GlobalKey::new();
2004            let icon_key = GlobalKey::new();
2005            let label_key = GlobalKey::new();
2006            let style = OutlinedButton::style_from()
2007                .padding(EdgeInsetsGeometry::ZERO)
2008                .visual_density(VisualDensity::STANDARD) // dx=0, dy=0
2009                .build();
2010            let theme = default_theme(tester);
2011            tester.pump_widget(material_app(
2012                theme,
2013                Align::new()
2014                    .alignment(AlignmentGeometry::TOP_LEFT)
2015                    .child(
2016                        SizedBox::new().width(200.0).child(
2017                            OutlinedButton::icon(
2018                                pressed(),
2019                                SizedBox::new()
2020                                    .key(label_key.clone().into())
2021                                    .width(50.0)
2022                                    .height(100.0),
2023                            )
2024                            .key(button_key.clone().into())
2025                            .style(style)
2026                            .icon(
2027                                SizedBox::new()
2028                                    .key(icon_key.clone().into())
2029                                    .width(50.0)
2030                                    .height(100.0),
2031                            ),
2032                        ),
2033                    )
2034                    .into_widget(),
2035            ));
2036
2037            // The button's label and icon are separated by a gap of 8:
2038            // 46 [icon 50] 8 [label 50] 46
2039            // The overall button width is 200. So:
2040            // icon.x = 46
2041            // label.x = 46 + 50 + 8 = 104
2042            let rect_of = |key: &GlobalKey| tester.get_rect(key);
2043            assert_eq!(
2044                rect_of(&button_key),
2045                Rect::from_ltrb(0.0, 0.0, 200.0, 100.0)
2046            );
2047            assert_eq!(rect_of(&icon_key), Rect::from_ltrb(46.0, 0.0, 96.0, 100.0));
2048            assert_eq!(
2049                rect_of(&label_key),
2050                Rect::from_ltrb(104.0, 0.0, 154.0, 100.0)
2051            );
2052        });
2053    }
2054
2055    #[test]
2056    fn style_from_cursors_show_while_hovered_and_the_default_is_basic() {
2057        test_widgets(|tester| {
2058            let frame = |on_pressed: Option<Listener>, custom: bool| {
2059                let mut button = OutlinedButton::new(on_pressed, Some(Text::new("button")));
2060                if custom {
2061                    button = button.style(
2062                        OutlinedButton::style_from()
2063                            .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
2064                            .disabled_mouse_cursor(SystemMouseCursors::GRAB.into())
2065                            .build(),
2066                    );
2067                }
2068                ltr(MouseRegion::new()
2069                    .cursor(SystemMouseCursors::FORBIDDEN.into())
2070                    .child(button))
2071            };
2072            let is = |tester: &WidgetTester, cursor: waft_services::SystemMouseCursor| {
2073                tester.active_cursor(1) == MouseCursorRef::from(cursor)
2074            };
2075
2076            tester.pump_widget(frame(pressed(), true));
2077            let mut gesture = TestPointer::mouse(1, 0);
2078            tester.add_pointer(&mut gesture, Offset::ZERO);
2079            tester.pump();
2080            assert!(is(tester, SystemMouseCursors::TEXT));
2081
2082            // Test cursor when disabled
2083            tester.pump_widget(frame(None, true));
2084            assert!(is(tester, SystemMouseCursors::GRAB));
2085
2086            // Test default cursor
2087            tester.pump_widget(frame(pressed(), false));
2088            assert!(is(
2089                tester,
2090                if K_IS_WEB {
2091                    SystemMouseCursors::CLICK
2092                } else {
2093                    SystemMouseCursors::BASIC
2094                }
2095            ));
2096
2097            // Test default cursor when disabled
2098            tester.pump_widget(frame(None, false));
2099            assert!(is(tester, SystemMouseCursors::BASIC));
2100        });
2101    }
2102
2103    #[test]
2104    fn style_from_sets_the_foreground_and_background_colors() {
2105        test_widgets(|tester| {
2106            let theme = default_theme(tester);
2107            let purple = Colors::PURPLE.primary();
2108            tester.pump_widget(material_app(
2109                theme,
2110                OutlinedButton::new(pressed(), Some(Text::new("button")))
2111                    .style(
2112                        OutlinedButton::style_from()
2113                            .foreground_color(Colors::WHITE)
2114                            .background_color(purple)
2115                            .build(),
2116                    )
2117                    .into_widget(),
2118            ));
2119            material(tester, |material| {
2120                assert_eq!(material.color, Some(purple));
2121                assert_eq!(
2122                    material
2123                        .text_style
2124                        .as_ref()
2125                        .and_then(|style| style.color.as_deref().copied()),
2126                    Some(Colors::WHITE)
2127                );
2128            });
2129        });
2130    }
2131
2132    // 'OutlinedButton.icon statesController'; the plain button's case is button_style_button.rs's.
2133    #[test]
2134    fn an_icon_buttons_states_controller_follows_hover_press_and_disable() {
2135        test_widgets(|tester| {
2136            let count = Rc::new(Cell::new(0));
2137            let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
2138            controller.add_listener(&mut tester.cell.borrow_mut(), {
2139                let count = Rc::clone(&count);
2140                Listener::new(move |_app| count.set(count.get() + 1))
2141            });
2142            let frame = |tester: &WidgetTester, enabled: bool| {
2143                let theme = default_theme(tester);
2144                app_centered(
2145                    theme,
2146                    OutlinedButton::icon(
2147                        if enabled { pressed() } else { None },
2148                        Text::new("button"),
2149                    )
2150                    .states_controller(controller.clone())
2151                    .icon(Icon::new(Some(Icons::add()))),
2152                )
2153            };
2154            let value =
2155                |tester: &WidgetTester| tester.cell.borrow().get(&controller).value().clone();
2156
2157            let first = frame(tester, true);
2158            tester.pump_widget(first);
2159            assert_eq!(value(tester), states(&[]));
2160            assert_eq!(count.get(), 0);
2161
2162            let label = *find::text("button")
2163                .evaluate(tester)
2164                .first()
2165                .expect("the label");
2166            let center = tester.get_rect(label).center();
2167            let mut gesture = mouse();
2168            tester.add_pointer(&mut gesture, Offset::ZERO);
2169            tester.move_to(&mut gesture, center, false);
2170            tester.pump_and_settle();
2171            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
2172            assert_eq!(count.get(), 1);
2173
2174            tester.move_to(&mut gesture, Offset::ZERO, false);
2175            tester.pump_and_settle();
2176            assert_eq!(value(tester), states(&[]));
2177            assert_eq!(count.get(), 2);
2178
2179            tester.move_to(&mut gesture, center, false);
2180            tester.pump_and_settle();
2181            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
2182            assert_eq!(count.get(), 3);
2183
2184            tester.send(&gesture, PointerChange::Down);
2185            tester.pump_and_settle();
2186            assert_eq!(
2187                value(tester),
2188                states(&[WidgetState::Hovered, WidgetState::Pressed])
2189            );
2190            assert_eq!(count.get(), 4);
2191
2192            tester.up(&gesture);
2193            tester.pump_and_settle();
2194            assert_eq!(value(tester), states(&[WidgetState::Hovered]));
2195            assert_eq!(count.get(), 5);
2196
2197            tester.move_to(&mut gesture, Offset::ZERO, false);
2198            tester.pump_and_settle();
2199            assert_eq!(value(tester), states(&[]));
2200            assert_eq!(count.get(), 6);
2201
2202            tester.down(&mut gesture, center);
2203            tester.pump_and_settle();
2204            assert_eq!(
2205                value(tester),
2206                states(&[WidgetState::Hovered, WidgetState::Pressed])
2207            );
2208            assert_eq!(count.get(), 8); // adds hovered and pressed - two changes
2209
2210            // If the button is rebuilt disabled, then the pressed state is
2211            // removed.
2212            let disabled = frame(tester, false);
2213            tester.pump_widget(disabled);
2214            tester.pump_and_settle();
2215            assert_eq!(
2216                value(tester),
2217                states(&[WidgetState::Hovered, WidgetState::Disabled])
2218            );
2219            assert_eq!(count.get(), 10); // removes pressed and adds disabled - two changes
2220            tester.move_to(&mut gesture, Offset::ZERO, true);
2221            tester.pump_and_settle();
2222            assert_eq!(value(tester), states(&[WidgetState::Disabled]));
2223            assert_eq!(count.get(), 11);
2224        });
2225    }
2226
2227    #[test]
2228    fn style_from_with_only_an_enabled_cursor_builds() {
2229        // This is a regression test for https://github.com/flutter/flutter/issues/118071.
2230        test_widgets(|tester| {
2231            tester.pump_widget(ltr(OutlinedButton::new(
2232                pressed(),
2233                Some(Text::new("button")),
2234            )
2235            .style(
2236                OutlinedButton::style_from()
2237                    .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
2238                    .build(),
2239            )));
2240        });
2241    }
2242
2243    #[test]
2244    fn style_from_a_lone_background_color_applies_when_disabled_too() {
2245        // Regression test for an internal Google issue: b/323399158
2246        test_widgets(|tester| {
2247            let background_color = Color::new(0xFF000022);
2248            let frame = |on_pressed: Option<Listener>| {
2249                ltr(
2250                    OutlinedButton::new(on_pressed, Some(Text::new("button"))).style(
2251                        OutlinedButton::style_from()
2252                            .background_color(background_color)
2253                            .build(),
2254                    ),
2255                )
2256            };
2257
2258            tester.pump_widget(frame(pressed())); // enabled
2259            material(tester, |material| {
2260                assert_eq!(material.color, Some(background_color))
2261            });
2262
2263            tester.pump_widget(frame(None)); // onPressed: null - disabled
2264            material(tester, |material| {
2265                assert_eq!(material.color, Some(background_color))
2266            });
2267        });
2268    }
2269
2270    /// `MaterialApp(home: Directionality(textDirection, Center(button)))`.
2271    fn icon_alignment_frame(
2272        tester: &WidgetTester,
2273        text_direction: TextDirection,
2274        button: OutlinedButtonIcon,
2275    ) -> WidgetRef {
2276        let theme = default_theme(tester);
2277        material_app(
2278            theme,
2279            Directionality::new(
2280                text_direction,
2281                Center::new().child(button.icon(Icon::new(Some(Icons::add())))),
2282            )
2283            .into_widget(),
2284        )
2285    }
2286
2287    #[test]
2288    fn the_icon_sits_at_the_start_by_default_in_both_directions() {
2289        test_widgets(|tester| {
2290            // Test default iconAlignment when textDirection is ltr.
2291            let frame = icon_alignment_frame(
2292                tester,
2293                TextDirection::Ltr,
2294                OutlinedButton::icon(pressed(), Text::new("button")),
2295            );
2296            tester.pump_widget(frame);
2297            // The icon is aligned to the left of the button.
2298            // 16.0 - padding between icon and button edge.
2299            assert_eq!(button_rect(tester).left, icon_rect(tester).left - 16.0);
2300
2301            // Test default iconAlignment when textDirection is rtl.
2302            let frame = icon_alignment_frame(
2303                tester,
2304                TextDirection::Rtl,
2305                OutlinedButton::icon(pressed(), Text::new("button")),
2306            );
2307            tester.pump_widget(frame);
2308            // The icon is aligned to the right of the button.
2309            // 16.0 - padding between icon and button edge.
2310            assert_f32_equals(button_rect(tester).right, icon_rect(tester).right + 16.0);
2311        });
2312    }
2313
2314    #[test]
2315    fn icon_alignment_places_the_icon_at_either_end_in_both_directions() {
2316        test_widgets(|tester| {
2317            let mut case = |text_direction, icon_alignment| {
2318                let frame = icon_alignment_frame(
2319                    tester,
2320                    text_direction,
2321                    OutlinedButton::icon(pressed(), Text::new("button"))
2322                        .icon_alignment(icon_alignment),
2323                );
2324                tester.pump_widget(frame);
2325                (button_rect(tester), icon_rect(tester))
2326            };
2327
2328            // The icon is aligned to the left of the button.
2329            let (button, icon) = case(TextDirection::Ltr, IconAlignment::Start);
2330            assert_eq!(button.left, icon.left - 16.0);
2331
2332            // The icon is aligned to the right of the button.
2333            let (button, icon) = case(TextDirection::Ltr, IconAlignment::End);
2334            assert_f32_equals(button.right, icon.right + 24.0);
2335
2336            // The icon is aligned to the right of the button.
2337            let (button, icon) = case(TextDirection::Rtl, IconAlignment::Start);
2338            assert_f32_equals(button.right, icon.right + 16.0);
2339
2340            // The icon is aligned to the left of the button.
2341            let (button, icon) = case(TextDirection::Rtl, IconAlignment::End);
2342            assert_eq!(button.left, icon.left - 24.0);
2343        });
2344    }
2345
2346    #[test]
2347    fn the_icon_follows_the_style_icon_alignment() {
2348        test_widgets(|tester| {
2349            let mut case = |style: ButtonStyle| {
2350                let theme = default_theme(tester);
2351                tester.pump_widget(app_centered(
2352                    theme,
2353                    OutlinedButton::icon(pressed(), Text::new("button"))
2354                        .style(style)
2355                        .icon(Icon::new(Some(Icons::add()))),
2356                ));
2357                (button_rect(tester), icon_rect(tester))
2358            };
2359
2360            let (button, icon) = case(ButtonStyle::new());
2361            assert_eq!(button.left, icon.left - 16.0);
2362
2363            let (button, icon) = case(ButtonStyle::new().icon_alignment(IconAlignment::End));
2364            assert_f32_equals(button.right, icon.right + 24.0);
2365        });
2366    }
2367
2368    #[test]
2369    fn style_from_sets_the_icon_size_colors_and_alignment() {
2370        // Regression test for https://github.com/flutter/flutter/issues/154798.
2371        test_widgets(|tester| {
2372            let icon_color = Color::new(0xFFF000FF);
2373            let icon_size = 32.0;
2374            let disabled_icon_color = Color::new(0xFFFFF000);
2375            let frame = |tester: &WidgetTester, enabled: bool| {
2376                let theme = default_theme(tester);
2377                material_app(
2378                    theme,
2379                    Material::new()
2380                        .child(
2381                            Center::new().child(
2382                                OutlinedButton::icon(
2383                                    if enabled { pressed() } else { None },
2384                                    Text::new("Button"),
2385                                )
2386                                .style(
2387                                    OutlinedButton::style_from()
2388                                        .icon_color(icon_color)
2389                                        .icon_size(icon_size)
2390                                        .icon_alignment(IconAlignment::End)
2391                                        .disabled_icon_color(disabled_icon_color)
2392                                        .build(),
2393                                )
2394                                .icon(Icon::new(Some(Icons::add()))),
2395                            ),
2396                        )
2397                        .into_widget(),
2398                )
2399            };
2400
2401            // Test enabled button.
2402            let enabled = frame(tester, true);
2403            tester.pump_widget(enabled);
2404            assert_eq!(icon_rect(tester).size(), Size::new(icon_size, icon_size));
2405            assert_eq!(
2406                tester.icon_style().color.as_deref().copied(),
2407                Some(icon_color)
2408            );
2409
2410            // Test disabled button.
2411            let disabled = frame(tester, false);
2412            tester.pump_widget(disabled);
2413            tester.pump_and_settle();
2414            assert_eq!(
2415                tester.icon_style().color.as_deref().copied(),
2416                Some(disabled_icon_color)
2417            );
2418
2419            assert_f32_equals(button_rect(tester).right, icon_rect(tester).right + 24.0);
2420        });
2421    }
2422
2423    #[test]
2424    fn the_icon_takes_the_style_from_foreground_color_over_the_default_icon_color() {
2425        // Regression test for https://github.com/flutter/flutter/issues/162839.
2426        test_widgets(|tester| {
2427            let foreground_color = Color::new(0xFFFF1234);
2428            let theme = default_theme(tester);
2429            tester.pump_widget(material_app(
2430                theme,
2431                Material::new()
2432                    .child(
2433                        Center::new().child(
2434                            OutlinedButton::icon(pressed(), Text::new("Button"))
2435                                .style(
2436                                    OutlinedButton::style_from()
2437                                        .foreground_color(foreground_color)
2438                                        .build(),
2439                                )
2440                                .icon(Icon::new(Some(Icons::add()))),
2441                        ),
2442                    )
2443                    .into_widget(),
2444            ));
2445            assert_eq!(
2446                tester.icon_style().color.as_deref().copied(),
2447                Some(foreground_color)
2448            );
2449        });
2450    }
2451
2452    #[test]
2453    fn an_icon_button_keeps_its_focus_when_its_icon_is_removed() {
2454        test_widgets(|tester| {
2455            let frame = |tester: &WidgetTester, icon: bool| {
2456                let theme = default_theme(tester);
2457                let mut button = OutlinedButton::icon(pressed(), Text::new("button"));
2458                if icon {
2459                    button = button.icon(Icon::new(Some(Icons::abc())));
2460                }
2461                app_centered(theme, button)
2462            };
2463            let button_focus_node = |tester: &WidgetTester| {
2464                let label = *find::text("button")
2465                    .evaluate(tester)
2466                    .first()
2467                    .expect("the label");
2468                let mut app = tester.cell.borrow_mut();
2469                waft_widgets::Focus::of(&mut app, label, false, true)
2470            };
2471
2472            // Build once with an icon.
2473            let with_icon = frame(tester, true);
2474            tester.pump_widget(with_icon);
2475            let node = button_focus_node(tester);
2476            node.request_focus(&mut tester.cell.borrow_mut(), None);
2477            tester.pump_and_settle();
2478            assert!(button_focus_node(tester).has_focus(&tester.cell.borrow_mut()));
2479
2480            // Rebuild without icon.
2481            let without_icon = frame(tester, false);
2482            tester.pump_widget(without_icon);
2483
2484            // The button should still be focused.
2485            assert!(button_focus_node(tester).has_focus(&tester.cell.borrow_mut()));
2486        });
2487    }
2488}