Skip to main content

waft_material/
button_style.rs

1//! Flutter counterpart: material_ui's `button_style.dart`.
2//!
3//! A state-dependent field holds a [`WidgetStatePropertyRef`] of `Option<T>`: Dart's
4//! `WidgetStateProperty<T?>`, whose `null` lets the next style decide.
5
6use std::any::TypeId;
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9use std::time::Duration;
10
11use waft_embedder::{Color, SignedDuration, Size, lerp_double};
12use waft_foundation::{App, DiagnosticsProperty, EnumProperty};
13use waft_painting::{
14    AlignmentGeometry, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef, TextStyle,
15};
16use waft_services::MouseCursorRef;
17use waft_widgets::{
18    BuildContext, WidgetRef, WidgetStateBorderSide, WidgetStateProperty, WidgetStatePropertyRef,
19    WidgetStates,
20};
21
22use crate::button_style_button::IconAlignment;
23use crate::ink_well::InteractiveInkFeatureFactoryRef;
24use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
25
26/// Defines size variants for Material 3 Expressive button components.
27///
28/// Each size variant represents a named visual scale. For example, a Material
29/// 3 Expressive `IconButton` uses this value to choose its container size, icon
30/// size, and padding.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum ButtonSizeVariant {
33    /// The smallest button size.
34    XSmall,
35
36    /// A small button size.
37    Small,
38
39    /// A medium button size.
40    Medium,
41
42    /// A large button size.
43    Large,
44
45    /// The largest button size.
46    XLarge,
47}
48
49/// Defines the width variants for Material 3 Expressive `IconButton`.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub enum IconButtonWidthVariant {
52    /// A narrower icon button.
53    Narrow,
54
55    /// The standard icon button width.
56    Standard,
57
58    /// A wider icon button.
59    Wide,
60}
61
62/// Defines shape variants for Material 3 Expressive button components.
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
64pub enum ButtonShapeVariant {
65    /// A rounded button shape.
66    ///
67    /// For example, a Material 3 Expressive `IconButton` with this variant uses
68    /// rounder default container shapes.
69    Round,
70
71    /// A squared button shape.
72    ///
73    /// For example, a Material 3 Expressive `IconButton` with this variant uses
74    /// more squared default container shapes.
75    Square,
76}
77
78/// The type for [`ButtonStyle::background_builder`] and [`ButtonStyle::foreground_builder`].
79///
80/// The `states` parameter is the button's current pressed/hovered/etc state. The `child` is
81/// typically a descendant of the returned widget.
82///
83/// [`ButtonStyle`]'s `==` compares two builders as Dart compares two function values:
84/// [`new`](Self::new) equals only its clones; [`function`](Self::function) equals any other
85/// built from the same function, as two tear-offs of one static method are identical (see
86/// the porting skill's callback-identity pattern).
87#[derive(Clone)]
88pub struct ButtonLayerBuilder {
89    builder: Rc<ButtonLayerBuilderFn>,
90    identity: ButtonLayerBuilderIdentity,
91}
92
93/// The function a [`ButtonLayerBuilder`] calls.
94type ButtonLayerBuilderFn =
95    dyn Fn(&mut App, BuildContext, &WidgetStates, Option<WidgetRef>) -> WidgetRef;
96
97/// Equality key: closures compare by allocation, functions by the `TypeId` of the function
98/// item.
99#[derive(Clone, Copy, PartialEq)]
100enum ButtonLayerBuilderIdentity {
101    Closure,
102    Function(TypeId),
103}
104
105impl ButtonLayerBuilder {
106    /// Wraps a closure; it equals only its clones.
107    pub fn new(
108        builder: impl Fn(&mut App, BuildContext, &WidgetStates, Option<WidgetRef>) -> WidgetRef
109        + 'static,
110    ) -> ButtonLayerBuilder {
111        ButtonLayerBuilder {
112            builder: Rc::new(builder),
113            identity: ButtonLayerBuilderIdentity::Closure,
114        }
115    }
116
117    /// A function, comparable like a Dart tear-off of a static method.
118    ///
119    /// Pass the function by name. A fn pointer or capturing closure is rejected: it has no
120    /// canonical identity.
121    pub fn function<F>(builder: F) -> ButtonLayerBuilder
122    where
123        F: Fn(&mut App, BuildContext, &WidgetStates, Option<WidgetRef>) -> WidgetRef + 'static,
124    {
125        const {
126            assert!(
127                std::mem::size_of::<F>() == 0,
128                "pass the function by name: a fn pointer or capturing closure has no canonical \
129                 identity"
130            )
131        };
132        ButtonLayerBuilder {
133            builder: Rc::new(builder),
134            identity: ButtonLayerBuilderIdentity::Function(TypeId::of::<F>()),
135        }
136    }
137
138    /// Calls the builder.
139    pub fn call(
140        &self,
141        app: &mut App,
142        context: BuildContext,
143        states: &WidgetStates,
144        child: Option<WidgetRef>,
145    ) -> WidgetRef {
146        (self.builder)(app, context, states, child)
147    }
148}
149
150impl PartialEq for ButtonLayerBuilder {
151    fn eq(&self, other: &ButtonLayerBuilder) -> bool {
152        match (self.identity, other.identity) {
153            (ButtonLayerBuilderIdentity::Closure, ButtonLayerBuilderIdentity::Closure) => {
154                Rc::ptr_eq(&self.builder, &other.builder)
155            }
156            (mine, theirs) => mine == theirs,
157        }
158    }
159}
160
161impl Debug for ButtonLayerBuilder {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.write_str("ButtonLayerBuilder")
164    }
165}
166
167/// The visual properties that most buttons have in common.
168///
169/// Buttons and their themes have a ButtonStyle property which defines the visual
170/// properties whose default values are to be overridden. The default values are
171/// defined by the individual button widgets and are typically based on overall
172/// theme's `ThemeData::color_scheme` and `ThemeData::text_theme`.
173///
174/// All of the ButtonStyle properties are null by default.
175///
176/// Many of the ButtonStyle properties are [`WidgetStateProperty`] objects which
177/// resolve to different values depending on the button's state. For example
178/// the [`Color`] properties are defined with `WidgetStateProperty<Option<Color>>` and
179/// can resolve to different colors depending on if the button is pressed,
180/// hovered, focused, disabled, etc.
181///
182/// These properties can override the default value for just one state or all of
183/// them. For example to create an `ElevatedButton` whose background color is the
184/// color scheme’s primary color with 50% opacity, but only when the button is
185/// pressed, one could write:
186///
187/// ```text
188/// ElevatedButton::new(on_pressed, Text::new("Fly me to the moon"))
189///     .style(ButtonStyle::new().background_color(
190///         <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
191///             if states.contains(&WidgetState::Pressed) {
192///                 return Some(primary.with_opacity(0.5));
193///             }
194///             None // Use the component's default.
195///         }),
196///     ))
197/// ```
198///
199/// In this case the background color for all other button states would fallback
200/// to the ElevatedButton’s default values. To unconditionally set the button's
201/// [`background_color`](Self::background_color) for all states one could write:
202///
203/// ```text
204/// ElevatedButton::new(on_pressed, Text::new("Let me play among the stars"))
205///     .style(ButtonStyle::new().background_color(Rc::new(WidgetStatePropertyAll::new(
206///         Some(Colors::GREEN.primary()),
207///     ))))
208/// ```
209///
210/// Configuring a ButtonStyle directly makes it possible to very
211/// precisely control the button’s visual attributes for all states.
212/// This level of control is typically required when a custom
213/// “branded” look and feel is desirable. However, in many cases it’s
214/// useful to make relatively sweeping changes based on a few initial
215/// parameters with simple values. The button `style_from()` methods
216/// enable such sweeping changes. See for example:
217/// `ElevatedButton::style_from`, `FilledButton::style_from`,
218/// `OutlinedButton::style_from`, `TextButton::style_from`.
219///
220/// For example, to override the default text and icon colors for a
221/// `TextButton`, as well as its overlay color, with all of the
222/// standard opacity adjustments for the pressed, focused, and
223/// hovered states, one could write:
224///
225/// ```text
226/// TextButton::new(on_pressed, Text::new("Let me see what spring is like"))
227///     .style(TextButton::style_from().foreground_color(Colors::GREEN.primary()))
228/// ```
229///
230/// To configure all of the application's text buttons in the same
231/// way, specify the overall theme's `text_button_theme`.
232///
233/// ## Material 3 button types
234///
235/// Material Design 3 specifies five types of common buttons. Flutter provides
236/// support for these using the following button classes:
237///
238/// | Type         | Flutter implementation  |
239/// | :----------- | :---------------------- |
240/// | Elevated     | `ElevatedButton`        |
241/// | Filled       | `FilledButton`          |
242/// | Filled Tonal | `FilledButton::tonal`   |
243/// | Outlined     | `OutlinedButton`        |
244/// | Text         | `TextButton`            |
245///
246/// See also:
247///
248///  * `ElevatedButtonTheme`, the theme for `ElevatedButton`s.
249///  * `FilledButtonTheme`, the theme for `FilledButton`s.
250///  * `OutlinedButtonTheme`, the theme for `OutlinedButton`s.
251///  * `TextButtonTheme`, the theme for `TextButton`s.
252#[derive(Clone, Default)]
253pub struct ButtonStyle {
254    /// The style for a button's `Text` widget descendants.
255    ///
256    /// The color of the [`text_style`](Self::text_style) is typically not used directly, the
257    /// [`foreground_color`](Self::foreground_color) is used instead.
258    pub text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
259
260    /// The button's background fill color.
261    pub background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
262
263    /// The color for the button's `Text` widget descendants.
264    ///
265    /// This color is typically used instead of the color of the
266    /// [`text_style`](Self::text_style). All of the components that compute defaults from
267    /// [`ButtonStyle`] values compute a default [`foreground_color`](Self::foreground_color)
268    /// and use that instead of the [`text_style`](Self::text_style)'s color.
269    pub foreground_color: Option<WidgetStatePropertyRef<Option<Color>>>,
270
271    /// The highlight color that's typically used to indicate that
272    /// the button is focused, hovered, or pressed.
273    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
274
275    /// The shadow color of the button's `Material`.
276    ///
277    /// The material's elevation shadow can be difficult to see for
278    /// dark themes, so by default the button classes add a
279    /// semi-transparent overlay to indicate elevation. See
280    /// `ThemeData::apply_elevation_overlay_color`.
281    pub shadow_color: Option<WidgetStatePropertyRef<Option<Color>>>,
282
283    /// The surface tint color of the button's `Material`.
284    ///
285    /// See `Material::surface_tint_color` for more details.
286    pub surface_tint_color: Option<WidgetStatePropertyRef<Option<Color>>>,
287
288    /// The elevation of the button's `Material`.
289    pub elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
290
291    /// The padding between the button's boundary and its child.
292    ///
293    /// The vertical aspect of the default or user-specified padding is adjusted
294    /// automatically based on [`visual_density`](Self::visual_density).
295    ///
296    /// When the visual density is [`VisualDensity::COMPACT`], the top and bottom insets
297    /// are reduced by 8 pixels or set to 0 pixels if the result of the reduced padding
298    /// is negative. For example: the visual density defaults to [`VisualDensity::COMPACT`]
299    /// on desktop and web, so if the provided padding is 16 pixels on the top and bottom,
300    /// it will be reduced to 8 pixels on the top and bottom. If the provided padding
301    /// is 4 pixels, the result will be no padding on the top and bottom.
302    ///
303    /// When the visual density is [`VisualDensity::COMFORTABLE`], the top and bottom insets
304    /// are reduced by 4 pixels or set to 0 pixels if the result of the reduced padding
305    /// is negative.
306    ///
307    /// When the visual density is [`VisualDensity::STANDARD`] the top and bottom insets
308    /// are not changed. The visual density defaults to [`VisualDensity::STANDARD`] on mobile.
309    ///
310    /// See `ThemeData::visual_density` for more details.
311    pub padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
312
313    /// The minimum size of the button itself before applying
314    /// [`visual_density`](Self::visual_density).
315    ///
316    /// The size of the rectangle the button lies within may be larger
317    /// per [`tap_target_size`](Self::tap_target_size).
318    ///
319    /// This value must be less than or equal to [`maximum_size`](Self::maximum_size).
320    ///
321    /// The minimum size is adjusted automatically based on
322    /// [`visual_density`](Self::visual_density).
323    ///
324    /// When visual density is [`VisualDensity::COMPACT`], the minimum size is
325    /// reduced by 8 pixels on both dimensions.
326    ///
327    /// When visual density is [`VisualDensity::COMFORTABLE`], the minimum size is
328    /// [`minimum_size`](Self::minimum_size) reduced by 4 pixels on both dimensions.
329    ///
330    /// When visual density is [`VisualDensity::STANDARD`], the minimum size is
331    /// [`minimum_size`](Self::minimum_size).
332    pub minimum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
333
334    /// The button's size.
335    ///
336    /// This size is still constrained by the style's [`minimum_size`](Self::minimum_size)
337    /// and [`maximum_size`](Self::maximum_size). Fixed size dimensions whose value is
338    /// [`f64::INFINITY`] are ignored.
339    ///
340    /// The size of the rectangle the button lies within may be larger
341    /// per [`tap_target_size`](Self::tap_target_size).
342    ///
343    /// To specify buttons with a fixed width and the default height use
344    /// `Size::from_width(320.0)`. Similarly, to specify a fixed
345    /// height and the default width use `Size::from_height(100.0)`.
346    pub fixed_size: Option<WidgetStatePropertyRef<Option<Size>>>,
347
348    /// The maximum size of the button itself.
349    ///
350    /// A `Size::INFINITE` or null value for this property means that
351    /// the button's maximum size is not constrained.
352    ///
353    /// This value must be greater than or equal to [`minimum_size`](Self::minimum_size).
354    pub maximum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
355
356    /// The icon's color inside of the button.
357    pub icon_color: Option<WidgetStatePropertyRef<Option<Color>>>,
358
359    /// The icon's size inside of the button.
360    pub icon_size: Option<WidgetStatePropertyRef<Option<f64>>>,
361
362    /// The alignment of the button's icon.
363    ///
364    /// This property is supported for the following button types:
365    ///
366    ///  * `ElevatedButton::icon`.
367    ///  * `FilledButton::icon`.
368    ///  * `FilledButton::tonal_icon`.
369    ///  * `OutlinedButton::icon`.
370    ///  * `TextButton::icon`.
371    ///
372    /// See also:
373    ///
374    ///  * [`IconAlignment`], for more information about the different icon
375    ///    alignments.
376    pub icon_alignment: Option<IconAlignment>,
377
378    /// The color and weight of the button's outline.
379    ///
380    /// This value is combined with [`shape`](Self::shape) to create a shape decorated
381    /// with an outline.
382    pub side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
383
384    /// The shape of the button's underlying `Material`.
385    ///
386    /// This shape is combined with [`side`](Self::side) to create a shape decorated
387    /// with an outline.
388    pub shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
389
390    /// The cursor for a mouse pointer when it enters or is hovering over
391    /// this button's `InkWell`.
392    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
393
394    /// Defines how compact the button's layout will be.
395    ///
396    /// See also:
397    ///
398    ///  * `ThemeData::visual_density`, which specifies the
399    ///    [`visual_density`](Self::visual_density) for all widgets within a `Theme`.
400    pub visual_density: Option<VisualDensity>,
401
402    /// Configures the minimum size of the area within which the button may be pressed.
403    ///
404    /// If the [`tap_target_size`](Self::tap_target_size) is larger than
405    /// [`minimum_size`](Self::minimum_size), the button will include a transparent margin
406    /// that responds to taps.
407    ///
408    /// Always defaults to `ThemeData::material_tap_target_size`.
409    pub tap_target_size: Option<MaterialTapTargetSize>,
410
411    /// Defines the duration of animated changes for [`shape`](Self::shape) and
412    /// [`elevation`](Self::elevation).
413    ///
414    /// Typically the component default value is `K_THEME_CHANGE_DURATION`.
415    pub animation_duration: Option<Duration>,
416
417    /// Whether detected gestures should provide acoustic and/or haptic feedback.
418    ///
419    /// For example, on Android a tap will produce a clicking sound and a
420    /// long-press will produce a short vibration, when feedback is enabled.
421    ///
422    /// Typically the component default value is true.
423    ///
424    /// See also:
425    ///
426    ///  * `Feedback` for providing platform-specific feedback to certain actions.
427    pub enable_feedback: Option<bool>,
428
429    /// The alignment of the button's child.
430    ///
431    /// Typically buttons are sized to be just big enough to contain the child and its
432    /// padding. If the button's size is constrained to a fixed size, for example by
433    /// enclosing it with a `SizedBox`, this property defines how the child is aligned
434    /// within the available space.
435    ///
436    /// Always defaults to `Alignment::CENTER`.
437    pub alignment: Option<AlignmentGeometry>,
438
439    /// Creates the `InkWell` splash factory, which defines the appearance of
440    /// "ink" splashes that occur in response to taps.
441    ///
442    /// Use `NoSplash::splash_factory()` to defeat ink splash rendering.
443    pub splash_factory: Option<InteractiveInkFeatureFactoryRef>,
444
445    /// Creates a widget that becomes the child of the button's `Material`
446    /// and whose child is the rest of the button, including the button's
447    /// `child` parameter.
448    ///
449    /// The widget created by [`background_builder`](Self::background_builder) is
450    /// constrained to be the same size as the overall button and will appear behind the
451    /// button's child. The widget created by [`foreground_builder`](Self::foreground_builder)
452    /// is constrained to be the same size as the button's child, i.e. it's
453    /// inset by [`ButtonStyle::padding`] and aligned by the button's
454    /// [`ButtonStyle::alignment`].
455    ///
456    /// By default the returned widget is clipped to the Material's [`ButtonStyle::shape`].
457    ///
458    /// See also:
459    ///
460    ///  * [`foreground_builder`](Self::foreground_builder), to create a widget that's as big
461    ///    as the button's child and is layered behind the child.
462    ///  * `ButtonStyleButtonData::clip_behavior`, for more information about
463    ///    configuring clipping.
464    pub background_builder: Option<ButtonLayerBuilder>,
465
466    /// Creates a Widget that contains the button's child parameter which is used
467    /// instead of the button's child.
468    ///
469    /// The returned widget is clipped by the button's
470    /// [`ButtonStyle::shape`], inset by the button's [`ButtonStyle::padding`]
471    /// and aligned by the button's [`ButtonStyle::alignment`].
472    ///
473    /// See also:
474    ///
475    ///  * [`background_builder`](Self::background_builder), to create a widget that's as big
476    ///    as the button and is layered behind the button's child.
477    ///  * `ButtonStyleButtonData::clip_behavior`, for more information about
478    ///    configuring clipping.
479    pub foreground_builder: Option<ButtonLayerBuilder>,
480
481    /// The Material 3 Expressive size variant for this button.
482    ///
483    /// A size variant selects a component-defined token set rather than a single
484    /// dimension. For example, an `IconButton` uses this value to choose its
485    /// default container size, padding, and icon size when it is using
486    /// `StyleVariant::Material3Expressive`.
487    ///
488    /// Use [`minimum_size`](Self::minimum_size), [`fixed_size`](Self::fixed_size),
489    /// [`maximum_size`](Self::maximum_size), [`padding`](Self::padding), or
490    /// [`icon_size`](Self::icon_size) to directly override those individual style
491    /// properties.
492    pub size_variant: Option<ButtonSizeVariant>,
493
494    /// The Material 3 Expressive width variant for an `IconButton`.
495    ///
496    /// A width variant selects the leading and trailing space tokens used to
497    /// compute an icon button's default horizontal padding and minimum width when
498    /// it is using `StyleVariant::Material3Expressive`. It does not change the
499    /// button's height or icon size.
500    ///
501    /// This property is only used by icon buttons. Use [`padding`](Self::padding),
502    /// [`minimum_size`](Self::minimum_size), [`fixed_size`](Self::fixed_size), or
503    /// [`maximum_size`](Self::maximum_size) to directly override the resulting layout.
504    pub icon_button_width: Option<IconButtonWidthVariant>,
505
506    /// The Material 3 Expressive shape variant for this button.
507    ///
508    /// A shape variant selects between component-defined token families, such as
509    /// round and square shapes. For `IconButton`, this affects the default
510    /// container and selected-state shapes when it is using
511    /// `StyleVariant::Material3Expressive`; state-specific tokens, such as the
512    /// pressed shape, are still resolved by the component defaults.
513    ///
514    /// Use [`shape`](Self::shape) to provide a specific [`OutlinedBorder`] or stateful shape
515    /// override instead of selecting one of the Material 3 Expressive shape
516    /// variants.
517    pub shape_variant: Option<ButtonShapeVariant>,
518}
519
520crate::theme_data_getters::theme_data_getters! {
521    /// Dart's getters of `ButtonStyle`: the theme data answers with its fields, and a defaults
522    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
523    /// are read.
524    pub trait ButtonStyleGetters for ButtonStyle, fields: button_style {
525        text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
526        background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
527        foreground_color: Option<WidgetStatePropertyRef<Option<Color>>>,
528        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
529        shadow_color: Option<WidgetStatePropertyRef<Option<Color>>>,
530        surface_tint_color: Option<WidgetStatePropertyRef<Option<Color>>>,
531        elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
532        padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
533        minimum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
534        fixed_size: Option<WidgetStatePropertyRef<Option<Size>>>,
535        maximum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
536        icon_color: Option<WidgetStatePropertyRef<Option<Color>>>,
537        icon_size: Option<WidgetStatePropertyRef<Option<f64>>>,
538        icon_alignment: Option<IconAlignment>,
539        side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
540        shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
541        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
542        visual_density: Option<VisualDensity>,
543        tap_target_size: Option<MaterialTapTargetSize>,
544        animation_duration: Option<Duration>,
545        enable_feedback: Option<bool>,
546        alignment: Option<AlignmentGeometry>,
547        splash_factory: Option<InteractiveInkFeatureFactoryRef>,
548        background_builder: Option<ButtonLayerBuilder>,
549        foreground_builder: Option<ButtonLayerBuilder>,
550        size_variant: Option<ButtonSizeVariant>,
551        icon_button_width: Option<IconButtonWidthVariant>,
552        shape_variant: Option<ButtonShapeVariant>,
553    }
554}
555
556/// The fluent setters of Dart's named `ButtonStyle` arguments, which `copyWith` shares.
557macro_rules! button_style_setters {
558    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
559        $(
560            #[doc = concat!("Dart `ButtonStyle(", $dart, ":)`.")]
561            pub fn $field(mut self, $field: $ty) -> ButtonStyle {
562                self.$field = Some($field);
563                self
564            }
565        )*
566    };
567}
568
569impl ButtonStyle {
570    /// Create a [`ButtonStyle`].
571    pub fn new() -> ButtonStyle {
572        ButtonStyle::default()
573    }
574
575    button_style_setters!(
576        text_style: WidgetStatePropertyRef<Option<TextStyle>> => "textStyle",
577        background_color: WidgetStatePropertyRef<Option<Color>> => "backgroundColor",
578        foreground_color: WidgetStatePropertyRef<Option<Color>> => "foregroundColor",
579        overlay_color: WidgetStatePropertyRef<Option<Color>> => "overlayColor",
580        shadow_color: WidgetStatePropertyRef<Option<Color>> => "shadowColor",
581        surface_tint_color: WidgetStatePropertyRef<Option<Color>> => "surfaceTintColor",
582        elevation: WidgetStatePropertyRef<Option<f64>> => "elevation",
583        padding: WidgetStatePropertyRef<Option<EdgeInsetsGeometry>> => "padding",
584        minimum_size: WidgetStatePropertyRef<Option<Size>> => "minimumSize",
585        fixed_size: WidgetStatePropertyRef<Option<Size>> => "fixedSize",
586        maximum_size: WidgetStatePropertyRef<Option<Size>> => "maximumSize",
587        icon_color: WidgetStatePropertyRef<Option<Color>> => "iconColor",
588        icon_size: WidgetStatePropertyRef<Option<f64>> => "iconSize",
589        icon_alignment: IconAlignment => "iconAlignment",
590        side: WidgetStatePropertyRef<Option<BorderSide>> => "side",
591        shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>> => "shape",
592        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> => "mouseCursor",
593        visual_density: VisualDensity => "visualDensity",
594        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
595        animation_duration: Duration => "animationDuration",
596        enable_feedback: bool => "enableFeedback",
597        alignment: AlignmentGeometry => "alignment",
598        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
599        background_builder: ButtonLayerBuilder => "backgroundBuilder",
600        foreground_builder: ButtonLayerBuilder => "foregroundBuilder",
601        size_variant: ButtonSizeVariant => "sizeVariant",
602        icon_button_width: IconButtonWidthVariant => "iconButtonWidth",
603        shape_variant: ButtonShapeVariant => "shapeVariant",
604    );
605
606    /// Returns a copy of this ButtonStyle with the given fields replaced with
607    /// the new values.
608    ///
609    /// Chain setters: `style.copy_with().elevation(e)`.
610    pub fn copy_with(&self) -> ButtonStyle {
611        self.clone()
612    }
613
614    /// Returns a copy of this ButtonStyle where the non-null fields in `style`
615    /// have replaced the corresponding null fields in this ButtonStyle.
616    ///
617    /// In other words, `style` is used to fill in unspecified (null) fields
618    /// this ButtonStyle.
619    pub fn merge(&self, style: Option<&ButtonStyle>) -> ButtonStyle {
620        let Some(style) = style else {
621            return self.clone();
622        };
623        ButtonStyle {
624            text_style: self.text_style.clone().or_else(|| style.text_style.clone()),
625            background_color: self
626                .background_color
627                .clone()
628                .or_else(|| style.background_color.clone()),
629            foreground_color: self
630                .foreground_color
631                .clone()
632                .or_else(|| style.foreground_color.clone()),
633            overlay_color: self
634                .overlay_color
635                .clone()
636                .or_else(|| style.overlay_color.clone()),
637            shadow_color: self
638                .shadow_color
639                .clone()
640                .or_else(|| style.shadow_color.clone()),
641            surface_tint_color: self
642                .surface_tint_color
643                .clone()
644                .or_else(|| style.surface_tint_color.clone()),
645            elevation: self.elevation.clone().or_else(|| style.elevation.clone()),
646            padding: self.padding.clone().or_else(|| style.padding.clone()),
647            minimum_size: self
648                .minimum_size
649                .clone()
650                .or_else(|| style.minimum_size.clone()),
651            fixed_size: self.fixed_size.clone().or_else(|| style.fixed_size.clone()),
652            maximum_size: self
653                .maximum_size
654                .clone()
655                .or_else(|| style.maximum_size.clone()),
656            icon_color: self.icon_color.clone().or_else(|| style.icon_color.clone()),
657            icon_size: self.icon_size.clone().or_else(|| style.icon_size.clone()),
658            icon_alignment: self.icon_alignment.or(style.icon_alignment),
659            side: self.side.clone().or_else(|| style.side.clone()),
660            shape: self.shape.clone().or_else(|| style.shape.clone()),
661            mouse_cursor: self
662                .mouse_cursor
663                .clone()
664                .or_else(|| style.mouse_cursor.clone()),
665            visual_density: self.visual_density.or(style.visual_density),
666            tap_target_size: self.tap_target_size.or(style.tap_target_size),
667            animation_duration: self.animation_duration.or(style.animation_duration),
668            enable_feedback: self.enable_feedback.or(style.enable_feedback),
669            alignment: self.alignment.or(style.alignment),
670            splash_factory: self
671                .splash_factory
672                .clone()
673                .or_else(|| style.splash_factory.clone()),
674            background_builder: self
675                .background_builder
676                .clone()
677                .or_else(|| style.background_builder.clone()),
678            foreground_builder: self
679                .foreground_builder
680                .clone()
681                .or_else(|| style.foreground_builder.clone()),
682            size_variant: self.size_variant.or(style.size_variant),
683            icon_button_width: self.icon_button_width.or(style.icon_button_width),
684            shape_variant: self.shape_variant.or(style.shape_variant),
685        }
686    }
687
688    /// Linearly interpolate between two [`ButtonStyle`]s.
689    pub fn lerp(a: Option<&ButtonStyle>, b: Option<&ButtonStyle>, t: f64) -> Option<ButtonStyle> {
690        match (a, b) {
691            (None, None) => return None,
692            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
693            _ => {}
694        }
695        Some(ButtonStyle {
696            text_style: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
697                a.and_then(|a| a.text_style.clone()),
698                b.and_then(|b| b.text_style.clone()),
699                t,
700                |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
701            ),
702            background_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
703                a.and_then(|a| a.background_color.clone()),
704                b.and_then(|b| b.background_color.clone()),
705                t,
706                Color::lerp,
707            ),
708            foreground_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
709                a.and_then(|a| a.foreground_color.clone()),
710                b.and_then(|b| b.foreground_color.clone()),
711                t,
712                Color::lerp,
713            ),
714            overlay_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
715                a.and_then(|a| a.overlay_color.clone()),
716                b.and_then(|b| b.overlay_color.clone()),
717                t,
718                Color::lerp,
719            ),
720            shadow_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
721                a.and_then(|a| a.shadow_color.clone()),
722                b.and_then(|b| b.shadow_color.clone()),
723                t,
724                Color::lerp,
725            ),
726            surface_tint_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
727                a.and_then(|a| a.surface_tint_color.clone()),
728                b.and_then(|b| b.surface_tint_color.clone()),
729                t,
730                Color::lerp,
731            ),
732            elevation: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
733                a.and_then(|a| a.elevation.clone()),
734                b.and_then(|b| b.elevation.clone()),
735                t,
736                lerp_double,
737            ),
738            padding: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
739                a.and_then(|a| a.padding.clone()),
740                b.and_then(|b| b.padding.clone()),
741                t,
742                EdgeInsetsGeometry::lerp,
743            ),
744            minimum_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
745                a.and_then(|a| a.minimum_size.clone()),
746                b.and_then(|b| b.minimum_size.clone()),
747                t,
748                Size::lerp,
749            ),
750            fixed_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
751                a.and_then(|a| a.fixed_size.clone()),
752                b.and_then(|b| b.fixed_size.clone()),
753                t,
754                Size::lerp,
755            ),
756            maximum_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
757                a.and_then(|a| a.maximum_size.clone()),
758                b.and_then(|b| b.maximum_size.clone()),
759                t,
760                Size::lerp,
761            ),
762            icon_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
763                a.and_then(|a| a.icon_color.clone()),
764                b.and_then(|b| b.icon_color.clone()),
765                t,
766                Color::lerp,
767            ),
768            icon_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
769                a.and_then(|a| a.icon_size.clone()),
770                b.and_then(|b| b.icon_size.clone()),
771                t,
772                lerp_double,
773            ),
774            icon_alignment: if t < 0.5 {
775                a.and_then(|a| a.icon_alignment)
776            } else {
777                b.and_then(|b| b.icon_alignment)
778            },
779            side: WidgetStateBorderSide::lerp(
780                a.and_then(|a| a.side.clone()),
781                b.and_then(|b| b.side.clone()),
782                t,
783            ),
784            shape: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
785                a.and_then(|a| a.shape.clone()),
786                b.and_then(|b| b.shape.clone()),
787                t,
788                |a, b, t| OutlinedBorderRef::lerp(a.as_ref(), b.as_ref(), t),
789            ),
790            mouse_cursor: if t < 0.5 {
791                a.and_then(|a| a.mouse_cursor.clone())
792            } else {
793                b.and_then(|b| b.mouse_cursor.clone())
794            },
795            visual_density: if t < 0.5 {
796                a.and_then(|a| a.visual_density)
797            } else {
798                b.and_then(|b| b.visual_density)
799            },
800            tap_target_size: if t < 0.5 {
801                a.and_then(|a| a.tap_target_size)
802            } else {
803                b.and_then(|b| b.tap_target_size)
804            },
805            animation_duration: if t < 0.5 {
806                a.and_then(|a| a.animation_duration)
807            } else {
808                b.and_then(|b| b.animation_duration)
809            },
810            enable_feedback: if t < 0.5 {
811                a.and_then(|a| a.enable_feedback)
812            } else {
813                b.and_then(|b| b.enable_feedback)
814            },
815            alignment: AlignmentGeometry::lerp(
816                a.and_then(|a| a.alignment),
817                b.and_then(|b| b.alignment),
818                t,
819            ),
820            splash_factory: if t < 0.5 {
821                a.and_then(|a| a.splash_factory.clone())
822            } else {
823                b.and_then(|b| b.splash_factory.clone())
824            },
825            background_builder: if t < 0.5 {
826                a.and_then(|a| a.background_builder.clone())
827            } else {
828                b.and_then(|b| b.background_builder.clone())
829            },
830            foreground_builder: if t < 0.5 {
831                a.and_then(|a| a.foreground_builder.clone())
832            } else {
833                b.and_then(|b| b.foreground_builder.clone())
834            },
835            size_variant: if t < 0.5 {
836                a.and_then(|a| a.size_variant)
837            } else {
838                b.and_then(|b| b.size_variant)
839            },
840            icon_button_width: if t < 0.5 {
841                a.and_then(|a| a.icon_button_width)
842            } else {
843                b.and_then(|b| b.icon_button_width)
844            },
845            shape_variant: if t < 0.5 {
846                a.and_then(|a| a.shape_variant)
847            } else {
848                b.and_then(|b| b.shape_variant)
849            },
850        })
851    }
852}
853
854impl PartialEq for ButtonStyle {
855    fn eq(&self, other: &ButtonStyle) -> bool {
856        if std::ptr::eq(self, other) {
857            return true;
858        }
859        other.text_style == self.text_style
860            && other.background_color == self.background_color
861            && other.foreground_color == self.foreground_color
862            && other.overlay_color == self.overlay_color
863            && other.shadow_color == self.shadow_color
864            && other.surface_tint_color == self.surface_tint_color
865            && other.elevation == self.elevation
866            && other.padding == self.padding
867            && other.minimum_size == self.minimum_size
868            && other.fixed_size == self.fixed_size
869            && other.maximum_size == self.maximum_size
870            && other.icon_color == self.icon_color
871            && other.icon_size == self.icon_size
872            && other.icon_alignment == self.icon_alignment
873            && other.side == self.side
874            && other.shape == self.shape
875            && other.mouse_cursor == self.mouse_cursor
876            && other.visual_density == self.visual_density
877            && other.tap_target_size == self.tap_target_size
878            && other.animation_duration == self.animation_duration
879            && other.enable_feedback == self.enable_feedback
880            && other.alignment == self.alignment
881            && other.splash_factory == self.splash_factory
882            && other.background_builder == self.background_builder
883            && other.foreground_builder == self.foreground_builder
884            && other.size_variant == self.size_variant
885            && other.icon_button_width == self.icon_button_width
886            && other.shape_variant == self.shape_variant
887    }
888}
889
890impl Debug for ButtonStyle {
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        let mut properties = f.debug_struct("ButtonStyle");
893        macro_rules! property {
894            ($($field:ident),* $(,)?) => {
895                $(
896                    if let Some(value) = &self.$field {
897                        properties.field(stringify!($field), value);
898                    }
899                )*
900            };
901        }
902        property!(
903            text_style,
904            background_color,
905            foreground_color,
906            overlay_color,
907            shadow_color,
908            surface_tint_color,
909            elevation,
910            padding,
911            minimum_size,
912            fixed_size,
913            maximum_size,
914            icon_color,
915            icon_size,
916            icon_alignment,
917            side,
918            shape,
919            mouse_cursor,
920            visual_density,
921            tap_target_size,
922            animation_duration,
923            enable_feedback,
924            alignment,
925            background_builder,
926            foreground_builder,
927            size_variant,
928            icon_button_width,
929            shape_variant,
930        );
931        properties.finish()
932    }
933}
934
935impl waft_foundation::Diagnosticable for ButtonStyle {
936    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
937        properties.add(
938            DiagnosticsProperty::<String>::new(
939                "textStyle",
940                self.text_style
941                    .as_deref()
942                    .map(|property| property.to_string()),
943            )
944            .default_value(None),
945        );
946        properties.add(
947            DiagnosticsProperty::<String>::new(
948                "backgroundColor",
949                self.background_color
950                    .as_deref()
951                    .map(|property| property.to_string()),
952            )
953            .default_value(None),
954        );
955        properties.add(
956            DiagnosticsProperty::<String>::new(
957                "foregroundColor",
958                self.foreground_color
959                    .as_deref()
960                    .map(|property| property.to_string()),
961            )
962            .default_value(None),
963        );
964        properties.add(
965            DiagnosticsProperty::<String>::new(
966                "overlayColor",
967                self.overlay_color
968                    .as_deref()
969                    .map(|property| property.to_string()),
970            )
971            .default_value(None),
972        );
973        properties.add(
974            DiagnosticsProperty::<String>::new(
975                "shadowColor",
976                self.shadow_color
977                    .as_deref()
978                    .map(|property| property.to_string()),
979            )
980            .default_value(None),
981        );
982        properties.add(
983            DiagnosticsProperty::<String>::new(
984                "surfaceTintColor",
985                self.surface_tint_color
986                    .as_deref()
987                    .map(|property| property.to_string()),
988            )
989            .default_value(None),
990        );
991        properties.add(
992            DiagnosticsProperty::<String>::new(
993                "elevation",
994                self.elevation
995                    .as_deref()
996                    .map(|property| property.to_string()),
997            )
998            .default_value(None),
999        );
1000        properties.add(
1001            DiagnosticsProperty::<String>::new(
1002                "padding",
1003                self.padding.as_deref().map(|property| property.to_string()),
1004            )
1005            .default_value(None),
1006        );
1007        properties.add(
1008            DiagnosticsProperty::<String>::new(
1009                "minimumSize",
1010                self.minimum_size
1011                    .as_deref()
1012                    .map(|property| property.to_string()),
1013            )
1014            .default_value(None),
1015        );
1016        properties.add(
1017            DiagnosticsProperty::<String>::new(
1018                "fixedSize",
1019                self.fixed_size
1020                    .as_deref()
1021                    .map(|property| property.to_string()),
1022            )
1023            .default_value(None),
1024        );
1025        properties.add(
1026            DiagnosticsProperty::<String>::new(
1027                "maximumSize",
1028                self.maximum_size
1029                    .as_deref()
1030                    .map(|property| property.to_string()),
1031            )
1032            .default_value(None),
1033        );
1034        properties.add(
1035            DiagnosticsProperty::<String>::new(
1036                "iconColor",
1037                self.icon_color
1038                    .as_deref()
1039                    .map(|property| property.to_string()),
1040            )
1041            .default_value(None),
1042        );
1043        properties.add(
1044            DiagnosticsProperty::<String>::new(
1045                "iconSize",
1046                self.icon_size
1047                    .as_deref()
1048                    .map(|property| property.to_string()),
1049            )
1050            .default_value(None),
1051        );
1052        properties.add(
1053            EnumProperty::<IconAlignment>::new("iconAlignment", self.icon_alignment)
1054                .default_value(None),
1055        );
1056        properties.add(
1057            DiagnosticsProperty::<String>::new(
1058                "side",
1059                self.side.as_deref().map(|property| property.to_string()),
1060            )
1061            .default_value(None),
1062        );
1063        properties.add(
1064            DiagnosticsProperty::<String>::new(
1065                "shape",
1066                self.shape.as_deref().map(|property| property.to_string()),
1067            )
1068            .default_value(None),
1069        );
1070        properties.add(
1071            DiagnosticsProperty::<String>::new(
1072                "mouseCursor",
1073                self.mouse_cursor
1074                    .as_deref()
1075                    .map(|property| property.to_string()),
1076            )
1077            .default_value(None),
1078        );
1079        properties.add(
1080            DiagnosticsProperty::<VisualDensity>::new("visualDensity", self.visual_density)
1081                .default_value(None),
1082        );
1083        properties.add(
1084            EnumProperty::<MaterialTapTargetSize>::new("tapTargetSize", self.tap_target_size)
1085                .default_value(None),
1086        );
1087        properties.add(
1088            DiagnosticsProperty::<SignedDuration>::new(
1089                "animationDuration",
1090                self.animation_duration.map(SignedDuration::from),
1091            )
1092            .default_value(None),
1093        );
1094        properties.add(
1095            DiagnosticsProperty::<bool>::new("enableFeedback", self.enable_feedback)
1096                .default_value(None),
1097        );
1098        properties.add(
1099            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", self.alignment)
1100                .default_value(None),
1101        );
1102        properties.add(
1103            DiagnosticsProperty::<String>::new(
1104                "backgroundBuilder",
1105                self.background_builder
1106                    .as_ref()
1107                    .map(|builder| builder.to_string()),
1108            )
1109            .default_value(None),
1110        );
1111        properties.add(
1112            DiagnosticsProperty::<String>::new(
1113                "foregroundBuilder",
1114                self.foreground_builder
1115                    .as_ref()
1116                    .map(|builder| builder.to_string()),
1117            )
1118            .default_value(None),
1119        );
1120    }
1121}
1122
1123impl fmt::Display for ButtonStyle {
1124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
1126    }
1127}
1128
1129impl fmt::Display for ButtonLayerBuilder {
1130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131        f.write_str("Closure: (BuildContext, Set<WidgetState>, Widget?) => Widget")
1132    }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137    use waft_painting::{BorderStyle, StadiumBorder};
1138    use waft_services::SystemMouseCursors;
1139    use waft_widgets::{WidgetState, WidgetStatePropertyAll};
1140
1141    use super::*;
1142
1143    fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
1144        Rc::new(WidgetStatePropertyAll::new(Some(value)))
1145    }
1146
1147    // button_style_test.dart 'ButtonStyle copyWith, merge, ==, hashCode basics'.
1148    #[test]
1149    fn an_empty_style_equals_its_copy_and_its_merge_with_an_empty_style() {
1150        assert_eq!(ButtonStyle::new(), ButtonStyle::new().copy_with());
1151        assert_eq!(
1152            ButtonStyle::new().merge(Some(&ButtonStyle::new())),
1153            ButtonStyle::new()
1154        );
1155    }
1156
1157    // button_style_test.dart 'ButtonStyle lerp special cases'.
1158    #[test]
1159    fn lerp_of_nothing_is_nothing_and_of_one_style_with_itself_is_that_style() {
1160        assert!(ButtonStyle::lerp(None, None, 0.0).is_none());
1161        let data = ButtonStyle::new().elevation(all(1.0));
1162        assert_eq!(ButtonStyle::lerp(Some(&data), Some(&data), 0.5), Some(data));
1163    }
1164
1165    // button_style_test.dart 'ButtonStyle defaults'.
1166    #[test]
1167    fn every_property_of_a_new_style_is_null() {
1168        let style = ButtonStyle::new();
1169        assert!(style.text_style.is_none());
1170        assert!(style.background_color.is_none());
1171        assert!(style.foreground_color.is_none());
1172        assert!(style.overlay_color.is_none());
1173        assert!(style.shadow_color.is_none());
1174        assert!(style.surface_tint_color.is_none());
1175        assert!(style.elevation.is_none());
1176        assert!(style.padding.is_none());
1177        assert!(style.minimum_size.is_none());
1178        assert!(style.fixed_size.is_none());
1179        assert!(style.maximum_size.is_none());
1180        assert!(style.icon_color.is_none());
1181        assert!(style.icon_size.is_none());
1182        assert!(style.side.is_none());
1183        assert!(style.shape.is_none());
1184        assert!(style.mouse_cursor.is_none());
1185        assert!(style.visual_density.is_none());
1186        assert!(style.tap_target_size.is_none());
1187        assert!(style.animation_duration.is_none());
1188        assert!(style.enable_feedback.is_none());
1189        assert!(style.alignment.is_none());
1190        assert!(style.splash_factory.is_none());
1191        assert!(style.background_builder.is_none());
1192        assert!(style.foreground_builder.is_none());
1193        assert!(style.size_variant.is_none());
1194        assert!(style.icon_button_width.is_none());
1195        assert!(style.shape_variant.is_none());
1196    }
1197
1198    // button_style_test.dart 'ButtonStyle copyWith, merge'.
1199    #[test]
1200    fn a_style_equals_an_empty_copy_given_every_field_and_an_empty_style_merged_with_it() {
1201        let text_style = all(TextStyle::new().font_size(10.0));
1202        let background_color = all(Color::new(0xfffffff1));
1203        let foreground_color = all(Color::new(0xfffffff2));
1204        let overlay_color = all(Color::new(0xfffffff3));
1205        let shadow_color = all(Color::new(0xfffffff4));
1206        let surface_tint_color = all(Color::new(0xfffffff5));
1207        let elevation = all(1.0);
1208        let padding = all(EdgeInsetsGeometry::all(1.0));
1209        let minimum_size = all(Size::new(1.0, 2.0));
1210        let fixed_size = all(Size::new(3.0, 4.0));
1211        let maximum_size = all(Size::new(5.0, 6.0));
1212        let icon_color = all(Color::new(0xfffffff6));
1213        let icon_size = all(48.0);
1214        let side = all(BorderSide::default());
1215        let shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>> = Rc::new(
1216            WidgetStatePropertyAll::new(Some(OutlinedBorderRef::new(StadiumBorder::default()))),
1217        );
1218        let mouse_cursor = all::<MouseCursorRef>(SystemMouseCursors::FORBIDDEN.into());
1219        let visual_density = VisualDensity::COMPACT;
1220        let tap_target_size = MaterialTapTargetSize::ShrinkWrap;
1221        let animation_duration = Duration::from_secs(1);
1222        let enable_feedback = true;
1223        let size_variant = ButtonSizeVariant::Small;
1224        let icon_button_width = IconButtonWidthVariant::Standard;
1225        let shape_variant = ButtonShapeVariant::Round;
1226
1227        let style = ButtonStyle::new()
1228            .text_style(Rc::clone(&text_style))
1229            .background_color(Rc::clone(&background_color))
1230            .foreground_color(Rc::clone(&foreground_color))
1231            .overlay_color(Rc::clone(&overlay_color))
1232            .shadow_color(Rc::clone(&shadow_color))
1233            .surface_tint_color(Rc::clone(&surface_tint_color))
1234            .elevation(Rc::clone(&elevation))
1235            .padding(Rc::clone(&padding))
1236            .minimum_size(Rc::clone(&minimum_size))
1237            .fixed_size(Rc::clone(&fixed_size))
1238            .maximum_size(Rc::clone(&maximum_size))
1239            .icon_color(Rc::clone(&icon_color))
1240            .icon_size(Rc::clone(&icon_size))
1241            .side(Rc::clone(&side))
1242            .shape(Rc::clone(&shape))
1243            .mouse_cursor(Rc::clone(&mouse_cursor))
1244            .visual_density(visual_density)
1245            .tap_target_size(tap_target_size)
1246            .animation_duration(animation_duration)
1247            .enable_feedback(enable_feedback)
1248            .size_variant(size_variant)
1249            .icon_button_width(icon_button_width)
1250            .shape_variant(shape_variant);
1251
1252        assert_eq!(
1253            style,
1254            ButtonStyle::new()
1255                .copy_with()
1256                .text_style(text_style)
1257                .background_color(background_color)
1258                .foreground_color(foreground_color)
1259                .overlay_color(overlay_color)
1260                .shadow_color(shadow_color)
1261                .surface_tint_color(surface_tint_color)
1262                .elevation(elevation)
1263                .padding(padding)
1264                .minimum_size(minimum_size)
1265                .fixed_size(fixed_size)
1266                .maximum_size(maximum_size)
1267                .icon_color(icon_color)
1268                .icon_size(icon_size)
1269                .side(side)
1270                .shape(shape)
1271                .mouse_cursor(mouse_cursor)
1272                .visual_density(visual_density)
1273                .tap_target_size(tap_target_size)
1274                .animation_duration(animation_duration)
1275                .enable_feedback(enable_feedback)
1276                .size_variant(size_variant)
1277                .icon_button_width(icon_button_width)
1278                .shape_variant(shape_variant)
1279        );
1280
1281        assert_eq!(style, ButtonStyle::new().merge(Some(&style)));
1282
1283        assert_eq!(style.copy_with(), style.merge(Some(&ButtonStyle::new())));
1284    }
1285
1286    // button_style_test.dart 'ButtonStyle.lerp selects discrete variants at midpoint'.
1287    #[test]
1288    fn lerp_switches_the_discrete_variants_at_the_midpoint() {
1289        let a = ButtonStyle::new()
1290            .size_variant(ButtonSizeVariant::XSmall)
1291            .icon_button_width(IconButtonWidthVariant::Narrow)
1292            .shape_variant(ButtonShapeVariant::Round);
1293        let b = ButtonStyle::new()
1294            .size_variant(ButtonSizeVariant::XLarge)
1295            .icon_button_width(IconButtonWidthVariant::Wide)
1296            .shape_variant(ButtonShapeVariant::Square);
1297
1298        let before = ButtonStyle::lerp(Some(&a), Some(&b), 0.49).expect("two styles");
1299        assert_eq!(before.size_variant, Some(ButtonSizeVariant::XSmall));
1300        assert_eq!(
1301            before.icon_button_width,
1302            Some(IconButtonWidthVariant::Narrow)
1303        );
1304        assert_eq!(before.shape_variant, Some(ButtonShapeVariant::Round));
1305        let at = ButtonStyle::lerp(Some(&a), Some(&b), 0.5).expect("two styles");
1306        assert_eq!(at.size_variant, Some(ButtonSizeVariant::XLarge));
1307        assert_eq!(at.icon_button_width, Some(IconButtonWidthVariant::Wide));
1308        assert_eq!(at.shape_variant, Some(ButtonShapeVariant::Square));
1309    }
1310
1311    // button_style_test.dart 'ButtonStyle.lerp BorderSide'.
1312    #[test]
1313    fn lerp_fades_a_missing_side_from_or_to_an_empty_one() {
1314        assert!(ButtonStyle::lerp(None, None, 0.0).is_none());
1315        assert!(ButtonStyle::lerp(None, None, 0.5).is_none());
1316        assert!(ButtonStyle::lerp(None, None, 1.0).is_none());
1317
1318        let black_side = BorderSide::default();
1319        let white_side = BorderSide {
1320            color: Color::new(0xFFFFFFFF),
1321            ..BorderSide::default()
1322        };
1323        let empty_black_side = BorderSide {
1324            width: 0.0,
1325            color: Color::new(0x00000000),
1326            ..BorderSide::default()
1327        };
1328
1329        let black_style = ButtonStyle::new().side(all(black_side));
1330        let white_style = ButtonStyle::new().side(all(white_side));
1331
1332        // WidgetStatePropertyAll(value) properties resolve to value
1333        // for any set of states.
1334        let states = WidgetStates::new();
1335        let side = |a: Option<&ButtonStyle>, b: Option<&ButtonStyle>, t: f64| {
1336            ButtonStyle::lerp(a, b, t)
1337                .and_then(|style| style.side)
1338                .and_then(|side| side.resolve(&states))
1339        };
1340
1341        assert_eq!(
1342            side(Some(&black_style), Some(&black_style), 0.0),
1343            Some(black_side)
1344        );
1345        assert_eq!(
1346            side(Some(&black_style), Some(&black_style), 0.5),
1347            Some(black_side)
1348        );
1349        assert_eq!(
1350            side(Some(&black_style), Some(&black_style), 1.0),
1351            Some(black_side)
1352        );
1353
1354        assert_eq!(side(Some(&black_style), None, 0.0), Some(black_side));
1355        assert_eq!(
1356            side(Some(&black_style), None, 0.5),
1357            Some(BorderSide::lerp(black_side, empty_black_side, 0.5))
1358        );
1359        assert_eq!(side(Some(&black_style), None, 1.0), Some(empty_black_side));
1360
1361        assert_eq!(side(None, Some(&black_style), 0.0), Some(empty_black_side));
1362        assert_eq!(
1363            side(None, Some(&black_style), 0.5),
1364            Some(BorderSide::lerp(empty_black_side, black_side, 0.5))
1365        );
1366        assert_eq!(side(None, Some(&black_style), 1.0), Some(black_side));
1367
1368        assert_eq!(
1369            side(Some(&black_style), Some(&white_style), 0.0),
1370            Some(black_side)
1371        );
1372        assert_eq!(
1373            side(Some(&black_style), Some(&white_style), 0.5),
1374            Some(BorderSide::lerp(black_side, white_side, 0.5))
1375        );
1376        assert_eq!(
1377            side(Some(&black_style), Some(&white_style), 1.0),
1378            Some(white_side)
1379        );
1380    }
1381
1382    #[test]
1383    fn lerp_of_nullable_properties_resolves_to_the_lerped_values() {
1384        let a = ButtonStyle::new()
1385            .elevation(all(2.0))
1386            .shape(Rc::new(WidgetStatePropertyAll::new(Some(
1387                OutlinedBorderRef::new(StadiumBorder::default()),
1388            ))));
1389        let b = ButtonStyle::new().elevation(<dyn WidgetStateProperty<Option<f64>>>::resolve_with(
1390            |states| states.contains(&WidgetState::Pressed).then_some(6.0),
1391        ));
1392        let lerped = ButtonStyle::lerp(Some(&a), Some(&b), 0.5).expect("two styles");
1393        let elevation = lerped.elevation.expect("both sides");
1394        assert_eq!(elevation.resolve(&WidgetStates::new()), Some(1.0));
1395        assert_eq!(
1396            elevation.resolve(&WidgetStates::from([WidgetState::Pressed])),
1397            Some(4.0)
1398        );
1399        let shape = lerped
1400            .shape
1401            .expect("one side")
1402            .resolve(&WidgetStates::new())
1403            .expect("a shape scaled from the stadium");
1404        assert!(shape.as_any().downcast_ref::<StadiumBorder>().is_some());
1405    }
1406
1407    // button_style_test.dart 'Default ButtonStyle debugFillProperties'.
1408    #[test]
1409    fn a_new_style_describes_no_property() {
1410        assert_eq!(format!("{:?}", ButtonStyle::new()), "ButtonStyle");
1411    }
1412
1413    // button_style_test.dart 'ButtonStyle debugFillProperties'.
1414    #[test]
1415    fn a_style_describes_the_properties_it_sets_in_dart_order() {
1416        let text_style = all(TextStyle::new().font_size(10.0));
1417        let background_color = all(Color::new(0xfffffff1));
1418        let foreground_color = all(Color::new(0xfffffff2));
1419        let overlay_color = all(Color::new(0xfffffff3));
1420        let shadow_color = all(Color::new(0xfffffff4));
1421        let surface_tint_color = all(Color::new(0xfffffff5));
1422        let elevation = all(1.5);
1423        let padding = all(EdgeInsetsGeometry::all(1.0));
1424        let minimum_size = all(Size::new(1.0, 2.0));
1425        let side = all(BorderSide::new(
1426            Color::new(0xfffffff6),
1427            4.0,
1428            BorderStyle::Solid,
1429            BorderSide::STROKE_ALIGN_INSIDE,
1430        ));
1431        let maximum_size = all(Size::new(100.0, 200.0));
1432        let icon_color = all(Color::new(0xfffffff6));
1433        let icon_size = all(48.1);
1434        let shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>> = Rc::new(
1435            WidgetStatePropertyAll::new(Some(OutlinedBorderRef::new(StadiumBorder::default()))),
1436        );
1437        let mouse_cursor = all::<MouseCursorRef>(SystemMouseCursors::FORBIDDEN.into());
1438        let style = ButtonStyle::new()
1439            .text_style(text_style.clone())
1440            .background_color(background_color.clone())
1441            .foreground_color(foreground_color.clone())
1442            .overlay_color(overlay_color.clone())
1443            .shadow_color(shadow_color.clone())
1444            .surface_tint_color(surface_tint_color.clone())
1445            .elevation(elevation.clone())
1446            .padding(padding.clone())
1447            .minimum_size(minimum_size.clone())
1448            .side(side.clone())
1449            .maximum_size(maximum_size.clone())
1450            .icon_color(icon_color.clone())
1451            .icon_size(icon_size.clone())
1452            .shape(shape.clone())
1453            .mouse_cursor(mouse_cursor.clone())
1454            .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1455            .animation_duration(Duration::from_secs(1))
1456            .enable_feedback(true)
1457            .size_variant(ButtonSizeVariant::Small)
1458            .icon_button_width(IconButtonWidthVariant::Standard)
1459            .shape_variant(ButtonShapeVariant::Round);
1460
1461        let description = format!("{style:?}");
1462        let expected = [
1463            format!("text_style: {text_style:?}"),
1464            format!("background_color: {background_color:?}"),
1465            format!("foreground_color: {foreground_color:?}"),
1466            format!("overlay_color: {overlay_color:?}"),
1467            format!("shadow_color: {shadow_color:?}"),
1468            format!("surface_tint_color: {surface_tint_color:?}"),
1469            format!("elevation: {elevation:?}"),
1470            format!("padding: {padding:?}"),
1471            format!("minimum_size: {minimum_size:?}"),
1472            format!("maximum_size: {maximum_size:?}"),
1473            format!("icon_color: {icon_color:?}"),
1474            format!("icon_size: {icon_size:?}"),
1475            format!("side: {side:?}"),
1476            format!("shape: {shape:?}"),
1477            format!("mouse_cursor: {mouse_cursor:?}"),
1478            "tap_target_size: ShrinkWrap".to_owned(),
1479            "animation_duration: 1s".to_owned(),
1480            "enable_feedback: true".to_owned(),
1481            "size_variant: Small".to_owned(),
1482            "icon_button_width: Standard".to_owned(),
1483            "shape_variant: Round".to_owned(),
1484        ];
1485        assert_eq!(
1486            description,
1487            format!("ButtonStyle {{ {} }}", expected.join(", "))
1488        );
1489    }
1490    // button_style_test.dart 'Default ButtonStyle debugFillProperties'.
1491    #[test]
1492    fn a_new_style_has_no_described_property() {
1493        assert_eq!(
1494            waft_widgets::testing::describe_properties(|properties| {
1495                waft_foundation::Diagnosticable::debug_fill_properties(
1496                    &ButtonStyle::new(),
1497                    properties,
1498                )
1499            }),
1500            Vec::<String>::new()
1501        );
1502    }
1503
1504    // button_style_test.dart 'ButtonStyle debugFillProperties'.
1505    #[test]
1506    fn an_assigned_style_lists_every_property_in_dart_order() {
1507        let style = ButtonStyle::new()
1508            .text_style(Rc::new(WidgetStatePropertyAll::new(Some(
1509                TextStyle::new().font_size(10.0),
1510            ))))
1511            .background_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1512                0xfffffff1,
1513            )))))
1514            .foreground_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1515                0xfffffff2,
1516            )))))
1517            .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1518                0xfffffff3,
1519            )))))
1520            .shadow_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1521                0xfffffff4,
1522            )))))
1523            .surface_tint_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1524                0xfffffff5,
1525            )))))
1526            .elevation(Rc::new(WidgetStatePropertyAll::new(Some(1.5))))
1527            .padding(Rc::new(WidgetStatePropertyAll::new(Some(
1528                EdgeInsetsGeometry::all(1.0),
1529            ))))
1530            .minimum_size(Rc::new(WidgetStatePropertyAll::new(Some(Size::new(
1531                1.0, 2.0,
1532            )))))
1533            .maximum_size(Rc::new(WidgetStatePropertyAll::new(Some(Size::new(
1534                100.0, 200.0,
1535            )))))
1536            .icon_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1537                0xfffffff6,
1538            )))))
1539            .icon_size(Rc::new(WidgetStatePropertyAll::new(Some(48.1))))
1540            .side(Rc::new(WidgetStatePropertyAll::new(Some(BorderSide::new(
1541                Color::new(0xfffffff6),
1542                4.0,
1543                BorderStyle::Solid,
1544                1.0,
1545            )))))
1546            .shape(Rc::new(WidgetStatePropertyAll::new(Some(
1547                OutlinedBorderRef::new(StadiumBorder::new(BorderSide::NONE)),
1548            ))))
1549            .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(
1550                SystemMouseCursors::FORBIDDEN.into(),
1551            ))))
1552            .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1553            .animation_duration(Duration::from_secs(1))
1554            .enable_feedback(true);
1555        assert_eq!(
1556            waft_widgets::testing::describe_properties(|properties| {
1557                waft_foundation::Diagnosticable::debug_fill_properties(&style, properties)
1558            }),
1559            [
1560                format!(
1561                    "textStyle: WidgetStatePropertyAll({})",
1562                    TextStyle::new().font_size(10.0)
1563                ),
1564                format!(
1565                    "backgroundColor: WidgetStatePropertyAll({})",
1566                    Color::new(0xfffffff1)
1567                ),
1568                format!(
1569                    "foregroundColor: WidgetStatePropertyAll({})",
1570                    Color::new(0xfffffff2)
1571                ),
1572                format!(
1573                    "overlayColor: WidgetStatePropertyAll({})",
1574                    Color::new(0xfffffff3)
1575                ),
1576                format!(
1577                    "shadowColor: WidgetStatePropertyAll({})",
1578                    Color::new(0xfffffff4)
1579                ),
1580                format!(
1581                    "surfaceTintColor: WidgetStatePropertyAll({})",
1582                    Color::new(0xfffffff5)
1583                ),
1584                "elevation: WidgetStatePropertyAll(1.5)".to_string(),
1585                "padding: WidgetStatePropertyAll(EdgeInsets.all(1.0))".to_string(),
1586                "minimumSize: WidgetStatePropertyAll(Size(1.0, 2.0))".to_string(),
1587                "maximumSize: WidgetStatePropertyAll(Size(100.0, 200.0))".to_string(),
1588                format!(
1589                    "iconColor: WidgetStatePropertyAll({})",
1590                    Color::new(0xfffffff6)
1591                ),
1592                "iconSize: WidgetStatePropertyAll(48.1)".to_string(),
1593                format!(
1594                    "side: WidgetStatePropertyAll(BorderSide(color: {}, width: 4.0, strokeAlign: 1.0))",
1595                    Color::new(0xfffffff6)
1596                ),
1597                "shape: WidgetStatePropertyAll(StadiumBorder(BorderSide(width: 0.0, style: none)))"
1598                    .to_string(),
1599                "mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(forbidden))".to_string(),
1600                "tapTargetSize: shrinkWrap".to_string(),
1601                "animationDuration: 0:00:01.000000".to_string(),
1602                "enableFeedback: true".to_string(),
1603            ]
1604        );
1605    }
1606
1607    // Flutter's "Default ButtonStyle debugFillProperties".
1608    #[test]
1609    fn a_button_style_describes_nothing_by_default() {
1610        assert_eq!(
1611            waft_widgets::testing::describe_properties(|properties| {
1612                waft_foundation::Diagnosticable::debug_fill_properties(
1613                    &ButtonStyle::new(),
1614                    properties,
1615                )
1616            }),
1617            Vec::<String>::new()
1618        );
1619    }
1620}