Skip to main content

waft_material/
button_theme.rs

1//! Flutter counterpart: material_ui's `button_theme.dart`.
2
3use std::fmt::{self, Debug};
4use std::time::Duration;
5
6use waft_embedder::{Brightness, Color, Radius};
7use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty, FlagProperty};
8use waft_painting::{
9    BorderRadiusGeometry, BorderSide, ColorProperty, EdgeInsetsGeometry, RoundedRectangleBorder,
10    ShapeBorderRef,
11};
12use waft_rendering::BoxConstraints;
13use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
14
15use crate::color_scheme::ColorScheme;
16use crate::colors::Colors;
17use crate::constants::K_THEME_CHANGE_DURATION;
18use crate::material_button::MaterialButton;
19use crate::theme::Theme;
20use crate::theme_data::{MaterialTapTargetSize, ThemeData};
21
22/// Used with [`ButtonTheme`] and [`ButtonThemeData`] to define a button's base colors, and the
23/// defaults for the button's minimum size, internal padding, and shape.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub enum ButtonTextTheme {
26    /// Button text is black or white depending on `ThemeData::brightness`.
27    Normal,
28
29    /// Button text is `ColorScheme::secondary`.
30    Accent,
31
32    /// Button text is based on `ThemeData::primary_color`.
33    Primary,
34}
35
36/// Used with [`ButtonTheme`] and [`ButtonThemeData`] to define how the button bar should size
37/// itself with either constraints or internal padding.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39pub enum ButtonBarLayoutBehavior {
40    /// Button bars will be constrained to a minimum height of 52.
41    ///
42    /// This setting is require to create button bars which conform to the Material Design
43    /// specification.
44    Constrained,
45
46    /// Button bars will calculate their padding from the button theme padding.
47    Padded,
48}
49
50/// Used with [`ButtonThemeData`] to configure the color and geometry of buttons.
51///
52/// This class is planned to be deprecated in a future release. Please use one or more of these
53/// buttons and associated themes instead:
54///
55///  * `ElevatedButton`, `ElevatedButtonTheme`, `ElevatedButtonThemeData`,
56///  * `FilledButton`, `FilledButtonTheme`, `FilledButtonThemeData`,
57///  * `OutlinedButton`, `OutlinedButtonTheme`, `OutlinedButtonThemeData`
58///  * `TextButton`, `TextButtonTheme`, `TextButtonThemeData`,
59///
60/// A button theme can be specified as part of the overall Material theme using
61/// `ThemeData::button_theme`. The Material theme's button theme data can be overridden with
62/// [`ButtonTheme`].
63///
64/// The actual appearance of buttons depends on the button theme, the button's enabled state,
65/// its elevation (if any), and the overall [`Theme`].
66///
67/// See also:
68///
69///  * `RawMaterialButton`, which can be used to configure a button that doesn't depend on any
70///    inherited themes.
71#[derive(Debug)]
72pub struct ButtonTheme {
73    pub key: Option<KeyRef>,
74    /// Specifies the color and geometry of buttons.
75    pub data: ButtonThemeData,
76    pub child: WidgetRef,
77}
78
79impl ButtonTheme {
80    /// Creates a button theme.
81    #[cfg_attr(debug_assertions, track_caller)]
82    pub fn new<K>(child: impl IntoWidget<K>) -> ButtonTheme {
83        ButtonTheme::from_button_theme_data(ButtonThemeData::new(), child)
84    }
85
86    /// Creates a button theme from `data`.
87    #[cfg_attr(debug_assertions, track_caller)]
88    pub fn from_button_theme_data<K>(
89        data: ButtonThemeData,
90        child: impl IntoWidget<K>,
91    ) -> ButtonTheme {
92        ButtonTheme {
93            key: None,
94            data,
95            child: child.into_widget(),
96        }
97    }
98
99    /// Dart `ButtonTheme(key:)`.
100    pub fn key(mut self, key: KeyRef) -> ButtonTheme {
101        self.key = Some(key);
102        self
103    }
104
105    /// Dart `ButtonTheme(textTheme:)`.
106    pub fn text_theme(mut self, text_theme: ButtonTextTheme) -> ButtonTheme {
107        self.data = self.data.with_text_theme(text_theme);
108        self
109    }
110
111    /// Dart `ButtonTheme(layoutBehavior:)`.
112    pub fn layout_behavior(mut self, layout_behavior: ButtonBarLayoutBehavior) -> ButtonTheme {
113        self.data = self.data.with_layout_behavior(layout_behavior);
114        self
115    }
116
117    /// Dart `ButtonTheme(minWidth:)`.
118    pub fn min_width(mut self, min_width: f64) -> ButtonTheme {
119        self.data = self.data.with_min_width(min_width);
120        self
121    }
122
123    /// Dart `ButtonTheme(height:)`.
124    pub fn height(mut self, height: f64) -> ButtonTheme {
125        self.data = self.data.with_height(height);
126        self
127    }
128
129    /// Dart `ButtonTheme(padding:)`.
130    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ButtonTheme {
131        self.data = self.data.with_padding(padding);
132        self
133    }
134
135    /// Dart `ButtonTheme(shape:)`.
136    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ButtonTheme {
137        self.data = self.data.with_shape(shape);
138        self
139    }
140
141    /// Dart `ButtonTheme(alignedDropdown:)`.
142    pub fn aligned_dropdown(mut self, aligned_dropdown: bool) -> ButtonTheme {
143        self.data = self.data.with_aligned_dropdown(aligned_dropdown);
144        self
145    }
146
147    /// Dart `ButtonTheme(buttonColor:)`.
148    pub fn button_color(mut self, button_color: Color) -> ButtonTheme {
149        self.data = self.data.with_button_color(button_color);
150        self
151    }
152
153    /// Dart `ButtonTheme(disabledColor:)`.
154    pub fn disabled_color(mut self, disabled_color: Color) -> ButtonTheme {
155        self.data = self.data.with_disabled_color(disabled_color);
156        self
157    }
158
159    /// Dart `ButtonTheme(focusColor:)`.
160    pub fn focus_color(mut self, focus_color: Color) -> ButtonTheme {
161        self.data = self.data.with_focus_color(focus_color);
162        self
163    }
164
165    /// Dart `ButtonTheme(hoverColor:)`.
166    pub fn hover_color(mut self, hover_color: Color) -> ButtonTheme {
167        self.data = self.data.with_hover_color(hover_color);
168        self
169    }
170
171    /// Dart `ButtonTheme(highlightColor:)`.
172    pub fn highlight_color(mut self, highlight_color: Color) -> ButtonTheme {
173        self.data = self.data.with_highlight_color(highlight_color);
174        self
175    }
176
177    /// Dart `ButtonTheme(splashColor:)`.
178    pub fn splash_color(mut self, splash_color: Color) -> ButtonTheme {
179        self.data = self.data.with_splash_color(splash_color);
180        self
181    }
182
183    /// Dart `ButtonTheme(colorScheme:)`.
184    pub fn color_scheme(mut self, color_scheme: ColorScheme) -> ButtonTheme {
185        self.data = self.data.with_color_scheme(color_scheme);
186        self
187    }
188
189    /// Dart `ButtonTheme(materialTapTargetSize:)`.
190    pub fn material_tap_target_size(
191        mut self,
192        material_tap_target_size: MaterialTapTargetSize,
193    ) -> ButtonTheme {
194        self.data = self
195            .data
196            .with_material_tap_target_size(material_tap_target_size);
197        self
198    }
199
200    /// Retrieves the [`ButtonThemeData`] from the closest ancestor [`ButtonTheme`] widget.
201    ///
202    /// Typical usage is as follows:
203    ///
204    /// ```text
205    /// let theme = ButtonTheme::of(app, context);
206    /// ```
207    pub fn of(app: &mut App, context: BuildContext) -> ButtonThemeData {
208        let inherited_button_theme =
209            context.depend_on_inherited_widget_of_exact_type::<ButtonTheme>(app);
210        let mut button_theme = inherited_button_theme.map(|theme| theme.data.clone());
211        if button_theme
212            .as_ref()
213            .is_none_or(|button_theme| button_theme.color_scheme.is_none())
214        {
215            // if buttonTheme or buttonTheme.colorScheme is null
216            let theme = Theme::of(app, context);
217            let mut theme_button_theme = button_theme.unwrap_or_else(|| theme.button_theme.clone());
218            if theme_button_theme.color_scheme.is_none() {
219                theme_button_theme = theme_button_theme.copy_with().with_color_scheme(
220                    theme
221                        .button_theme
222                        .color_scheme
223                        .clone()
224                        .unwrap_or_else(|| theme.color_scheme.clone()),
225                );
226                debug_assert!(theme_button_theme.color_scheme.is_some());
227            }
228            button_theme = Some(theme_button_theme);
229        }
230        button_theme.expect("filled above")
231    }
232}
233
234impl InheritedTheme for ButtonTheme {
235    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
236        ButtonTheme::from_button_theme_data(self.data.clone(), child).into_widget()
237    }
238}
239
240impl InheritedWidget for ButtonTheme {
241    fn key(&self) -> Option<&KeyRef> {
242        self.key.as_ref()
243    }
244
245    fn child(&self) -> &WidgetRef {
246        &self.child
247    }
248
249    fn update_should_notify(&self, old_widget: &ButtonTheme) -> bool {
250        self.data != old_widget.data
251    }
252
253    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
254        Some(self)
255    }
256}
257
258/// Used with [`ButtonTheme`] to configure the color and geometry of buttons.
259///
260/// This class is planned to be deprecated in a future release. Please use one or more of these
261/// buttons and associated themes instead:
262///
263///  * `TextButton`, `TextButtonTheme`, `TextButtonThemeData`,
264///  * `ElevatedButton`, `ElevatedButtonTheme`, `ElevatedButtonThemeData`,
265///  * `OutlinedButton`, `OutlinedButtonTheme`, `OutlinedButtonThemeData`
266///
267/// A button theme can be specified as part of the overall Material theme using
268/// `ThemeData::button_theme`. The Material theme's button theme data can be overridden with
269/// [`ButtonTheme`].
270///
271/// [`padding`](Self::padding) and [`shape`](Self::shape) are getters that fall back to a
272/// default for the [`text_theme`](Self::text_theme), so the fields hold only what was given;
273/// [`copy_with`](Self::copy_with), as Dart's `copyWith`, keeps the worked-out values.
274#[derive(Clone)]
275pub struct ButtonThemeData {
276    /// The minimum width for buttons.
277    ///
278    /// The actual horizontal space allocated for a button's child is at least this value less
279    /// the theme's horizontal [`padding`](Self::padding).
280    ///
281    /// Defaults to 88.0 logical pixels.
282    pub min_width: f64,
283
284    /// The minimum height for buttons.
285    ///
286    /// Defaults to 36.0 logical pixels.
287    pub height: f64,
288
289    /// Defines a button's base colors, and the defaults for the button's minimum size, internal
290    /// padding, and shape.
291    ///
292    /// Despite the name, this property is not a `TextTheme`, its value is not a collection of
293    /// `TextStyle`s.
294    pub text_theme: ButtonTextTheme,
295
296    /// Defines whether a `ButtonBar` should size itself with a minimum size constraint or with
297    /// padding.
298    ///
299    /// Defaults to [`ButtonBarLayoutBehavior::Padded`].
300    pub layout_behavior: ButtonBarLayoutBehavior,
301
302    padding: Option<EdgeInsetsGeometry>,
303
304    shape: Option<ShapeBorderRef>,
305
306    /// If true, then a `DropdownButton` menu's width will match the button's width.
307    ///
308    /// If false (the default), then the dropdown's menu will be wider than its button. In
309    /// either case the dropdown button will line up the leading edge of the menu's value with
310    /// the leading edge of the values displayed by the menu items.
311    ///
312    /// This property only affects `DropdownButton` and its menu.
313    pub aligned_dropdown: bool,
314
315    /// The background fill color.
316    ///
317    /// This property is null by default.
318    ///
319    /// If the button is in the focused, hovering, or highlighted state, then the `focus_color`,
320    /// `hover_color`, or `highlight_color` will take precedence over the `button_color`.
321    button_color: Option<Color>,
322
323    /// The background fill color when disabled.
324    ///
325    /// This property is null by default.
326    disabled_color: Option<Color>,
327
328    /// The fill color of the button when it has the input focus.
329    ///
330    /// This property is null by default.
331    ///
332    /// If the button is in the hovering or highlighted state, then the `hover_color` or
333    /// `highlight_color` will take precedence over the `focus_color`.
334    focus_color: Option<Color>,
335
336    /// The fill color of the button when a pointer is hovering over it.
337    ///
338    /// This property is null by default.
339    ///
340    /// If the button is in the highlighted state, then the `highlight_color` will take
341    /// precedence over the `hover_color`.
342    hover_color: Option<Color>,
343
344    /// The color of the overlay that appears when a button is pressed.
345    ///
346    /// This property is null by default.
347    highlight_color: Option<Color>,
348
349    /// The color of the ink "splash" overlay that appears when a button is tapped.
350    ///
351    /// This property is null by default.
352    splash_color: Option<Color>,
353
354    /// A set of thirteen colors that can be used to derive the button theme's colors.
355    ///
356    /// This property was added much later than the theme's set of highly specific colors, like
357    /// `ThemeData::highlight_color` and `ThemeData::splash_color` etc.
358    ///
359    /// The colors for new button classes can be defined exclusively in terms of
360    /// [`color_scheme`](Self::color_scheme). When it's possible, the existing buttons will
361    /// (continue to) gradually migrate to it.
362    pub color_scheme: Option<ColorScheme>,
363
364    // The minimum size of a button's tap target.
365    //
366    // This property is null by default.
367    material_tap_target_size: Option<MaterialTapTargetSize>,
368}
369
370impl ButtonThemeData {
371    /// Create a button theme object that can be used with [`ButtonTheme`] or `ThemeData`.
372    ///
373    /// The [`min_width`](Self::min_width) and [`height`](Self::height) parameters must greater
374    /// than or equal to zero.
375    pub fn new() -> ButtonThemeData {
376        ButtonThemeData {
377            min_width: 88.0,
378            height: 36.0,
379            text_theme: ButtonTextTheme::Normal,
380            layout_behavior: ButtonBarLayoutBehavior::Padded,
381            padding: None,
382            shape: None,
383            aligned_dropdown: false,
384            button_color: None,
385            disabled_color: None,
386            focus_color: None,
387            hover_color: None,
388            highlight_color: None,
389            splash_color: None,
390            color_scheme: None,
391            material_tap_target_size: None,
392        }
393    }
394
395    /// Dart `ButtonThemeData(textTheme:)`.
396    pub fn with_text_theme(mut self, text_theme: ButtonTextTheme) -> ButtonThemeData {
397        self.text_theme = text_theme;
398        self
399    }
400
401    /// Dart `ButtonThemeData(minWidth:)`.
402    pub fn with_min_width(mut self, min_width: f64) -> ButtonThemeData {
403        debug_assert!(min_width >= 0.0);
404        self.min_width = min_width;
405        self
406    }
407
408    /// Dart `ButtonThemeData(height:)`.
409    pub fn with_height(mut self, height: f64) -> ButtonThemeData {
410        debug_assert!(height >= 0.0);
411        self.height = height;
412        self
413    }
414
415    /// Dart `ButtonThemeData(padding:)`.
416    pub fn with_padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ButtonThemeData {
417        self.padding = Some(padding.into());
418        self
419    }
420
421    /// Dart `ButtonThemeData(shape:)`.
422    pub fn with_shape(mut self, shape: impl Into<ShapeBorderRef>) -> ButtonThemeData {
423        self.shape = Some(shape.into());
424        self
425    }
426
427    /// Dart `ButtonThemeData(layoutBehavior:)`.
428    pub fn with_layout_behavior(
429        mut self,
430        layout_behavior: ButtonBarLayoutBehavior,
431    ) -> ButtonThemeData {
432        self.layout_behavior = layout_behavior;
433        self
434    }
435
436    /// Dart `ButtonThemeData(alignedDropdown:)`.
437    pub fn with_aligned_dropdown(mut self, aligned_dropdown: bool) -> ButtonThemeData {
438        self.aligned_dropdown = aligned_dropdown;
439        self
440    }
441
442    /// Dart `ButtonThemeData(buttonColor:)`.
443    pub fn with_button_color(mut self, button_color: Color) -> ButtonThemeData {
444        self.button_color = Some(button_color);
445        self
446    }
447
448    /// Dart `ButtonThemeData(disabledColor:)`.
449    pub fn with_disabled_color(mut self, disabled_color: Color) -> ButtonThemeData {
450        self.disabled_color = Some(disabled_color);
451        self
452    }
453
454    /// Dart `ButtonThemeData(focusColor:)`.
455    pub fn with_focus_color(mut self, focus_color: Color) -> ButtonThemeData {
456        self.focus_color = Some(focus_color);
457        self
458    }
459
460    /// Dart `ButtonThemeData(hoverColor:)`.
461    pub fn with_hover_color(mut self, hover_color: Color) -> ButtonThemeData {
462        self.hover_color = Some(hover_color);
463        self
464    }
465
466    /// Dart `ButtonThemeData(highlightColor:)`.
467    pub fn with_highlight_color(mut self, highlight_color: Color) -> ButtonThemeData {
468        self.highlight_color = Some(highlight_color);
469        self
470    }
471
472    /// Dart `ButtonThemeData(splashColor:)`.
473    pub fn with_splash_color(mut self, splash_color: Color) -> ButtonThemeData {
474        self.splash_color = Some(splash_color);
475        self
476    }
477
478    /// Dart `ButtonThemeData(colorScheme:)`.
479    pub fn with_color_scheme(mut self, color_scheme: ColorScheme) -> ButtonThemeData {
480        self.color_scheme = Some(color_scheme);
481        self
482    }
483
484    /// Dart `ButtonThemeData(materialTapTargetSize:)`.
485    pub fn with_material_tap_target_size(
486        mut self,
487        material_tap_target_size: MaterialTapTargetSize,
488    ) -> ButtonThemeData {
489        self.material_tap_target_size = Some(material_tap_target_size);
490        self
491    }
492
493    /// Convenience that returns [`min_width`](Self::min_width) and [`height`](Self::height) as
494    /// a [`BoxConstraints`] object.
495    pub fn constraints(&self) -> BoxConstraints {
496        BoxConstraints::new()
497            .min_width(self.min_width)
498            .min_height(self.height)
499    }
500
501    /// Padding for a button's child (typically the button's label).
502    ///
503    /// Defaults to 24.0 on the left and right if [`text_theme`](Self::text_theme) is
504    /// [`ButtonTextTheme::Primary`], 16.0 on the left and right otherwise.
505    pub fn padding(&self) -> EdgeInsetsGeometry {
506        self.padding.unwrap_or(match self.text_theme {
507            ButtonTextTheme::Normal => EdgeInsetsGeometry::symmetric(0.0, 16.0),
508            ButtonTextTheme::Accent => EdgeInsetsGeometry::symmetric(0.0, 16.0),
509            ButtonTextTheme::Primary => EdgeInsetsGeometry::symmetric(0.0, 24.0),
510        })
511    }
512
513    /// The shape of a button's material.
514    ///
515    /// The button's highlight and splash are clipped to this shape. If the button has an
516    /// elevation, then its drop shadow is defined by this shape as well.
517    ///
518    /// Defaults to a rounded rectangle with circular corner radii of 4.0 if
519    /// [`text_theme`](Self::text_theme) is [`ButtonTextTheme::Primary`], a rounded rectangle
520    /// with circular corner radii of 2.0 otherwise.
521    pub fn shape(&self) -> ShapeBorderRef {
522        match &self.shape {
523            Some(shape) => shape.clone(),
524            None => match self.text_theme {
525                ButtonTextTheme::Normal | ButtonTextTheme::Accent => {
526                    ShapeBorderRef::new(RoundedRectangleBorder::new(
527                        BorderSide::NONE,
528                        BorderRadiusGeometry::all(Radius::circular(2.0)),
529                    ))
530                }
531                ButtonTextTheme::Primary => ShapeBorderRef::new(RoundedRectangleBorder::new(
532                    BorderSide::NONE,
533                    BorderRadiusGeometry::all(Radius::circular(4.0)),
534                )),
535            },
536        }
537    }
538
539    fn color_scheme(&self) -> &ColorScheme {
540        self.color_scheme
541            .as_ref()
542            .expect("a button theme has a color scheme")
543    }
544
545    /// The `button`'s overall brightness.
546    ///
547    /// Returns the button's `colorBrightness` if it is non-null, otherwise the color scheme's
548    /// `brightness`.
549    pub fn get_brightness(&self, button: &MaterialButton) -> Brightness {
550        button
551            .color_brightness
552            .unwrap_or_else(|| self.color_scheme().brightness())
553    }
554
555    /// Defines the `button`'s base colors, and the defaults for the button's minimum size,
556    /// internal padding, and shape.
557    pub fn get_text_theme(&self, button: &MaterialButton) -> ButtonTextTheme {
558        button.text_theme.unwrap_or(self.text_theme)
559    }
560
561    /// The foreground color of the `button`'s text and icon when `on_pressed` is null.
562    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
563    pub fn get_disabled_text_color(&self, button: &MaterialButton) -> Color {
564        button
565            .text_color
566            .or(button.disabled_text_color)
567            .unwrap_or_else(|| self.color_scheme().on_surface().with_opacity(0.38))
568    }
569
570    /// The `button`'s background color when `on_pressed` is null.
571    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
572    pub fn get_disabled_fill_color(&self, button: &MaterialButton) -> Color {
573        button
574            .disabled_color
575            .or(self.disabled_color)
576            .unwrap_or_else(|| self.color_scheme().on_surface().with_opacity(0.38))
577    }
578
579    /// The button's background fill color, or `None` for buttons that don't have a background
580    /// color.
581    pub fn get_fill_color(&self, button: &MaterialButton) -> Option<Color> {
582        // Dart goes on to the theme's colors only for a subclass of `MaterialButton`, and a Rust
583        // type has no subclass.
584        if button.enabled() {
585            button.color
586        } else {
587            button.disabled_color
588        }
589    }
590
591    /// The foreground color of the `button`'s text and icon.
592    pub fn get_text_color(&self, button: &MaterialButton) -> Color {
593        if !button.enabled() {
594            return self.get_disabled_text_color(button);
595        }
596        if let Some(text_color) = button.text_color {
597            return text_color;
598        }
599        match self.get_text_theme(button) {
600            ButtonTextTheme::Normal => {
601                if self.get_brightness(button) == Brightness::Dark {
602                    Colors::WHITE
603                } else {
604                    Colors::BLACK87
605                }
606            }
607            ButtonTextTheme::Accent => self.color_scheme().secondary(),
608            ButtonTextTheme::Primary => {
609                let fill_is_dark = match self.get_fill_color(button) {
610                    Some(fill_color) => {
611                        ThemeData::estimate_brightness_for_color(fill_color) == Brightness::Dark
612                    }
613                    None => self.get_brightness(button) == Brightness::Dark,
614                };
615                if fill_is_dark {
616                    Colors::WHITE
617                } else {
618                    Colors::BLACK
619                }
620            }
621        }
622    }
623
624    /// The color of the ink "splash" overlay that appears when the (enabled) `button` is
625    /// tapped.
626    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
627    pub fn get_splash_color(&self, button: &MaterialButton) -> Color {
628        if let Some(splash_color) = button.splash_color {
629            return splash_color;
630        }
631        if let Some(splash_color) = self.splash_color
632            && matches!(
633                self.get_text_theme(button),
634                ButtonTextTheme::Normal | ButtonTextTheme::Accent
635            )
636        {
637            return splash_color;
638        }
639        self.get_text_color(button).with_opacity(0.12)
640    }
641
642    /// The fill color of the button when it has input focus.
643    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
644    pub fn get_focus_color(&self, button: &MaterialButton) -> Color {
645        button
646            .focus_color
647            .or(self.focus_color)
648            .unwrap_or_else(|| self.get_text_color(button).with_opacity(0.12))
649    }
650
651    /// The fill color of the button when a pointer is hovering over it.
652    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
653    pub fn get_hover_color(&self, button: &MaterialButton) -> Color {
654        button
655            .hover_color
656            .or(self.hover_color)
657            .unwrap_or_else(|| self.get_text_color(button).with_opacity(0.04))
658    }
659
660    /// The color of the overlay that appears when the `button` is pressed.
661    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
662    pub fn get_highlight_color(&self, button: &MaterialButton) -> Color {
663        if let Some(highlight_color) = button.highlight_color {
664            return highlight_color;
665        }
666        match self.get_text_theme(button) {
667            ButtonTextTheme::Normal | ButtonTextTheme::Accent => self
668                .highlight_color
669                .unwrap_or_else(|| self.get_text_color(button).with_opacity(0.16)),
670            ButtonTextTheme::Primary => Colors::TRANSPARENT,
671        }
672    }
673
674    /// The `button`'s elevation when it is enabled and has not been pressed.
675    pub fn get_elevation(&self, button: &MaterialButton) -> f64 {
676        button.elevation.unwrap_or(2.0)
677    }
678
679    /// The `button`'s elevation when it is enabled and has focus.
680    pub fn get_focus_elevation(&self, button: &MaterialButton) -> f64 {
681        button.focus_elevation.unwrap_or(4.0)
682    }
683
684    /// The `button`'s elevation when it is enabled and hovered.
685    pub fn get_hover_elevation(&self, button: &MaterialButton) -> f64 {
686        button.hover_elevation.unwrap_or(4.0)
687    }
688
689    /// The `button`'s elevation when it is enabled and pressed.
690    pub fn get_highlight_elevation(&self, button: &MaterialButton) -> f64 {
691        button.highlight_elevation.unwrap_or(8.0)
692    }
693
694    /// The `button`'s elevation when `on_pressed` is null.
695    pub fn get_disabled_elevation(&self, button: &MaterialButton) -> f64 {
696        button.disabled_elevation.unwrap_or(0.0)
697    }
698
699    /// Padding for the `button`'s child (typically the button's label).
700    pub fn get_padding(&self, button: &MaterialButton) -> EdgeInsetsGeometry {
701        button
702            .padding
703            .or(self.padding)
704            .unwrap_or_else(|| match self.get_text_theme(button) {
705                ButtonTextTheme::Normal | ButtonTextTheme::Accent => {
706                    EdgeInsetsGeometry::symmetric(0.0, 16.0)
707                }
708                ButtonTextTheme::Primary => EdgeInsetsGeometry::symmetric(0.0, 24.0),
709            })
710    }
711
712    /// The shape of the `button`'s `Material`.
713    pub fn get_shape(&self, button: &MaterialButton) -> ShapeBorderRef {
714        button.shape.clone().unwrap_or_else(|| self.shape())
715    }
716
717    /// The duration of the `button`'s highlight animation.
718    pub fn get_animation_duration(&self, button: &MaterialButton) -> Duration {
719        button.animation_duration.unwrap_or(K_THEME_CHANGE_DURATION)
720    }
721
722    /// The `BoxConstraints` that define the `button`'s size.
723    pub fn get_constraints(&self, _button: &MaterialButton) -> BoxConstraints {
724        self.constraints()
725    }
726
727    /// The minimum size of the `button`'s tap target.
728    pub fn get_material_tap_target_size(&self, button: &MaterialButton) -> MaterialTapTargetSize {
729        button
730            .material_tap_target_size
731            .or(self.material_tap_target_size)
732            .unwrap_or(MaterialTapTargetSize::Padded)
733    }
734
735    /// Creates a copy of this button theme data object with the matching fields replaced with
736    /// the non-null parameter values.
737    ///
738    /// The copy holds this theme's [`padding`](Self::padding) and [`shape`](Self::shape) as
739    /// given values, their defaults included, as Dart's `copyWith` passes `this.padding` and
740    /// `this.shape` on.
741    pub fn copy_with(&self) -> ButtonThemeData {
742        let mut copy = self.clone();
743        copy.padding = Some(self.padding());
744        copy.shape = Some(self.shape());
745        copy
746    }
747}
748
749impl Default for ButtonThemeData {
750    fn default() -> ButtonThemeData {
751        ButtonThemeData::new()
752    }
753}
754
755impl PartialEq for ButtonThemeData {
756    fn eq(&self, other: &ButtonThemeData) -> bool {
757        other.text_theme == self.text_theme
758            && other.min_width == self.min_width
759            && other.height == self.height
760            && other.padding() == self.padding()
761            && other.shape() == self.shape()
762            && other.aligned_dropdown == self.aligned_dropdown
763            && other.button_color == self.button_color
764            && other.disabled_color == self.disabled_color
765            && other.focus_color == self.focus_color
766            && other.hover_color == self.hover_color
767            && other.highlight_color == self.highlight_color
768            && other.splash_color == self.splash_color
769            && other.color_scheme == self.color_scheme
770            && other.material_tap_target_size == self.material_tap_target_size
771    }
772}
773
774impl Debug for ButtonThemeData {
775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776        let default_theme = ButtonThemeData::new();
777        let mut properties = f.debug_struct("ButtonThemeData");
778        if self.text_theme != default_theme.text_theme {
779            properties.field("textTheme", &self.text_theme);
780        }
781        if self.min_width != default_theme.min_width {
782            properties.field("minWidth", &self.min_width);
783        }
784        if self.height != default_theme.height {
785            properties.field("height", &self.height);
786        }
787        if self.padding() != default_theme.padding() {
788            properties.field("padding", &self.padding());
789        }
790        if self.shape() != default_theme.shape() {
791            properties.field("shape", &self.shape());
792        }
793        if self.aligned_dropdown != default_theme.aligned_dropdown {
794            properties.field("alignedDropdown", &"dropdown width matches button");
795        }
796        if let Some(button_color) = &self.button_color {
797            properties.field("buttonColor", button_color);
798        }
799        if let Some(disabled_color) = &self.disabled_color {
800            properties.field("disabledColor", disabled_color);
801        }
802        if let Some(focus_color) = &self.focus_color {
803            properties.field("focusColor", focus_color);
804        }
805        if let Some(hover_color) = &self.hover_color {
806            properties.field("hoverColor", hover_color);
807        }
808        if let Some(highlight_color) = &self.highlight_color {
809            properties.field("highlightColor", highlight_color);
810        }
811        if let Some(splash_color) = &self.splash_color {
812            properties.field("splashColor", splash_color);
813        }
814        if self.color_scheme.is_some() {
815            properties.field("colorScheme", &"ColorScheme");
816        }
817        if let Some(material_tap_target_size) = &self.material_tap_target_size {
818            properties.field("materialTapTargetSize", material_tap_target_size);
819        }
820        properties.finish()
821    }
822}
823
824impl waft_foundation::Diagnosticable for ButtonThemeData {
825    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
826        let default_theme = ButtonThemeData::default();
827        properties.add(
828            EnumProperty::<ButtonTextTheme>::new("textTheme", Some(self.text_theme))
829                .default_value(Some(default_theme.text_theme)),
830        );
831        properties.add(
832            DoubleProperty::new("minWidth", self.min_width)
833                .default_value(Some(default_theme.min_width)),
834        );
835        properties.add(
836            DoubleProperty::new("height", self.height).default_value(Some(default_theme.height)),
837        );
838        properties.add(
839            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", Some(self.padding()))
840                .default_value(Some(default_theme.padding())),
841        );
842        properties.add(
843            DiagnosticsProperty::<ShapeBorderRef>::new("shape", Some(self.shape()))
844                .default_value(Some(default_theme.shape())),
845        );
846        properties.add(
847            FlagProperty::new("alignedDropdown", self.aligned_dropdown)
848                .default_value(Some(default_theme.aligned_dropdown))
849                .if_true("dropdown width matches button"),
850        );
851        properties.add(ColorProperty::new("buttonColor", self.button_color).default_value(None));
852        properties
853            .add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
854        properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
855        properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
856        properties
857            .add(ColorProperty::new("highlightColor", self.highlight_color).default_value(None));
858        properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
859        properties.add(
860            DiagnosticsProperty::<ColorScheme>::new("colorScheme", self.color_scheme.clone())
861                .default_value(default_theme.color_scheme.clone()),
862        );
863        properties.add(
864            DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
865                "materialTapTargetSize",
866                self.material_tap_target_size.map(waft_foundation::DartEnum),
867            )
868            .default_value(None),
869        );
870    }
871}
872
873impl std::fmt::Display for ButtonThemeData {
874    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
875        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
876    }
877}
878
879#[cfg(test)]
880mod tests {
881    use waft_painting::StadiumBorder;
882
883    use super::*;
884
885    fn rounded(radius: f64) -> ShapeBorderRef {
886        ShapeBorderRef::new(RoundedRectangleBorder::new(
887            BorderSide::NONE,
888            BorderRadiusGeometry::all(Radius::circular(radius)),
889        ))
890    }
891
892    fn rounded_rectangle_border() -> ShapeBorderRef {
893        ShapeBorderRef::new(RoundedRectangleBorder::new(
894            BorderSide::NONE,
895            BorderRadiusGeometry::ZERO,
896        ))
897    }
898
899    // button_theme_test.dart 'ButtonThemeData defaults'.
900    #[test]
901    fn a_new_button_theme_data_has_dart_defaults() {
902        let theme = ButtonThemeData::new();
903        assert_eq!(theme.text_theme, ButtonTextTheme::Normal);
904        assert_eq!(
905            theme.constraints(),
906            BoxConstraints::new().min_width(88.0).min_height(36.0)
907        );
908        assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
909        assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
910        assert!(!theme.aligned_dropdown);
911        assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Padded);
912    }
913
914    // button_theme_test.dart 'ButtonThemeData default overrides'.
915    #[test]
916    fn the_given_values_override_the_defaults() {
917        let theme = ButtonThemeData::new()
918            .with_text_theme(ButtonTextTheme::Primary)
919            .with_min_width(100.0)
920            .with_height(200.0)
921            .with_padding(EdgeInsetsGeometry::ZERO)
922            .with_shape(rounded_rectangle_border())
923            .with_aligned_dropdown(true);
924        assert_eq!(theme.text_theme, ButtonTextTheme::Primary);
925        assert_eq!(
926            theme.constraints(),
927            BoxConstraints::new().min_width(100.0).min_height(200.0)
928        );
929        assert_eq!(theme.padding(), EdgeInsetsGeometry::ZERO);
930        assert_eq!(Some(theme.shape()), Some(rounded_rectangle_border()));
931        assert!(theme.aligned_dropdown);
932    }
933
934    // button_theme_test.dart 'ButtonThemeData.copyWith'.
935    #[test]
936    fn copy_with_keeps_every_value_and_replaces_the_given_ones() {
937        let theme = ButtonThemeData::new().copy_with();
938        assert_eq!(theme.text_theme, ButtonTextTheme::Normal);
939        assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Padded);
940        assert_eq!(
941            theme.constraints(),
942            BoxConstraints::new().min_width(88.0).min_height(36.0)
943        );
944        assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
945        assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
946        assert!(!theme.aligned_dropdown);
947        assert!(theme.color_scheme.is_none());
948
949        let theme = ButtonThemeData::new()
950            .copy_with()
951            .with_text_theme(ButtonTextTheme::Primary)
952            .with_layout_behavior(ButtonBarLayoutBehavior::Constrained)
953            .with_min_width(100.0)
954            .with_height(200.0)
955            .with_padding(EdgeInsetsGeometry::ZERO)
956            .with_shape(StadiumBorder::new(BorderSide::NONE))
957            .with_aligned_dropdown(true)
958            .with_color_scheme(ColorScheme::dark())
959            .with_material_tap_target_size(MaterialTapTargetSize::ShrinkWrap);
960        assert_eq!(theme.text_theme, ButtonTextTheme::Primary);
961        assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Constrained);
962        assert_eq!(
963            theme.constraints(),
964            BoxConstraints::new().min_width(100.0).min_height(200.0)
965        );
966        assert_eq!(theme.padding(), EdgeInsetsGeometry::ZERO);
967        let stadium: ShapeBorderRef = ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE));
968        assert_eq!(Some(theme.shape()), Some(stadium));
969        assert!(theme.aligned_dropdown);
970        assert_eq!(theme.color_scheme, Some(ColorScheme::dark()));
971    }
972
973    // Dart's `copyWith` passes the `padding` and `shape` getters on, so a copy keeps the
974    // defaults of the text theme it was made from.
975    #[test]
976    fn a_copy_keeps_the_padding_and_shape_of_the_original_text_theme() {
977        let theme = ButtonThemeData::new()
978            .copy_with()
979            .with_text_theme(ButtonTextTheme::Primary);
980        assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
981        assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
982        assert_ne!(
983            theme,
984            ButtonThemeData::new().with_text_theme(ButtonTextTheme::Primary)
985        );
986    }
987}