Skip to main content

waft_material/
material_button.rs

1//! Flutter counterpart: material_ui's `material_button.dart`.
2
3use std::fmt;
4use std::time::Duration;
5
6use waft_embedder::{Brightness, Clip, Color};
7use waft_foundation::{
8    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Listener, ValueChanged,
9};
10use waft_painting::{ColorProperty, EdgeInsetsGeometry, ShapeBorderRef};
11use waft_services::MouseCursorRef;
12use waft_widgets::{BuildContext, FocusNodeRef, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
13
14use crate::button::RawMaterialButton;
15use crate::button_theme::{ButtonTextTheme, ButtonTheme};
16use crate::theme::Theme;
17use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
18
19/// A Material Design button.
20///
21/// To create a custom Material button consider using `TextButton`, `ElevatedButton`, or
22/// `OutlinedButton`.
23///
24/// The [`elevation`](Self::elevation), [`hover_elevation`](Self::hover_elevation),
25/// [`focus_elevation`](Self::focus_elevation), [`highlight_elevation`](Self::highlight_elevation)
26/// and [`disabled_elevation`](Self::disabled_elevation) arguments must be non-negative, if
27/// specified.
28pub struct MaterialButton {
29    pub key: Option<KeyRef>,
30    /// The callback that is called when the button is tapped or otherwise activated.
31    ///
32    /// If this callback and [`on_long_press`](Self::on_long_press) are null, then the button
33    /// will be disabled.
34    pub on_pressed: Option<Listener>,
35    /// The callback that is called when the button is long-pressed.
36    pub on_long_press: Option<Listener>,
37    /// Called by the underlying `InkWell` widget's `onHighlightChanged` callback.
38    pub on_highlight_changed: Option<ValueChanged<bool>>,
39    /// The cursor for a mouse pointer when it enters or is hovering over the button.
40    pub mouse_cursor: Option<MouseCursorRef>,
41    /// Defines the button's base colors, and the defaults for the button's minimum size,
42    /// internal padding, and shape.
43    pub text_theme: Option<ButtonTextTheme>,
44    /// The color to use for this button's text.
45    pub text_color: Option<Color>,
46    /// The color to use for this button's text when the button is disabled.
47    pub disabled_text_color: Option<Color>,
48    /// The button's fill color while it is in its default (unpressed, enabled) state.
49    pub color: Option<Color>,
50    /// The fill color of the button when the button is disabled.
51    pub disabled_color: Option<Color>,
52    /// The splash color of the button's `InkWell`.
53    pub splash_color: Option<Color>,
54    /// The fill color of the button's `Material` when it has the input focus.
55    pub focus_color: Option<Color>,
56    /// The fill color of the button's `Material` when a pointer is hovering over it.
57    pub hover_color: Option<Color>,
58    /// The highlight color of the button's `InkWell`.
59    pub highlight_color: Option<Color>,
60    /// The z-coordinate at which to place this button relative to its parent.
61    pub elevation: Option<f64>,
62    /// The elevation for the button's `Material` when the button is enabled and a pointer is
63    /// hovering over it.
64    pub hover_elevation: Option<f64>,
65    /// The elevation for the button's `Material` when the button is enabled and has the input
66    /// focus.
67    pub focus_elevation: Option<f64>,
68    /// The elevation for the button's `Material` relative to its parent when the button is
69    /// enabled and pressed.
70    pub highlight_elevation: Option<f64>,
71    /// The elevation for the button's `Material` relative to its parent when the button is not
72    /// enabled.
73    pub disabled_elevation: Option<f64>,
74    /// The theme brightness to use for this button.
75    pub color_brightness: Option<Brightness>,
76    /// The button's label.
77    pub child: Option<WidgetRef>,
78    /// The internal padding for the button's child.
79    pub padding: Option<EdgeInsetsGeometry>,
80    /// Defines how compact the button's layout will be.
81    pub visual_density: Option<VisualDensity>,
82    /// The shape of the button's `Material`.
83    pub shape: Option<waft_painting::ShapeBorderRef>,
84    /// How to clip the button's `Material`.
85    pub clip_behavior: Clip,
86    /// The focus node of the button.
87    pub focus_node: Option<FocusNodeRef>,
88    /// Whether the button will be selected as the initial focus when no other node in its
89    /// scope is currently focused.
90    pub autofocus: bool,
91    /// The duration of animated changes for shape and elevation.
92    pub animation_duration: Option<Duration>,
93    /// Configures the minimum size of the tap target.
94    pub material_tap_target_size: Option<MaterialTapTargetSize>,
95    /// The smallest horizontal extent that the button will occupy.
96    pub min_width: Option<f64>,
97    /// The vertical extent of the button.
98    pub height: Option<f64>,
99    /// Whether detected gestures should provide acoustic and/or haptic feedback.
100    pub enable_feedback: bool,
101}
102
103impl MaterialButton {
104    /// Creates a Material Design button; Dart's optional named arguments are the setters.
105    pub fn new(on_pressed: Option<Listener>) -> MaterialButton {
106        MaterialButton {
107            key: None,
108            on_pressed,
109            on_long_press: None,
110            on_highlight_changed: None,
111            mouse_cursor: None,
112            text_theme: None,
113            text_color: None,
114            disabled_text_color: None,
115            color: None,
116            disabled_color: None,
117            splash_color: None,
118            focus_color: None,
119            hover_color: None,
120            highlight_color: None,
121            elevation: None,
122            hover_elevation: None,
123            focus_elevation: None,
124            highlight_elevation: None,
125            disabled_elevation: None,
126            color_brightness: None,
127            child: None,
128            padding: None,
129            visual_density: None,
130            shape: None,
131            clip_behavior: Clip::None,
132            focus_node: None,
133            autofocus: false,
134            animation_duration: None,
135            material_tap_target_size: None,
136            min_width: None,
137            height: None,
138            enable_feedback: true,
139        }
140    }
141
142    /// Whether the button is enabled or disabled.
143    pub fn enabled(&self) -> bool {
144        self.on_pressed.is_some() || self.on_long_press.is_some()
145    }
146
147    /// Dart `MaterialButton(key:)`.
148    pub fn key(mut self, key: KeyRef) -> MaterialButton {
149        self.key = Some(key);
150        self
151    }
152
153    /// Dart `MaterialButton(onLongPress:)`.
154    pub fn on_long_press(mut self, on_long_press: Listener) -> MaterialButton {
155        self.on_long_press = Some(on_long_press);
156        self
157    }
158
159    /// Dart `MaterialButton(onHighlightChanged:)`.
160    pub fn on_highlight_changed(
161        mut self,
162        on_highlight_changed: ValueChanged<bool>,
163    ) -> MaterialButton {
164        self.on_highlight_changed = Some(on_highlight_changed);
165        self
166    }
167
168    /// Dart `MaterialButton(mouseCursor:)`.
169    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> MaterialButton {
170        self.mouse_cursor = Some(mouse_cursor);
171        self
172    }
173
174    /// Dart `MaterialButton(textTheme:)`.
175    pub fn text_theme(mut self, text_theme: ButtonTextTheme) -> MaterialButton {
176        self.text_theme = Some(text_theme);
177        self
178    }
179
180    /// Dart `MaterialButton(textColor:)`.
181    pub fn text_color(mut self, text_color: Color) -> MaterialButton {
182        self.text_color = Some(text_color);
183        self
184    }
185
186    /// Dart `MaterialButton(disabledTextColor:)`.
187    pub fn disabled_text_color(mut self, disabled_text_color: Color) -> MaterialButton {
188        self.disabled_text_color = Some(disabled_text_color);
189        self
190    }
191
192    /// Dart `MaterialButton(color:)`.
193    pub fn color(mut self, color: Color) -> MaterialButton {
194        self.color = Some(color);
195        self
196    }
197
198    /// Dart `MaterialButton(disabledColor:)`.
199    pub fn disabled_color(mut self, disabled_color: Color) -> MaterialButton {
200        self.disabled_color = Some(disabled_color);
201        self
202    }
203
204    /// Dart `MaterialButton(splashColor:)`.
205    pub fn splash_color(mut self, splash_color: Color) -> MaterialButton {
206        self.splash_color = Some(splash_color);
207        self
208    }
209
210    /// Dart `MaterialButton(focusColor:)`.
211    pub fn focus_color(mut self, focus_color: Color) -> MaterialButton {
212        self.focus_color = Some(focus_color);
213        self
214    }
215
216    /// Dart `MaterialButton(hoverColor:)`.
217    pub fn hover_color(mut self, hover_color: Color) -> MaterialButton {
218        self.hover_color = Some(hover_color);
219        self
220    }
221
222    /// Dart `MaterialButton(highlightColor:)`.
223    pub fn highlight_color(mut self, highlight_color: Color) -> MaterialButton {
224        self.highlight_color = Some(highlight_color);
225        self
226    }
227
228    /// Dart `MaterialButton(colorBrightness:)`.
229    pub fn color_brightness(mut self, color_brightness: Brightness) -> MaterialButton {
230        self.color_brightness = Some(color_brightness);
231        self
232    }
233
234    /// Dart `MaterialButton(elevation:)`.
235    pub fn elevation(mut self, elevation: f64) -> MaterialButton {
236        debug_assert!(elevation >= 0.0);
237        self.elevation = Some(elevation);
238        self
239    }
240
241    /// Dart `MaterialButton(focusElevation:)`.
242    pub fn focus_elevation(mut self, focus_elevation: f64) -> MaterialButton {
243        debug_assert!(focus_elevation >= 0.0);
244        self.focus_elevation = Some(focus_elevation);
245        self
246    }
247
248    /// Dart `MaterialButton(hoverElevation:)`.
249    pub fn hover_elevation(mut self, hover_elevation: f64) -> MaterialButton {
250        debug_assert!(hover_elevation >= 0.0);
251        self.hover_elevation = Some(hover_elevation);
252        self
253    }
254
255    /// Dart `MaterialButton(highlightElevation:)`.
256    pub fn highlight_elevation(mut self, highlight_elevation: f64) -> MaterialButton {
257        debug_assert!(highlight_elevation >= 0.0);
258        self.highlight_elevation = Some(highlight_elevation);
259        self
260    }
261
262    /// Dart `MaterialButton(disabledElevation:)`.
263    pub fn disabled_elevation(mut self, disabled_elevation: f64) -> MaterialButton {
264        debug_assert!(disabled_elevation >= 0.0);
265        self.disabled_elevation = Some(disabled_elevation);
266        self
267    }
268
269    /// Dart `MaterialButton(padding:)`.
270    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> MaterialButton {
271        self.padding = Some(padding.into());
272        self
273    }
274
275    /// Dart `MaterialButton(visualDensity:)`.
276    pub fn visual_density(mut self, visual_density: VisualDensity) -> MaterialButton {
277        self.visual_density = Some(visual_density);
278        self
279    }
280
281    /// Dart `MaterialButton(shape:)`.
282    pub fn shape(mut self, shape: impl Into<waft_painting::ShapeBorderRef>) -> MaterialButton {
283        self.shape = Some(shape.into());
284        self
285    }
286
287    /// Dart `MaterialButton(clipBehavior:)`.
288    pub fn clip_behavior(mut self, clip_behavior: Clip) -> MaterialButton {
289        self.clip_behavior = clip_behavior;
290        self
291    }
292
293    /// Dart `MaterialButton(focusNode:)`.
294    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> MaterialButton {
295        self.focus_node = Some(focus_node);
296        self
297    }
298
299    /// Dart `MaterialButton(autofocus:)`.
300    pub fn autofocus(mut self, autofocus: bool) -> MaterialButton {
301        self.autofocus = autofocus;
302        self
303    }
304
305    /// Dart `MaterialButton(animationDuration:)`.
306    pub fn animation_duration(mut self, animation_duration: Duration) -> MaterialButton {
307        self.animation_duration = Some(animation_duration);
308        self
309    }
310
311    /// Dart `MaterialButton(materialTapTargetSize:)`.
312    pub fn material_tap_target_size(
313        mut self,
314        material_tap_target_size: MaterialTapTargetSize,
315    ) -> MaterialButton {
316        self.material_tap_target_size = Some(material_tap_target_size);
317        self
318    }
319
320    /// Dart `MaterialButton(minWidth:)`.
321    pub fn min_width(mut self, min_width: f64) -> MaterialButton {
322        self.min_width = Some(min_width);
323        self
324    }
325
326    /// Dart `MaterialButton(height:)`.
327    pub fn height(mut self, height: f64) -> MaterialButton {
328        self.height = Some(height);
329        self
330    }
331
332    /// Dart `MaterialButton(enableFeedback:)`.
333    pub fn enable_feedback(mut self, enable_feedback: bool) -> MaterialButton {
334        self.enable_feedback = enable_feedback;
335        self
336    }
337
338    /// Dart `MaterialButton(child:)`.
339    #[cfg_attr(debug_assertions, track_caller)]
340    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MaterialButton {
341        self.child = Some(child.into_widget());
342        self
343    }
344}
345
346impl fmt::Debug for MaterialButton {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        f.debug_struct("MaterialButton")
349            .field("enabled", &self.enabled())
350            .finish_non_exhaustive()
351    }
352}
353
354impl StatelessWidget for MaterialButton {
355    fn key(&self) -> Option<&KeyRef> {
356        self.key.as_ref()
357    }
358
359    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
360        properties.add(FlagProperty::new("enabled", Some(self.enabled())).if_false("disabled"));
361        properties.add(
362            DiagnosticsProperty::<waft_foundation::DartEnum<ButtonTextTheme>>::new(
363                "textTheme",
364                self.text_theme.map(waft_foundation::DartEnum),
365            )
366            .default_value(None),
367        );
368        properties.add(ColorProperty::new("textColor", self.text_color).default_value(None));
369        properties.add(
370            ColorProperty::new("disabledTextColor", self.disabled_text_color).default_value(None),
371        );
372        properties.add(ColorProperty::new("color", self.color).default_value(None));
373        properties
374            .add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
375        properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
376        properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
377        properties
378            .add(ColorProperty::new("highlightColor", self.highlight_color).default_value(None));
379        properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
380        properties.add(
381            DiagnosticsProperty::<waft_foundation::DartEnum<Brightness>>::new(
382                "colorBrightness",
383                self.color_brightness.map(waft_foundation::DartEnum),
384            )
385            .default_value(None),
386        );
387        properties.add(
388            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
389                .default_value(None),
390        );
391        properties.add(
392            DiagnosticsProperty::<crate::theme_data::VisualDensity>::new(
393                "visualDensity",
394                self.visual_density,
395            )
396            .default_value(None),
397        );
398        properties.add(
399            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
400                .default_value(None),
401        );
402        properties.add(
403            DiagnosticsProperty::<String>::new(
404                "focusNode",
405                self.focus_node.as_ref().map(|node| node.to_string(app)),
406            )
407            .default_value(None),
408        );
409        properties.add(
410            DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
411                "materialTapTargetSize",
412                self.material_tap_target_size.map(waft_foundation::DartEnum),
413            )
414            .default_value(None),
415        );
416    }
417
418    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
419        let theme = Theme::of(app, context);
420        let button_theme = ButtonTheme::of(app, context);
421
422        let text_style = theme
423            .text_theme
424            .label_large
425            .clone()
426            .expect("the text theme has a label large")
427            .copy_with()
428            .color(button_theme.get_text_color(self));
429
430        let mut constraints = button_theme.get_constraints(self);
431        if let Some(min_width) = self.min_width {
432            constraints = constraints.min_width(min_width);
433        }
434        if let Some(height) = self.height {
435            constraints = constraints.min_height(height);
436        }
437
438        let mut button = RawMaterialButton::new(self.on_pressed.clone())
439            .enable_feedback(self.enable_feedback)
440            .text_style(text_style)
441            .focus_color(
442                self.focus_color
443                    .unwrap_or_else(|| button_theme.get_focus_color(self)),
444            )
445            .hover_color(
446                self.hover_color
447                    .unwrap_or_else(|| button_theme.get_hover_color(self)),
448            )
449            .highlight_color(self.highlight_color.unwrap_or(theme.highlight_color))
450            .splash_color(self.splash_color.unwrap_or(theme.splash_color))
451            .elevation(button_theme.get_elevation(self))
452            .focus_elevation(button_theme.get_focus_elevation(self))
453            .hover_elevation(button_theme.get_hover_elevation(self))
454            .highlight_elevation(button_theme.get_highlight_elevation(self))
455            .padding(button_theme.get_padding(self))
456            .visual_density(self.visual_density.unwrap_or(theme.visual_density))
457            .constraints(constraints)
458            .shape(button_theme.get_shape(self))
459            .clip_behavior(self.clip_behavior)
460            .autofocus(self.autofocus)
461            .animation_duration(button_theme.get_animation_duration(self))
462            .material_tap_target_size(
463                self.material_tap_target_size
464                    .unwrap_or(theme.material_tap_target_size),
465            )
466            .disabled_elevation(self.disabled_elevation.unwrap_or(0.0));
467
468        if let Some(on_long_press) = self.on_long_press.clone() {
469            button = button.on_long_press(on_long_press);
470        }
471        if let Some(on_highlight_changed) = self.on_highlight_changed.clone() {
472            button = button.on_highlight_changed(on_highlight_changed);
473        }
474        if let Some(mouse_cursor) = self.mouse_cursor.clone() {
475            button = button.mouse_cursor(mouse_cursor);
476        }
477        if let Some(fill_color) = button_theme.get_fill_color(self) {
478            button = button.fill_color(fill_color);
479        }
480        if let Some(focus_node) = self.focus_node.clone() {
481            button = button.focus_node(focus_node);
482        }
483        if let Some(child) = self.child.clone() {
484            button = button.child(child);
485        }
486        button.into_widget()
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use std::cell::Cell;
493    use std::rc::Rc;
494
495    use waft_embedder::{Clip, FontWeight, Offset, Radius, Rect, Size, TargetPlatform};
496    use waft_foundation::{K_IS_WEB, ValueKey};
497    use waft_painting::{
498        BorderRadius, BorderSide, EdgeInsets, RoundedRectangleBorder, ShapeBorder,
499    };
500    use waft_rendering::testing::{CanvasMethod, PaintCall, assert_paints, count_calls};
501    use waft_services::{MouseCursorRef, SystemMouseCursors};
502    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
503    use waft_widgets::{
504        Center, Container, Directionality, FocusHighlightStrategy, FocusNode, IntoWidget,
505        MouseRegion, SizedBox, Text, TextDirection,
506    };
507
508    use super::*;
509    use crate::ink_well::InkWell;
510    use crate::material::{Material, MaterialType};
511    use crate::test_support::{PaintInspection, material_app};
512    use crate::theme::Theme;
513    use crate::theme_data::ThemeData;
514
515    /// Dart's `ThemeData(useMaterial3: false)` on the test platform.
516    fn theme(app: &App) -> ThemeData {
517        ThemeData::builder()
518            .use_material3(false)
519            .platform(TargetPlatform::Android)
520            .build(app)
521    }
522
523    fn noop() -> Option<Listener> {
524        Some(Listener::new(|_app| {}))
525    }
526
527    fn button(on_pressed: bool) -> MaterialButton {
528        MaterialButton::new(on_pressed.then(|| Listener::new(|_app| {}))).child(Text::new("button"))
529    }
530
531    /// Dart's `pumpWidget(Directionality(textDirection: ltr, child: button))`: no `Material`
532    /// above it, so the tester's first ink features are the button's own.
533    fn pump_bare(tester: &mut WidgetTester, button: MaterialButton) {
534        let theme = theme(&tester.cell.borrow());
535        tester.pump_widget(material_app(
536            theme,
537            Directionality::new(TextDirection::Ltr, button).into_widget(),
538        ));
539    }
540
541    /// Dart's `pumpWidget(Theme(data: ThemeData(useMaterial3: false), child: Directionality(
542    /// textDirection: ltr, child: child)))`.
543    fn pump_themed<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
544        let theme = theme(&tester.cell.borrow());
545        tester.pump_widget(
546            Theme::new(theme, Directionality::new(TextDirection::Ltr, child)).into_widget(),
547        );
548    }
549
550    fn button_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
551        tester.widget(
552            find::descendant(
553                find::by_type::<MaterialButton>(),
554                find::by_type::<Material>(),
555            ),
556            read,
557        )
558    }
559
560    fn button_elevation(tester: &WidgetTester) -> f64 {
561        button_material(tester, |material| material.elevation)
562    }
563
564    fn raw_button_disabled_elevation(tester: &WidgetTester) -> f64 {
565        tester.widget(
566            find::descendant(
567                find::by_type::<MaterialButton>(),
568                find::by_type::<RawMaterialButton>(),
569            ),
570            |button: &RawMaterialButton| button.disabled_elevation,
571        )
572    }
573
574    fn enabled(tester: &WidgetTester) -> bool {
575        tester.widget(
576            find::by_type::<MaterialButton>(),
577            |button: &MaterialButton| button.enabled(),
578        )
579    }
580
581    /// The `Material` checks every step of `MaterialButton defaults` repeats.
582    fn assert_default_material(tester: &WidgetTester, elevation: f64, text_color: Color) {
583        let shape = RoundedRectangleBorder::new(
584            BorderSide::NONE,
585            BorderRadius::all(Radius::circular(2.0)).into(),
586        );
587        button_material(tester, |material| {
588            assert_eq!(material.animation_duration, Duration::from_millis(200));
589            assert!(material.border_on_foreground);
590            assert_eq!(material.border_radius, None);
591            assert_eq!(material.clip_behavior, Clip::None);
592            assert_eq!(material.color, None);
593            assert_eq!(material.elevation, elevation);
594            assert_eq!(material.shadow_color, None);
595            assert!(material.shape.as_deref() == Some(&shape as &dyn ShapeBorder));
596            let text_style = material.text_style.as_ref().expect("a text style");
597            assert_eq!(
598                text_style.color.as_ref().map(|color| color.color()),
599                Some(text_color)
600            );
601            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
602            assert_eq!(text_style.font_size, Some(14.0));
603            assert_eq!(text_style.font_weight, Some(FontWeight::W500));
604            assert_eq!(material.r#type, MaterialType::Transparency);
605        });
606    }
607
608    #[test]
609    fn material_button_defaults() {
610        test_widgets(|tester| {
611            // Enabled MaterialButton
612            pump_themed(tester, button(true));
613            assert_default_material(tester, 2.0, Color::new(0xdd000000));
614
615            let center = tester.get_center(find::by_type::<MaterialButton>());
616            let mut gesture = TestPointer::touch(1);
617            tester.down(&mut gesture, center);
618            tester.pump_and_settle();
619
620            // Only elevation changes when enabled and pressed.
621            assert_default_material(tester, 8.0, Color::new(0xdd000000));
622
623            // Disabled MaterialButton
624            pump_themed(tester, button(false));
625            assert_default_material(tester, 0.0, Color::new(0x61000000));
626
627            // Finish gesture to release resources.
628            tester.up(&gesture);
629            tester.pump_and_settle();
630        });
631    }
632
633    #[test]
634    fn does_material_button_work_with_hover() {
635        test_widgets(|tester| {
636            let hover_color = Color::new(0xff001122);
637            pump_bare(tester, button(true).hover_color(hover_color));
638
639            let mut gesture = TestPointer::mouse(1, 0);
640            tester.add_pointer(&mut gesture, Offset::ZERO);
641            tester.move_to(
642                &mut gesture,
643                tester.get_center(find::by_type::<MaterialButton>()),
644                false,
645            );
646            tester.pump_and_settle();
647
648            assert_paints(
649                tester.ink_list().ops(),
650                &[PaintCall::rect(Some(hover_color))],
651            );
652        });
653    }
654
655    #[test]
656    fn does_material_button_work_with_focus() {
657        test_widgets(|tester| {
658            let focus_color = Color::new(0xff001122);
659            let focus_node: FocusNodeRef =
660                FocusNode::new(&mut tester.cell.borrow_mut()).into_erased();
661            pump_bare(
662                tester,
663                button(true)
664                    .focus_color(focus_color)
665                    .focus_node(focus_node.clone()),
666            );
667
668            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
669            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
670            tester.pump_and_settle();
671
672            assert_paints(
673                tester.ink_list().ops(),
674                &[PaintCall::rect(Some(focus_color))],
675            );
676        });
677    }
678
679    #[test]
680    fn material_button_elevation_and_colors_have_proper_precedence() {
681        test_widgets(|tester| {
682            let elevation = 10.0;
683            let focus_elevation = 11.0;
684            let hover_elevation = 12.0;
685            let highlight_elevation = 13.0;
686            let focus_color = Color::new(0xff001122);
687            let hover_color = Color::new(0xff112233);
688            let highlight_color = Color::new(0xff223344);
689
690            let focus_node: FocusNodeRef =
691                FocusNode::new(&mut tester.cell.borrow_mut()).into_erased();
692            pump_bare(
693                tester,
694                button(true)
695                    .focus_color(focus_color)
696                    .hover_color(hover_color)
697                    .highlight_color(highlight_color)
698                    .elevation(elevation)
699                    .focus_elevation(focus_elevation)
700                    .hover_elevation(hover_elevation)
701                    .highlight_elevation(highlight_elevation)
702                    .focus_node(focus_node.clone()),
703            );
704            tester.pump_and_settle();
705            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
706
707            // Base elevation
708            assert_eq!(button_elevation(tester), elevation);
709
710            // Focus elevation overrides base
711            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
712            tester.pump_and_settle();
713            assert_paints(
714                tester.ink_list().ops(),
715                &[PaintCall::rect(Some(focus_color))],
716            );
717            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
718            assert_eq!(button_elevation(tester), focus_elevation);
719
720            // Hover elevation overrides focus
721            let mut gesture = TestPointer::mouse(1, 0);
722            tester.add_pointer(&mut gesture, Offset::ZERO);
723            tester.move_to(
724                &mut gesture,
725                tester.get_center(find::by_type::<MaterialButton>()),
726                false,
727            );
728            tester.pump_and_settle();
729            assert_paints(
730                tester.ink_list().ops(),
731                &[
732                    PaintCall::rect(Some(focus_color)),
733                    PaintCall::rect(Some(hover_color)),
734                ],
735            );
736            assert_eq!(button_elevation(tester), hover_elevation);
737            tester.remove_pointer(&gesture);
738
739            // Highlight elevation overrides hover
740            let mut gesture2 = TestPointer::touch(2);
741            tester.down(
742                &mut gesture2,
743                tester.get_center(find::by_type::<MaterialButton>()),
744            );
745            tester.pump_and_settle();
746            assert_paints(
747                tester.ink_list().ops(),
748                &[
749                    PaintCall::rect(Some(focus_color)),
750                    PaintCall::rect(Some(highlight_color)),
751                ],
752            );
753            assert_eq!(button_elevation(tester), highlight_elevation);
754            tester.up(&gesture2);
755        });
756    }
757
758    #[test]
759    fn material_button_s_disabled_color_takes_precedence_over_its_default_disabled_color() {
760        test_widgets(|tester| {
761            pump_bare(tester, button(false).disabled_color(Color::new(0xff00ff00)));
762            assert_eq!(
763                button_material(tester, |material| material.color),
764                Some(Color::new(0xff00ff00))
765            );
766        });
767    }
768
769    #[test]
770    fn material_button_gets_focus_when_autofocus_is_set() {
771        test_widgets(|tester| {
772            let focus_node: FocusNodeRef =
773                FocusNode::new(&mut tester.cell.borrow_mut()).into_erased();
774            let pump = |tester: &mut WidgetTester, autofocus: bool| {
775                let theme = ThemeData::builder().build(&tester.cell.borrow());
776                tester.pump_widget(material_app(
777                    theme,
778                    Center::new()
779                        .child(
780                            MaterialButton::new(noop())
781                                .autofocus(autofocus)
782                                .focus_node(focus_node.clone())
783                                .child(
784                                    Container::new()
785                                        .width(100.0)
786                                        .height(100.0)
787                                        .color(Color::new(0xffff0000)),
788                                ),
789                        )
790                        .into_widget(),
791                ));
792            };
793
794            pump(tester, false);
795            tester.pump();
796            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
797
798            pump(tester, true);
799            tester.pump();
800            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
801        });
802    }
803
804    #[test]
805    fn material_button_on_pressed_and_on_long_press_callbacks_are_correctly_called_when_non_null() {
806        test_widgets(|tester| {
807            let build_frame = |on_pressed: Option<Listener>, on_long_press: Option<Listener>| {
808                let mut button = MaterialButton::new(on_pressed).child(Text::new("button"));
809                if let Some(on_long_press) = on_long_press {
810                    button = button.on_long_press(on_long_press);
811                }
812                Directionality::new(TextDirection::Ltr, button)
813            };
814            let was_pressed = Rc::new(Cell::new(false));
815            let press = || {
816                let was_pressed = Rc::clone(&was_pressed);
817                Listener::new(move |_app| was_pressed.set(true))
818            };
819
820            // onPressed not null, onLongPress null.
821            pump_themed(tester, build_frame(Some(press()), None));
822            assert!(enabled(tester));
823            tester.tap(find::by_type::<MaterialButton>());
824            assert!(was_pressed.get());
825
826            // onPressed null, onLongPress not null.
827            was_pressed.set(false);
828            pump_themed(tester, build_frame(None, Some(press())));
829            assert!(enabled(tester));
830            tester.long_press(find::by_type::<MaterialButton>());
831            assert!(was_pressed.get());
832
833            // onPressed null, onLongPress null.
834            pump_themed(tester, build_frame(None, None));
835            assert!(!enabled(tester));
836        });
837    }
838
839    #[test]
840    fn material_button_on_pressed_and_on_long_press_callbacks_are_distinctly_recognized() {
841        test_widgets(|tester| {
842            let did_press_button = Rc::new(Cell::new(false));
843            let did_long_press_button = Rc::new(Cell::new(false));
844            let pressed = Rc::clone(&did_press_button);
845            let long_pressed = Rc::clone(&did_long_press_button);
846            pump_themed(
847                tester,
848                MaterialButton::new(Some(Listener::new(move |_app| pressed.set(true))))
849                    .on_long_press(Listener::new(move |_app| long_pressed.set(true)))
850                    .child(Text::new("button")),
851            );
852
853            assert!(enabled(tester));
854
855            assert!(!did_press_button.get());
856            tester.tap(find::by_type::<MaterialButton>());
857            assert!(did_press_button.get());
858
859            assert!(!did_long_press_button.get());
860            tester.long_press(find::by_type::<MaterialButton>());
861            assert!(did_long_press_button.get());
862        });
863    }
864
865    #[test]
866    fn material_button_changes_mouse_cursor_when_hovered() {
867        test_widgets(|tester| {
868            let in_region = |button: MaterialButton| {
869                MouseRegion::new()
870                    .cursor(SystemMouseCursors::FORBIDDEN.into())
871                    .child(button)
872            };
873            pump_themed(
874                tester,
875                in_region(
876                    MaterialButton::new(noop()).mouse_cursor(SystemMouseCursors::TEXT.into()),
877                ),
878            );
879
880            let mut gesture = TestPointer::mouse(1, 0);
881            tester.add_pointer(&mut gesture, Offset::ZERO);
882            tester.pump();
883
884            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
885            assert!(*tester.active_cursor(1) == *text);
886
887            // Test default cursor
888            pump_themed(tester, in_region(MaterialButton::new(noop())));
889            let expected: MouseCursorRef = if K_IS_WEB {
890                SystemMouseCursors::CLICK.into()
891            } else {
892                SystemMouseCursors::BASIC.into()
893            };
894            assert!(*tester.active_cursor(1) == *expected);
895
896            // Test default cursor when disabled
897            pump_themed(tester, in_region(MaterialButton::new(None)));
898            let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
899            assert!(*tester.active_cursor(1) == *basic);
900        });
901    }
902
903    /// Dart matches the clip's path against the button's rounded rect; the recorded clip keeps
904    /// no path, so this only checks that one is there.
905    #[test]
906    fn material_button_with_explicit_splash_color_and_highlight_color() {
907        test_widgets(|tester| {
908            let direct_splash_color = Color::new(0xFF000011);
909            let direct_highlight_color = Color::new(0xFF000011);
910            let themed = |tester: &WidgetTester,
911                          highlight_color: Option<Color>,
912                          splash_color: Option<Color>,
913                          button_widget: WidgetRef| {
914                let mut builder = ThemeData::builder()
915                    .use_material3(false)
916                    .platform(TargetPlatform::Android)
917                    .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap);
918                if let Some(highlight_color) = highlight_color {
919                    builder = builder.highlight_color(highlight_color);
920                }
921                if let Some(splash_color) = splash_color {
922                    builder = builder.splash_color(splash_color);
923                }
924                Directionality::new(
925                    TextDirection::Ltr,
926                    Theme::new(builder.build(&tester.cell.borrow()), button_widget),
927                )
928                .into_widget()
929            };
930            let ink_well_material = |tester: &WidgetTester| {
931                tester.nearest_material_ops(tester.element(find::by_type::<InkWell>()))
932            };
933
934            let button_widget = Center::new()
935                .child(
936                    MaterialButton::new(noop())
937                        .splash_color(direct_splash_color)
938                        .highlight_color(direct_highlight_color)
939                        .clip_behavior(Clip::AntiAlias),
940                )
941                .into_widget();
942            let widget = themed(tester, None, None, button_widget);
943            tester.pump_widget(widget);
944
945            let center = tester.get_center(find::by_type::<MaterialButton>());
946            let mut gesture = TestPointer::touch(1);
947            tester.down(&mut gesture, center);
948            tester.pump(); // start gesture
949            tester.pump_by(Duration::from_millis(200)); // wait for splash to be well under way
950
951            // Painter is translated to the center by the Center widget and not
952            // the Material widget.
953            let expected_clip_rect = Rect::from_ltrb(0.0, 0.0, 88.0, 36.0);
954            assert_eq!(
955                tester.get_size(find::by_type::<MaterialButton>()),
956                expected_clip_rect.size()
957            );
958            assert_paints(
959                &ink_well_material(tester),
960                &[
961                    PaintCall::Clip,
962                    PaintCall::circle(Some(direct_splash_color)),
963                    PaintCall::rect(Some(direct_highlight_color)),
964                ],
965            );
966
967            let theme_splash_color1 = Color::new(0xFF001100);
968            let theme_highlight_color1 = Color::new(0xFF001100);
969
970            let button_widget = Center::new()
971                .child(MaterialButton::new(noop()).clip_behavior(Clip::AntiAlias))
972                .into_widget();
973            let widget = themed(
974                tester,
975                Some(theme_highlight_color1),
976                Some(theme_splash_color1),
977                button_widget.clone(),
978            );
979            tester.pump_widget(widget);
980
981            assert_paints(
982                &ink_well_material(tester),
983                &[
984                    PaintCall::Clip,
985                    PaintCall::circle(Some(theme_splash_color1)),
986                    PaintCall::rect(Some(theme_highlight_color1)),
987                ],
988            );
989
990            let theme_splash_color2 = Color::new(0xFF002200);
991            let theme_highlight_color2 = Color::new(0xFF002200);
992
993            // same widget, so does not get updated because of us
994            let widget = themed(
995                tester,
996                Some(theme_highlight_color2),
997                Some(theme_splash_color2),
998                button_widget,
999            );
1000            tester.pump_widget(widget);
1001
1002            assert_paints(
1003                &ink_well_material(tester),
1004                &[
1005                    PaintCall::circle(Some(theme_splash_color2)),
1006                    PaintCall::rect(Some(theme_highlight_color2)),
1007                ],
1008            );
1009
1010            tester.up(&gesture);
1011        });
1012    }
1013
1014    #[test]
1015    fn material_button_has_no_clip_by_default() {
1016        test_widgets(|tester| {
1017            let button_key = KeyRef::from(ValueKey::new("button"));
1018            let theme = ThemeData::builder()
1019                .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1020                .build(&tester.cell.borrow());
1021            tester.pump_widget(
1022                Directionality::new(
1023                    TextDirection::Ltr,
1024                    Theme::new(
1025                        theme,
1026                        Center::new().child(MaterialButton::new(noop()).key(button_key.clone())),
1027                    ),
1028                )
1029                .into_widget(),
1030            );
1031
1032            let render = tester.render_object(find::by_key(button_key));
1033            assert_eq!(
1034                count_calls(&tester.painted_ops_deep(render), CanvasMethod::Clip),
1035                0
1036            );
1037        });
1038    }
1039
1040    #[test]
1041    fn material_button_min_width_and_height_parameters() {
1042        test_widgets(|tester| {
1043            let build_frame = |min_width: Option<f64>,
1044                               height: Option<f64>,
1045                               padding: EdgeInsets,
1046                               child: Option<WidgetRef>| {
1047                let mut button = MaterialButton::new(None)
1048                    .padding(padding)
1049                    .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap);
1050                if let Some(min_width) = min_width {
1051                    button = button.min_width(min_width);
1052                }
1053                if let Some(height) = height {
1054                    button = button.height(height);
1055                }
1056                if let Some(child) = child {
1057                    button = button.child(child);
1058                }
1059                Center::new().child(button)
1060            };
1061            let eight = || Some(SizedBox::new().width(8.0).height(8.0).into_widget());
1062            let cases = [
1063                (
1064                    Some(8.0),
1065                    Some(24.0),
1066                    EdgeInsets::ZERO,
1067                    None,
1068                    Size::new(8.0, 24.0),
1069                ),
1070                // Default minHeight constraint is 36, see RawMaterialButton.
1071                (
1072                    Some(8.0),
1073                    None,
1074                    EdgeInsets::ZERO,
1075                    None,
1076                    Size::new(8.0, 36.0),
1077                ),
1078                // Default minWidth constraint is 88, see RawMaterialButton.
1079                (
1080                    None,
1081                    Some(8.0),
1082                    EdgeInsets::ZERO,
1083                    None,
1084                    Size::new(88.0, 8.0),
1085                ),
1086                (None, None, EdgeInsets::ZERO, None, Size::new(88.0, 36.0)),
1087                (
1088                    None,
1089                    None,
1090                    EdgeInsets::all(4.0),
1091                    None,
1092                    Size::new(88.0, 36.0),
1093                ),
1094                // Size is defined by the padding.
1095                (
1096                    Some(0.0),
1097                    Some(0.0),
1098                    EdgeInsets::all(4.0),
1099                    None,
1100                    Size::new(8.0, 8.0),
1101                ),
1102                // Size is defined by the padded child.
1103                (
1104                    Some(0.0),
1105                    Some(0.0),
1106                    EdgeInsets::all(4.0),
1107                    eight(),
1108                    Size::new(16.0, 16.0),
1109                ),
1110                // Size is defined by the minWidth, height constraints.
1111                (
1112                    Some(18.0),
1113                    Some(18.0),
1114                    EdgeInsets::all(4.0),
1115                    eight(),
1116                    Size::new(18.0, 18.0),
1117                ),
1118            ];
1119            for (min_width, height, padding, child, expected) in cases {
1120                pump_themed(tester, build_frame(min_width, height, padding, child));
1121                assert_eq!(tester.get_size(find::by_type::<MaterialButton>()), expected);
1122            }
1123        });
1124    }
1125
1126    #[test]
1127    fn material_button_size_is_configurable_by_theme_data_material_tap_target_size() {
1128        test_widgets(|tester| {
1129            let pump = |tester: &mut WidgetTester, key: KeyRef, size: MaterialTapTargetSize| {
1130                let theme = ThemeData::builder()
1131                    .material_tap_target_size(size)
1132                    .build(&tester.cell.borrow());
1133                tester.pump_widget(
1134                    Theme::new(
1135                        theme,
1136                        Directionality::new(
1137                            TextDirection::Ltr,
1138                            Center::new().child(
1139                                MaterialButton::new(noop())
1140                                    .key(key)
1141                                    .child(SizedBox::new().width(50.0).height(8.0)),
1142                            ),
1143                        ),
1144                    )
1145                    .into_widget(),
1146                );
1147            };
1148
1149            let key1 = KeyRef::from(ValueKey::new("key1"));
1150            pump(tester, key1.clone(), MaterialTapTargetSize::Padded);
1151            assert_eq!(tester.get_size(find::by_key(key1)), Size::new(88.0, 48.0));
1152
1153            let key2 = KeyRef::from(ValueKey::new("key2"));
1154            pump(tester, key2.clone(), MaterialTapTargetSize::ShrinkWrap);
1155            assert_eq!(tester.get_size(find::by_key(key2)), Size::new(88.0, 36.0));
1156        });
1157    }
1158
1159    #[test]
1160    fn material_button_shape_overrides_button_theme_shape() {
1161        test_widgets(|tester| {
1162            let shape = waft_painting::StadiumBorder::new(BorderSide::NONE);
1163            pump_bare(tester, button(true).shape(shape));
1164            assert!(button_material(tester, |material| {
1165                material.shape.as_deref() == Some(&shape as &dyn ShapeBorder)
1166            }));
1167        });
1168    }
1169
1170    #[test]
1171    fn material_button_responds_to_density_changes() {
1172        test_widgets(|tester| {
1173            let key = KeyRef::from(ValueKey::new("test"));
1174            let child_key = KeyRef::from(ValueKey::new("test child"));
1175            let build_test =
1176                |tester: &mut WidgetTester, visual_density: VisualDensity, use_text: bool| {
1177                    let child = if use_text {
1178                        Text::new("Text").key(child_key.clone()).into_widget()
1179                    } else {
1180                        Container::new()
1181                            .key(child_key.clone())
1182                            .width(100.0)
1183                            .height(100.0)
1184                            .color(Color::new(0xffff0000))
1185                            .into_widget()
1186                    };
1187                    let theme = theme(&tester.cell.borrow());
1188                    tester.pump_widget(material_app(
1189                        theme,
1190                        Directionality::new(
1191                            TextDirection::Rtl,
1192                            Center::new().child(
1193                                MaterialButton::new(noop())
1194                                    .visual_density(visual_density)
1195                                    .key(key.clone())
1196                                    .child(child),
1197                            ),
1198                        )
1199                        .into_widget(),
1200                    ));
1201                };
1202            let cases = [
1203                (
1204                    VisualDensity::STANDARD,
1205                    false,
1206                    Size::new(132.0, 100.0),
1207                    Rect::from_ltrb(350.0, 250.0, 450.0, 350.0),
1208                ),
1209                (
1210                    VisualDensity::new(3.0, 3.0),
1211                    false,
1212                    Size::new(156.0, 124.0),
1213                    Rect::from_ltrb(350.0, 250.0, 450.0, 350.0),
1214                ),
1215                (
1216                    VisualDensity::new(-3.0, -3.0),
1217                    false,
1218                    Size::new(108.0, 100.0),
1219                    Rect::from_ltrb(350.0, 250.0, 450.0, 350.0),
1220                ),
1221                (
1222                    VisualDensity::STANDARD,
1223                    true,
1224                    Size::new(88.0, 48.0),
1225                    Rect::from_ltrb(372.0, 293.0, 428.0, 307.0),
1226                ),
1227                (
1228                    VisualDensity::new(3.0, 3.0),
1229                    true,
1230                    Size::new(112.0, 60.0),
1231                    Rect::from_ltrb(372.0, 293.0, 428.0, 307.0),
1232                ),
1233                (
1234                    VisualDensity::new(-3.0, -3.0),
1235                    true,
1236                    Size::new(76.0, 36.0),
1237                    Rect::from_ltrb(372.0, 293.0, 428.0, 307.0),
1238                ),
1239            ];
1240            for (visual_density, use_text, size, child_rect) in cases {
1241                build_test(tester, visual_density, use_text);
1242                tester.pump_and_settle();
1243                assert_eq!(tester.get_size(find::by_key(key.clone())), size);
1244                assert_eq!(tester.get_rect(find::by_key(child_key.clone())), child_rect);
1245            }
1246        });
1247    }
1248
1249    #[test]
1250    fn disabled_elevation_is_passed_to_raw_material_button() {
1251        test_widgets(|tester| {
1252            let disabled_elevation = 16.0;
1253            pump_bare(tester, button(false).disabled_elevation(disabled_elevation));
1254            assert_eq!(raw_button_disabled_elevation(tester), disabled_elevation);
1255        });
1256    }
1257
1258    #[test]
1259    fn material_button_disabled_elevation_defaults_to_0_0_when_not_provided() {
1260        test_widgets(|tester| {
1261            pump_bare(tester, button(false));
1262            assert_eq!(raw_button_disabled_elevation(tester), 0.0);
1263        });
1264    }
1265
1266    #[test]
1267    fn material_button_does_not_crash_at_zero_area() {
1268        test_widgets(|tester| {
1269            let theme = ThemeData::builder().build(&tester.cell.borrow());
1270            tester.pump_widget(material_app(
1271                theme,
1272                Center::new()
1273                    .child(
1274                        SizedBox::shrink().child(MaterialButton::new(noop()).child(Text::new("X"))),
1275                    )
1276                    .into_widget(),
1277            ));
1278            assert_eq!(
1279                tester.get_size(find::by_type::<MaterialButton>()),
1280                Size::ZERO
1281            );
1282        });
1283    }
1284}