Skip to main content

waft_material/
action_chip.rs

1//! Flutter counterpart: material_ui's `action_chip.dart` with its
2//! `generated/action_chip_defaults_m3.g.dart`.
3
4use std::rc::Rc;
5
6use waft_embedder::{Clip, Color};
7use waft_foundation::{App, Listener};
8use waft_painting::{AnyBorderSide, EdgeInsetsGeometry, OutlinedBorderRef};
9use waft_rendering::BoxConstraints;
10use waft_services::MouseCursorRef;
11use waft_widgets::{
12    BuildContext, FocusNodeRef, IconThemeData, IntoWidget, KeyRef, StatelessWidget, TextStyle,
13    WidgetRef, WidgetStatePropertyRef,
14};
15
16use crate::chip::{
17    ChipAnimationStyle, ChipVariant, DisabledChipAttributes, RawChip, chip_into_setters,
18    chip_non_negative_setters, chip_option_setters, chip_value_setters, chip_widget_setters,
19    impl_chip_attributes, impl_disabled_chip_attributes, impl_tappable_chip_attributes,
20};
21use crate::debug::debug_check_has_material;
22use crate::generated::action_chip_defaults_m3::ActionChipDefaultsM3;
23use crate::theme::Theme;
24use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
25
26/// A Material Design action chip.
27///
28/// Action chips are a set of options which trigger an action related to primary
29/// content. Action chips should appear dynamically and contextually in a UI.
30///
31/// Action chips can be tapped to trigger an action or show progress and
32/// confirmation. For Material 3, a disabled state is supported for Action
33/// chips and is specified with [`on_pressed`](Self::on_pressed) being null. For previous
34/// versions of Material Design, it is recommended to remove the Action chip from
35/// the interface entirely rather than display a disabled chip.
36///
37/// Action chips are displayed after primary content, such as below a card or
38/// persistently at the bottom of a screen.
39///
40/// The material button widgets, `ElevatedButton`, `TextButton`, and
41/// `OutlinedButton`, are an alternative to action chips, which should appear
42/// statically and consistently in a UI.
43///
44/// Requires one of its ancestors to be a `Material` widget.
45///
46/// ## Material Design 3
47///
48/// [`ActionChip`] can be used for both the Assist and Suggestion chips from
49/// Material Design 3. If `ThemeData::use_material3` is true, then [`ActionChip`]
50/// will be styled to match the Material Design 3 Assist and Suggestion chips.
51///
52/// See also:
53///
54///  * [`Chip`], a chip that displays information and can be deleted.
55///  * `InputChip`, a chip that represents a complex piece of information, such
56///    as an entity (person, place, or thing) or conversational text, in a
57///    compact form.
58///  * `ChoiceChip`, allows a single selection from a set of options. Choice
59///    chips contain related descriptive text or categories.
60///  * `CircleAvatar`, which shows images or initials of people.
61///  * `Wrap`, A widget that displays its children in multiple horizontal or
62///    vertical runs.
63///  * <https://material.io/design/components/chips.html>
64#[derive(Clone, Debug)]
65pub struct ActionChip {
66    pub key: Option<KeyRef>,
67    pub avatar: Option<WidgetRef>,
68    pub label: WidgetRef,
69    pub label_style: Option<TextStyle>,
70    pub label_padding: Option<EdgeInsetsGeometry>,
71    pub on_pressed: Option<Listener>,
72    pub press_elevation: Option<f64>,
73    pub tooltip: Option<String>,
74    pub side: Option<AnyBorderSide>,
75    pub shape: Option<OutlinedBorderRef>,
76    pub clip_behavior: Clip,
77    pub focus_node: Option<FocusNodeRef>,
78    pub autofocus: bool,
79    pub color: Option<WidgetStatePropertyRef<Option<Color>>>,
80    pub background_color: Option<Color>,
81    pub disabled_color: Option<Color>,
82    pub padding: Option<EdgeInsetsGeometry>,
83    pub visual_density: Option<VisualDensity>,
84    pub material_tap_target_size: Option<MaterialTapTargetSize>,
85    pub elevation: Option<f64>,
86    pub shadow_color: Option<Color>,
87    pub surface_tint_color: Option<Color>,
88    pub icon_theme: Option<IconThemeData>,
89    pub avatar_box_constraints: Option<BoxConstraints>,
90    pub chip_animation_style: Option<ChipAnimationStyle>,
91    pub mouse_cursor: Option<MouseCursorRef>,
92    chip_variant: ChipVariant,
93}
94
95impl ActionChip {
96    /// Create a chip that acts like a button.
97    ///
98    /// The [`elevation`](Self::elevation) and [`press_elevation`](Self::press_elevation) must be null or non-negative. Dart's named arguments are the setters.
99    #[cfg_attr(debug_assertions, track_caller)]
100    pub fn new<K>(label: impl IntoWidget<K>) -> ActionChip {
101        ActionChip {
102            key: None,
103            avatar: None,
104            label: label.into_widget(),
105            label_style: None,
106            label_padding: None,
107            on_pressed: None,
108            press_elevation: None,
109            tooltip: None,
110            side: None,
111            shape: None,
112            clip_behavior: Clip::None,
113            focus_node: None,
114            autofocus: false,
115            color: None,
116            background_color: None,
117            disabled_color: None,
118            padding: None,
119            visual_density: None,
120            material_tap_target_size: None,
121            elevation: None,
122            shadow_color: None,
123            surface_tint_color: None,
124            icon_theme: None,
125            avatar_box_constraints: None,
126            chip_animation_style: None,
127            mouse_cursor: None,
128            chip_variant: ChipVariant::Flat,
129        }
130    }
131
132    /// Create an elevated chip that acts like a button.
133    ///
134    /// The [`elevation`](Self::elevation) and [`press_elevation`](Self::press_elevation) must be null or non-negative. Dart's named arguments are the setters.
135    #[cfg_attr(debug_assertions, track_caller)]
136    pub fn elevated<K>(label: impl IntoWidget<K>) -> ActionChip {
137        ActionChip {
138            chip_variant: ChipVariant::Elevated,
139            ..ActionChip::new(label)
140        }
141    }
142
143    chip_option_setters!(
144        ActionChip;
145        key: KeyRef,
146        label_style: TextStyle,
147        on_pressed: Listener,
148        tooltip: String,
149        focus_node: FocusNodeRef,
150        color: WidgetStatePropertyRef<Option<Color>>,
151        background_color: Color,
152        disabled_color: Color,
153        visual_density: VisualDensity,
154        material_tap_target_size: MaterialTapTargetSize,
155        shadow_color: Color,
156        surface_tint_color: Color,
157        icon_theme: IconThemeData,
158        avatar_box_constraints: BoxConstraints,
159        chip_animation_style: ChipAnimationStyle,
160        mouse_cursor: MouseCursorRef,
161    );
162    chip_value_setters!(
163        ActionChip;
164        clip_behavior: Clip,
165        autofocus: bool,
166    );
167    chip_widget_setters!(ActionChip; avatar);
168    chip_into_setters!(
169        ActionChip;
170        label_padding: EdgeInsetsGeometry,
171        side: AnyBorderSide,
172        shape: OutlinedBorderRef,
173        padding: EdgeInsetsGeometry,
174    );
175    chip_non_negative_setters!(ActionChip; press_elevation, elevation);
176}
177
178impl StatelessWidget for ActionChip {
179    fn key(&self) -> Option<&KeyRef> {
180        self.key.as_ref()
181    }
182
183    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
184        debug_assert!(debug_check_has_material(app, context));
185        let is_enabled = DisabledChipAttributes::is_enabled(self);
186        let mut raw_chip = RawChip::new(self.label.clone());
187        if Theme::of(app, context).use_material3 {
188            raw_chip.default_properties = Some(Rc::new(ActionChipDefaultsM3::new(
189                context,
190                is_enabled,
191                self.chip_variant,
192            )));
193        }
194        raw_chip.avatar = self.avatar.clone();
195        raw_chip.on_pressed = self.on_pressed.clone();
196        raw_chip.press_elevation = self.press_elevation;
197        raw_chip.tooltip = self.tooltip.clone();
198        raw_chip.label_style = self.label_style.clone();
199        raw_chip.color = self.color.clone();
200        raw_chip.background_color = self.background_color;
201        raw_chip.side = self.side.clone();
202        raw_chip.shape = self.shape.clone();
203        raw_chip.clip_behavior = self.clip_behavior;
204        raw_chip.focus_node = self.focus_node.clone();
205        raw_chip.autofocus = self.autofocus;
206        raw_chip.disabled_color = self.disabled_color;
207        raw_chip.padding = self.padding;
208        raw_chip.visual_density = self.visual_density;
209        raw_chip.is_enabled = is_enabled;
210        raw_chip.label_padding = self.label_padding;
211        raw_chip.material_tap_target_size = self.material_tap_target_size;
212        raw_chip.elevation = self.elevation;
213        raw_chip.shadow_color = self.shadow_color;
214        raw_chip.surface_tint_color = self.surface_tint_color;
215        raw_chip.icon_theme = self.icon_theme.clone();
216        raw_chip.avatar_box_constraints = self.avatar_box_constraints;
217        raw_chip.chip_animation_style = self.chip_animation_style.clone();
218        raw_chip.mouse_cursor = self.mouse_cursor.clone();
219        raw_chip.into_widget()
220    }
221}
222
223impl_chip_attributes!(ActionChip);
224impl_tappable_chip_attributes!(ActionChip);
225impl_disabled_chip_attributes!(ActionChip, |chip| chip.on_pressed.is_some());
226
227#[cfg(test)]
228pub(crate) mod tests {
229
230    use waft_animation::AnimationStyle;
231    use waft_embedder::{Offset, PointerChange, Size};
232    use waft_foundation::K_IS_WEB;
233    use waft_painting::{
234        BorderRadiusGeometry, BorderSide, RoundedRectangleBorder, ShapeBorderRef, StadiumBorder,
235    };
236    use waft_rendering::BoxConstraints;
237    use waft_services::{MouseCursorRef, SystemMouseCursors};
238    use waft_widgets::{
239        AnyElement, Center, Column, CustomPaint, FocusHighlightStrategy, FocusNode, FocusNodeLeaf,
240        SizedBox, Text, WidgetState, WidgetStateMouseCursor, WidgetStateProperty,
241        WidgetStatePropertyRef,
242    };
243
244    use waft_widgets::testing::{
245        TestPointer, WidgetTester, assert_more_or_less_equals_within, find, test_widgets,
246    };
247
248    use super::*;
249    use crate::chip::tests::{
250        chip_material_of, icon_data, ink_decoration_color, label_style_color, only, text, wrap_ltr,
251    };
252    use crate::colors::Colors;
253    use crate::icons::Icons;
254    use crate::material::Material;
255    use crate::motion::Durations;
256    use crate::scaffold::Scaffold;
257    use crate::test_support::{PaintInspection, material_app};
258
259    use crate::theme_data::ThemeData;
260    use crate::tooltip::tests::{m2, m3};
261    use waft_rendering::testing::{PaintCall, paints};
262
263    const LABEL: &str = "action chip";
264
265    fn pump_chip(tester: &mut WidgetTester, theme: &ThemeData, chip: ActionChip, centered: bool) {
266        let home = if centered {
267            Material::new()
268                .child(Center::new().child(chip))
269                .into_widget()
270        } else {
271            Material::new().child(chip).into_widget()
272        };
273        tester.pump_widget(material_app(theme.clone(), home));
274    }
275
276    fn rounded_rectangle(side: BorderSide) -> Option<waft_painting::ShapeBorderRef> {
277        Some(waft_painting::ShapeBorderRef::new(
278            RoundedRectangleBorder::new(side, BorderRadiusGeometry::circular(8.0)),
279        ))
280    }
281
282    #[test]
283    fn material3_action_chip_defaults() {
284        test_widgets(|tester| {
285            let theme = m3(&tester.cell.borrow());
286
287            // Test enabled ActionChip defaults.
288            let enabled = ActionChip::new(Text::new(LABEL)).on_pressed(Listener::new(|_| {}));
289            pump_chip(tester, &theme, enabled, true);
290
291            // Test default chip size.
292            let size = tester.get_size(only::<ActionChip>(tester));
293            assert_more_or_less_equals_within(size.width(), 189.1, 0.01);
294            assert_more_or_less_equals_within(size.height(), 48.0, 0.01);
295            // Test default label style.
296            assert_eq!(
297                label_style_color(tester, LABEL),
298                Some(theme.color_scheme.on_surface())
299            );
300
301            let chip = only::<RawChip>(tester);
302            let (elevation, shadow_color, surface_tint_color, shape) =
303                chip_material_of(tester, chip);
304            assert_eq!(elevation, 0.0);
305            assert_eq!(shadow_color, Some(Colors::TRANSPARENT));
306            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
307            assert_eq!(
308                shape,
309                rounded_rectangle(BorderSide {
310                    color: theme.color_scheme.outline_variant(),
311                    ..BorderSide::default()
312                })
313            );
314            assert_eq!(ink_decoration_color(tester), None);
315
316            // Test disabled ActionChip defaults.
317            pump_chip(tester, &theme, ActionChip::new(Text::new(LABEL)), false);
318            tester.pump_and_settle();
319
320            let chip = only::<RawChip>(tester);
321            let (elevation, shadow_color, surface_tint_color, shape) =
322                chip_material_of(tester, chip);
323            assert_eq!(elevation, 0.0);
324            assert_eq!(shadow_color, Some(Colors::TRANSPARENT));
325            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
326            assert_eq!(
327                shape,
328                rounded_rectangle(BorderSide {
329                    color: theme.color_scheme.on_surface().with_alpha(0x1f),
330                    ..BorderSide::default()
331                })
332            );
333            assert_eq!(ink_decoration_color(tester), None);
334        });
335    }
336
337    #[test]
338    fn material3_action_chip_elevated_defaults() {
339        test_widgets(|tester| {
340            let theme = m3(&tester.cell.borrow());
341            let transparent_side = BorderSide {
342                color: Colors::TRANSPARENT,
343                ..BorderSide::default()
344            };
345
346            // Test enabled ActionChip.elevated defaults.
347            let enabled = ActionChip::elevated(Text::new(LABEL)).on_pressed(Listener::new(|_| {}));
348            pump_chip(tester, &theme, enabled, true);
349
350            let size = tester.get_size(only::<ActionChip>(tester));
351            assert_more_or_less_equals_within(size.width(), 189.1, 0.01);
352            assert_more_or_less_equals_within(size.height(), 48.0, 0.01);
353            assert_eq!(
354                label_style_color(tester, LABEL),
355                Some(theme.color_scheme.on_surface())
356            );
357
358            let chip = only::<RawChip>(tester);
359            let (elevation, shadow_color, surface_tint_color, shape) =
360                chip_material_of(tester, chip);
361            assert_eq!(elevation, 1.0);
362            assert_eq!(shadow_color, Some(theme.color_scheme.shadow()));
363            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
364            assert_eq!(shape, rounded_rectangle(transparent_side));
365            assert_eq!(
366                ink_decoration_color(tester),
367                Some(theme.color_scheme.surface_container_low())
368            );
369
370            // Test disabled ActionChip.elevated defaults.
371            pump_chip(
372                tester,
373                &theme,
374                ActionChip::elevated(Text::new(LABEL)),
375                false,
376            );
377            tester.pump_and_settle();
378
379            let chip = only::<RawChip>(tester);
380            let (elevation, shadow_color, surface_tint_color, shape) =
381                chip_material_of(tester, chip);
382            assert_eq!(elevation, 0.0);
383            assert_eq!(shadow_color, Some(theme.color_scheme.shadow()));
384            assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
385            assert_eq!(shape, rounded_rectangle(transparent_side));
386            assert_eq!(
387                ink_decoration_color(tester),
388                Some(theme.color_scheme.on_surface().with_alpha(0x1f))
389            );
390        });
391    }
392
393    #[test]
394    fn action_chip_can_be_tapped() {
395        test_widgets(|tester| {
396            let theme = m3(&tester.cell.borrow());
397            let pressed = std::rc::Rc::new(std::cell::Cell::new(0));
398            let chip = ActionChip::new(Text::new(LABEL)).on_pressed({
399                let pressed = std::rc::Rc::clone(&pressed);
400                Listener::new(move |_| pressed.set(pressed.get() + 1))
401            });
402            pump_chip(tester, &theme, chip, false);
403
404            let center = crate::chip::tests::center_of(tester, only::<ActionChip>(tester));
405            tester.tap_at(center, 1);
406            assert_eq!(pressed.get(), 1);
407        });
408    }
409
410    pub(crate) fn pump_wrapped<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
411        let root = wrap_ltr(tester, child);
412        tester.pump_widget(root);
413    }
414
415    pub(crate) fn material_of(tester: &WidgetTester, chip: AnyElement) -> AnyElement {
416        tester.descendants_of_type::<Material>(chip)[0]
417    }
418
419    /// Dart's `getMaterialBox(tester, chip)`: the first `CustomPaint` below the chip.
420    pub(crate) fn material_box(tester: &WidgetTester, chip: AnyElement) -> AnyElement {
421        tester.descendants_of_type::<CustomPaint>(chip)[0]
422    }
423
424    /// Dart's `paints..rrect(color: color)` on `getMaterialBox(tester, chip)`: the first
425    /// rounded rect the box and everything under it draw is of `color`.
426    pub(crate) fn paints_rrect_color(
427        tester: &WidgetTester,
428        chip: AnyElement,
429        color: Color,
430    ) -> bool {
431        let render = tester.render_box_of(material_box(tester, chip)).as_object();
432        let ops = tester.painted_ops_deep(render);
433        paints(&ops, &[PaintCall::rrect(Some(color))]).is_ok()
434    }
435
436    /// Dart's `paints..path(color: color)` on `getMaterialBox(tester, chip)`.
437    pub(crate) fn paints_path_color(tester: &WidgetTester, chip: AnyElement, color: Color) -> bool {
438        let render = tester.render_box_of(material_box(tester, chip)).as_object();
439        paints(
440            &tester.painted_ops_deep(render),
441            &[PaintCall::path(Some(color))],
442        )
443        .is_ok()
444    }
445
446    pub(crate) fn raw_chips(tester: &WidgetTester) -> Vec<AnyElement> {
447        find::by_type::<RawChip>().evaluate(tester)
448    }
449
450    #[test]
451    fn material2_action_chip_defaults() {
452        test_widgets(|tester| {
453            let theme = m2(&tester.cell.borrow());
454
455            // Test enabled ActionChip defaults.
456            pump_chip(
457                tester,
458                &theme,
459                ActionChip::new(Text::new(LABEL)).on_pressed(Listener::new(|_| {})),
460                true,
461            );
462
463            // Test default chip size.
464            assert_eq!(
465                tester.get_size(only::<ActionChip>(tester)),
466                Size::new(178.0, 48.0)
467            );
468            // Test default label style.
469            assert_eq!(
470                label_style_color(tester, LABEL),
471                theme
472                    .text_theme
473                    .body_large
474                    .as_ref()
475                    .and_then(|style| style.color.as_ref())
476                    .map(|color| color.color().with_alpha(0xde))
477            );
478
479            let (elevation, shadow_color, _, shape) =
480                chip_material_of(tester, only::<RawChip>(tester));
481            assert_eq!(elevation, 0.0);
482            assert_eq!(shadow_color, Some(Colors::BLACK));
483            assert_eq!(
484                shape,
485                Some(ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE)))
486            );
487            assert_eq!(
488                ink_decoration_color(tester),
489                Some(Colors::BLACK.with_alpha(0x1f))
490            );
491
492            // Test disabled ActionChip defaults.
493            pump_chip(tester, &theme, ActionChip::new(Text::new(LABEL)), false);
494            tester.pump_and_settle();
495
496            let (elevation, shadow_color, _, shape) =
497                chip_material_of(tester, only::<RawChip>(tester));
498            assert_eq!(elevation, 0.0);
499            assert_eq!(shadow_color, Some(Colors::BLACK));
500            assert_eq!(
501                shape,
502                Some(ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE)))
503            );
504            assert_eq!(ink_decoration_color(tester), Some(Colors::BLACK38));
505        });
506    }
507
508    fn two_chips(
509        color: Option<WidgetStatePropertyRef<Option<Color>>>,
510        colors: Option<(Color, Color)>,
511        enabled: bool,
512    ) -> Column {
513        let build = |mut chip: ActionChip| {
514            if enabled {
515                chip = chip.on_pressed(Listener::new(|_| {}));
516            }
517            if let Some(color) = &color {
518                chip = chip.color(color.clone());
519            }
520            if let Some((disabled, background)) = colors {
521                chip = chip.disabled_color(disabled).background_color(background);
522            }
523            chip.into_widget()
524        };
525        Column::new().children([
526            build(ActionChip::new(Text::new("ActionChip"))),
527            build(ActionChip::elevated(Text::new("ActionChip.elevated"))),
528        ])
529    }
530
531    fn check_enabled_and_disabled_colors(
532        tester: &mut WidgetTester,
533        build: impl Fn(bool) -> Column,
534        disabled_color: Color,
535        background_color: Color,
536    ) {
537        // Test enabled state.
538        pump_wrapped(tester, build(true));
539        let chips = raw_chips(tester);
540        // Enabled ActionChip should have the provided backgroundColor.
541        assert!(paints_rrect_color(tester, chips[0], background_color));
542        // Enabled elevated ActionChip should have the provided backgroundColor.
543        assert!(paints_rrect_color(tester, chips[1], background_color));
544
545        // Test disabled state.
546        pump_wrapped(tester, build(false));
547        tester.pump_and_settle();
548        let chips = raw_chips(tester);
549        // Disabled ActionChip should have the provided disabledColor.
550        assert!(paints_rrect_color(tester, chips[0], disabled_color));
551        // Disabled elevated ActionChip should have the provided disabledColor.
552        assert!(paints_rrect_color(tester, chips[1], disabled_color));
553    }
554
555    #[test]
556    fn action_chip_color_resolves_material_states() {
557        test_widgets(|tester| {
558            let disabled_color = Color::new(0xff00ff00);
559            let background_color = Color::new(0xff0000ff);
560            let color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
561                if states.contains(&WidgetState::Disabled) {
562                    return Some(disabled_color);
563                }
564                Some(background_color)
565            });
566            check_enabled_and_disabled_colors(
567                tester,
568                |enabled| two_chips(Some(color.clone()), None, enabled),
569                disabled_color,
570                background_color,
571            );
572        });
573    }
574
575    #[test]
576    fn action_chip_uses_provided_state_color_properties() {
577        test_widgets(|tester| {
578            let disabled_color = Color::new(0xff00ff00);
579            let background_color = Color::new(0xff0000ff);
580            check_enabled_and_disabled_colors(
581                tester,
582                |enabled| two_chips(None, Some((disabled_color, background_color)), enabled),
583                disabled_color,
584                background_color,
585            );
586        });
587    }
588
589    #[test]
590    fn action_chip_clip_behavior_properly_passes_through_to_the_material() {
591        test_widgets(|tester| {
592            let check = |tester: &WidgetTester, clip_behavior: Clip| {
593                let materials = find::by_type::<Material>().evaluate(tester);
594                // There should be two Material widgets, first Material is from the
595                // "wrapForChip" and last Material is from the "RawChip".
596                assert_eq!(materials.len(), 2);
597                let last = *materials.last().expect("a Material");
598                assert_eq!(
599                    tester.widget(last, |material: &Material| material.clip_behavior),
600                    clip_behavior
601                );
602            };
603            pump_wrapped(
604                tester,
605                ActionChip::new(Text::new("label")).on_pressed(Listener::new(|_| {})),
606            );
607            check(tester, Clip::None);
608
609            pump_wrapped(
610                tester,
611                ActionChip::new(Text::new("label"))
612                    .clip_behavior(Clip::AntiAlias)
613                    .on_pressed(Listener::new(|_| {})),
614            );
615            check(tester, Clip::AntiAlias);
616        });
617    }
618
619    #[test]
620    fn action_chip_uses_provided_icon_theme() {
621        test_widgets(|tester| {
622            let theme = m3(&tester.cell.borrow());
623            let build_chip = |tester: &mut WidgetTester, icon_theme: Option<IconThemeData>| {
624                let mut chip = ActionChip::new(Text::new("action chip"))
625                    .avatar(waft_widgets::Icon::new(Some(Icons::add())))
626                    .on_pressed(Listener::new(|_| {}));
627                if let Some(icon_theme) = icon_theme {
628                    chip = chip.icon_theme(icon_theme);
629                }
630                tester.pump_widget(material_app(
631                    theme.clone(),
632                    Material::new().child(chip).into_widget(),
633                ));
634            };
635
636            // Test default icon theme.
637            build_chip(tester, None);
638            assert_eq!(
639                icon_data(tester).color.map(|color| color.color()),
640                Some(theme.color_scheme.primary())
641            );
642
643            // Test provided icon theme.
644            build_chip(
645                tester,
646                Some(IconThemeData::new().color(Color::new(0xff00ff00))),
647            );
648            assert_eq!(
649                icon_data(tester).color.map(|color| color.color()),
650                Some(Color::new(0xff00ff00))
651            );
652        });
653    }
654
655    #[test]
656    fn action_chip_avatar_layout_constraints_can_be_customized() {
657        test_widgets(|tester| {
658            let border = 1.0;
659            let icon_size = 18.0;
660            let label_padding = 8.0;
661            let padding = 8.0;
662            let label_size = Size::new(100.0, 100.0);
663
664            let build_chip = |tester: &mut WidgetTester, constraints: Option<BoxConstraints>| {
665                let mut chip = ActionChip::new(
666                    waft_widgets::Container::new()
667                        .width(label_size.width())
668                        .height(label_size.width())
669                        .color(Color::new(0xFFFF0000)),
670                )
671                .avatar(waft_widgets::Icon::new(Some(Icons::favorite())));
672                if let Some(constraints) = constraints {
673                    chip = chip.avatar_box_constraints(constraints);
674                }
675                pump_wrapped(tester, Center::new().child(chip));
676            };
677            let chip_size = |tester: &WidgetTester| tester.get_size(only::<ActionChip>(tester));
678            let chip_top_left = |tester: &WidgetTester| {
679                tester
680                    .get_rect(material_of(tester, only::<RawChip>(tester)))
681                    .top_left()
682            };
683            let label_top_left = |tester: &WidgetTester| {
684                tester
685                    .get_rect(only::<waft_widgets::Container>(tester))
686                    .top_left()
687            };
688
689            // Test default avatar layout constraints.
690            build_chip(tester, None);
691            assert_eq!(chip_size(tester).width(), 234.0);
692            assert_eq!(chip_size(tester).height(), 118.0);
693
694            // Calculate the distance between avatar and chip edges.
695            let top_left = chip_top_left(tester);
696            let avatar_center =
697                tester.get_center(tester.element(find::by_icon(&Icons::favorite()).first()));
698            assert_eq!(
699                top_left.dx(),
700                avatar_center.dx() - (label_size.width() / 2.0) - padding - border
701            );
702            assert_eq!(
703                top_left.dy(),
704                avatar_center.dy() - (label_size.width() / 2.0) - padding - border
705            );
706
707            // Calculate the distance between avatar and label.
708            assert_eq!(
709                label_top_left(tester).dx(),
710                avatar_center.dx() + (label_size.width() / 2.0) + label_padding
711            );
712
713            // Test custom avatar layout constraints.
714            build_chip(
715                tester,
716                Some(BoxConstraints::tight_for_finite(
717                    f64::INFINITY,
718                    f64::INFINITY,
719                )),
720            );
721            tester.pump();
722
723            assert_eq!(chip_size(tester).width(), 152.0);
724            assert_eq!(chip_size(tester).height(), 118.0);
725
726            // Calculate the distance between avatar and chip edges.
727            let top_left = chip_top_left(tester);
728            assert_eq!(
729                top_left.dx(),
730                avatar_center.dx() - (icon_size / 2.0) - padding - border
731            );
732            assert_eq!(
733                top_left.dy(),
734                avatar_center.dy() - (label_size.width() / 2.0) - padding - border
735            );
736
737            // Calculate the distance between avatar and label.
738            assert_eq!(
739                label_top_left(tester).dx(),
740                avatar_center.dx() + (icon_size / 2.0) + label_padding
741            );
742        });
743    }
744
745    pub(crate) fn animation_style() -> ChipAnimationStyle {
746        ChipAnimationStyle::new()
747            .enable_animation(AnimationStyle::new(
748                None,
749                Some(Durations::EXTRALONG4),
750                None,
751                None,
752            ))
753            .select_animation(AnimationStyle::NO_ANIMATION)
754    }
755
756    pub(crate) fn assert_animation_style_passed_to_raw_chip<K>(
757        tester: &mut WidgetTester,
758        chip: impl IntoWidget<K>,
759    ) {
760        pump_wrapped(tester, Center::new().child(chip));
761        let passed = tester.widget(only::<RawChip>(tester), |raw_chip: &RawChip| {
762            raw_chip.chip_animation_style.clone()
763        });
764        let expected = animation_style();
765        let passed = passed.expect("a chip animation style");
766        assert_eq!(passed.enable_animation, expected.enable_animation);
767        assert_eq!(passed.select_animation, expected.select_animation);
768        assert_eq!(
769            passed.avatar_drawer_animation,
770            expected.avatar_drawer_animation
771        );
772        assert_eq!(
773            passed.delete_drawer_animation,
774            expected.delete_drawer_animation
775        );
776    }
777
778    #[test]
779    fn action_chip_chip_animation_style_is_passed_to_raw_chip() {
780        test_widgets(|tester| {
781            assert_animation_style_passed_to_raw_chip(
782                tester,
783                ActionChip::new(Text::new("ActionChip")).chip_animation_style(animation_style()),
784            );
785        });
786    }
787
788    #[test]
789    fn elevated_action_chip_chip_animation_style_is_passed_to_raw_chip() {
790        test_widgets(|tester| {
791            assert_animation_style_passed_to_raw_chip(
792                tester,
793                ActionChip::elevated(Text::new("ActionChip"))
794                    .chip_animation_style(animation_style()),
795            );
796        });
797    }
798
799    pub(crate) fn hover_over_chip(tester: &mut WidgetTester, mouse: &mut TestPointer) {
800        tester.add_pointer(mouse, Offset::new(10.0, 10.0));
801        tester.pump();
802        assert!(*tester.active_cursor(1) == *MouseCursorRef::from(SystemMouseCursors::BASIC));
803        let chip = tester.get_center(text(tester, "Chip"));
804        tester.move_to(mouse, chip, false);
805        tester.pump();
806    }
807
808    #[test]
809    fn action_chip_has_expected_default_mouse_cursor_on_hover() {
810        test_widgets(|tester| {
811            pump_wrapped(
812                tester,
813                Center::new()
814                    .child(ActionChip::new(Text::new("Chip")).on_pressed(Listener::new(|_| {}))),
815            );
816            let mut mouse = TestPointer::mouse(1, 0);
817            hover_over_chip(tester, &mut mouse);
818            let expected: MouseCursorRef = if K_IS_WEB {
819                SystemMouseCursors::CLICK.into()
820            } else {
821                SystemMouseCursors::BASIC.into()
822            };
823            assert!(*tester.active_cursor(1) == *expected);
824        });
825    }
826
827    #[test]
828    fn action_chip_mouse_cursor_behavior() {
829        test_widgets(|tester| {
830            let custom_cursor: MouseCursorRef = SystemMouseCursors::GRAB.into();
831            pump_wrapped(
832                tester,
833                Center::new()
834                    .child(ActionChip::new(Text::new("Chip")).mouse_cursor(custom_cursor.clone())),
835            );
836            let mut mouse = TestPointer::mouse(1, 0);
837            hover_over_chip(tester, &mut mouse);
838            assert!(*tester.active_cursor(1) == *custom_cursor);
839        });
840    }
841
842    #[test]
843    fn mouse_cursor_resolves_in_focused_unfocused_disabled_states() {
844        test_widgets(|tester| {
845            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
846            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
847
848            let build_chip = |tester: &mut WidgetTester, enabled: bool| {
849                let cursor = WidgetStateMouseCursor::from_map(vec![
850                    (
851                        WidgetState::Disabled.into(),
852                        SystemMouseCursors::FORBIDDEN.into(),
853                    ),
854                    (WidgetState::Focused.into(), SystemMouseCursors::GRAB.into()),
855                    (WidgetState::any(), SystemMouseCursors::BASIC.into()),
856                ]);
857                let mut chip = ActionChip::new(Text::new("Chip"))
858                    .mouse_cursor(cursor.into())
859                    .focus_node(focus_node.erase());
860                if enabled {
861                    chip = chip.on_pressed(Listener::new(|_| {}));
862                }
863                pump_wrapped(tester, Center::new().child(chip));
864            };
865
866            build_chip(tester, true);
867
868            // Unfocused case.
869            let mut mouse = TestPointer::mouse(1, 0);
870            let chip = tester.get_center(text(tester, "Chip"));
871            tester.add_pointer(&mut mouse, chip);
872            tester.pump();
873            tester.move_to(&mut mouse, chip, false);
874            assert!(*tester.active_cursor(1) == *MouseCursorRef::from(SystemMouseCursors::BASIC));
875
876            // Focused case.
877            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
878            tester.pump();
879            assert!(*tester.active_cursor(1) == *MouseCursorRef::from(SystemMouseCursors::GRAB));
880
881            // Disabled case.
882            build_chip(tester, false);
883            assert!(
884                *tester.active_cursor(1) == *MouseCursorRef::from(SystemMouseCursors::FORBIDDEN)
885            );
886            tester.send(&mouse, PointerChange::Remove);
887        });
888    }
889
890    #[test]
891    fn action_chip_renders_at_zero_area() {
892        test_widgets(|tester| {
893            let theme = m3(&tester.cell.borrow());
894            tester.pump_widget(material_app(
895                theme,
896                Center::new()
897                    .child(
898                        SizedBox::shrink()
899                            .child(Scaffold::new().body(ActionChip::new(Text::new("X")))),
900                    )
901                    .into_widget(),
902            ));
903            let x_text = text(tester, "X");
904            assert!(tester.get_size(x_text).is_empty());
905        });
906    }
907}