Skip to main content

waft_material/
text_button.rs

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