Skip to main content

waft_material/
button.rs

1//! Flutter counterpart: material_ui's `button.dart`.
2//!
3//! The `button_theme.dart` that Dart's file imports for its documentation waits with
4//! `material_button.dart`.
5
6use std::fmt;
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_embedder::{Clip, Color, Offset, Size, TextBaseline};
11use waft_foundation::{App, DiagnosticPropertiesBuilder, Handle, Listener, ValueChanged};
12use waft_painting::{
13    Alignment, EdgeInsets, EdgeInsetsGeometry, OutlinedBorderRef, RoundedRectangleBorder,
14    ShapeBorderRef, TextStyle, force_to_point,
15};
16use waft_rendering::{
17    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData,
18    ChildLayoutHelper, ChildLayouter, PaintingContext, RenderBox, RenderBoxBase, RenderBoxData,
19    RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
20    RenderObjectWithChildMixin, RenderShiftedBox,
21};
22use waft_services::MouseCursorRef;
23use waft_widgets::{
24    BuildContext, Center, ConstrainedBox, FocusNodeRef, IconTheme, IconThemeData, IntoWidget,
25    KeyRef, Padding, RenderObjectWidget, Semantics, SingleChildRenderObjectWidget, State,
26    StateData, StatefulWidget, WidgetRef, WidgetState, WidgetStateMouseCursor, WidgetStateProperty,
27    WidgetStates,
28};
29
30use crate::constants::{K_MIN_INTERACTIVE_DIMENSION, K_THEME_CHANGE_DURATION};
31use crate::ink_well::InkWell;
32use crate::material::{Material, MaterialType};
33use crate::material_state_mixin::{MaterialStateMixin, MaterialStateMixinData};
34use crate::theme::Theme;
35use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
36
37/// Creates a button based on `Semantics`, [`Material`], and [`InkWell`]
38/// widgets.
39///
40/// This class does not use the current `Theme` or `ButtonTheme` to
41/// compute default values for unspecified parameters. It's intended to
42/// be used for custom Material buttons that optionally incorporate defaults
43/// from the themes or from app-specific sources.
44///
45/// This class is planned to be deprecated in a future release, see
46/// `ButtonStyleButton`, the base class of `ElevatedButton`, `FilledButton`,
47/// `OutlinedButton` and `TextButton`.
48///
49/// See also:
50///
51///  * `ElevatedButton`, a filled button whose material elevates when pressed.
52///  * `FilledButton`, a filled button that doesn't elevate when pressed.
53///  * `FilledButton.tonal`, a filled button variant that uses a secondary fill color.
54///  * `OutlinedButton`, a button with an outlined border and no fill color.
55///  * `TextButton`, a button with no outline or fill color.
56pub struct RawMaterialButton {
57    pub key: Option<KeyRef>,
58
59    /// Called when the button is tapped or otherwise activated.
60    ///
61    /// If this callback and [`on_long_press`](Self::on_long_press) are null, then the button
62    /// will be disabled.
63    ///
64    /// See also:
65    ///
66    ///  * [`enabled`](Self::enabled), which is true if the button is enabled.
67    pub on_pressed: Option<Listener>,
68
69    /// Called when the button is long-pressed.
70    ///
71    /// If this callback and [`on_pressed`](Self::on_pressed) are null, then the button will be
72    /// disabled.
73    ///
74    /// See also:
75    ///
76    ///  * [`enabled`](Self::enabled), which is true if the button is enabled.
77    pub on_long_press: Option<Listener>,
78
79    /// Called by the underlying [`InkWell`] widget's `InkWell.on_highlight_changed`
80    /// callback.
81    ///
82    /// If [`on_pressed`](Self::on_pressed) changes from null to non-null while a gesture is
83    /// ongoing, this can fire during the build phase (in which case calling
84    /// [`State::set_state`] is not allowed).
85    pub on_highlight_changed: Option<ValueChanged<bool>>,
86
87    /// The cursor for a mouse pointer when it enters or is hovering over the
88    /// button.
89    ///
90    /// If [`mouse_cursor`](Self::mouse_cursor) is a [`WidgetStateMouseCursor`],
91    /// `WidgetStateProperty::resolve` is used for the following [`WidgetState`]s:
92    ///
93    ///  * [`WidgetState::Pressed`].
94    ///  * [`WidgetState::Hovered`].
95    ///  * [`WidgetState::Focused`].
96    ///  * [`WidgetState::Disabled`].
97    ///
98    /// If this property is null, [`WidgetStateMouseCursor::adaptive_clickable`] will be used.
99    pub mouse_cursor: Option<MouseCursorRef>,
100
101    /// Defines the default text style, with [`Material::text_style`], for the
102    /// button's [`child`](Self::child).
103    ///
104    /// If `TextStyle.color` is a `WidgetStateProperty<Color>`, `WidgetStateProperty::resolve`
105    /// is used for the following [`WidgetState`]s:
106    ///
107    ///  * [`WidgetState::Pressed`].
108    ///  * [`WidgetState::Hovered`].
109    ///  * [`WidgetState::Focused`].
110    ///  * [`WidgetState::Disabled`].
111    pub text_style: Option<TextStyle>,
112
113    /// The color of the button's [`Material`].
114    pub fill_color: Option<Color>,
115
116    /// The color for the button's [`Material`] when it has the input focus.
117    pub focus_color: Option<Color>,
118
119    /// The color for the button's [`Material`] when a pointer is hovering over it.
120    pub hover_color: Option<Color>,
121
122    /// The highlight color for the button's [`InkWell`].
123    pub highlight_color: Option<Color>,
124
125    /// The splash color for the button's [`InkWell`].
126    pub splash_color: Option<Color>,
127
128    /// The elevation for the button's [`Material`] when the button
129    /// is [`enabled`](Self::enabled) but not pressed.
130    ///
131    /// Defaults to 2.0. The value is always non-negative.
132    ///
133    /// See also:
134    ///
135    ///  * [`highlight_elevation`](Self::highlight_elevation), the default elevation.
136    ///  * [`hover_elevation`](Self::hover_elevation), the elevation when a pointer is
137    ///    hovering over the button.
138    ///  * [`focus_elevation`](Self::focus_elevation), the elevation when the button is
139    ///    focused.
140    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
141    ///    disabled.
142    pub elevation: f64,
143
144    /// The elevation for the button's [`Material`] when the button
145    /// is [`enabled`](Self::enabled) and a pointer is hovering over it.
146    ///
147    /// Defaults to 4.0. The value is always non-negative.
148    ///
149    /// If the button is [`enabled`](Self::enabled), and being pressed (in the highlighted
150    /// state), then the [`highlight_elevation`](Self::highlight_elevation) take precedence
151    /// over the [`hover_elevation`](Self::hover_elevation).
152    ///
153    /// See also:
154    ///
155    ///  * [`elevation`](Self::elevation), the default elevation.
156    ///  * [`focus_elevation`](Self::focus_elevation), the elevation when the button is
157    ///    focused.
158    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
159    ///    disabled.
160    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
161    ///    is pressed.
162    pub hover_elevation: f64,
163
164    /// The elevation for the button's [`Material`] when the button
165    /// is [`enabled`](Self::enabled) and has the input focus.
166    ///
167    /// Defaults to 4.0. The value is always non-negative.
168    ///
169    /// If the button is [`enabled`](Self::enabled), and being pressed (in the highlighted
170    /// state), or a mouse cursor is hovering over the button, then the
171    /// [`hover_elevation`](Self::hover_elevation) and
172    /// [`highlight_elevation`](Self::highlight_elevation) take precedence over the
173    /// [`focus_elevation`](Self::focus_elevation).
174    ///
175    /// See also:
176    ///
177    ///  * [`elevation`](Self::elevation), the default elevation.
178    ///  * [`hover_elevation`](Self::hover_elevation), the elevation when a pointer is
179    ///    hovering over the button.
180    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
181    ///    disabled.
182    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
183    ///    is pressed.
184    pub focus_elevation: f64,
185
186    /// The elevation for the button's [`Material`] when the button
187    /// is [`enabled`](Self::enabled) and pressed.
188    ///
189    /// Defaults to 8.0. The value is always non-negative.
190    ///
191    /// See also:
192    ///
193    ///  * [`elevation`](Self::elevation), the default elevation.
194    ///  * [`hover_elevation`](Self::hover_elevation), the elevation when a pointer is
195    ///    hovering over the button.
196    ///  * [`focus_elevation`](Self::focus_elevation), the elevation when the button is
197    ///    focused.
198    ///  * [`disabled_elevation`](Self::disabled_elevation), the elevation when the button is
199    ///    disabled.
200    pub highlight_elevation: f64,
201
202    /// The elevation for the button's [`Material`] when the button
203    /// is not [`enabled`](Self::enabled).
204    ///
205    /// Defaults to 0.0. The value is always non-negative.
206    ///
207    /// See also:
208    ///
209    ///  * [`elevation`](Self::elevation), the default elevation.
210    ///  * [`hover_elevation`](Self::hover_elevation), the elevation when a pointer is
211    ///    hovering over the button.
212    ///  * [`focus_elevation`](Self::focus_elevation), the elevation when the button is
213    ///    focused.
214    ///  * [`highlight_elevation`](Self::highlight_elevation), the elevation when the button
215    ///    is pressed.
216    pub disabled_elevation: f64,
217
218    /// The internal padding for the button's [`child`](Self::child).
219    pub padding: EdgeInsetsGeometry,
220
221    /// Defines how compact the button's layout will be.
222    ///
223    /// See also:
224    ///
225    ///  * `ThemeData::visual_density`, which specifies the [`visual_density`](Self::visual_density)
226    ///    for all widgets within a `Theme`.
227    pub visual_density: VisualDensity,
228
229    /// Defines the button's size.
230    ///
231    /// Typically used to constrain the button's minimum size.
232    pub constraints: BoxConstraints,
233
234    /// The shape of the button's [`Material`].
235    ///
236    /// The button's highlight and splash are clipped to this shape. If the
237    /// button has an elevation, then its drop shadow is defined by this shape.
238    ///
239    /// If [`shape`](Self::shape) is a [`WidgetStateOutlinedBorder`](waft_widgets::WidgetStateOutlinedBorder),
240    /// `WidgetStateProperty::resolve` is used for the following [`WidgetState`]s:
241    ///
242    /// * [`WidgetState::Pressed`].
243    /// * [`WidgetState::Hovered`].
244    /// * [`WidgetState::Focused`].
245    /// * [`WidgetState::Disabled`].
246    pub shape: ShapeBorderRef,
247
248    /// Defines the duration of animated changes for [`shape`](Self::shape) and
249    /// [`elevation`](Self::elevation).
250    ///
251    /// The default value is [`K_THEME_CHANGE_DURATION`].
252    pub animation_duration: Duration,
253
254    /// The content will be clipped (or not) according to this option.
255    ///
256    /// Defaults to [`Clip::None`].
257    pub clip_behavior: Clip,
258
259    /// An optional focus node to use as the focus node for this widget.
260    ///
261    /// See `Focus::focus_node`.
262    pub focus_node: Option<FocusNodeRef>,
263
264    /// True if this widget will be selected as the initial focus when no other node in its
265    /// scope is currently focused.
266    ///
267    /// See `Focus::autofocus`.
268    pub autofocus: bool,
269
270    /// Configures the minimum size of the tap target.
271    ///
272    /// Defaults to [`MaterialTapTargetSize::Padded`].
273    ///
274    /// See also:
275    ///
276    ///  * [`MaterialTapTargetSize`], for a description of how this affects tap targets.
277    pub material_tap_target_size: MaterialTapTargetSize,
278
279    /// Typically the button's label.
280    pub child: Option<WidgetRef>,
281
282    /// Whether detected gestures should provide acoustic and/or haptic feedback.
283    ///
284    /// For example, on Android a tap will produce a clicking sound and a
285    /// long-press will produce a short vibration, when feedback is enabled.
286    ///
287    /// See also:
288    ///
289    ///  * `Feedback` for providing platform-specific feedback to certain actions.
290    pub enable_feedback: bool,
291}
292
293impl RawMaterialButton {
294    /// Create a button based on `Semantics`, [`Material`], and [`InkWell`] widgets.
295    ///
296    /// The [`elevation`](Self::elevation), [`focus_elevation`](Self::focus_elevation),
297    /// [`hover_elevation`](Self::hover_elevation),
298    /// [`highlight_elevation`](Self::highlight_elevation), and
299    /// [`disabled_elevation`](Self::disabled_elevation) parameters must be non-negative.
300    pub fn new(on_pressed: Option<Listener>) -> RawMaterialButton {
301        RawMaterialButton {
302            key: None,
303            on_pressed,
304            on_long_press: None,
305            on_highlight_changed: None,
306            mouse_cursor: None,
307            text_style: None,
308            fill_color: None,
309            focus_color: None,
310            hover_color: None,
311            highlight_color: None,
312            splash_color: None,
313            elevation: 2.0,
314            focus_elevation: 4.0,
315            hover_elevation: 4.0,
316            highlight_elevation: 8.0,
317            disabled_elevation: 0.0,
318            padding: EdgeInsetsGeometry::ZERO,
319            visual_density: VisualDensity::STANDARD,
320            constraints: BoxConstraints::new().min_width(88.0).min_height(36.0),
321            shape: ShapeBorderRef::new(RoundedRectangleBorder::default()),
322            animation_duration: K_THEME_CHANGE_DURATION,
323            clip_behavior: Clip::None,
324            focus_node: None,
325            autofocus: false,
326            material_tap_target_size: MaterialTapTargetSize::Padded,
327            child: None,
328            enable_feedback: true,
329        }
330    }
331
332    /// Dart `RawMaterialButton(key:)`.
333    pub fn key(mut self, key: KeyRef) -> RawMaterialButton {
334        self.key = Some(key);
335        self
336    }
337
338    /// Dart `RawMaterialButton(onLongPress:)`.
339    pub fn on_long_press(mut self, on_long_press: Listener) -> RawMaterialButton {
340        self.on_long_press = Some(on_long_press);
341        self
342    }
343
344    /// Dart `RawMaterialButton(onHighlightChanged:)`.
345    pub fn on_highlight_changed(
346        mut self,
347        on_highlight_changed: ValueChanged<bool>,
348    ) -> RawMaterialButton {
349        self.on_highlight_changed = Some(on_highlight_changed);
350        self
351    }
352
353    /// Dart `RawMaterialButton(mouseCursor:)`.
354    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> RawMaterialButton {
355        self.mouse_cursor = Some(mouse_cursor);
356        self
357    }
358
359    /// Dart `RawMaterialButton(textStyle:)`.
360    pub fn text_style(mut self, text_style: TextStyle) -> RawMaterialButton {
361        self.text_style = Some(text_style);
362        self
363    }
364
365    /// Dart `RawMaterialButton(fillColor:)`.
366    pub fn fill_color(mut self, fill_color: Color) -> RawMaterialButton {
367        self.fill_color = Some(fill_color);
368        self
369    }
370
371    /// Dart `RawMaterialButton(focusColor:)`.
372    pub fn focus_color(mut self, focus_color: Color) -> RawMaterialButton {
373        self.focus_color = Some(focus_color);
374        self
375    }
376
377    /// Dart `RawMaterialButton(hoverColor:)`.
378    pub fn hover_color(mut self, hover_color: Color) -> RawMaterialButton {
379        self.hover_color = Some(hover_color);
380        self
381    }
382
383    /// Dart `RawMaterialButton(highlightColor:)`.
384    pub fn highlight_color(mut self, highlight_color: Color) -> RawMaterialButton {
385        self.highlight_color = Some(highlight_color);
386        self
387    }
388
389    /// Dart `RawMaterialButton(splashColor:)`.
390    pub fn splash_color(mut self, splash_color: Color) -> RawMaterialButton {
391        self.splash_color = Some(splash_color);
392        self
393    }
394
395    /// Dart `RawMaterialButton(elevation:)`.
396    pub fn elevation(mut self, elevation: f64) -> RawMaterialButton {
397        debug_assert!(elevation >= 0.0);
398        self.elevation = elevation;
399        self
400    }
401
402    /// Dart `RawMaterialButton(focusElevation:)`.
403    pub fn focus_elevation(mut self, focus_elevation: f64) -> RawMaterialButton {
404        debug_assert!(focus_elevation >= 0.0);
405        self.focus_elevation = focus_elevation;
406        self
407    }
408
409    /// Dart `RawMaterialButton(hoverElevation:)`.
410    pub fn hover_elevation(mut self, hover_elevation: f64) -> RawMaterialButton {
411        debug_assert!(hover_elevation >= 0.0);
412        self.hover_elevation = hover_elevation;
413        self
414    }
415
416    /// Dart `RawMaterialButton(highlightElevation:)`.
417    pub fn highlight_elevation(mut self, highlight_elevation: f64) -> RawMaterialButton {
418        debug_assert!(highlight_elevation >= 0.0);
419        self.highlight_elevation = highlight_elevation;
420        self
421    }
422
423    /// Dart `RawMaterialButton(disabledElevation:)`.
424    pub fn disabled_elevation(mut self, disabled_elevation: f64) -> RawMaterialButton {
425        debug_assert!(disabled_elevation >= 0.0);
426        self.disabled_elevation = disabled_elevation;
427        self
428    }
429
430    /// Dart `RawMaterialButton(padding:)`.
431    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> RawMaterialButton {
432        let padding = padding.into();
433        self.padding = padding;
434        self
435    }
436
437    /// Dart `RawMaterialButton(visualDensity:)`.
438    pub fn visual_density(mut self, visual_density: VisualDensity) -> RawMaterialButton {
439        self.visual_density = visual_density;
440        self
441    }
442
443    /// Dart `RawMaterialButton(constraints:)`.
444    pub fn constraints(mut self, constraints: BoxConstraints) -> RawMaterialButton {
445        self.constraints = constraints;
446        self
447    }
448
449    /// Dart `RawMaterialButton(shape:)`.
450    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> RawMaterialButton {
451        self.shape = shape.into();
452        self
453    }
454
455    /// Dart `RawMaterialButton(animationDuration:)`.
456    pub fn animation_duration(mut self, animation_duration: Duration) -> RawMaterialButton {
457        self.animation_duration = animation_duration;
458        self
459    }
460
461    /// Dart `RawMaterialButton(clipBehavior:)`.
462    pub fn clip_behavior(mut self, clip_behavior: Clip) -> RawMaterialButton {
463        self.clip_behavior = clip_behavior;
464        self
465    }
466
467    /// Dart `RawMaterialButton(focusNode:)`.
468    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> RawMaterialButton {
469        self.focus_node = Some(focus_node);
470        self
471    }
472
473    /// Dart `RawMaterialButton(autofocus:)`.
474    pub fn autofocus(mut self, autofocus: bool) -> RawMaterialButton {
475        self.autofocus = autofocus;
476        self
477    }
478
479    /// Dart `RawMaterialButton(materialTapTargetSize:)`.
480    pub fn material_tap_target_size(
481        mut self,
482        material_tap_target_size: MaterialTapTargetSize,
483    ) -> RawMaterialButton {
484        self.material_tap_target_size = material_tap_target_size;
485        self
486    }
487
488    /// Dart `RawMaterialButton(child:)`.
489    #[cfg_attr(debug_assertions, track_caller)]
490    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RawMaterialButton {
491        self.child = Some(child.into_widget());
492        self
493    }
494
495    /// Dart `RawMaterialButton(enableFeedback:)`.
496    pub fn enable_feedback(mut self, enable_feedback: bool) -> RawMaterialButton {
497        self.enable_feedback = enable_feedback;
498        self
499    }
500
501    /// Whether the button is enabled or disabled.
502    ///
503    /// Buttons are disabled by default. To enable a button, set its
504    /// [`on_pressed`](Self::on_pressed) or [`on_long_press`](Self::on_long_press) properties
505    /// to a non-null value.
506    pub fn enabled(&self) -> bool {
507        self.on_pressed.is_some() || self.on_long_press.is_some()
508    }
509}
510
511impl fmt::Debug for RawMaterialButton {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.debug_struct("RawMaterialButton")
514            .field("enabled", &self.enabled())
515            .field("fill_color", &self.fill_color)
516            .field("elevation", &self.elevation)
517            .field("child", &self.child)
518            .finish_non_exhaustive()
519    }
520}
521
522impl StatefulWidget for RawMaterialButton {
523    type State = RawMaterialButtonState;
524
525    fn key(&self) -> Option<&KeyRef> {
526        self.key.as_ref()
527    }
528
529    fn create_state(&self) -> RawMaterialButtonState {
530        RawMaterialButtonState {
531            state: StateData::new(),
532            material_state: MaterialStateMixinData::new(),
533        }
534    }
535}
536
537/// Dart's `_RawMaterialButtonState`.
538pub struct RawMaterialButtonState {
539    state: StateData<RawMaterialButton>,
540    material_state: MaterialStateMixinData,
541}
542
543impl RawMaterialButtonState {
544    fn effective_elevation(self: Handle<Self>, app: &App) -> f64 {
545        let widget = self.widget(app);
546        // These conditionals are in order of precedence, so be careful about
547        // reorganizing them.
548        if self.is_disabled(app) {
549            return widget.disabled_elevation;
550        }
551        if self.is_pressed(app) {
552            return widget.highlight_elevation;
553        }
554        if self.is_hovered(app) {
555            return widget.hover_elevation;
556        }
557        if self.is_focused(app) {
558            return widget.focus_elevation;
559        }
560        widget.elevation
561    }
562}
563
564/// Dart's `WidgetStateProperty.resolveAs<ShapeBorder?>(shape, states)`: the border a
565/// [`WidgetStateOutlinedBorder`](waft_widgets::WidgetStateOutlinedBorder) resolves to, and any
566/// other border itself.
567fn resolve_shape(shape: &ShapeBorderRef, states: &WidgetStates) -> Option<ShapeBorderRef> {
568    let Some(outlined) = shape.as_outlined_border_ref() else {
569        return Some(shape.clone());
570    };
571    let resolved =
572        <dyn WidgetStateProperty<Option<OutlinedBorderRef>>>::resolve_as(&Some(outlined), states);
573    resolved.map(ShapeBorderRef::from)
574}
575
576impl MaterialStateMixin for RawMaterialButtonState {
577    fn material_state_data(self: Handle<Self>, app: &App) -> &MaterialStateMixinData {
578        &app.get(self).material_state
579    }
580
581    fn material_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut MaterialStateMixinData {
582        &mut app.get_mut(self).material_state
583    }
584}
585
586impl State for RawMaterialButtonState {
587    type Widget = RawMaterialButton;
588    waft_widgets::state_accessors!();
589
590    fn debug_fill_properties(
591        self: Handle<Self>,
592        app: &App,
593        properties: &mut DiagnosticPropertiesBuilder,
594    ) {
595        self.material_state_data(app)
596            .debug_fill_properties(properties);
597    }
598
599    fn init_state(self: Handle<Self>, app: &mut App) {
600        let enabled = self.widget(app).enabled();
601        self.set_material_state(app, WidgetState::Disabled, !enabled);
602    }
603
604    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RawMaterialButton) {
605        let enabled = self.widget(app).enabled();
606        self.set_material_state(app, WidgetState::Disabled, !enabled);
607        // If the button is disabled while a press gesture is currently ongoing,
608        // InkWell makes a call to handleHighlightChanged. This causes an exception
609        // because it calls setState in the middle of a build. To preempt this, we
610        // manually update pressed to false when this situation occurs.
611        if self.is_disabled(app) && self.is_pressed(app) {
612            self.remove_material_state(app, WidgetState::Pressed);
613        }
614    }
615
616    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
617        // Dart reads the theme where it builds the `Material`; `widget` below borrows `app`.
618        let theme = Theme::of(app, context);
619        let widget = self.widget(app);
620        let states = self.material_states(app);
621        let effective_text_color = <dyn WidgetStateProperty<Color>>::resolve_as(
622            &widget
623                .text_style
624                .as_ref()
625                .and_then(|text_style| text_style.color.clone()),
626            states,
627        );
628        let effective_shape = resolve_shape(&widget.shape, states);
629        let density_adjustment = widget.visual_density.base_size_adjustment();
630        let effective_constraints = widget
631            .visual_density
632            .effective_constraints(widget.constraints);
633        let mouse_cursor: MouseCursorRef = widget
634            .mouse_cursor
635            .clone()
636            .unwrap_or_else(|| Rc::new(WidgetStateMouseCursor::adaptive_clickable()));
637        let effective_mouse_cursor =
638            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states);
639        let padding = widget
640            .padding
641            .add(EdgeInsetsGeometry::Insets(EdgeInsets::only(
642                density_adjustment.dx(),
643                density_adjustment.dy(),
644                density_adjustment.dx(),
645                density_adjustment.dy(),
646            )))
647            .clamp(&EdgeInsetsGeometry::ZERO, &EdgeInsetsGeometry::INFINITY);
648
649        let mut center = Center::new().width_factor(1.0).height_factor(1.0);
650        if let Some(child) = &widget.child {
651            center = center.child(child.clone());
652        }
653        let mut icon_theme_data = IconThemeData::new();
654        if let Some(color) = effective_text_color.clone() {
655            icon_theme_data = icon_theme_data.color(color);
656        }
657        let mut ink_well =
658            InkWell::new()
659                .can_request_focus(widget.enabled())
660                .on_focus_change(self.update_material_state(WidgetState::Focused, None))
661                .autofocus(widget.autofocus)
662                .on_highlight_changed(self.update_material_state(
663                    WidgetState::Pressed,
664                    widget.on_highlight_changed.clone(),
665                ))
666                .on_hover(self.update_material_state(WidgetState::Hovered, None))
667                .enable_feedback(widget.enable_feedback)
668                .mouse_cursor(effective_mouse_cursor)
669                .child(IconTheme::merge(
670                    None,
671                    icon_theme_data,
672                    Padding::new(padding).child(center),
673                ));
674        if let Some(focus_node) = widget.focus_node.clone() {
675            ink_well = ink_well.focus_node(focus_node);
676        }
677        if let Some(splash_color) = widget.splash_color {
678            ink_well = ink_well.splash_color(splash_color);
679        }
680        if let Some(highlight_color) = widget.highlight_color {
681            ink_well = ink_well.highlight_color(highlight_color);
682        }
683        if let Some(focus_color) = widget.focus_color {
684            ink_well = ink_well.focus_color(focus_color);
685        }
686        if let Some(hover_color) = widget.hover_color {
687            ink_well = ink_well.hover_color(hover_color);
688        }
689        if let Some(on_pressed) = widget.on_pressed.clone() {
690            ink_well = ink_well.on_tap(on_pressed);
691        }
692        if let Some(on_long_press) = widget.on_long_press.clone() {
693            ink_well = ink_well.on_long_press(on_long_press);
694        }
695        if let Some(effective_shape) = &effective_shape {
696            ink_well = ink_well.custom_border(effective_shape.clone());
697        }
698
699        let mut material = Material::new()
700            .elevation(self.effective_elevation(app))
701            .r#type(if widget.fill_color.is_none() {
702                MaterialType::Transparency
703            } else {
704                MaterialType::Button
705            })
706            .animation_duration(widget.animation_duration)
707            .clip_behavior(widget.clip_behavior)
708            .child(ink_well);
709        if let Some(text_style) = &widget.text_style {
710            let mut text_style = text_style.copy_with();
711            if let Some(color) = effective_text_color {
712                text_style = text_style.color(color);
713            }
714            material = material.text_style(text_style);
715        }
716        if let Some(effective_shape) = effective_shape {
717            material = material.shape(effective_shape);
718        }
719        if let Some(fill_color) = widget.fill_color {
720            material = material.color(fill_color);
721        }
722        // For compatibility during the M3 migration the default shadow needs to be passed.
723        if theme.use_material3 {
724            material = material.shadow_color(theme.shadow_color);
725        }
726        let result = ConstrainedBox::new(effective_constraints).child(material);
727
728        let min_size = match widget.material_tap_target_size {
729            MaterialTapTargetSize::Padded => {
730                let min_size = Size::new(
731                    K_MIN_INTERACTIVE_DIMENSION + density_adjustment.dx(),
732                    K_MIN_INTERACTIVE_DIMENSION + density_adjustment.dy(),
733                );
734                debug_assert!(min_size.width() >= 0.0);
735                debug_assert!(min_size.height() >= 0.0);
736                min_size
737            }
738            MaterialTapTargetSize::ShrinkWrap => Size::ZERO,
739        };
740
741        Semantics::new()
742            .container(true)
743            .button(true)
744            .enabled(widget.enabled())
745            .child(InputPadding {
746                child: Some(result.into_widget()),
747                min_size,
748            })
749            .into_widget()
750    }
751}
752
753/// A widget to pad the area around a `MaterialButton`'s inner [`Material`].
754///
755/// Redirect taps that occur in the padded area around the child to the center
756/// of the child. This increases the size of the button and the button's
757/// "tap target", but not its material or its ink splashes.
758///
759/// Dart's `_InputPadding`.
760#[derive(Debug)]
761struct InputPadding {
762    child: Option<WidgetRef>,
763    min_size: Size,
764}
765
766impl RenderObjectWidget for InputPadding {
767    type RenderObject = RenderInputPadding;
768
769    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
770        RenderInputPadding::new(app, self.min_size, None).as_object()
771    }
772
773    fn update_render_object(
774        &self,
775        app: &mut App,
776        _context: BuildContext,
777        render_object: RenderHandle<RenderInputPadding>,
778    ) {
779        render_object.set_min_size(app, self.min_size);
780    }
781}
782
783impl SingleChildRenderObjectWidget for InputPadding {
784    fn child(&self) -> Option<&WidgetRef> {
785        self.child.as_ref()
786    }
787}
788
789/// Dart's `_RenderInputPadding`.
790struct RenderInputPadding {
791    render_object: RenderObjectData,
792    render_box: RenderBoxData,
793    child: RenderObjectWithChildData<AnyRenderBox>,
794    min_size: Size,
795}
796
797impl RenderInputPadding {
798    fn new(
799        app: &mut App,
800        min_size: Size,
801        child: Option<AnyRenderBox>,
802    ) -> RenderHandle<RenderInputPadding> {
803        let this = RenderHandle::new_box(
804            app,
805            RenderInputPadding {
806                render_object: RenderObjectData::new(),
807                render_box: RenderBoxData::new(),
808                child: RenderObjectWithChildData::new(),
809                min_size,
810            },
811        );
812        this.set_child(app, child);
813        this
814    }
815
816    fn min_size(self: RenderHandle<Self>, app: &App) -> Size {
817        self.get(app).min_size
818    }
819
820    fn set_min_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
821        if self.min_size(app) == value {
822            return;
823        }
824        self.get_mut(app).min_size = value;
825        RenderBox::mark_needs_layout(self, app);
826    }
827
828    fn compute_size(
829        self: RenderHandle<Self>,
830        app: &mut App,
831        constraints: BoxConstraints,
832        layout_child: ChildLayouter,
833    ) -> Size {
834        if let Some(child) = self.child(app) {
835            let min_size = self.min_size(app);
836            let child_size = layout_child(app, child, constraints);
837            let width = child_size.width().max(min_size.width());
838            let height = child_size.height().max(min_size.height());
839            return constraints.constrain(Size::new(width, height));
840        }
841        Size::ZERO
842    }
843}
844
845impl RenderObjectWithChildMixin for RenderInputPadding {
846    type ChildType = AnyRenderBox;
847
848    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
849        &self.get(app).child
850    }
851
852    fn child_data_mut(
853        self: RenderHandle<Self>,
854        app: &mut App,
855    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
856        &mut self.get_mut(app).child
857    }
858}
859
860impl RenderShiftedBox for RenderInputPadding {}
861
862impl RenderObject for RenderInputPadding {
863    waft_rendering::render_object_accessors!();
864
865    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
866        let constraints = self.constraints(app);
867        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
868        self.set_size(app, size);
869        if let Some(child) = self.child(app) {
870            let child_size = child.size(app);
871            child.parent_data_of_mut::<BoxParentData>(app).offset =
872                Alignment::CENTER.along_offset(size - child_size);
873        }
874    }
875
876    fn paint(
877        self: RenderHandle<Self>,
878        app: &mut App,
879        context: &mut PaintingContext,
880        offset: Offset,
881    ) {
882        RenderShiftedBox::paint(self, app, context, offset);
883    }
884
885    fn visit_children(
886        self: RenderHandle<Self>,
887        app: &App,
888        visitor: &mut dyn FnMut(AnyRenderObject),
889    ) {
890        if let Some(child) = self.child(app) {
891            visitor(child.as_object());
892        }
893    }
894}
895
896impl RenderBox for RenderInputPadding {
897    waft_rendering::render_box_accessors!();
898
899    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
900        if let Some(child) = self.child(app) {
901            return child
902                .get_min_intrinsic_width(app, height)
903                .max(self.min_size(app).width());
904        }
905        0.0
906    }
907
908    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
909        if let Some(child) = self.child(app) {
910            return child
911                .get_min_intrinsic_height(app, width)
912                .max(self.min_size(app).height());
913        }
914        0.0
915    }
916
917    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
918        if let Some(child) = self.child(app) {
919            return child
920                .get_max_intrinsic_width(app, height)
921                .max(self.min_size(app).width());
922        }
923        0.0
924    }
925
926    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
927        if let Some(child) = self.child(app) {
928            return child
929                .get_max_intrinsic_height(app, width)
930                .max(self.min_size(app).height());
931        }
932        0.0
933    }
934
935    fn compute_dry_layout(
936        self: RenderHandle<Self>,
937        app: &mut App,
938        constraints: BoxConstraints,
939    ) -> Size {
940        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
941    }
942
943    fn compute_dry_baseline(
944        self: RenderHandle<Self>,
945        app: &mut App,
946        constraints: BoxConstraints,
947        baseline: TextBaseline,
948    ) -> Option<f64> {
949        let child = self.child(app)?;
950        let result = child.get_dry_baseline(app, constraints, baseline)?;
951        let child_size = child.get_dry_layout(app, constraints);
952        let size = self.get_dry_layout(app, constraints);
953        Some(result + Alignment::CENTER.along_offset(size - child_size).dy())
954    }
955
956    fn compute_distance_to_actual_baseline(
957        self: RenderHandle<Self>,
958        app: &mut App,
959        baseline: TextBaseline,
960    ) -> Option<f64> {
961        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
962    }
963
964    fn hit_test_children(
965        self: RenderHandle<Self>,
966        app: &mut App,
967        result: &mut BoxHitTestResult<'_>,
968        position: Offset,
969    ) -> bool {
970        RenderShiftedBox::hit_test_children(self, app, result, position)
971    }
972
973    fn hit_test(
974        self: RenderHandle<Self>,
975        app: &mut App,
976        result: &mut BoxHitTestResult<'_>,
977        position: Offset,
978    ) -> bool {
979        if RenderBoxBase::hit_test(self, app, result, position) {
980            return true;
981        }
982        let child = self.child(app).expect("a hit on the padding needs a child");
983        let center = child.size(app).center(Offset::ZERO);
984        result.add_with_raw_transform(Some(force_to_point(center)), center, |result, position| {
985            debug_assert!(
986                (position.dx() - center.dx()).abs() <= center.dx().abs() * f32::EPSILON as f64
987                    && (position.dy() - center.dy()).abs()
988                        <= center.dy().abs() * f32::EPSILON as f64,
989                "the forced transform maps every hit to the child's center"
990            );
991            child.hit_test(app, result, center)
992        })
993    }
994}
995
996#[cfg(test)]
997mod tests {
998    use std::any::Any;
999    use std::cell::Cell;
1000
1001    use waft_embedder::{Rect, TextDirection};
1002    use waft_gestures::{GestureBinding, HitTestResult};
1003    use waft_rendering::BoxHitTestEntry;
1004    use waft_services::SystemMouseCursors;
1005    use waft_widgets::{
1006        Actions, ActivateIntent, Builder, ColoredBox, Column, CrossAxisAlignment, Directionality,
1007        FocusHighlightStrategy, FocusManager, FocusNode, FocusScope, GlobalKey, MouseRegion,
1008        SizedBox, Text,
1009    };
1010
1011    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
1012
1013    use super::*;
1014    use crate::test_support::{PaintInspection, path_like};
1015    use crate::theme_data::ThemeData;
1016    use waft_rendering::testing::RecordedCall;
1017
1018    fn noop() -> Option<Listener> {
1019        Some(Listener::new(|_app| {}))
1020    }
1021
1022    /// `Theme(data: ThemeData(useMaterial3: false), child: Directionality(ltr, child))`.
1023    fn m2_ltr<K>(tester: &WidgetTester, child: impl IntoWidget<K>) -> WidgetRef {
1024        let data = ThemeData::builder()
1025            .use_material3(false)
1026            .build(&tester.cell.borrow());
1027        Theme::new(data, Directionality::new(TextDirection::Ltr, child)).into_widget()
1028    }
1029
1030    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1031        Directionality::new(TextDirection::Ltr, child).into_widget()
1032    }
1033
1034    fn center_of_view() -> Offset {
1035        WidgetTester::SIZE.center(Offset::ZERO)
1036    }
1037
1038    fn set_highlight_strategy(tester: &WidgetTester, strategy: FocusHighlightStrategy) {
1039        let mut app = tester.cell.borrow_mut();
1040        FocusManager::instance(&mut app).set_highlight_strategy(&mut app, strategy);
1041    }
1042
1043    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
1044        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
1045    }
1046
1047    /// Dart's `Text(text)`.
1048    fn label(text: &str) -> Text {
1049        Text::new(text)
1050    }
1051
1052    fn red_square() -> SizedBox {
1053        SizedBox::new()
1054            .width(100.0)
1055            .height(100.0)
1056            .child(ColoredBox::new(Color::new(0xffff0000)))
1057    }
1058
1059    /// The colors of the rects the first material's ink features draw.
1060    fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
1061        tester
1062            .ink_calls()
1063            .into_iter()
1064            .filter_map(|drawn| match drawn {
1065                RecordedCall::Rect { color, .. } => Some(color.to_argb32()),
1066                _ => None,
1067            })
1068            .collect()
1069    }
1070
1071    /// The colors and bounds of the circles (paths) the first material's ink features draw.
1072    fn ink_circles(tester: &WidgetTester) -> Vec<(u32, Rect)> {
1073        tester
1074            .ink_calls()
1075            .into_iter()
1076            .filter_map(|drawn| {
1077                path_like(&drawn).map(|(color, bounds)| (color.to_argb32(), bounds))
1078            })
1079            .collect()
1080    }
1081
1082    /// Whether the first material draws a circle of the color `rgb`, whatever its alpha.
1083    fn has_splash(tester: &WidgetTester, rgb: u32) -> bool {
1084        ink_circles(tester)
1085            .iter()
1086            .any(|(color, _)| color & 0x00ff_ffff == rgb)
1087    }
1088
1089    /// Dart's `finder.hitTestable()` for the render object of `key`'s widget: it is on the path
1090    /// of a hit test at its own center.
1091    fn is_hit_testable(tester: &WidgetTester, key: &GlobalKey) -> bool {
1092        let render = tester.render_object(key);
1093        let render_box = render.as_box().expect("a render box");
1094        let mut app = tester.cell.borrow_mut();
1095        let center =
1096            render_box.local_to_global(&app, render_box.size(&app).center(Offset::ZERO), None);
1097        let view = app.platform().views().into_iter().next().expect("one view");
1098        let mut result = HitTestResult::new();
1099        GestureBinding::instance(&mut app).hit_test_in_view(
1100            &mut app,
1101            &mut result,
1102            center,
1103            view.id(),
1104        );
1105        result.path().iter().any(|entry| {
1106            (entry.target() as &dyn Any)
1107                .downcast_ref::<BoxHitTestEntry>()
1108                .is_some_and(|hit| hit.target().as_object() == render)
1109        })
1110    }
1111
1112    fn rect_of(tester: &WidgetTester, key: &GlobalKey) -> Rect {
1113        let render_box = tester.render_object(key).as_box().expect("a render box");
1114        let app = tester.cell.borrow();
1115        let origin = render_box.local_to_global(&app, Offset::ZERO, None);
1116        origin & render_box.size(&app)
1117    }
1118
1119    #[test]
1120    fn raw_material_button_responds_when_tapped() {
1121        test_widgets(|tester| {
1122            let pressed = Rc::new(Cell::new(false));
1123            let splash_color = Color::new(0xff00ff00);
1124            tester.pump_widget(m2_ltr(
1125                tester,
1126                Center::new().child(
1127                    RawMaterialButton::new(Some(Listener::new({
1128                        let pressed = Rc::clone(&pressed);
1129                        move |_app| pressed.set(true)
1130                    })))
1131                    .splash_color(splash_color)
1132                    .child(label("BUTTON")),
1133                ),
1134            ));
1135
1136            tester.tap_at(center_of_view(), 1);
1137            tester.pump_by(Duration::from_millis(10));
1138            // valo records no circle of radius 0, which the splash has until its first
1139            // frame after this one; by then it has begun to fade.
1140            tester.pump_by(Duration::from_millis(16));
1141
1142            assert!(has_splash(tester, 0x00ff00));
1143
1144            tester.pump_and_settle();
1145
1146            assert!(pressed.get());
1147        });
1148    }
1149
1150    /// Dart sends the shortcuts' keys; here the intent is invoked at a context under the
1151    /// button, where the focused `Shortcuts` would invoke it.
1152    #[test]
1153    fn raw_material_button_responds_to_shortcut_when_activated() {
1154        test_widgets(|tester| {
1155            let pressed = Rc::new(Cell::new(false));
1156            let inner: Rc<Cell<Option<BuildContext>>> = Rc::default();
1157            let focus_node = focus_node(tester);
1158            tester.pump_widget(m2_ltr(
1159                tester,
1160                Center::new().child(
1161                    RawMaterialButton::new(Some(Listener::new({
1162                        let pressed = Rc::clone(&pressed);
1163                        move |_app| pressed.set(true)
1164                    })))
1165                    .splash_color(Color::new(0xff00ff00))
1166                    .focus_node(focus_node.clone())
1167                    .child(Builder::new({
1168                        let inner = Rc::clone(&inner);
1169                        move |_app, context| {
1170                            inner.set(Some(context));
1171                            SizedBox::shrink().into_widget()
1172                        }
1173                    })),
1174                ),
1175            ));
1176            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1177            tester.pump();
1178            let context = inner.get().expect("built");
1179
1180            for _ in 0..2 {
1181                pressed.set(false);
1182                Actions::invoke(&mut tester.cell.borrow_mut(), context, &ActivateIntent);
1183                tester.pump_by(Duration::from_millis(10));
1184                // valo records no circle of radius 0, which the splash has until its first
1185                // frame after this one.
1186                tester.pump_by(Duration::from_millis(16));
1187                assert!(has_splash(tester, 0x00ff00));
1188                tester.pump_and_settle();
1189                assert!(pressed.get());
1190            }
1191        });
1192    }
1193
1194    #[test]
1195    fn material_tap_target_size_padded_expands_hit_test_area() {
1196        test_widgets(|tester| {
1197            let pressed = Rc::new(Cell::new(0));
1198            tester.pump_widget(ltr(RawMaterialButton::new(Some(Listener::new({
1199                let pressed = Rc::clone(&pressed);
1200                move |_app| pressed.set(pressed.get() + 1)
1201            })))
1202            .constraints(BoxConstraints::tight(Size::new(10.0, 10.0)))
1203            .material_tap_target_size(MaterialTapTargetSize::Padded)
1204            .child(label("+"))));
1205
1206            tester.tap_at(Offset::new(40.0, 400.0), 1);
1207
1208            assert_eq!(pressed.get(), 1);
1209        });
1210    }
1211
1212    fn splash_case(tester: &mut WidgetTester, at: impl Fn(Offset) -> Offset) -> Vec<(u32, Rect)> {
1213        let splash_color = Color::new(0xAA0000FF);
1214        tester.pump_widget(m2_ltr(
1215            tester,
1216            Center::new().child(
1217                RawMaterialButton::new(noop())
1218                    .material_tap_target_size(MaterialTapTargetSize::Padded)
1219                    .fill_color(Color::new(0xFFEF5350))
1220                    .highlight_color(Color::new(0xAAFF0000))
1221                    .splash_color(splash_color)
1222                    .child(SizedBox::new()),
1223            ),
1224        ));
1225        let mut gesture = TestPointer::touch(1);
1226        tester.down(&mut gesture, at(center_of_view()));
1227        tester.pump(); // start gesture
1228        tester.pump_by(Duration::from_millis(200)); // wait for splash to be well under way
1229        let circles = ink_circles(tester);
1230        tester.up(&gesture);
1231        circles
1232    }
1233
1234    #[test]
1235    fn ink_splash_from_center_tap_originates_in_correct_location() {
1236        test_widgets(|tester| {
1237            let circles = splash_case(tester, |center| center);
1238            // centered in material button.
1239            assert!(
1240                circles.iter().any(|(color, bounds)| *color == 0xAA0000FF
1241                    && bounds.center() == Offset::new(44.0, 18.0)),
1242                "{circles:?}"
1243            );
1244        });
1245    }
1246
1247    #[test]
1248    fn ink_splash_from_tap_above_material_originates_in_correct_location() {
1249        test_widgets(|tester| {
1250            // The top center of the button's 88x36 material, which is centered in the view.
1251            let circles = splash_case(tester, |center| center - Offset::new(0.0, 18.0));
1252            // paints above material
1253            assert!(
1254                circles.iter().any(|(color, bounds)| *color == 0xAA0000FF
1255                    && bounds.center() == Offset::new(44.0, 0.0)),
1256                "{circles:?}"
1257            );
1258        });
1259    }
1260
1261    /// Not in Flutter's file, whose version of this case taps where the root's tight
1262    /// constraints put the button anyway: a tap in the padding around a 10x10 material reaches
1263    /// it, and the semantics case's 48x48 size is the padding's. Like Dart's, the redirect does not
1264    /// check the position is in bounds.
1265    #[test]
1266    fn a_tap_in_the_padding_around_the_material_reaches_the_button() {
1267        test_widgets(|tester| {
1268            let key = GlobalKey::new();
1269            let pressed = Rc::new(Cell::new(0));
1270            tester.pump_widget(m2_ltr(
1271                tester,
1272                Center::new().child(
1273                    RawMaterialButton::new(Some(Listener::new({
1274                        let pressed = Rc::clone(&pressed);
1275                        move |_app| pressed.set(pressed.get() + 1)
1276                    })))
1277                    .key(key.clone().into())
1278                    .constraints(BoxConstraints::tight(Size::new(10.0, 10.0)))
1279                    .material_tap_target_size(MaterialTapTargetSize::Padded)
1280                    .child(label("+")),
1281                ),
1282            ));
1283            assert_eq!(tester.get_size(&key), Size::new(48.0, 48.0));
1284
1285            tester.tap_at(center_of_view() + Offset::new(20.0, 0.0), 1);
1286            assert_eq!(pressed.get(), 1);
1287        });
1288    }
1289
1290    #[test]
1291    fn off_center_child_is_hit_testable() {
1292        test_widgets(|tester| {
1293            let key = GlobalKey::new();
1294            tester.pump_widget(m2_ltr(
1295                tester,
1296                Column::new().children([RawMaterialButton::new(noop())
1297                    .material_tap_target_size(MaterialTapTargetSize::Padded)
1298                    .child(
1299                        SizedBox::square(Some(400.0)).child(
1300                            Column::new()
1301                                .main_axis_alignment(waft_rendering::MainAxisAlignment::End)
1302                                .children([SizedBox::new()
1303                                    .height(50.0)
1304                                    .width(400.0)
1305                                    .child(label("Material").key(key.clone().into()))
1306                                    .into_widget()]),
1307                        ),
1308                    )
1309                    .into_widget()]),
1310            ));
1311            assert!(is_hit_testable(tester, &key));
1312        });
1313    }
1314
1315    #[test]
1316    fn smaller_child_is_hit_testable() {
1317        test_widgets(|tester| {
1318            let key = GlobalKey::new();
1319            tester.pump_widget(m2_ltr(
1320                tester,
1321                Column::new().children([RawMaterialButton::new(noop())
1322                    .material_tap_target_size(MaterialTapTargetSize::Padded)
1323                    .child(
1324                        SizedBox::new()
1325                            .key(key.clone().into())
1326                            .width(8.0)
1327                            .height(8.0)
1328                            .child(ColoredBox::new(Color::new(0xFFAABBCC))),
1329                    )
1330                    .into_widget()]),
1331            ));
1332            assert!(is_hit_testable(tester, &key));
1333        });
1334    }
1335
1336    #[test]
1337    fn raw_material_button_can_be_expanded_by_parent_constraints() {
1338        test_widgets(|tester| {
1339            let key = GlobalKey::new();
1340            tester.pump_widget(m2_ltr(
1341                tester,
1342                Column::new()
1343                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
1344                    .children([RawMaterialButton::new(noop())
1345                        .key(key.clone().into())
1346                        .child(SizedBox::new())
1347                        .into_widget()]),
1348            ));
1349
1350            assert_eq!(tester.get_size(&key), Size::new(800.0, 48.0));
1351        });
1352    }
1353
1354    #[test]
1355    fn raw_material_button_handles_focus() {
1356        test_widgets(|tester| {
1357            let focus_node = focus_node(tester);
1358            let focus_color = Color::new(0xff00ff00);
1359
1360            set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
1361            tester.pump_widget(m2_ltr(
1362                tester,
1363                Center::new().child(
1364                    RawMaterialButton::new(noop())
1365                        .focus_node(focus_node.clone())
1366                        .focus_color(focus_color)
1367                        .child(red_square()),
1368                ),
1369            ));
1370            assert!(!ink_rect_colors(tester).contains(&0xff00ff00));
1371
1372            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1373            tester.pump_and_settle();
1374
1375            assert!(ink_rect_colors(tester).contains(&0xff00ff00));
1376        });
1377    }
1378
1379    #[test]
1380    fn raw_material_button_loses_focus_when_disabled() {
1381        test_widgets(|tester| {
1382            let focus_node = focus_node(tester);
1383            tester.pump_widget(m2_ltr(
1384                tester,
1385                Center::new().child(
1386                    RawMaterialButton::new(noop())
1387                        .autofocus(true)
1388                        .focus_node(focus_node.clone())
1389                        .child(red_square()),
1390                ),
1391            ));
1392
1393            tester.pump();
1394            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1395
1396            tester.pump_widget(m2_ltr(
1397                tester,
1398                Center::new().child(
1399                    RawMaterialButton::new(None)
1400                        .focus_node(focus_node.clone())
1401                        .child(red_square()),
1402                ),
1403            ));
1404
1405            tester.pump();
1406            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
1407        });
1408    }
1409
1410    #[test]
1411    fn disabled_raw_material_button_cant_be_traversed_to() {
1412        test_widgets(|tester| {
1413            let focus_node1 = focus_node(tester);
1414            let focus_node2 = focus_node(tester);
1415            tester.pump_widget(m2_ltr(
1416                tester,
1417                FocusScope::new(
1418                    Center::new().child(
1419                        Column::new().children([
1420                            RawMaterialButton::new(noop())
1421                                .autofocus(true)
1422                                .focus_node(focus_node1.clone())
1423                                .child(red_square())
1424                                .into_widget(),
1425                            RawMaterialButton::new(None)
1426                                .autofocus(true)
1427                                .focus_node(focus_node2.clone())
1428                                .child(red_square())
1429                                .into_widget(),
1430                        ]),
1431                    ),
1432                ),
1433            ));
1434            tester.pump();
1435
1436            assert!(focus_node1.has_primary_focus(&tester.cell.borrow()));
1437            assert!(!focus_node2.has_primary_focus(&tester.cell.borrow()));
1438
1439            assert!(!focus_node1.next_focus(&mut tester.cell.borrow_mut()));
1440            tester.pump();
1441
1442            assert!(focus_node1.has_primary_focus(&tester.cell.borrow()));
1443            assert!(!focus_node2.has_primary_focus(&tester.cell.borrow()));
1444        });
1445    }
1446
1447    #[test]
1448    fn raw_material_button_handles_hover() {
1449        test_widgets(|tester| {
1450            let key = GlobalKey::new();
1451            let hover_color = Color::new(0xff00ff00);
1452
1453            set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
1454            tester.pump_widget(m2_ltr(
1455                tester,
1456                Center::new().child(
1457                    RawMaterialButton::new(noop())
1458                        .key(key.clone().into())
1459                        .hover_color(hover_color)
1460                        .hover_elevation(10.5)
1461                        .child(red_square()),
1462                ),
1463            ));
1464            let mut mouse = TestPointer::mouse(1, 0);
1465            tester.add_pointer(&mut mouse, Offset::ZERO);
1466            assert!(!ink_rect_colors(tester).contains(&0xff00ff00));
1467
1468            tester.move_to(&mut mouse, tester.get_center(&key), false);
1469            tester.pump_and_settle();
1470
1471            assert!(ink_rect_colors(tester).contains(&0xff00ff00));
1472        });
1473    }
1474
1475    #[test]
1476    fn raw_material_button_on_pressed_and_on_long_press_callbacks_are_correctly_called_when_non_null()
1477     {
1478        test_widgets(|tester| {
1479            let key = GlobalKey::new();
1480            let was_pressed = Rc::new(Cell::new(false));
1481            let was_pressed_listener = || {
1482                let was_pressed = Rc::clone(&was_pressed);
1483                Listener::new(move |_app| was_pressed.set(true))
1484            };
1485            // Returns the button's `enabled`, which Dart reads off `tester.widget`.
1486            let build_frame = |tester: &mut WidgetTester,
1487                               on_pressed: Option<Listener>,
1488                               on_long_press: Option<Listener>|
1489             -> bool {
1490                let mut button = RawMaterialButton::new(on_pressed)
1491                    .key(key.clone().into())
1492                    .child(label("button"));
1493                button.on_long_press = on_long_press;
1494                let enabled = button.enabled();
1495                tester.pump_widget(ltr(button));
1496                enabled
1497            };
1498
1499            // onPressed not null, onLongPress null.
1500            was_pressed.set(false);
1501            assert!(build_frame(tester, Some(was_pressed_listener()), None));
1502            tester.tap_at(tester.get_center(&key), 1);
1503            assert!(was_pressed.get());
1504
1505            // onPressed null, onLongPress not null.
1506            was_pressed.set(false);
1507            assert!(build_frame(tester, None, Some(was_pressed_listener())));
1508            tester.long_press_at(tester.get_center(&key), 2);
1509            assert!(was_pressed.get());
1510
1511            // onPressed null, onLongPress null.
1512            assert!(!build_frame(tester, None, None));
1513        });
1514    }
1515
1516    #[test]
1517    fn raw_material_button_on_pressed_and_on_long_press_callbacks_are_distinctly_recognized() {
1518        test_widgets(|tester| {
1519            let key = GlobalKey::new();
1520            let did_press_button = Rc::new(Cell::new(false));
1521            let did_long_press_button = Rc::new(Cell::new(false));
1522            tester.pump_widget(ltr(RawMaterialButton::new(Some(Listener::new({
1523                let did_press_button = Rc::clone(&did_press_button);
1524                move |_app| did_press_button.set(true)
1525            })))
1526            .key(key.clone().into())
1527            .on_long_press(Listener::new({
1528                let did_long_press_button = Rc::clone(&did_long_press_button);
1529                move |_app| did_long_press_button.set(true)
1530            }))
1531            .child(label("button"))));
1532
1533            assert!(!did_press_button.get());
1534            tester.tap_at(tester.get_center(&key), 1);
1535            assert!(did_press_button.get());
1536
1537            assert!(!did_long_press_button.get());
1538            tester.long_press_at(tester.get_center(&key), 2);
1539            assert!(did_long_press_button.get());
1540        });
1541    }
1542
1543    #[test]
1544    fn raw_material_button_responds_to_density_changes() {
1545        test_widgets(|tester| {
1546            let key = GlobalKey::new();
1547            let child_key = GlobalKey::new();
1548
1549            let build_test =
1550                |tester: &mut WidgetTester, visual_density: VisualDensity, use_text: bool| {
1551                    let child: WidgetRef = if use_text {
1552                        label("Text").key(child_key.clone().into()).into_widget()
1553                    } else {
1554                        SizedBox::new()
1555                            .key(child_key.clone().into())
1556                            .width(100.0)
1557                            .height(100.0)
1558                            .child(ColoredBox::new(Color::new(0xffff0000)))
1559                            .into_widget()
1560                    };
1561                    let data = ThemeData::builder()
1562                        .use_material3(false)
1563                        .build(&tester.cell.borrow());
1564                    tester.pump_widget(
1565                        Theme::new(
1566                            data,
1567                            Directionality::new(
1568                                TextDirection::Rtl,
1569                                Center::new().child(
1570                                    RawMaterialButton::new(noop())
1571                                        .visual_density(visual_density)
1572                                        .key(key.clone().into())
1573                                        .child(child),
1574                                ),
1575                            ),
1576                        )
1577                        .into_widget(),
1578                    );
1579                };
1580
1581            build_test(tester, VisualDensity::STANDARD, false);
1582            tester.pump_and_settle();
1583            assert_eq!(tester.get_size(&key), Size::new(100.0, 100.0));
1584            assert_eq!(
1585                rect_of(tester, &child_key),
1586                Rect::from_ltrb(350.0, 250.0, 450.0, 350.0)
1587            );
1588
1589            build_test(tester, VisualDensity::new(3.0, 3.0), false);
1590            tester.pump_and_settle();
1591            assert_eq!(tester.get_size(&key), Size::new(124.0, 124.0));
1592            assert_eq!(
1593                rect_of(tester, &child_key),
1594                Rect::from_ltrb(350.0, 250.0, 450.0, 350.0)
1595            );
1596
1597            build_test(tester, VisualDensity::new(-3.0, -3.0), false);
1598            tester.pump_and_settle();
1599            assert_eq!(tester.get_size(&key), Size::new(100.0, 100.0));
1600            assert_eq!(
1601                rect_of(tester, &child_key),
1602                Rect::from_ltrb(350.0, 250.0, 450.0, 350.0)
1603            );
1604
1605            build_test(tester, VisualDensity::STANDARD, true);
1606            tester.pump_and_settle();
1607            assert_eq!(tester.get_size(&key), Size::new(88.0, 48.0));
1608            assert_eq!(
1609                rect_of(tester, &child_key),
1610                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1611            );
1612
1613            build_test(tester, VisualDensity::new(3.0, 3.0), true);
1614            tester.pump_and_settle();
1615            assert_eq!(tester.get_size(&key), Size::new(100.0, 60.0));
1616            assert_eq!(
1617                rect_of(tester, &child_key),
1618                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1619            );
1620
1621            build_test(tester, VisualDensity::new(-3.0, -3.0), true);
1622            tester.pump_and_settle();
1623            assert_eq!(tester.get_size(&key), Size::new(76.0, 36.0));
1624            assert_eq!(
1625                rect_of(tester, &child_key),
1626                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1627            );
1628        });
1629    }
1630
1631    fn active_cursor(tester: &WidgetTester) -> MouseCursorRef {
1632        let mut app = tester.cell.borrow_mut();
1633        let tracker = waft_rendering::RendererBinding::instance(&mut app).mouse_tracker(&app);
1634        tracker
1635            .debug_device_active_cursor(&app, 1)
1636            .expect("the mouse is over the view")
1637    }
1638
1639    #[test]
1640    fn raw_material_button_changes_mouse_cursor_as_expected_when_hovered() {
1641        test_widgets(|tester| {
1642            let in_region = |child: RawMaterialButton| {
1643                ltr(MouseRegion::new()
1644                    .cursor(SystemMouseCursors::FORBIDDEN.into())
1645                    .child(child))
1646            };
1647            tester.pump_widget(in_region(
1648                RawMaterialButton::new(noop()).mouse_cursor(SystemMouseCursors::TEXT.into()),
1649            ));
1650            let mut mouse = TestPointer::mouse(1, 0);
1651            tester.add_pointer(&mut mouse, Offset::ZERO);
1652            tester.pump();
1653
1654            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
1655            assert!(*active_cursor(tester) == *text);
1656
1657            // Test default cursor
1658            tester.pump_widget(in_region(RawMaterialButton::new(noop())));
1659            let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
1660            assert!(*active_cursor(tester) == *basic);
1661
1662            // Test default cursor when disabled
1663            tester.pump_widget(in_region(RawMaterialButton::new(None)));
1664            assert!(*active_cursor(tester) == *basic);
1665        });
1666    }
1667
1668    /// Not in Flutter's file: `resolve_shape` stands for its `resolveAs<ShapeBorder?>`.
1669    #[test]
1670    fn a_widget_state_outlined_border_resolves_to_the_border_of_the_states() {
1671        let enabled = RoundedRectangleBorder::default();
1672        let disabled = RoundedRectangleBorder {
1673            border_radius: waft_painting::BorderRadius::circular(8.0).into(),
1674            ..RoundedRectangleBorder::default()
1675        };
1676        let property = waft_widgets::WidgetStateOutlinedBorder::resolve_with({
1677            move |states| {
1678                let border = if states.contains(&WidgetState::Disabled) {
1679                    disabled
1680                } else {
1681                    enabled
1682                };
1683                Some(OutlinedBorderRef::new(border))
1684            }
1685        });
1686
1687        let resolved = |shape: &ShapeBorderRef, states: &[WidgetState]| {
1688            resolve_shape(shape, &states.iter().copied().collect()).expect("a border")
1689        };
1690
1691        let property = ShapeBorderRef::new(property);
1692        assert!(resolved(&property, &[]).eq_shape(&enabled));
1693        assert!(resolved(&property, &[WidgetState::Disabled]).eq_shape(&disabled));
1694        // A border that is not a property is its own value.
1695        let disabled = ShapeBorderRef::new(disabled);
1696        assert_eq!(resolved(&disabled, &[]), disabled);
1697    }
1698
1699    #[test]
1700    fn raw_material_button_does_not_crash_at_zero_area() {
1701        test_widgets(|tester| {
1702            let key = GlobalKey::new();
1703            tester.pump_widget(m2_ltr(
1704                tester,
1705                Center::new().child(
1706                    SizedBox::shrink()
1707                        .child(RawMaterialButton::new(noop()).key(key.clone().into())),
1708                ),
1709            ));
1710            assert_eq!(tester.get_size(&key), Size::ZERO);
1711        });
1712    }
1713}