Skip to main content

waft_material/
elevated_button_theme.rs

1//! Flutter counterpart: material_ui's `elevated_button_theme.dart`.
2
3use waft_foundation::{App, DiagnosticsProperty};
4use waft_widgets::{
5    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef, downcast_widget,
6};
7
8use crate::button_style::ButtonStyle;
9use crate::theme::Theme;
10use crate::theme_data::StyleVariant;
11
12/// A [`ButtonStyle`] that overrides the default appearance of
13/// `ElevatedButton`s when it's used with [`ElevatedButtonTheme`] or with the
14/// overall `Theme`'s `ThemeData::elevated_button_theme`.
15///
16/// The [`style`](Self::style)'s properties override `ElevatedButton`'s default style,
17/// i.e. the [`ButtonStyle`] returned by `ElevatedButton::default_style_of`. Only
18/// the style's non-null property values or resolved non-null
19/// `WidgetStateProperty` values are used.
20///
21/// See also:
22///
23///  * [`ElevatedButtonTheme`], the theme which is configured with this class.
24///  * `ElevatedButton::default_style_of`, which returns the default [`ButtonStyle`]
25///    for text buttons.
26///  * `ElevatedButton::style_from`, which converts simple values into a
27///    [`ButtonStyle`] that's consistent with `ElevatedButton`'s defaults.
28///  * `WidgetStateProperty::resolve`, "resolve" a material state property
29///    to a simple value based on a set of `WidgetState`s.
30///  * `ThemeData::elevated_button_theme`, which can be used to override the default
31///    [`ButtonStyle`] for `ElevatedButton`s below the overall `Theme`.
32#[derive(Clone, Debug, Default, PartialEq)]
33pub struct ElevatedButtonThemeData {
34    /// Overrides for `ElevatedButton`'s default style.
35    ///
36    /// Non-null properties or non-null resolved `WidgetStateProperty`
37    /// values override the [`ButtonStyle`] returned by
38    /// `ElevatedButton::default_style_of`.
39    ///
40    /// If [`style`](Self::style) is null, then this theme doesn't override anything.
41    pub style: Option<ButtonStyle>,
42
43    /// The style variant of Material Design used by `ElevatedButton`.
44    ///
45    /// Set this to [`StyleVariant::Material3Expressive`] to opt elevated buttons
46    /// into the Material 3 Expressive style.
47    ///
48    /// If null, the variant is inherited from the closest enclosing
49    /// [`ElevatedButtonTheme`] that specifies one, and then from
50    /// `ThemeData::elevated_button_theme`. If none of them specify a variant,
51    /// `ElevatedButton` uses [`StyleVariant::Material3`]. To keep a subtree on
52    /// Material 3 when an ancestor opts into Material 3 Expressive, set this to
53    /// [`StyleVariant::Material3`].
54    ///
55    /// An enclosing [`ElevatedButtonTheme`] takes precedence over
56    /// `ThemeData::elevated_button_theme`, even when a closer `Theme` specifies a
57    /// different variant. This matches [`ElevatedButtonTheme::of`], which only uses
58    /// `ThemeData::elevated_button_theme` when there is no enclosing
59    /// [`ElevatedButtonTheme`]. To change the variant of a subtree, wrap it in an
60    /// [`ElevatedButtonTheme`].
61    ///
62    /// See also:
63    ///
64    ///  * [`ElevatedButtonTheme::variant_of`], which returns the variant that
65    ///    applies at a given location.
66    pub variant: Option<StyleVariant>,
67}
68
69impl ElevatedButtonThemeData {
70    /// Creates an [`ElevatedButtonThemeData`].
71    ///
72    /// The [`style`](Self::style) may be null.
73    pub fn new() -> ElevatedButtonThemeData {
74        ElevatedButtonThemeData::default()
75    }
76
77    /// Dart `ElevatedButtonThemeData(style:)`.
78    pub fn style(mut self, style: ButtonStyle) -> ElevatedButtonThemeData {
79        self.style = Some(style);
80        self
81    }
82
83    /// Dart `ElevatedButtonThemeData(variant:)`.
84    pub fn variant(mut self, variant: StyleVariant) -> ElevatedButtonThemeData {
85        self.variant = Some(variant);
86        self
87    }
88
89    /// Linearly interpolate between two elevated button themes.
90    pub fn lerp(
91        a: Option<&ElevatedButtonThemeData>,
92        b: Option<&ElevatedButtonThemeData>,
93        t: f64,
94    ) -> Option<ElevatedButtonThemeData> {
95        match (a, b) {
96            (None, None) => return None,
97            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
98            _ => {}
99        }
100        Some(ElevatedButtonThemeData {
101            style: ButtonStyle::lerp(
102                a.and_then(|a| a.style.as_ref()),
103                b.and_then(|b| b.style.as_ref()),
104                t,
105            ),
106            variant: if t < 0.5 {
107                a.and_then(|a| a.variant)
108            } else {
109                b.and_then(|b| b.variant)
110            },
111        })
112    }
113}
114
115/// Overrides the default [`ButtonStyle`] of its `ElevatedButton` descendants.
116///
117/// See also:
118///
119///  * [`ElevatedButtonThemeData`], which is used to configure this theme.
120///  * `ElevatedButton::default_style_of`, which returns the default [`ButtonStyle`]
121///    for elevated buttons.
122///  * `ElevatedButton::style_from`, which converts simple values into a
123///    [`ButtonStyle`] that's consistent with `ElevatedButton`'s defaults.
124///  * `ThemeData::elevated_button_theme`, which can be used to override the default
125///    [`ButtonStyle`] for `ElevatedButton`s below the overall `Theme`.
126#[derive(Debug)]
127pub struct ElevatedButtonTheme {
128    pub key: Option<KeyRef>,
129    /// The configuration of this theme.
130    pub data: ElevatedButtonThemeData,
131    pub child: WidgetRef,
132}
133
134impl ElevatedButtonTheme {
135    /// Create a [`ElevatedButtonTheme`].
136    #[cfg_attr(debug_assertions, track_caller)]
137    pub fn new<K>(data: ElevatedButtonThemeData, child: impl IntoWidget<K>) -> ElevatedButtonTheme {
138        ElevatedButtonTheme {
139            key: None,
140            data,
141            child: child.into_widget(),
142        }
143    }
144
145    /// Dart `ElevatedButtonTheme(key:)`.
146    pub fn key(mut self, key: KeyRef) -> ElevatedButtonTheme {
147        self.key = Some(key);
148        self
149    }
150
151    /// Retrieves the [`ElevatedButtonThemeData`] from the closest ancestor
152    /// [`ElevatedButtonTheme`].
153    ///
154    /// If there is no enclosing [`ElevatedButtonTheme`] widget, then
155    /// `ThemeData::elevated_button_theme` is used.
156    ///
157    /// The returned [`ElevatedButtonThemeData::variant`] is the value specified by
158    /// that theme, which can be null even when an ancestor specifies a variant.
159    /// Use [`variant_of`](Self::variant_of) to get the variant that applies at the given
160    /// `context`.
161    ///
162    /// Typical usage is as follows:
163    ///
164    /// ```text
165    /// let theme = ElevatedButtonTheme::of(app, context);
166    /// ```
167    pub fn of(app: &mut App, context: BuildContext) -> ElevatedButtonThemeData {
168        match context.depend_on_inherited_widget_of_exact_type::<ElevatedButtonTheme>(app) {
169            Some(button_theme) => button_theme.data.clone(),
170            None => Theme::of(app, context).elevated_button_theme.clone(),
171        }
172    }
173
174    /// Returns the [`StyleVariant`] that `ElevatedButton`s use at the given
175    /// `context`.
176    ///
177    /// The closest enclosing [`ElevatedButtonTheme`] whose
178    /// [`ElevatedButtonThemeData::variant`] is non-null determines the variant, so
179    /// an [`ElevatedButtonTheme`] that doesn't specify a variant inherits it from
180    /// its ancestors. If none of the enclosing [`ElevatedButtonTheme`]s specify a
181    /// variant, the variant of `ThemeData::elevated_button_theme` is used. If that
182    /// is also null, [`StyleVariant::Material3`] is returned.
183    ///
184    /// Typical usage is as follows:
185    ///
186    /// ```text
187    /// let variant = ElevatedButtonTheme::variant_of(app, context);
188    /// ```
189    pub fn variant_of(app: &mut App, context: BuildContext) -> StyleVariant {
190        let mut element =
191            context.get_element_for_inherited_widget_of_exact_type::<ElevatedButtonTheme>(app);
192        while let Some(current) = element {
193            // Depend on every theme that is visited, so that a change to any of them
194            // rebuilds the dependent.
195            let widget = context.depend_on_inherited_element(app, current, None);
196            let variant = downcast_widget::<ElevatedButtonTheme>(&*widget)
197                .expect("found by type")
198                .data
199                .variant;
200            if let Some(variant) = variant {
201                return variant;
202            }
203            // Calling get_element_for_inherited_widget_of_exact_type on the element itself
204            // would return the same element, so continue the search from its parent.
205            let mut parent = None;
206            current.visit_ancestor_elements(app, &mut |ancestor| {
207                parent = Some(ancestor);
208                false
209            });
210            element = parent.and_then(|parent| {
211                parent.get_element_for_inherited_widget_of_exact_type::<ElevatedButtonTheme>(app)
212            });
213        }
214        Theme::of(app, context)
215            .elevated_button_theme
216            .variant
217            .unwrap_or(StyleVariant::Material3)
218    }
219}
220
221impl InheritedTheme for ElevatedButtonTheme {
222    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
223        ElevatedButtonTheme::new(self.data.clone(), child).into_widget()
224    }
225}
226
227impl InheritedWidget for ElevatedButtonTheme {
228    fn key(&self) -> Option<&KeyRef> {
229        self.key.as_ref()
230    }
231
232    fn child(&self) -> &WidgetRef {
233        &self.child
234    }
235
236    fn update_should_notify(&self, old_widget: &ElevatedButtonTheme) -> bool {
237        self.data != old_widget.data
238    }
239
240    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
241        Some(self)
242    }
243}
244
245impl waft_foundation::Diagnosticable for ElevatedButtonThemeData {
246    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
247        properties.add(
248            DiagnosticsProperty::<crate::button_style::ButtonStyle>::new(
249                "style",
250                self.style.clone(),
251            )
252            .default_value(None),
253        );
254    }
255}
256
257impl std::fmt::Display for ElevatedButtonThemeData {
258    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
259        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    #![allow(deprecated)]
266    use waft_widgets::Text;
267    use waft_widgets::testing::assert_f32_equals;
268
269    use std::cell::Cell;
270    use std::rc::Rc;
271    use std::time::Duration;
272
273    use waft_embedder::{Color, FontWeight, Radius, Size};
274    use waft_foundation::{Listener, ValueNotifier};
275    use waft_painting::{
276        Alignment, AlignmentGeometry, BorderRadius, BorderSide, BorderStyle, EdgeInsetsGeometry,
277        OutlinedBorderRef, RoundedRectangleBorder, ShapeBorder, StadiumBorder, TextStyle,
278    };
279    use waft_services::{MouseCursorRef, SystemMouseCursors};
280    use waft_widgets::{
281        Align, AnyElement, Builder, Center, Icon, IconTheme, KeyRef, Row, SizedBox,
282        ValueListenableBuilder, WidgetState, WidgetStateProperty, WidgetStatePropertyAll,
283        WidgetStates,
284    };
285
286    use waft_widgets::testing::{WidgetTester, find, test_widgets};
287
288    use super::*;
289    use crate::button_style::{ButtonShapeVariant, ButtonSizeVariant};
290    use crate::button_style_button::IconAlignment;
291    use crate::color_scheme::ColorScheme;
292    use crate::colors::Colors;
293    use crate::elevated_button::ElevatedButton;
294    use crate::icons::Icons;
295    use crate::ink_well::InkWell;
296    use crate::material::Material;
297    use crate::test_support::material_app;
298    use crate::theme_data::{MaterialTapTargetSize, ThemeData};
299
300    fn pressed() -> Option<Listener> {
301        Some(Listener::new(|_app| {}))
302    }
303
304    fn text(text: &str) -> WidgetRef {
305        Text::new(text).into_widget()
306    }
307
308    fn states(states: &[WidgetState]) -> WidgetStates {
309        states.iter().copied().collect()
310    }
311
312    fn is_inside<W: 'static>(tester: &WidgetTester, element: AnyElement) -> bool {
313        let ancestors = tester.ancestors(element);
314        let app = tester.cell.borrow();
315        ancestors
316            .into_iter()
317            .any(|ancestor| downcast_widget::<W>(&**ancestor.widget(&app)).is_some())
318    }
319
320    /// The first `W` below an `ElevatedButton`.
321    fn in_button<W: 'static>(tester: &WidgetTester) -> AnyElement {
322        find::by_type::<W>()
323            .evaluate(tester)
324            .into_iter()
325            .find(|element| is_inside::<ElevatedButton>(tester, *element))
326            .expect("a descendant of the button")
327    }
328
329    fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
330        tester.widget::<Material, R>(in_button::<Material>(tester), read)
331    }
332
333    fn text_color(material: &Material) -> Option<Color> {
334        material
335            .text_style
336            .as_ref()
337            .and_then(|text_style| text_style.color.as_ref())
338            .map(|color| color.color())
339    }
340
341    fn rounded(radius: f64) -> RoundedRectangleBorder {
342        RoundedRectangleBorder::new(
343            BorderSide::NONE,
344            BorderRadius::all(Radius::circular(radius)).into(),
345        )
346    }
347
348    // elevated_button_theme_test.dart 'ElevatedButtonThemeData supports Material style
349    // variants'.
350    #[test]
351    fn the_theme_data_carries_a_variant_that_lerps_at_the_midpoint() {
352        let material3 = ElevatedButtonThemeData::new().variant(StyleVariant::Material3);
353        let expressive = ElevatedButtonThemeData::new().variant(StyleVariant::Material3Expressive);
354
355        assert_eq!(material3.variant, Some(StyleVariant::Material3));
356        assert_eq!(expressive.variant, Some(StyleVariant::Material3Expressive));
357        assert_eq!(
358            ElevatedButtonThemeData::lerp(Some(&material3), Some(&expressive), 0.49),
359            Some(material3.clone())
360        );
361        assert_eq!(
362            ElevatedButtonThemeData::lerp(Some(&material3), Some(&expressive), 0.5),
363            Some(expressive.clone())
364        );
365        assert_ne!(material3, expressive);
366    }
367
368    // elevated_button_theme_test.dart 'ElevatedButtonThemeData hashCode, diagnostics, and lerp
369    // include variant', without the hash code (deferred) and with `Debug` for the diagnostics.
370    #[test]
371    fn the_debug_description_and_lerp_include_the_variant() {
372        let expressive = ElevatedButtonThemeData::new().variant(StyleVariant::Material3Expressive);
373        assert!(format!("{expressive:?}").contains("Material3Expressive"));
374        assert_eq!(
375            ElevatedButtonThemeData::lerp(None, Some(&expressive), 0.4).and_then(|t| t.variant),
376            None
377        );
378        assert_eq!(
379            ElevatedButtonThemeData::lerp(None, Some(&expressive), 0.6).and_then(|t| t.variant),
380            Some(StyleVariant::Material3Expressive)
381        );
382    }
383
384    // elevated_button_theme_test.dart 'ElevatedButtonThemeData lerp special cases'.
385    #[test]
386    fn lerp_of_nothing_is_nothing_and_of_a_theme_with_itself_is_that_theme() {
387        assert_eq!(ElevatedButtonThemeData::lerp(None, None, 0.0), None);
388        let data = ElevatedButtonThemeData::new();
389        assert_eq!(
390            ElevatedButtonThemeData::lerp(Some(&data), Some(&data), 0.5),
391            Some(data)
392        );
393    }
394
395    // elevated_button_theme_test.dart 'Material3: Passing no ElevatedButtonTheme returns
396    // defaults' and 'Material2: Passing no ElevatedButtonTheme returns defaults'.
397    #[test]
398    fn without_a_button_theme_the_button_shows_its_defaults() {
399        for use_material3 in [true, false] {
400            test_widgets(|tester| {
401                let color_scheme = ColorScheme::light();
402                let theme = ThemeData::from(color_scheme.clone())
403                    .use_material3(use_material3)
404                    .build(&tester.cell.borrow());
405                tester.pump_widget(material_app(
406                    theme,
407                    Center::new()
408                        .child(ElevatedButton::new(pressed(), Some(text("button"))))
409                        .into_widget(),
410                ));
411
412                material(tester, |material| {
413                    assert_eq!(material.animation_duration, Duration::from_millis(200));
414                    assert!(material.border_radius.is_none());
415                    let shape = material.shape.as_deref().expect("a shape");
416                    if use_material3 {
417                        assert_eq!(material.color, Some(color_scheme.surface()));
418                        assert_eq!(material.elevation, 1.0);
419                        assert_eq!(material.shadow_color, Some(color_scheme.shadow()));
420                        assert!(shape.eq_shape(&StadiumBorder::default()));
421                        assert_eq!(text_color(material), Some(color_scheme.primary()));
422                    } else {
423                        assert_eq!(material.color, Some(color_scheme.primary()));
424                        assert_eq!(material.elevation, 2.0);
425                        assert_eq!(material.shadow_color, Some(Color::new(0xff000000)));
426                        assert!(shape.eq_shape(&rounded(4.0)));
427                        assert_eq!(text_color(material), Some(color_scheme.on_primary()));
428                    }
429                    let text_style = material.text_style.as_ref().expect("a text style");
430                    assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
431                    assert_eq!(text_style.font_size, Some(14.0));
432                    assert_eq!(text_style.font_weight, Some(FontWeight::W500));
433                });
434                let align = in_button::<Align>(tester);
435                tester.widget::<Align, _>(align, |align| {
436                    assert!(align.alignment == AlignmentGeometry::from(Alignment::CENTER));
437                });
438            });
439        }
440    }
441
442    const FOREGROUND_COLOR: Color = Color::new(0xff000001);
443    const BACKGROUND_COLOR: Color = Color::new(0xff000002);
444    const DISABLED_COLOR: Color = Color::new(0xff000003);
445    const SHADOW_COLOR: Color = Color::new(0xff000004);
446    const ELEVATION: f64 = 1.0;
447    const MINIMUM_SIZE: Size = Size::new(200.0, 200.0);
448    const ANIMATION_DURATION: Duration = Duration::from_millis(25);
449    const ENABLE_FEEDBACK: bool = false;
450    const ALIGNMENT: AlignmentGeometry = AlignmentGeometry::CENTER_LEFT;
451
452    fn side() -> BorderSide {
453        BorderSide::new(
454            Colors::GREEN.primary(),
455            2.0,
456            BorderStyle::Solid,
457            BorderSide::STROKE_ALIGN_INSIDE,
458        )
459    }
460
461    fn shape() -> RoundedRectangleBorder {
462        RoundedRectangleBorder::new(side(), BorderRadius::all(Radius::circular(2.0)).into())
463    }
464
465    /// The style of the group '[Theme, TextTheme, ElevatedButton style overrides]'.
466    fn override_style() -> ButtonStyle {
467        let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
468        let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
469        ElevatedButton::style_from()
470            .foreground_color(FOREGROUND_COLOR)
471            .disabled_foreground_color(DISABLED_COLOR)
472            .background_color(BACKGROUND_COLOR)
473            .disabled_background_color(DISABLED_COLOR)
474            .shadow_color(SHADOW_COLOR)
475            .elevation(ELEVATION)
476            .text_style(TextStyle::new().font_size(12.0))
477            .padding(EdgeInsetsGeometry::all(3.0))
478            .minimum_size(MINIMUM_SIZE)
479            .side(side())
480            .shape(OutlinedBorderRef::new(shape()))
481            .enabled_mouse_cursor(text)
482            .disabled_mouse_cursor(grab)
483            .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
484            .animation_duration(ANIMATION_DURATION)
485            .enable_feedback(ENABLE_FEEDBACK)
486            .alignment(ALIGNMENT)
487            .build()
488    }
489
490    fn override_frame(
491        tester: &WidgetTester,
492        button_style: Option<ButtonStyle>,
493        theme_style: Option<ButtonStyle>,
494        overall_style: Option<ButtonStyle>,
495    ) -> WidgetRef {
496        let child = Builder::new(move |_app, _context| {
497            let mut button = ElevatedButton::new(pressed(), Some(text("button")));
498            if let Some(button_style) = &button_style {
499                button = button.style(button_style.clone());
500            }
501            button.into_widget()
502        })
503        .into_widget();
504        let mut overall = ElevatedButtonThemeData::new();
505        overall.style = overall_style;
506        let theme = ThemeData::from(ColorScheme::light())
507            .use_material3(false)
508            .build(&tester.cell.borrow())
509            .copy_with()
510            .elevated_button_theme(overall)
511            .build();
512        material_app(
513            theme,
514            Center::new()
515                // If the ElevatedButtonTheme widget is present, it's used
516                // instead of the Theme's ThemeData.ElevatedButtonTheme.
517                .child(match theme_style {
518                    None => child,
519                    Some(theme_style) => ElevatedButtonTheme::new(
520                        ElevatedButtonThemeData::new().style(theme_style),
521                        child,
522                    )
523                    .into_widget(),
524                })
525                .into_widget(),
526        )
527    }
528
529    fn check_button(tester: &WidgetTester) {
530        material(tester, |material| {
531            assert_eq!(text_color(material), Some(FOREGROUND_COLOR));
532            assert_eq!(
533                material
534                    .text_style
535                    .as_ref()
536                    .and_then(|text_style| text_style.font_size),
537                Some(12.0)
538            );
539            assert_eq!(material.color, Some(BACKGROUND_COLOR));
540            assert_eq!(material.shadow_color, Some(SHADOW_COLOR));
541            assert_eq!(material.elevation, ELEVATION);
542            assert!(material.border_radius.is_none());
543            assert!(material.shape.as_deref() == Some(&shape() as &dyn ShapeBorder));
544            assert_eq!(material.animation_duration, ANIMATION_DURATION);
545        });
546        tester.widget::<InkWell, _>(in_button::<InkWell>(tester), |ink_well| {
547            let response = &ink_well.ink_response;
548            let cursor = response.mouse_cursor.clone().expect("a mouse cursor");
549            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
550            let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
551            assert!(
552                *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&cursor, &states(&[]))
553                    == *text
554            );
555            assert!(
556                *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
557                    &cursor,
558                    &states(&[WidgetState::Disabled])
559                ) == *grab
560            );
561            let overlay = response.overlay_color.as_ref().expect("an overlay color");
562            assert_eq!(
563                overlay.resolve(&states(&[WidgetState::Hovered])),
564                Some(FOREGROUND_COLOR.with_opacity(0.08))
565            );
566            assert_eq!(
567                overlay.resolve(&states(&[WidgetState::Focused])),
568                Some(FOREGROUND_COLOR.with_opacity(0.1))
569            );
570            assert_eq!(
571                overlay.resolve(&states(&[WidgetState::Pressed])),
572                Some(FOREGROUND_COLOR.with_opacity(0.1))
573            );
574            assert_eq!(response.enable_feedback, ENABLE_FEEDBACK);
575        });
576        let button = find::by_type::<ElevatedButton>().evaluate(tester)[0];
577        let size = tester.get_size(button);
578        assert_eq!(size, Size::new(200.0, 200.0));
579        let align = in_button::<Align>(tester);
580        tester.widget::<Align, _>(align, |align| assert!(align.alignment == ALIGNMENT));
581    }
582
583    // elevated_button_theme_test.dart group '[Theme, TextTheme, ElevatedButton style
584    // overrides]': each of its six cases.
585    #[test]
586    fn the_button_style_the_button_theme_and_the_overall_theme_each_override_the_defaults() {
587        test_widgets(|tester| {
588            let empty = || Some(ButtonStyle::new());
589            // Each case is [button style, button theme style, overall theme style].
590            let cases: [[Option<ButtonStyle>; 3]; 6] = [
591                // Button style overrides defaults.
592                [Some(override_style()), None, None],
593                // Button theme style overrides defaults.
594                [None, Some(override_style()), None],
595                // Overall Theme button theme style overrides defaults.
596                [None, None, Some(override_style())],
597                // Same as the previous tests with empty ButtonStyle's instead of null.
598                // Button style overrides defaults, empty theme and overall styles.
599                [Some(override_style()), empty(), empty()],
600                // Button theme style overrides defaults, empty button and overall styles.
601                [empty(), Some(override_style()), empty()],
602                // Overall Theme button theme style overrides defaults, null theme and empty
603                // overall style.
604                [empty(), None, Some(override_style())],
605            ];
606            for [button_style, theme_style, overall_style] in cases {
607                let frame = override_frame(tester, button_style, theme_style, overall_style);
608                tester.pump_widget(frame);
609                tester.pump_and_settle(); // allow the animations to finish
610                check_button(tester);
611            }
612        });
613    }
614
615    // elevated_button_theme_test.dart 'Material3 - ElevatedButton respects Theme shadowColor'
616    // and 'Material2 - ElevatedButton respects Theme shadowColor'.
617    #[test]
618    fn the_shadow_color_comes_from_the_button_then_its_theme_then_the_overall_theme() {
619        test_widgets(|tester| {
620            let shadow_color = Color::new(0xff000001);
621            let overridden_color = Color::new(0xff000002);
622            for use_material3 in [true, false] {
623                let build_frame =
624                    |tester: &WidgetTester,
625                     overall_shadow_color: Option<Color>,
626                     theme_shadow_color: Option<Color>,
627                     button_shadow_color: Option<Color>| {
628                        let theme = if use_material3 {
629                            let mut color_scheme = ColorScheme::light();
630                            if let Some(overall) = overall_shadow_color {
631                                color_scheme = color_scheme.copy_with().with_shadow(overall);
632                            }
633                            ThemeData::from(color_scheme).build(&tester.cell.borrow())
634                        } else {
635                            let theme = ThemeData::from(ColorScheme::light())
636                                .use_material3(false)
637                                .build(&tester.cell.borrow());
638                            match overall_shadow_color {
639                                Some(overall) => theme.copy_with().shadow_color(overall).build(),
640                                None => theme,
641                            }
642                        };
643                        let style_from = |color: Option<Color>| {
644                            let mut style = ElevatedButton::style_from();
645                            if let Some(color) = color {
646                                style = style.shadow_color(color);
647                            }
648                            style.build()
649                        };
650                        let button_style = style_from(button_shadow_color);
651                        material_app(
652                            theme,
653                            Center::new()
654                                .child(ElevatedButtonTheme::new(
655                                    ElevatedButtonThemeData::new()
656                                        .style(style_from(theme_shadow_color)),
657                                    Builder::new(move |_app, _context| {
658                                        ElevatedButton::new(pressed(), Some(text("button")))
659                                            .style(button_style.clone())
660                                            .into_widget()
661                                    }),
662                                ))
663                                .into_widget(),
664                        )
665                    };
666                let shadow =
667                    |tester: &WidgetTester| material(tester, |material| material.shadow_color);
668
669                let frame = build_frame(tester, None, None, None);
670                tester.pump_widget(frame);
671                assert_eq!(shadow(tester), Some(Colors::BLACK)); //default
672
673                for (overall, theme, button) in [
674                    (Some(shadow_color), None, None),
675                    (None, Some(shadow_color), None),
676                    (None, None, Some(shadow_color)),
677                    (Some(overridden_color), Some(shadow_color), None),
678                    (None, Some(overridden_color), Some(shadow_color)),
679                ] {
680                    let frame = build_frame(tester, overall, theme, button);
681                    tester.pump_widget(frame);
682                    tester.pump_and_settle(); // theme animation
683                    assert_eq!(shadow(tester), Some(shadow_color));
684                }
685            }
686        });
687    }
688
689    fn icon_button_frame(tester: &WidgetTester, theme: ThemeData) -> WidgetRef {
690        let _ = tester;
691        material_app(
692            theme,
693            Center::new()
694                .child(
695                    ElevatedButton::icon(pressed(), text("button"))
696                        .icon(Icon::new(Some(Icons::add()))),
697                )
698                .into_widget(),
699        )
700    }
701
702    // elevated_button_theme_test.dart 'ElevatedButton.icon respects ElevatedButtonTheme
703    // ButtonStyle.iconAlignment'.
704    #[test]
705    fn an_icon_button_takes_its_icon_alignment_from_the_theme() {
706        test_widgets(|tester| {
707            let build = |tester: &WidgetTester, icon_alignment: Option<IconAlignment>| {
708                let mut style = ButtonStyle::new();
709                style.icon_alignment = icon_alignment;
710                let theme = ThemeData::builder()
711                    .elevated_button_theme(ElevatedButtonThemeData::new().style(style))
712                    .build(&tester.cell.borrow());
713                icon_button_frame(tester, theme)
714            };
715            let rects = |tester: &WidgetTester| {
716                let material = tester.get_rect(in_button::<Material>(tester));
717                let icon = tester.get_rect(find::by_type::<Icon>().evaluate(tester)[0]);
718                (material, icon)
719            };
720
721            let frame = build(tester, None);
722            tester.pump_widget(frame);
723            let (button, icon) = rects(tester);
724            assert_eq!(button.left, icon.left - 16.0);
725
726            let frame = build(tester, Some(IconAlignment::End));
727            tester.pump_widget(frame);
728            tester.pump_and_settle();
729            let (button, icon) = rects(tester);
730            assert_f32_equals(button.right, icon.right + 24.0);
731        });
732    }
733
734    // elevated_button_theme_test.dart 'ElevatedButton icon uses provided ElevatedButtonTheme
735    // foregroundColor over default icon color'.
736    #[test]
737    fn an_icon_takes_the_theme_foreground_color() {
738        test_widgets(|tester| {
739            let foreground_color = Color::new(0xFFFFA500);
740            let icon_color = Rc::new(Cell::new(None));
741            let probe = Builder::new({
742                let icon_color = Rc::clone(&icon_color);
743                move |app, context| {
744                    icon_color.set(IconTheme::of(app, context).color.map(|color| color.color()));
745                    SizedBox::new().width(18.0).height(18.0).into_widget()
746                }
747            });
748            let theme = ThemeData::builder()
749                .elevated_button_theme(
750                    ElevatedButtonThemeData::new().style(
751                        ElevatedButton::style_from()
752                            .foreground_color(foreground_color)
753                            .build(),
754                    ),
755                )
756                .build(&tester.cell.borrow());
757            tester.pump_widget(material_app(
758                theme,
759                Material::new()
760                    .child(
761                        Center::new()
762                            .child(ElevatedButton::icon(pressed(), text("Button")).icon(probe)),
763                    )
764                    .into_widget(),
765            ));
766            assert_eq!(icon_color.get(), Some(foreground_color));
767        });
768    }
769
770    // A square elevated button uses a RoundedRectangleBorder in Material 3
771    // Expressive. Material 3 ignores shapeVariant and uses a StadiumBorder.
772    fn square_button() -> WidgetRef {
773        ElevatedButton::new(pressed(), Some(text("Button")))
774            .key(button_key())
775            .style(ButtonStyle::new().shape_variant(ButtonShapeVariant::Square))
776            .into_widget()
777    }
778
779    fn button_key() -> KeyRef {
780        waft_foundation::ValueKey::new("button".to_owned()).into()
781    }
782
783    fn custom_style() -> ButtonStyle {
784        ButtonStyle::new().foreground_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
785            0xffff0000,
786        )))))
787    }
788
789    fn is_stadium(tester: &WidgetTester) -> bool {
790        material(tester, |material| {
791            material
792                .shape
793                .as_ref()
794                .is_some_and(|shape| shape.as_any().downcast_ref::<StadiumBorder>().is_some())
795        })
796    }
797
798    fn is_rounded_rectangle(tester: &WidgetTester) -> bool {
799        material(tester, |material| {
800            material.shape.as_ref().is_some_and(|shape| {
801                shape
802                    .as_any()
803                    .downcast_ref::<RoundedRectangleBorder>()
804                    .is_some()
805            })
806        })
807    }
808
809    /// Builds the square button and reports the variant that applies to it.
810    fn button_with_variant(variant: &Rc<Cell<Option<StyleVariant>>>) -> WidgetRef {
811        let variant = Rc::clone(variant);
812        Builder::new(move |app, context| {
813            variant.set(Some(ElevatedButtonTheme::variant_of(app, context)));
814            square_button()
815        })
816        .into_widget()
817    }
818
819    fn variant_data(variant: StyleVariant) -> ElevatedButtonThemeData {
820        ElevatedButtonThemeData::new().variant(variant)
821    }
822
823    fn variant_theme(tester: &WidgetTester, variant: StyleVariant) -> ThemeData {
824        ThemeData::builder()
825            .elevated_button_theme(variant_data(variant))
826            .build(&tester.cell.borrow())
827    }
828
829    fn default_theme(tester: &WidgetTester) -> ThemeData {
830        ThemeData::new(&tester.cell.borrow())
831    }
832
833    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'returns
834    // material3 when no theme specifies a variant'.
835    #[test]
836    fn variant_of_is_material_3_when_no_theme_names_one() {
837        test_widgets(|tester| {
838            let variant = Rc::new(Cell::new(None));
839            let theme = default_theme(tester);
840            tester.pump_widget(material_app(
841                theme,
842                Center::new()
843                    .child(ElevatedButtonTheme::new(
844                        ElevatedButtonThemeData::new().style(custom_style()),
845                        button_with_variant(&variant),
846                    ))
847                    .into_widget(),
848            ));
849            assert_eq!(variant.get(), Some(StyleVariant::Material3));
850            assert!(is_stadium(tester));
851        });
852    }
853
854    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'returns the
855    // variant of ThemeData.elevatedButtonTheme'.
856    #[test]
857    fn variant_of_falls_back_to_the_theme_data_variant() {
858        test_widgets(|tester| {
859            let variant = Rc::new(Cell::new(None));
860            let theme = variant_theme(tester, StyleVariant::Material3Expressive);
861            tester.pump_widget(material_app(
862                theme,
863                Center::new()
864                    .child(button_with_variant(&variant))
865                    .into_widget(),
866            ));
867            assert_eq!(variant.get(), Some(StyleVariant::Material3Expressive));
868            assert!(is_rounded_rectangle(tester));
869        });
870    }
871
872    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'a nested
873    // ElevatedButtonTheme without a variant inherits it from an ElevatedButtonTheme', 'an
874    // ElevatedButtonTheme without a variant inherits it from ThemeData.elevatedButtonTheme' and
875    // 'an explicit variant overrides the variant of the ancestors'.
876    #[test]
877    fn variant_of_takes_the_nearest_theme_that_names_one() {
878        test_widgets(|tester| {
879            // Nested in an expressive ElevatedButtonTheme.
880            let variant = Rc::new(Cell::new(None));
881            let theme = default_theme(tester);
882            tester.pump_widget(material_app(
883                theme,
884                Center::new()
885                    .child(ElevatedButtonTheme::new(
886                        variant_data(StyleVariant::Material3Expressive),
887                        ElevatedButtonTheme::new(
888                            ElevatedButtonThemeData::new().style(custom_style()),
889                            button_with_variant(&variant),
890                        ),
891                    ))
892                    .into_widget(),
893            ));
894            tester.pump_and_settle();
895            assert_eq!(variant.get(), Some(StyleVariant::Material3Expressive));
896            assert!(is_rounded_rectangle(tester));
897
898            // Under an expressive ThemeData.
899            let variant = Rc::new(Cell::new(None));
900            let theme = variant_theme(tester, StyleVariant::Material3Expressive);
901            tester.pump_widget(material_app(
902                theme,
903                Center::new()
904                    .child(ElevatedButtonTheme::new(
905                        ElevatedButtonThemeData::new().style(custom_style()),
906                        button_with_variant(&variant),
907                    ))
908                    .into_widget(),
909            ));
910            tester.pump_and_settle();
911            assert_eq!(variant.get(), Some(StyleVariant::Material3Expressive));
912            assert!(is_rounded_rectangle(tester));
913
914            // An explicit Material 3 below an expressive ancestor.
915            let variant = Rc::new(Cell::new(None));
916            let theme = default_theme(tester);
917            tester.pump_widget(material_app(
918                theme,
919                Center::new()
920                    .child(ElevatedButtonTheme::new(
921                        variant_data(StyleVariant::Material3Expressive),
922                        ElevatedButtonTheme::new(
923                            ElevatedButtonThemeData::new()
924                                .style(custom_style())
925                                .variant(StyleVariant::Material3),
926                            button_with_variant(&variant),
927                        ),
928                    ))
929                    .into_widget(),
930            ));
931            tester.pump_and_settle();
932            assert_eq!(variant.get(), Some(StyleVariant::Material3));
933            assert!(is_stadium(tester));
934        });
935    }
936
937    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'an enclosing
938    // ElevatedButtonTheme takes precedence over a closer Theme'.
939    #[test]
940    fn an_enclosing_button_theme_wins_over_a_closer_theme() {
941        test_widgets(|tester| {
942            let variant = Rc::new(Cell::new(None));
943            let theme = default_theme(tester);
944            let closer = variant_theme(tester, StyleVariant::Material3);
945            tester.pump_widget(material_app(
946                theme,
947                Center::new()
948                    .child(ElevatedButtonTheme::new(
949                        variant_data(StyleVariant::Material3Expressive),
950                        Theme::new(closer, button_with_variant(&variant)),
951                    ))
952                    .into_widget(),
953            ));
954            assert_eq!(variant.get(), Some(StyleVariant::Material3Expressive));
955            assert!(is_rounded_rectangle(tester));
956        });
957    }
958
959    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'ElevatedButton
960    // is rebuilt when an ElevatedButtonTheme above the closest one changes'.
961    #[test]
962    fn the_button_rebuilds_when_a_farther_theme_changes() {
963        test_widgets(|tester| {
964            let variant = tester
965                .cell
966                .borrow_mut()
967                .create(ValueNotifier::new(Some(StyleVariant::Material3Expressive)));
968            // The subtree is made once, so it is only rebuilt through its
969            // dependency on the outer ElevatedButtonTheme.
970            let child = ElevatedButtonTheme::new(
971                ElevatedButtonThemeData::new().style(custom_style()),
972                square_button(),
973            )
974            .into_widget();
975            let theme = default_theme(tester);
976            tester.pump_widget(material_app(
977                theme,
978                Center::new()
979                    .child(
980                        ValueListenableBuilder::new(
981                            Rc::new(variant.clone()),
982                            |_app, _context, value: &Option<StyleVariant>, child| {
983                                let mut data = ElevatedButtonThemeData::new();
984                                data.variant = *value;
985                                ElevatedButtonTheme::new(data, child.expect("a child").clone())
986                                    .into_widget()
987                            },
988                        )
989                        .child(child),
990                    )
991                    .into_widget(),
992            ));
993            assert!(is_rounded_rectangle(tester));
994
995            variant.set_value(&mut tester.cell.borrow_mut(), Some(StyleVariant::Material3));
996            tester.pump_and_settle();
997            assert!(is_stadium(tester));
998        });
999    }
1000
1001    // elevated_button_theme_test.dart group 'ElevatedButtonTheme.variantOf', 'ElevatedButton.icon
1002    // uses the inherited variant for the icon-label gap'.
1003    #[test]
1004    fn an_icon_button_gap_follows_the_inherited_variant() {
1005        test_widgets(|tester| {
1006            let theme = default_theme(tester);
1007            tester.pump_widget(material_app(
1008                theme,
1009                Center::new()
1010                    .child(ElevatedButtonTheme::new(
1011                        variant_data(StyleVariant::Material3Expressive),
1012                        ElevatedButtonTheme::new(
1013                            ElevatedButtonThemeData::new().style(custom_style()),
1014                            ElevatedButton::icon(pressed(), text("Button"))
1015                                .icon(Icon::new(Some(Icons::add())))
1016                                .key(button_key())
1017                                .style(ButtonStyle::new().size_variant(ButtonSizeVariant::Large)),
1018                        ),
1019                    ))
1020                    .into_widget(),
1021            ));
1022
1023            // Large Material 3 Expressive buttons have a 12 pixel gap between the
1024            // icon and the label. Material 3 uses 8 pixels.
1025            let row = in_button::<Row>(tester);
1026            assert_eq!(tester.widget::<Row, _>(row, |row| row.spacing), 12.0);
1027        });
1028    }
1029    // Flutter's "Default ElevatedButtonThemeData debugFillProperties".
1030    #[test]
1031    fn a_elevated_button_theme_data_describes_nothing_by_default() {
1032        assert_eq!(
1033            waft_widgets::testing::describe_properties(|properties| {
1034                waft_foundation::Diagnosticable::debug_fill_properties(
1035                    &ElevatedButtonThemeData::new(),
1036                    properties,
1037                )
1038            }),
1039            Vec::<String>::new()
1040        );
1041    }
1042}