Skip to main content

waft_material/
chip_theme.rs

1//! Flutter counterpart: material_ui's `chip_theme.dart`.
2
3use waft_embedder::{Brightness, Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty};
5use waft_painting::{
6    AnyBorderSide, AnyColor, BorderSide, ColorProperty, EdgeInsets, EdgeInsetsGeometry,
7    OutlinedBorderRef, TextStyle,
8};
9use waft_rendering::BoxConstraints;
10use waft_widgets::{
11    BuildContext, IconThemeData, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
12    WidgetStateBorderSide, WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
13};
14
15use crate::colors::Colors;
16use crate::theme::Theme;
17use crate::theme_data::ThemeData;
18
19/// Applies a chip theme to descendant [`Chip`](crate::Chip) widgets.
20///
21/// Descendant widgets obtain the current theme's [`ChipThemeData`] object using
22/// [`ChipTheme::of`]. When a widget uses [`ChipTheme::of`], it is automatically rebuilt if
23/// the theme later changes.
24///
25/// The [`ChipThemeData`] is also used as the default chip theme data in the overall
26/// `ThemeData`, as `ThemeData::chip_theme`.
27///
28/// See also:
29///
30///  * [`ChipThemeData`], which describes the actual configuration of a chip theme.
31///  * `ThemeData`, which describes the overall theme information for the application.
32#[derive(Debug)]
33pub struct ChipTheme {
34    pub key: Option<KeyRef>,
35    /// Specifies the color, shape, and text style values for descendant chip widgets.
36    pub data: ChipThemeData,
37    pub child: WidgetRef,
38}
39
40impl ChipTheme {
41    /// Applies the given theme [`data`](Self::data) to [`child`](Self::child).
42    #[cfg_attr(debug_assertions, track_caller)]
43    pub fn new<K>(data: ChipThemeData, child: impl IntoWidget<K>) -> ChipTheme {
44        ChipTheme {
45            key: None,
46            data,
47            child: child.into_widget(),
48        }
49    }
50
51    /// Dart `ChipTheme(key:)`.
52    pub fn key(mut self, key: KeyRef) -> ChipTheme {
53        self.key = Some(key);
54        self
55    }
56
57    /// Returns the [`data`](Self::data) from the closest [`ChipTheme`] ancestor. If there is
58    /// no ancestor, it returns `ThemeData::chip_theme`.
59    ///
60    /// Typical usage is as follows:
61    ///
62    /// ```text
63    /// let theme = ChipTheme::of(app, context);
64    /// ```
65    pub fn of(app: &mut App, context: BuildContext) -> ChipThemeData {
66        match context.depend_on_inherited_widget_of_exact_type::<ChipTheme>(app) {
67            Some(inherited_theme) => inherited_theme.data.clone(),
68            None => Theme::of(app, context).chip_theme.clone(),
69        }
70    }
71}
72
73impl InheritedTheme for ChipTheme {
74    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
75        ChipTheme::new(self.data.clone(), child).into_widget()
76    }
77}
78
79impl InheritedWidget for ChipTheme {
80    fn key(&self) -> Option<&KeyRef> {
81        self.key.as_ref()
82    }
83
84    fn child(&self) -> &WidgetRef {
85        &self.child
86    }
87
88    fn update_should_notify(&self, old_widget: &ChipTheme) -> bool {
89        self.data != old_widget.data
90    }
91
92    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
93        Some(self)
94    }
95}
96
97/// Holds the color, shape, and text styles for a Material widget subtree.
98///
99/// [`ChipThemeData`] is used by [`ChipTheme`] to control the visual properties of chip
100/// widgets in a widget hierarchy.
101///
102/// To obtain the current [`ChipThemeData`] for a given [`BuildContext`], use
103/// [`ChipTheme::of`]. A widget's build method can use [`ChipTheme::of`] to obtain the
104/// current visual properties for a chip.
105///
106/// The `ChipTheme` constructor is used to apply a [`ChipThemeData`] to a subtree, and
107/// `ThemeData::chip_theme` is the default that applies when there is no [`ChipTheme`].
108///
109/// See also:
110///
111///  * [`ChipTheme`], a widget that sets the theme data for a subtree.
112///  * `ThemeData`, which describes the overall theme information for the application.
113#[derive(Clone, Debug, Default)]
114pub struct ChipThemeData {
115    /// Overrides the default for `ChipAttributes::color`.
116    pub color: Option<WidgetStatePropertyRef<Option<Color>>>,
117
118    /// Color to be used for the unselected, enabled chip's background.
119    ///
120    /// The default is light grey.
121    pub background_color: Option<Color>,
122
123    /// The [`Color`] for the delete icon. The default is `Color(0xde000000)` (slightly
124    /// transparent black) for light themes, and `Color(0xdeffffff)` (slightly transparent
125    /// white) for dark themes.
126    ///
127    /// May be set to null, in which case the ambient `IconTheme.color` is used.
128    pub delete_icon_color: Option<AnyColor>,
129
130    /// Color to be used for the chip's background, indicating that it is disabled.
131    ///
132    /// The chip is disabled when `DisabledChipAttributes::is_enabled` is false, or all three
133    /// of `SelectableChipAttributes::on_selected`, `TappableChipAttributes::on_pressed`, and
134    /// `DeletableChipAttributes::on_deleted` are null.
135    pub disabled_color: Option<Color>,
136
137    /// Color to be used for the chip's background, indicating that it is selected.
138    ///
139    /// The chip is selected when `SelectableChipAttributes::selected` is true.
140    pub selected_color: Option<Color>,
141
142    /// An alternate color to be used for the chip's background, indicating that it is
143    /// selected. For example, this color can be used for a `ChoiceChip` when selected.
144    pub secondary_selected_color: Option<Color>,
145
146    /// Color of the chip's shadow when the elevation is greater than 0.
147    pub shadow_color: Option<Color>,
148
149    /// Color of the chip's surface tint overlay when its elevation is greater than 0.
150    ///
151    /// This is not recommended for use. Material 3 spec introduced a set of tone-based
152    /// surfaces and surface containers in its `ColorScheme`, which provide more flexibility.
153    /// The intention is to eventually remove surface tint color from the framework.
154    pub surface_tint_color: Option<Color>,
155
156    /// Color of the chip's shadow when the elevation is greater than 0 and the chip is
157    /// selected.
158    pub selected_shadow_color: Option<Color>,
159
160    /// Whether or not to show a check mark when
161    /// `SelectableChipAttributes::selected` is true.
162    pub show_checkmark: Option<bool>,
163
164    /// Color of the chip's check mark when a check mark is visible.
165    ///
166    /// This will override the color set by the platform's brightness setting.
167    pub checkmark_color: Option<Color>,
168
169    /// The padding around the [`label`](crate::ChipAttributes::label) widget.
170    ///
171    /// By default, this is 4 logical pixels at the beginning and the end of the label, and
172    /// zero on top and bottom.
173    pub label_padding: Option<EdgeInsetsGeometry>,
174
175    /// The padding between the contents of the chip and the outside
176    /// [`shape`](Self::shape).
177    ///
178    /// Defaults to 4 logical pixels on all sides.
179    pub padding: Option<EdgeInsetsGeometry>,
180
181    /// The color and weight of the chip's outline.
182    ///
183    /// This value is combined with [`shape`](Self::shape) to create a shape decorated with
184    /// an outline. To omit the outline entirely, pass [`BorderSide::NONE`] to
185    /// [`side`](Self::side).
186    pub side: Option<AnyBorderSide>,
187
188    /// The border to draw around the chip.
189    ///
190    /// This shape is combined with [`side`](Self::side) to create a shape decorated with an
191    /// outline.
192    pub shape: Option<OutlinedBorderRef>,
193
194    /// The style to be applied to the chip's label.
195    ///
196    /// This only has an effect on label widgets that respect the `DefaultTextStyle`, such as
197    /// `Text`.
198    pub label_style: Option<TextStyle>,
199
200    /// An alternate style to be applied to the chip's label, indicating that it is selected.
201    ///
202    /// This only has an effect on label widgets that respect the `DefaultTextStyle`, such as
203    /// `Text`.
204    pub secondary_label_style: Option<TextStyle>,
205
206    /// Overrides the default for the brightness of the chip.
207    pub brightness: Option<Brightness>,
208
209    /// The elevation to be applied to the chip. Defaults to 0.
210    pub elevation: Option<f64>,
211
212    /// The elevation to be applied to the chip during the press motion. Defaults to 8.
213    pub press_elevation: Option<f64>,
214
215    /// Theme used for all icons in the chip.
216    pub icon_theme: Option<IconThemeData>,
217
218    /// Optional size constraints for the avatar.
219    ///
220    /// When unspecified, defaults to a minimum size of chip height or label height
221    /// (whichever is greater) and a padding of 8.0 pixels on all sides.
222    pub avatar_box_constraints: Option<BoxConstraints>,
223
224    /// Optional size constraints for the delete icon.
225    ///
226    /// When unspecified, defaults to a minimum size of chip height or label height
227    /// (whichever is greater) and a padding of 8.0 pixels on all sides.
228    pub delete_icon_box_constraints: Option<BoxConstraints>,
229}
230
231crate::theme_data_getters::theme_data_getters! {
232    /// Dart's getters of `ChipThemeData`: the theme data answers with its fields, and a
233    /// defaults subclass (Dart's `_ChipDefaultsM3(context, isEnabled)` and its kin) computes
234    /// the ones it overrides when they are read.
235    pub trait ChipThemeDataGetters for ChipThemeData, fields: chip_theme_data {
236        color: Option<WidgetStatePropertyRef<Option<Color>>>,
237        background_color: Option<Color>,
238        delete_icon_color: Option<AnyColor>,
239        disabled_color: Option<Color>,
240        selected_color: Option<Color>,
241        secondary_selected_color: Option<Color>,
242        shadow_color: Option<Color>,
243        surface_tint_color: Option<Color>,
244        selected_shadow_color: Option<Color>,
245        show_checkmark: Option<bool>,
246        checkmark_color: Option<Color>,
247        label_padding: Option<EdgeInsetsGeometry>,
248        padding: Option<EdgeInsetsGeometry>,
249        side: Option<AnyBorderSide>,
250        shape: Option<OutlinedBorderRef>,
251        label_style: Option<TextStyle>,
252        secondary_label_style: Option<TextStyle>,
253        brightness: Option<Brightness>,
254        elevation: Option<f64>,
255        press_elevation: Option<f64>,
256        icon_theme: Option<IconThemeData>,
257        avatar_box_constraints: Option<BoxConstraints>,
258        delete_icon_box_constraints: Option<BoxConstraints>,
259    }
260}
261
262impl ChipThemeData {
263    /// Create a [`ChipThemeData`] given a set of exact values. Dart's optional named
264    /// arguments are the fluent setters.
265    ///
266    /// This will rarely be used directly. It is used by [`lerp`](Self::lerp) to create
267    /// intermediate themes based on two themes.
268    pub fn new() -> ChipThemeData {
269        ChipThemeData::default()
270    }
271
272    /// Dart's `ChipThemeData.fromDefaults`: generates a [`ChipThemeData`] from a brightness,
273    /// a primary color, a secondary color, and a text style.
274    ///
275    /// Only one of `primary_color` or `brightness` may be given, and one of them must be:
276    /// `brightness` is derived from `primary_color` when that is given, and the primary color
277    /// is black or white from `brightness` when it is not.
278    ///
279    /// The `secondary_color` is used for the selection state. The colors, opacities and
280    /// padding of the result are Material Design defaults.
281    pub fn from_defaults(
282        brightness: Option<Brightness>,
283        primary_color: Option<Color>,
284        secondary_color: Color,
285        label_style: TextStyle,
286    ) -> ChipThemeData {
287        debug_assert!(
288            primary_color.is_some() || brightness.is_some(),
289            "One of primaryColor or brightness must be specified"
290        );
291        debug_assert!(
292            primary_color.is_none() || brightness.is_none(),
293            "Only one of primaryColor or brightness may be specified"
294        );
295
296        let brightness = match primary_color {
297            Some(primary_color) => Some(ThemeData::estimate_brightness_for_color(primary_color)),
298            None => brightness,
299        };
300
301        // These are Material Design defaults, and are used to derive
302        // component Colors (with opacity) from base colors.
303        const BACKGROUND_ALPHA: i32 = 0x1f; // 12%
304        const DELETE_ICON_ALPHA: i32 = 0xde; // 87%
305        const DISABLED_ALPHA: i32 = 0x0c; // 38% * 12% = 5%
306        const SELECT_ALPHA: i32 = 0x3d; // 12% + 12% = 24%
307        const TEXT_LABEL_ALPHA: i32 = 0xde; // 87%
308        let padding = EdgeInsetsGeometry::from(EdgeInsets::all(4.0));
309
310        let primary_color = primary_color.unwrap_or(if brightness == Some(Brightness::Light) {
311            Colors::BLACK
312        } else {
313            Colors::WHITE
314        });
315        let background_color = primary_color.with_alpha(BACKGROUND_ALPHA);
316        let delete_icon_color = primary_color.with_alpha(DELETE_ICON_ALPHA);
317        let disabled_color = primary_color.with_alpha(DISABLED_ALPHA);
318        let selected_color = primary_color.with_alpha(SELECT_ALPHA);
319        let secondary_selected_color = secondary_color.with_alpha(SELECT_ALPHA);
320        let secondary_label_style = label_style
321            .copy_with()
322            .color(secondary_color.with_alpha(TEXT_LABEL_ALPHA));
323        let label_style = label_style
324            .copy_with()
325            .color(primary_color.with_alpha(TEXT_LABEL_ALPHA));
326
327        ChipThemeData::new()
328            .background_color(background_color)
329            .delete_icon_color(delete_icon_color)
330            .disabled_color(disabled_color)
331            .selected_color(selected_color)
332            .secondary_selected_color(secondary_selected_color)
333            .shadow_color(Colors::BLACK)
334            .selected_shadow_color(Colors::BLACK)
335            .show_checkmark(true)
336            .padding(padding)
337            .label_style(label_style)
338            .secondary_label_style(secondary_label_style)
339            .brightness_value(brightness)
340            .elevation(0.0)
341            .press_elevation(8.0)
342            .icon_theme(IconThemeData::new().size(18.0))
343    }
344
345    /// Dart `ChipThemeData(color:)`.
346    pub fn color(mut self, color: WidgetStatePropertyRef<Option<Color>>) -> ChipThemeData {
347        self.color = Some(color);
348        self
349    }
350
351    /// Dart `ChipThemeData(backgroundColor:)`.
352    pub fn background_color(mut self, background_color: Color) -> ChipThemeData {
353        self.background_color = Some(background_color);
354        self
355    }
356
357    /// Dart `ChipThemeData(deleteIconColor:)`.
358    pub fn delete_icon_color(mut self, delete_icon_color: impl Into<AnyColor>) -> ChipThemeData {
359        self.delete_icon_color = Some(delete_icon_color.into());
360        self
361    }
362
363    /// Dart `ChipThemeData(disabledColor:)`.
364    pub fn disabled_color(mut self, disabled_color: Color) -> ChipThemeData {
365        self.disabled_color = Some(disabled_color);
366        self
367    }
368
369    /// Dart `ChipThemeData(selectedColor:)`.
370    pub fn selected_color(mut self, selected_color: Color) -> ChipThemeData {
371        self.selected_color = Some(selected_color);
372        self
373    }
374
375    /// Dart `ChipThemeData(secondarySelectedColor:)`.
376    pub fn secondary_selected_color(mut self, secondary_selected_color: Color) -> ChipThemeData {
377        self.secondary_selected_color = Some(secondary_selected_color);
378        self
379    }
380
381    /// Dart `ChipThemeData(shadowColor:)`.
382    pub fn shadow_color(mut self, shadow_color: Color) -> ChipThemeData {
383        self.shadow_color = Some(shadow_color);
384        self
385    }
386
387    /// Dart `ChipThemeData(surfaceTintColor:)`.
388    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> ChipThemeData {
389        self.surface_tint_color = Some(surface_tint_color);
390        self
391    }
392
393    /// Dart `ChipThemeData(selectedShadowColor:)`.
394    pub fn selected_shadow_color(mut self, selected_shadow_color: Color) -> ChipThemeData {
395        self.selected_shadow_color = Some(selected_shadow_color);
396        self
397    }
398
399    /// Dart `ChipThemeData(showCheckmark:)`.
400    pub fn show_checkmark(mut self, show_checkmark: bool) -> ChipThemeData {
401        self.show_checkmark = Some(show_checkmark);
402        self
403    }
404
405    /// Dart `ChipThemeData(checkmarkColor:)`.
406    pub fn checkmark_color(mut self, checkmark_color: Color) -> ChipThemeData {
407        self.checkmark_color = Some(checkmark_color);
408        self
409    }
410
411    /// Dart `ChipThemeData(labelPadding:)`.
412    pub fn label_padding(mut self, label_padding: impl Into<EdgeInsetsGeometry>) -> ChipThemeData {
413        self.label_padding = Some(label_padding.into());
414        self
415    }
416
417    /// Dart `ChipThemeData(padding:)`.
418    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ChipThemeData {
419        self.padding = Some(padding.into());
420        self
421    }
422
423    /// Dart `ChipThemeData(side:)`.
424    pub fn side(mut self, side: impl Into<AnyBorderSide>) -> ChipThemeData {
425        self.side = Some(side.into());
426        self
427    }
428
429    /// Dart `ChipThemeData(shape:)`.
430    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> ChipThemeData {
431        self.shape = Some(shape.into());
432        self
433    }
434
435    /// Dart `ChipThemeData(labelStyle:)`.
436    pub fn label_style(mut self, label_style: TextStyle) -> ChipThemeData {
437        self.label_style = Some(label_style);
438        self
439    }
440
441    /// Dart `ChipThemeData(secondaryLabelStyle:)`.
442    pub fn secondary_label_style(mut self, secondary_label_style: TextStyle) -> ChipThemeData {
443        self.secondary_label_style = Some(secondary_label_style);
444        self
445    }
446
447    /// Dart `ChipThemeData(brightness:)`.
448    pub fn brightness(mut self, brightness: Brightness) -> ChipThemeData {
449        self.brightness = Some(brightness);
450        self
451    }
452
453    /// [`brightness`](Self::brightness) from a value that may be absent, as
454    /// [`from_defaults`](Self::from_defaults) derives it.
455    fn brightness_value(mut self, brightness: Option<Brightness>) -> ChipThemeData {
456        self.brightness = brightness;
457        self
458    }
459
460    /// Dart `ChipThemeData(elevation:)`.
461    pub fn elevation(mut self, elevation: f64) -> ChipThemeData {
462        self.elevation = Some(elevation);
463        self
464    }
465
466    /// Dart `ChipThemeData(pressElevation:)`.
467    pub fn press_elevation(mut self, press_elevation: f64) -> ChipThemeData {
468        self.press_elevation = Some(press_elevation);
469        self
470    }
471
472    /// Dart `ChipThemeData(iconTheme:)`.
473    pub fn icon_theme(mut self, icon_theme: IconThemeData) -> ChipThemeData {
474        self.icon_theme = Some(icon_theme);
475        self
476    }
477
478    /// Dart `ChipThemeData(avatarBoxConstraints:)`.
479    pub fn avatar_box_constraints(
480        mut self,
481        avatar_box_constraints: BoxConstraints,
482    ) -> ChipThemeData {
483        self.avatar_box_constraints = Some(avatar_box_constraints);
484        self
485    }
486
487    /// Dart `ChipThemeData(deleteIconBoxConstraints:)`.
488    pub fn delete_icon_box_constraints(
489        mut self,
490        delete_icon_box_constraints: BoxConstraints,
491    ) -> ChipThemeData {
492        self.delete_icon_box_constraints = Some(delete_icon_box_constraints);
493        self
494    }
495
496    /// Creates a copy of this object but with the given fields replaced with the new
497    /// values.
498    ///
499    /// Dart's named arguments are the fluent setters on the copy
500    /// (`data.copy_with().elevation(4.0)`).
501    pub fn copy_with(&self) -> ChipThemeData {
502        self.clone()
503    }
504
505    /// Linearly interpolate between two chip themes.
506    ///
507    /// {@macro dart.ui.shadow.lerp}
508    pub fn lerp(
509        a: Option<&ChipThemeData>,
510        b: Option<&ChipThemeData>,
511        t: f64,
512    ) -> Option<ChipThemeData> {
513        match (a, b) {
514            (None, None) => return None,
515            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
516            _ => {}
517        }
518        Some(ChipThemeData {
519            color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
520                a.and_then(|a| a.color.clone()),
521                b.and_then(|b| b.color.clone()),
522                t,
523                Color::lerp,
524            ),
525            background_color: Color::lerp(
526                a.and_then(|a| a.background_color),
527                b.and_then(|b| b.background_color),
528                t,
529            ),
530            delete_icon_color: Color::lerp(
531                a.and_then(|a| a.delete_icon_color.as_ref().map(AnyColor::color)),
532                b.and_then(|b| b.delete_icon_color.as_ref().map(AnyColor::color)),
533                t,
534            )
535            .map(AnyColor::from),
536            disabled_color: Color::lerp(
537                a.and_then(|a| a.disabled_color),
538                b.and_then(|b| b.disabled_color),
539                t,
540            ),
541            selected_color: Color::lerp(
542                a.and_then(|a| a.selected_color),
543                b.and_then(|b| b.selected_color),
544                t,
545            ),
546            secondary_selected_color: Color::lerp(
547                a.and_then(|a| a.secondary_selected_color),
548                b.and_then(|b| b.secondary_selected_color),
549                t,
550            ),
551            shadow_color: Color::lerp(
552                a.and_then(|a| a.shadow_color),
553                b.and_then(|b| b.shadow_color),
554                t,
555            ),
556            surface_tint_color: Color::lerp(
557                a.and_then(|a| a.surface_tint_color),
558                b.and_then(|b| b.surface_tint_color),
559                t,
560            ),
561            selected_shadow_color: Color::lerp(
562                a.and_then(|a| a.selected_shadow_color),
563                b.and_then(|b| b.selected_shadow_color),
564                t,
565            ),
566            show_checkmark: Some(if t < 0.5 {
567                a.and_then(|a| a.show_checkmark).unwrap_or(true)
568            } else {
569                b.and_then(|b| b.show_checkmark).unwrap_or(true)
570            }),
571            checkmark_color: Color::lerp(
572                a.and_then(|a| a.checkmark_color),
573                b.and_then(|b| b.checkmark_color),
574                t,
575            ),
576            label_padding: EdgeInsetsGeometry::lerp(
577                a.and_then(|a| a.label_padding),
578                b.and_then(|b| b.label_padding),
579                t,
580            ),
581            padding: EdgeInsetsGeometry::lerp(
582                a.and_then(|a| a.padding),
583                b.and_then(|b| b.padding),
584                t,
585            ),
586            side: Self::lerp_sides(
587                a.and_then(|a| a.side.as_ref()),
588                b.and_then(|b| b.side.as_ref()),
589                t,
590            )
591            .map(AnyBorderSide::new),
592            shape: OutlinedBorderRef::lerp(
593                a.and_then(|a| a.shape.as_ref()),
594                b.and_then(|b| b.shape.as_ref()),
595                t,
596            ),
597            label_style: TextStyle::lerp(
598                a.and_then(|a| a.label_style.as_ref()),
599                b.and_then(|b| b.label_style.as_ref()),
600                t,
601            ),
602            secondary_label_style: TextStyle::lerp(
603                a.and_then(|a| a.secondary_label_style.as_ref()),
604                b.and_then(|b| b.secondary_label_style.as_ref()),
605                t,
606            ),
607            brightness: Some(if t < 0.5 {
608                a.and_then(|a| a.brightness).unwrap_or(Brightness::Light)
609            } else {
610                b.and_then(|b| b.brightness).unwrap_or(Brightness::Light)
611            }),
612            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
613            press_elevation: lerp_double(
614                a.and_then(|a| a.press_elevation),
615                b.and_then(|b| b.press_elevation),
616                t,
617            ),
618            icon_theme: if a.is_some_and(|a| a.icon_theme.is_some())
619                || b.is_some_and(|b| b.icon_theme.is_some())
620            {
621                Some(IconThemeData::lerp(
622                    a.and_then(|a| a.icon_theme.as_ref()),
623                    b.and_then(|b| b.icon_theme.as_ref()),
624                    t,
625                ))
626            } else {
627                None
628            },
629            avatar_box_constraints: BoxConstraints::lerp(
630                a.and_then(|a| a.avatar_box_constraints),
631                b.and_then(|b| b.avatar_box_constraints),
632                t,
633            ),
634            delete_icon_box_constraints: BoxConstraints::lerp(
635                a.and_then(|a| a.delete_icon_box_constraints),
636                b.and_then(|b| b.delete_icon_box_constraints),
637                t,
638            ),
639        })
640    }
641
642    // Special case because BorderSide.lerp() doesn't support null arguments.
643    fn lerp_sides(
644        a: Option<&AnyBorderSide>,
645        b: Option<&AnyBorderSide>,
646        t: f64,
647    ) -> Option<BorderSide> {
648        if a.is_none() && b.is_none() {
649            return None;
650        }
651        let a = a.and_then(Self::resolve_unconditionally);
652        let b = b.and_then(Self::resolve_unconditionally);
653        let a = a.unwrap_or_else(|| BorderSide {
654            width: 0.0,
655            color: b.expect("b! in Dart").color.with_alpha(0),
656            ..BorderSide::default()
657        });
658        let b = b.unwrap_or_else(|| BorderSide {
659            width: 0.0,
660            color: a.color.with_alpha(0),
661            ..BorderSide::default()
662        });
663
664        Some(BorderSide::lerp(a, b, t))
665    }
666
667    /// Dart's `if (a is WidgetStateBorderSide) { a = a.resolve(const <WidgetState>{}); }`.
668    fn resolve_unconditionally(side: &AnyBorderSide) -> Option<BorderSide> {
669        match side.extension::<WidgetStateBorderSide>() {
670            Some(side) => side.resolve(&WidgetStates::new()),
671            None => Some(**side),
672        }
673    }
674}
675
676impl PartialEq for ChipThemeData {
677    fn eq(&self, other: &ChipThemeData) -> bool {
678        if std::ptr::eq(self, other) {
679            return true;
680        }
681        other.color == self.color
682            && other.background_color == self.background_color
683            && other.delete_icon_color == self.delete_icon_color
684            && other.disabled_color == self.disabled_color
685            && other.selected_color == self.selected_color
686            && other.secondary_selected_color == self.secondary_selected_color
687            && other.shadow_color == self.shadow_color
688            && other.surface_tint_color == self.surface_tint_color
689            && other.selected_shadow_color == self.selected_shadow_color
690            && other.show_checkmark == self.show_checkmark
691            && other.checkmark_color == self.checkmark_color
692            && other.label_padding == self.label_padding
693            && other.padding == self.padding
694            && other.side == self.side
695            && other.shape == self.shape
696            && other.label_style == self.label_style
697            && other.secondary_label_style == self.secondary_label_style
698            && other.brightness == self.brightness
699            && other.elevation == self.elevation
700            && other.press_elevation == self.press_elevation
701            && other.icon_theme == self.icon_theme
702            && other.avatar_box_constraints == self.avatar_box_constraints
703            && other.delete_icon_box_constraints == self.delete_icon_box_constraints
704    }
705}
706
707impl waft_foundation::Diagnosticable for ChipThemeData {
708    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
709        properties.add(
710            DiagnosticsProperty::<String>::new(
711                "color",
712                self.color.as_deref().map(|property| property.to_string()),
713            )
714            .default_value(None),
715        );
716        properties
717            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
718        properties.add(
719            DiagnosticsProperty::<AnyColor>::new("deleteIconColor", self.delete_icon_color.clone())
720                .default_value(None),
721        );
722        properties
723            .add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
724        properties
725            .add(ColorProperty::new("selectedColor", self.selected_color).default_value(None));
726        properties.add(
727            ColorProperty::new("secondarySelectedColor", self.secondary_selected_color)
728                .default_value(None),
729        );
730        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
731        properties.add(
732            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
733        );
734        properties.add(
735            ColorProperty::new("selectedShadowColor", self.selected_shadow_color)
736                .default_value(None),
737        );
738        properties.add(
739            DiagnosticsProperty::<bool>::new("showCheckmark", self.show_checkmark)
740                .default_value(None),
741        );
742        properties
743            .add(ColorProperty::new("checkMarkColor", self.checkmark_color).default_value(None));
744        properties.add(
745            DiagnosticsProperty::<EdgeInsetsGeometry>::new("labelPadding", self.label_padding)
746                .default_value(None),
747        );
748        properties.add(
749            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
750                .default_value(None),
751        );
752        properties.add(
753            DiagnosticsProperty::<AnyBorderSide>::new("side", self.side.clone())
754                .default_value(None),
755        );
756        properties.add(
757            DiagnosticsProperty::<OutlinedBorderRef>::new("shape", self.shape.clone())
758                .default_value(None),
759        );
760        properties.add(
761            DiagnosticsProperty::<TextStyle>::new("labelStyle", self.label_style.clone())
762                .default_value(None),
763        );
764        properties.add(
765            DiagnosticsProperty::<TextStyle>::new(
766                "secondaryLabelStyle",
767                self.secondary_label_style.clone(),
768            )
769            .default_value(None),
770        );
771        properties.add(
772            EnumProperty::<Brightness>::new("brightness", self.brightness).default_value(None),
773        );
774        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
775        properties
776            .add(DoubleProperty::new("pressElevation", self.press_elevation).default_value(None));
777        properties.add(
778            DiagnosticsProperty::<waft_widgets::IconThemeData>::new(
779                "iconTheme",
780                self.icon_theme.clone(),
781            )
782            .default_value(None),
783        );
784        properties.add(
785            DiagnosticsProperty::<BoxConstraints>::new(
786                "avatarBoxConstraints",
787                self.avatar_box_constraints,
788            )
789            .default_value(None),
790        );
791        properties.add(
792            DiagnosticsProperty::<BoxConstraints>::new(
793                "deleteIconBoxConstraints",
794                self.delete_icon_box_constraints,
795            )
796            .default_value(None),
797        );
798    }
799}
800
801impl std::fmt::Display for ChipThemeData {
802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
803        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use crate::choice_chip::ChoiceChip;
810    use crate::color_scheme::ColorScheme;
811    use crate::scaffold::Scaffold;
812    use std::cell::Cell;
813    use std::time::Duration;
814    use waft_embedder::Offset;
815    use waft_foundation::Listener;
816    use waft_painting::{BeveledRectangleBorder, BorderSide, StadiumBorder};
817    use waft_widgets::{
818        Focus, FocusNode, WidgetState, WidgetStateColor, WidgetStateOutlinedBorder,
819    };
820
821    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
822
823    use super::*;
824    use crate::test_support::{PaintInspection, is_same_color_as};
825
826    fn fallback_body_large(tester: &mut WidgetTester, color: Color) -> TextStyle {
827        let theme_data = ThemeData::fallback(&tester.cell.borrow(), None);
828        theme_data
829            .text_theme
830            .body_large
831            .expect("the fallback has bodyLarge")
832            .copy_with()
833            .color(color)
834    }
835
836    fn label_color(data: &ChipThemeData) -> Option<Color> {
837        data.label_style
838            .as_ref()
839            .and_then(|style| style.color.as_ref())
840            .map(|color| color.color())
841    }
842
843    fn secondary_label_color(data: &ChipThemeData) -> Option<Color> {
844        data.secondary_label_style
845            .as_ref()
846            .and_then(|style| style.color.as_ref())
847            .map(|color| color.color())
848    }
849
850    fn same(actual: Option<Color>, expected: Color) {
851        let actual = actual.expect("a color");
852        assert!(
853            is_same_color_as(actual, expected),
854            "{actual:?} is not the same color as {expected:?}"
855        );
856    }
857
858    #[test]
859    fn chip_theme_data_copy_with_equals_and_hash_code_basics() {
860        assert_eq!(ChipThemeData::new(), ChipThemeData::new().copy_with());
861    }
862
863    #[test]
864    fn chip_theme_data_lerp_special_cases() {
865        assert_eq!(ChipThemeData::lerp(None, None, 0.0), None);
866        let data = ChipThemeData::new();
867        assert_eq!(
868            ChipThemeData::lerp(Some(&data), Some(&data), 0.5),
869            Some(data)
870        );
871    }
872
873    #[test]
874    fn chip_theme_data_defaults() {
875        let data = ChipThemeData::new();
876        assert!(data.color.is_none());
877        assert_eq!(data.background_color, None);
878        assert_eq!(data.delete_icon_color, None);
879        assert_eq!(data.disabled_color, None);
880        assert_eq!(data.selected_color, None);
881        assert_eq!(data.secondary_selected_color, None);
882        assert_eq!(data.shadow_color, None);
883        assert_eq!(data.surface_tint_color, None);
884        assert_eq!(data.selected_shadow_color, None);
885        assert_eq!(data.show_checkmark, None);
886        assert_eq!(data.checkmark_color, None);
887        assert_eq!(data.label_padding, None);
888        assert_eq!(data.padding, None);
889        assert!(data.side.is_none());
890        assert!(data.shape.is_none());
891        assert_eq!(data.label_style, None);
892        assert_eq!(data.secondary_label_style, None);
893        assert_eq!(data.brightness, None);
894        assert_eq!(data.elevation, None);
895        assert_eq!(data.press_elevation, None);
896        assert_eq!(data.icon_theme, None);
897        assert_eq!(data.avatar_box_constraints, None);
898        assert_eq!(data.delete_icon_box_constraints, None);
899    }
900
901    #[test]
902    fn chip_theme_from_defaults() {
903        let label_style = TextStyle::new();
904        let chip_theme = ChipThemeData::from_defaults(
905            Some(Brightness::Light),
906            None,
907            Colors::RED.primary(),
908            label_style.clone(),
909        );
910        assert_eq!(
911            chip_theme.background_color,
912            Some(Colors::BLACK.with_alpha(0x1f))
913        );
914        assert_eq!(
915            chip_theme.delete_icon_color,
916            Some(Colors::BLACK.with_alpha(0xde).into())
917        );
918        assert_eq!(
919            chip_theme.disabled_color,
920            Some(Colors::BLACK.with_alpha(0x0c))
921        );
922        assert_eq!(
923            chip_theme.selected_color,
924            Some(Colors::BLACK.with_alpha(0x3d))
925        );
926        assert_eq!(
927            chip_theme.secondary_selected_color,
928            Some(Colors::RED.primary().with_alpha(0x3d))
929        );
930        assert_eq!(chip_theme.shadow_color, Some(Colors::BLACK));
931        assert_eq!(chip_theme.surface_tint_color, None);
932        assert_eq!(chip_theme.selected_shadow_color, Some(Colors::BLACK));
933        assert_eq!(chip_theme.show_checkmark, Some(true));
934        assert_eq!(chip_theme.checkmark_color, None);
935        assert_eq!(chip_theme.label_padding, None);
936        assert_eq!(chip_theme.padding, Some(EdgeInsets::all(4.0).into()));
937        assert!(chip_theme.side.is_none());
938        assert!(chip_theme.shape.is_none());
939        assert_eq!(
940            chip_theme.label_style,
941            Some(
942                label_style
943                    .copy_with()
944                    .color(Colors::BLACK.with_alpha(0xde))
945            )
946        );
947        assert_eq!(
948            chip_theme.secondary_label_style,
949            Some(
950                label_style
951                    .copy_with()
952                    .color(Colors::RED.primary().with_alpha(0xde))
953            )
954        );
955        assert_eq!(chip_theme.brightness, Some(Brightness::Light));
956        assert_eq!(chip_theme.elevation, Some(0.0));
957        assert_eq!(chip_theme.press_elevation, Some(8.0));
958
959        let teal = Colors::TEAL_ACCENT.shade200();
960        let chip_theme =
961            ChipThemeData::from_defaults(Some(Brightness::Dark), None, teal, TextStyle::new());
962        assert_eq!(
963            chip_theme.background_color,
964            Some(Colors::WHITE.with_alpha(0x1f))
965        );
966        assert_eq!(
967            chip_theme.delete_icon_color,
968            Some(Colors::WHITE.with_alpha(0xde).into())
969        );
970        assert_eq!(
971            chip_theme.disabled_color,
972            Some(Colors::WHITE.with_alpha(0x0c))
973        );
974        assert_eq!(
975            chip_theme.selected_color,
976            Some(Colors::WHITE.with_alpha(0x3d))
977        );
978        assert_eq!(
979            chip_theme.secondary_selected_color,
980            Some(teal.with_alpha(0x3d))
981        );
982        assert_eq!(chip_theme.shadow_color, Some(Colors::BLACK));
983        assert_eq!(chip_theme.selected_shadow_color, Some(Colors::BLACK));
984        assert_eq!(chip_theme.show_checkmark, Some(true));
985        assert_eq!(chip_theme.checkmark_color, None);
986        assert_eq!(chip_theme.label_padding, None);
987        assert_eq!(chip_theme.padding, Some(EdgeInsets::all(4.0).into()));
988        assert!(chip_theme.side.is_none());
989        assert!(chip_theme.shape.is_none());
990        assert_eq!(
991            chip_theme.label_style,
992            Some(
993                label_style
994                    .copy_with()
995                    .color(Colors::WHITE.with_alpha(0xde))
996            )
997        );
998        assert_eq!(
999            chip_theme.secondary_label_style,
1000            Some(label_style.copy_with().color(teal.with_alpha(0xde)))
1001        );
1002        assert_eq!(chip_theme.brightness, Some(Brightness::Dark));
1003        assert_eq!(chip_theme.elevation, Some(0.0));
1004        assert_eq!(chip_theme.press_elevation, Some(8.0));
1005    }
1006
1007    #[test]
1008    fn chip_theme_data_generates_correct_opacities_for_defaults() {
1009        test_widgets(|tester| {
1010            let custom_color1 = Color::new(0xcafefeed);
1011            let custom_color2 = Color::new(0xdeadbeef);
1012            let custom_style = fallback_body_large(tester, custom_color2);
1013
1014            let light_theme = ChipThemeData::from_defaults(
1015                Some(Brightness::Light),
1016                None,
1017                custom_color1,
1018                custom_style.clone(),
1019            );
1020            assert_eq!(
1021                light_theme.background_color,
1022                Some(Colors::BLACK.with_alpha(0x1f))
1023            );
1024            assert_eq!(
1025                light_theme.delete_icon_color,
1026                Some(Colors::BLACK.with_alpha(0xde).into())
1027            );
1028            assert_eq!(
1029                light_theme.disabled_color,
1030                Some(Colors::BLACK.with_alpha(0x0c))
1031            );
1032            assert_eq!(
1033                light_theme.selected_color,
1034                Some(Colors::BLACK.with_alpha(0x3d))
1035            );
1036            assert_eq!(
1037                light_theme.secondary_selected_color,
1038                Some(custom_color1.with_alpha(0x3d))
1039            );
1040            assert_eq!(light_theme.label_padding, None);
1041            assert_eq!(light_theme.padding, Some(EdgeInsets::all(4.0).into()));
1042            assert!(light_theme.side.is_none());
1043            assert!(light_theme.shape.is_none());
1044            assert_eq!(
1045                label_color(&light_theme),
1046                Some(Colors::BLACK.with_alpha(0xde))
1047            );
1048            assert_eq!(
1049                secondary_label_color(&light_theme),
1050                Some(custom_color1.with_alpha(0xde))
1051            );
1052            assert_eq!(light_theme.brightness, Some(Brightness::Light));
1053
1054            let dark_theme = ChipThemeData::from_defaults(
1055                Some(Brightness::Dark),
1056                None,
1057                custom_color1,
1058                custom_style.clone(),
1059            );
1060            assert_eq!(
1061                dark_theme.background_color,
1062                Some(Colors::WHITE.with_alpha(0x1f))
1063            );
1064            assert_eq!(
1065                dark_theme.delete_icon_color,
1066                Some(Colors::WHITE.with_alpha(0xde).into())
1067            );
1068            assert_eq!(
1069                dark_theme.disabled_color,
1070                Some(Colors::WHITE.with_alpha(0x0c))
1071            );
1072            assert_eq!(
1073                dark_theme.selected_color,
1074                Some(Colors::WHITE.with_alpha(0x3d))
1075            );
1076            assert_eq!(
1077                dark_theme.secondary_selected_color,
1078                Some(custom_color1.with_alpha(0x3d))
1079            );
1080            assert_eq!(dark_theme.label_padding, None);
1081            assert_eq!(dark_theme.padding, Some(EdgeInsets::all(4.0).into()));
1082            assert!(dark_theme.side.is_none());
1083            assert!(dark_theme.shape.is_none());
1084            assert_eq!(
1085                label_color(&dark_theme),
1086                Some(Colors::WHITE.with_alpha(0xde))
1087            );
1088            assert_eq!(
1089                secondary_label_color(&dark_theme),
1090                Some(custom_color1.with_alpha(0xde))
1091            );
1092            assert_eq!(dark_theme.brightness, Some(Brightness::Dark));
1093
1094            let custom_theme = ChipThemeData::from_defaults(
1095                None,
1096                Some(custom_color1),
1097                custom_color2,
1098                custom_style,
1099            );
1100            assert_eq!(
1101                custom_theme.delete_icon_color,
1102                Some(custom_color1.with_alpha(0xde).into())
1103            );
1104            assert_eq!(
1105                custom_theme.disabled_color,
1106                Some(custom_color1.with_alpha(0x0c))
1107            );
1108            assert_eq!(
1109                custom_theme.selected_color,
1110                Some(custom_color1.with_alpha(0x3d))
1111            );
1112            assert_eq!(
1113                custom_theme.secondary_selected_color,
1114                Some(custom_color2.with_alpha(0x3d))
1115            );
1116            assert_eq!(custom_theme.label_padding, None);
1117            assert_eq!(custom_theme.padding, Some(EdgeInsets::all(4.0).into()));
1118            assert!(custom_theme.side.is_none());
1119            assert!(custom_theme.shape.is_none());
1120            assert_eq!(
1121                label_color(&custom_theme),
1122                Some(custom_color1.with_alpha(0xde))
1123            );
1124            assert_eq!(
1125                secondary_label_color(&custom_theme),
1126                Some(custom_color2.with_alpha(0xde))
1127            );
1128            assert_eq!(custom_theme.brightness, Some(Brightness::Light));
1129        });
1130    }
1131
1132    fn black_chip_theme(tester: &mut WidgetTester) -> ChipThemeData {
1133        ChipThemeData::from_defaults(
1134            Some(Brightness::Dark),
1135            None,
1136            Colors::BLACK,
1137            fallback_body_large(tester, Colors::BLACK),
1138        )
1139        .elevation(1.0)
1140        .label_padding(EdgeInsets::symmetric(0.0, 8.0))
1141        .shape(StadiumBorder::new(BorderSide::NONE))
1142        .side(BorderSide::default())
1143        .press_elevation(4.0)
1144        .shadow_color(Colors::BLACK)
1145        .surface_tint_color(Colors::BLACK)
1146        .selected_shadow_color(Colors::BLACK)
1147        .show_checkmark(false)
1148        .checkmark_color(Colors::BLACK)
1149        .icon_theme(IconThemeData::new().size(26.0))
1150    }
1151
1152    fn white_chip_theme(tester: &mut WidgetTester) -> ChipThemeData {
1153        ChipThemeData::from_defaults(
1154            Some(Brightness::Light),
1155            None,
1156            Colors::WHITE,
1157            fallback_body_large(tester, Colors::WHITE),
1158        )
1159        .padding(EdgeInsets::all(2.0))
1160        .label_padding(EdgeInsets::only(0.0, 8.0, 0.0, 8.0))
1161        .shape(BeveledRectangleBorder::default())
1162        .side(BorderSide {
1163            color: Colors::WHITE,
1164            ..BorderSide::default()
1165        })
1166        .elevation(5.0)
1167        .press_elevation(10.0)
1168        .shadow_color(Colors::WHITE)
1169        .surface_tint_color(Colors::WHITE)
1170        .selected_shadow_color(Colors::WHITE)
1171        .show_checkmark(true)
1172        .checkmark_color(Colors::WHITE)
1173        .icon_theme(IconThemeData::new().size(22.0))
1174    }
1175
1176    fn is_beveled(data: &ChipThemeData) -> bool {
1177        data.shape.as_ref().is_some_and(|shape| {
1178            shape
1179                .as_any()
1180                .downcast_ref::<BeveledRectangleBorder>()
1181                .is_some()
1182        })
1183    }
1184
1185    fn is_stadium(data: &ChipThemeData) -> bool {
1186        data.shape
1187            .as_ref()
1188            .is_some_and(|shape| shape.as_any().downcast_ref::<StadiumBorder>().is_some())
1189    }
1190
1191    fn side_color(data: &ChipThemeData) -> Option<Color> {
1192        data.side.as_ref().map(|side| side.value().color)
1193    }
1194
1195    #[test]
1196    fn chip_theme_data_lerps_correctly() {
1197        test_widgets(|tester| {
1198            let black = black_chip_theme(tester);
1199            let white = white_chip_theme(tester);
1200
1201            let lerp = ChipThemeData::lerp(Some(&black), Some(&white), 0.5).expect("a theme");
1202            let middle_grey = Color::new(0xff7f7f7f);
1203            same(lerp.background_color, middle_grey.with_alpha(0x1f));
1204            same(
1205                lerp.delete_icon_color.as_ref().map(AnyColor::color),
1206                middle_grey.with_alpha(0xde),
1207            );
1208            same(lerp.disabled_color, middle_grey.with_alpha(0x0c));
1209            same(lerp.selected_color, middle_grey.with_alpha(0x3d));
1210            same(lerp.secondary_selected_color, middle_grey.with_alpha(0x3d));
1211            same(lerp.shadow_color, middle_grey);
1212            same(lerp.surface_tint_color, middle_grey);
1213            same(lerp.selected_shadow_color, middle_grey);
1214            assert_eq!(lerp.show_checkmark, Some(true));
1215            assert_eq!(lerp.label_padding, Some(EdgeInsets::all(4.0).into()));
1216            assert_eq!(lerp.padding, Some(EdgeInsets::all(3.0).into()));
1217            same(side_color(&lerp), middle_grey);
1218            assert!(is_beveled(&lerp));
1219            same(label_color(&lerp), middle_grey.with_alpha(0xde));
1220            same(secondary_label_color(&lerp), middle_grey.with_alpha(0xde));
1221            assert_eq!(lerp.brightness, Some(Brightness::Light));
1222            assert_eq!(lerp.elevation, Some(3.0));
1223            assert_eq!(lerp.press_elevation, Some(7.0));
1224            same(lerp.checkmark_color, middle_grey);
1225            assert_eq!(lerp.icon_theme, Some(IconThemeData::new().size(24.0)));
1226
1227            assert_eq!(ChipThemeData::lerp(None, None, 0.25), None);
1228
1229            let a_null_25 = ChipThemeData::lerp(None, Some(&white), 0.25).expect("a theme");
1230            same(a_null_25.background_color, Colors::BLACK.with_alpha(0x08));
1231            same(
1232                a_null_25.delete_icon_color.as_ref().map(AnyColor::color),
1233                Colors::BLACK.with_alpha(0x38),
1234            );
1235            same(a_null_25.disabled_color, Colors::BLACK.with_alpha(0x03));
1236            same(a_null_25.selected_color, Colors::BLACK.with_alpha(0x0f));
1237            same(
1238                a_null_25.secondary_selected_color,
1239                Colors::WHITE.with_alpha(0x0f),
1240            );
1241            same(a_null_25.shadow_color, Colors::WHITE.with_alpha(0x40));
1242            same(a_null_25.surface_tint_color, Colors::WHITE.with_alpha(0x40));
1243            same(
1244                a_null_25.selected_shadow_color,
1245                Colors::WHITE.with_alpha(0x40),
1246            );
1247            assert_eq!(a_null_25.show_checkmark, Some(true));
1248            assert_eq!(
1249                a_null_25.label_padding,
1250                Some(EdgeInsets::only(0.0, 2.0, 0.0, 2.0).into())
1251            );
1252            assert_eq!(a_null_25.padding, Some(EdgeInsets::all(0.5).into()));
1253            same(side_color(&a_null_25), Colors::WHITE.with_alpha(0x3f));
1254            assert!(is_beveled(&a_null_25));
1255            same(label_color(&a_null_25), Colors::BLACK.with_alpha(0x38));
1256            same(
1257                secondary_label_color(&a_null_25),
1258                Colors::WHITE.with_alpha(0x38),
1259            );
1260            assert_eq!(a_null_25.brightness, Some(Brightness::Light));
1261            assert_eq!(a_null_25.elevation, Some(1.25));
1262            assert_eq!(a_null_25.press_elevation, Some(2.5));
1263            same(a_null_25.checkmark_color, Colors::WHITE.with_alpha(0x40));
1264            assert_eq!(a_null_25.icon_theme, Some(IconThemeData::new().size(5.5)));
1265
1266            let a_null_75 = ChipThemeData::lerp(None, Some(&white), 0.75).expect("a theme");
1267            same(a_null_75.background_color, Colors::BLACK.with_alpha(0x17));
1268            same(
1269                a_null_75.delete_icon_color.as_ref().map(AnyColor::color),
1270                Colors::BLACK.with_alpha(0xa7),
1271            );
1272            same(a_null_75.disabled_color, Colors::BLACK.with_alpha(0x09));
1273            same(a_null_75.selected_color, Colors::BLACK.with_alpha(0x2e));
1274            same(
1275                a_null_75.secondary_selected_color,
1276                Colors::WHITE.with_alpha(0x2e),
1277            );
1278            same(a_null_75.shadow_color, Colors::WHITE.with_alpha(0xbf));
1279            same(a_null_75.surface_tint_color, Colors::WHITE.with_alpha(0xbf));
1280            same(
1281                a_null_75.selected_shadow_color,
1282                Colors::WHITE.with_alpha(0xbf),
1283            );
1284            assert_eq!(a_null_75.show_checkmark, Some(true));
1285            assert_eq!(
1286                a_null_75.label_padding,
1287                Some(EdgeInsets::only(0.0, 6.0, 0.0, 6.0).into())
1288            );
1289            assert_eq!(a_null_75.padding, Some(EdgeInsets::all(1.5).into()));
1290            same(side_color(&a_null_75), Colors::WHITE.with_alpha(0xbf));
1291            assert!(is_beveled(&a_null_75));
1292            same(label_color(&a_null_75), Colors::BLACK.with_alpha(0xa7));
1293            same(
1294                secondary_label_color(&a_null_75),
1295                Colors::WHITE.with_alpha(0xa7),
1296            );
1297            assert_eq!(a_null_75.brightness, Some(Brightness::Light));
1298            assert_eq!(a_null_75.elevation, Some(3.75));
1299            assert_eq!(a_null_75.press_elevation, Some(7.5));
1300            same(a_null_75.checkmark_color, Colors::WHITE.with_alpha(0xbf));
1301            assert_eq!(a_null_75.icon_theme, Some(IconThemeData::new().size(16.5)));
1302
1303            let b_null_25 = ChipThemeData::lerp(Some(&black), None, 0.25).expect("a theme");
1304            same(b_null_25.background_color, Colors::WHITE.with_alpha(0x17));
1305            same(
1306                b_null_25.delete_icon_color.as_ref().map(AnyColor::color),
1307                Colors::WHITE.with_alpha(0xa7),
1308            );
1309            same(b_null_25.disabled_color, Colors::WHITE.with_alpha(0x09));
1310            same(b_null_25.selected_color, Colors::WHITE.with_alpha(0x2e));
1311            same(
1312                b_null_25.secondary_selected_color,
1313                Colors::BLACK.with_alpha(0x2e),
1314            );
1315            same(b_null_25.shadow_color, Colors::BLACK.with_alpha(0xbf));
1316            same(b_null_25.surface_tint_color, Colors::BLACK.with_alpha(0xbf));
1317            same(
1318                b_null_25.selected_shadow_color,
1319                Colors::BLACK.with_alpha(0xbf),
1320            );
1321            assert_eq!(b_null_25.show_checkmark, Some(false));
1322            assert_eq!(
1323                b_null_25.label_padding,
1324                Some(EdgeInsets::symmetric(0.0, 6.0).into())
1325            );
1326            assert_eq!(b_null_25.padding, Some(EdgeInsets::all(3.0).into()));
1327            same(side_color(&b_null_25), Colors::BLACK.with_alpha(0xbf));
1328            assert!(is_stadium(&b_null_25));
1329            same(label_color(&b_null_25), Colors::WHITE.with_alpha(0xa7));
1330            same(
1331                secondary_label_color(&b_null_25),
1332                Colors::BLACK.with_alpha(0xa7),
1333            );
1334            assert_eq!(b_null_25.brightness, Some(Brightness::Dark));
1335            assert_eq!(b_null_25.elevation, Some(0.75));
1336            assert_eq!(b_null_25.press_elevation, Some(3.0));
1337            same(b_null_25.checkmark_color, Colors::BLACK.with_alpha(0xbf));
1338            assert_eq!(b_null_25.icon_theme, Some(IconThemeData::new().size(19.5)));
1339
1340            let b_null_75 = ChipThemeData::lerp(Some(&black), None, 0.75).expect("a theme");
1341            same(b_null_75.background_color, Colors::WHITE.with_alpha(0x08));
1342            same(
1343                b_null_75.delete_icon_color.as_ref().map(AnyColor::color),
1344                Colors::WHITE.with_alpha(0x38),
1345            );
1346            same(b_null_75.disabled_color, Colors::WHITE.with_alpha(0x03));
1347            same(b_null_75.selected_color, Colors::WHITE.with_alpha(0x0f));
1348            same(
1349                b_null_75.secondary_selected_color,
1350                Colors::BLACK.with_alpha(0x0f),
1351            );
1352            same(b_null_75.shadow_color, Colors::BLACK.with_alpha(0x40));
1353            same(b_null_75.surface_tint_color, Colors::BLACK.with_alpha(0x40));
1354            same(
1355                b_null_75.selected_shadow_color,
1356                Colors::BLACK.with_alpha(0x40),
1357            );
1358            assert_eq!(b_null_75.show_checkmark, Some(true));
1359            assert_eq!(
1360                b_null_75.label_padding,
1361                Some(EdgeInsets::symmetric(0.0, 2.0).into())
1362            );
1363            assert_eq!(b_null_75.padding, Some(EdgeInsets::all(1.0).into()));
1364            same(side_color(&b_null_75), Colors::BLACK.with_alpha(0x3f));
1365            assert!(is_stadium(&b_null_75));
1366            same(label_color(&b_null_75), Colors::WHITE.with_alpha(0x38));
1367            same(
1368                secondary_label_color(&b_null_75),
1369                Colors::BLACK.with_alpha(0x38),
1370            );
1371            assert_eq!(b_null_75.brightness, Some(Brightness::Light));
1372            assert_eq!(b_null_75.elevation, Some(0.25));
1373            assert_eq!(b_null_75.press_elevation, Some(1.0));
1374            same(b_null_75.checkmark_color, Colors::BLACK.with_alpha(0x40));
1375            assert_eq!(b_null_75.icon_theme, Some(IconThemeData::new().size(6.5)));
1376        });
1377    }
1378
1379    // Dart's helpers of chip_theme_test.dart.
1380
1381    use std::rc::Rc;
1382
1383    use waft_embedder::Size;
1384    use waft_painting::{CircleBorder, RoundedRectangleBorder, ShapeBorderRef};
1385    use waft_widgets::{
1386        AnyElement, Builder, Center, Container, CustomPaint, DefaultTextStyle, Directionality,
1387        Icon, IconTheme, SizedBox, Text, TextDirection,
1388    };
1389
1390    use crate::chip::{RawChip, tests::only};
1391    use crate::icons::Icons;
1392    use crate::material::Material;
1393    use waft_embedder::valo::Op;
1394
1395    use crate::test_support::material_app;
1396
1397    use waft_rendering::testing::{
1398        CanvasMethod, PaintCall, PaintedStyle, assert_paints, colors_match, paints,
1399    };
1400    fn pump_app(tester: &mut WidgetTester, theme: ThemeData, home: WidgetRef) {
1401        tester.pump_widget(material_app(theme, home));
1402    }
1403
1404    fn theme_with(tester: &WidgetTester, chip_theme: ChipThemeData, material3: bool) -> ThemeData {
1405        ThemeData::builder()
1406            .use_material3(material3)
1407            .chip_theme(chip_theme)
1408            .build(&tester.cell.borrow())
1409    }
1410
1411    /// Dart's `Directionality(textDirection: ltr, child: Material(child: Center(child: chip)))`.
1412    fn centered_material(chip: RawChip) -> WidgetRef {
1413        Directionality::new(
1414            TextDirection::Ltr,
1415            Material::new()
1416                .child(Center::new().child(chip))
1417                .into_widget(),
1418        )
1419        .into_widget()
1420    }
1421
1422    fn avatar_chip() -> RawChip {
1423        RawChip::new(SizedBox::new().width(100.0).height(100.0))
1424            .avatar(Icon::new(Some(Icons::add())))
1425            .on_selected(Rc::new(|_app, _value| {}))
1426    }
1427
1428    /// Dart's `getMaterialBox`: the first `CustomPaint` below the `RawChip`, with what it and
1429    /// everything under it draws, as Dart's `paints` records it.
1430    fn material_box_ops(tester: &WidgetTester) -> Vec<Op> {
1431        let custom_paint = tester.descendants_of_type::<CustomPaint>(only::<RawChip>(tester))[0];
1432        tester.painted_ops_deep(tester.render_box_of(custom_paint).as_object())
1433    }
1434
1435    /// What the `RawChip` and everything under it draws.
1436    fn raw_chip_ops(tester: &WidgetTester) -> Vec<Op> {
1437        tester.painted_ops_deep(tester.render_box_of(only::<RawChip>(tester)).as_object())
1438    }
1439
1440    /// Dart's `paints..rect(color:)`: the first `drawRect` is of `color`.
1441    fn paints_rect(ops: &[Op], color: Color) -> bool {
1442        ops.iter()
1443            .find(|op| CanvasMethod::of(op) == CanvasMethod::DrawRect)
1444            .is_some_and(
1445                |op| matches!(op, Op::DrawRect { paint, .. } if colors_match(paint.color, color)),
1446            )
1447    }
1448
1449    fn material_of_chip(tester: &WidgetTester) -> AnyElement {
1450        tester.descendants_of_type::<Material>(only::<RawChip>(tester))[0]
1451    }
1452
1453    fn material_elevation(tester: &WidgetTester) -> f64 {
1454        tester.widget(material_of_chip(tester), |material: &Material| {
1455            material.elevation
1456        })
1457    }
1458
1459    fn material_shape(tester: &WidgetTester) -> Option<ShapeBorderRef> {
1460        tester.widget(material_of_chip(tester), |material: &Material| {
1461            material.shape.clone()
1462        })
1463    }
1464
1465    fn icon_theme_data(tester: &WidgetTester) -> IconThemeData {
1466        let icon_theme = tester.descendants_of_type::<IconTheme>(only::<RawChip>(tester))[0];
1467        tester.widget(icon_theme, |icon_theme: &IconTheme| icon_theme.data.clone())
1468    }
1469
1470    fn icon_color(tester: &WidgetTester) -> Option<Color> {
1471        icon_theme_data(tester).color.map(|color| color.color())
1472    }
1473
1474    /// Dart's `getLabelStyle`: the last `DefaultTextStyle` below the `RawChip`.
1475    fn label_font_size(tester: &WidgetTester) -> Option<f64> {
1476        let styles = tester.descendants_of_type::<DefaultTextStyle>(only::<RawChip>(tester));
1477        let last = *styles.last().expect("a DefaultTextStyle");
1478        tester.widget(last, |style: &DefaultTextStyle| style.style.font_size)
1479    }
1480
1481    fn rounded_rectangle_with_side(color: Color) -> ShapeBorderRef {
1482        ShapeBorderRef::new(RoundedRectangleBorder::default().copy_with(
1483            Some(BorderSide {
1484                color,
1485                ..BorderSide::default()
1486            }),
1487            None,
1488        ))
1489    }
1490
1491    fn chip_theme_for_overrides() -> ChipThemeData {
1492        ChipThemeData::new()
1493            .background_color(Color::new(0xff112233))
1494            .elevation(4.0)
1495            .padding(EdgeInsets::all(50.0))
1496            .label_padding(EdgeInsets::all(25.0))
1497            .shape(RoundedRectangleBorder::default())
1498            .label_style(TextStyle::new().font_size(32.0))
1499            .icon_theme(IconThemeData::new().color(Color::new(0xff332211)))
1500    }
1501
1502    fn assert_chip_uses_theme(tester: &WidgetTester, size: Size, shape: ShapeBorderRef) {
1503        let chip_theme = chip_theme_for_overrides();
1504        assert!(paints_rect(
1505            &material_box_ops(tester),
1506            chip_theme.background_color.expect("a color")
1507        ));
1508        assert_eq!(material_elevation(tester), 4.0);
1509        assert_eq!(tester.get_size(only::<RawChip>(tester)), size); // label + padding + labelPadding
1510        assert_eq!(material_shape(tester), Some(shape));
1511        assert_eq!(label_font_size(tester), Some(32.0));
1512        assert_eq!(icon_color(tester), Some(Color::new(0xff332211)));
1513    }
1514
1515    #[test]
1516    fn material3_chip_uses_theme_data_chip_theme() {
1517        test_widgets(|tester| {
1518            let theme = theme_with(tester, chip_theme_for_overrides(), true);
1519            let outline_variant = theme.color_scheme.outline_variant();
1520            pump_app(tester, theme, centered_material(avatar_chip()));
1521            assert_chip_uses_theme(
1522                tester,
1523                Size::new(402.0, 252.0),
1524                rounded_rectangle_with_side(outline_variant),
1525            );
1526        });
1527    }
1528
1529    #[test]
1530    fn material2_chip_uses_theme_data_chip_theme() {
1531        test_widgets(|tester| {
1532            let theme = theme_with(tester, chip_theme_for_overrides(), false);
1533            pump_app(tester, theme, centered_material(avatar_chip()));
1534            assert_chip_uses_theme(
1535                tester,
1536                Size::new(400.0, 250.0),
1537                ShapeBorderRef::new(RoundedRectangleBorder::default()),
1538            );
1539        });
1540    }
1541
1542    fn local_chip_theme_home(chip_theme: ChipThemeData) -> WidgetRef {
1543        ChipTheme::new(
1544            chip_theme,
1545            Builder::new(|_app, _context| centered_material(avatar_chip())),
1546        )
1547        .into_widget()
1548    }
1549
1550    #[test]
1551    fn material3_chip_uses_local_chip_theme() {
1552        test_widgets(|tester| {
1553            let theme = theme_with(tester, ChipThemeData::new(), true);
1554            let outline_variant = theme.color_scheme.outline_variant();
1555            pump_app(
1556                tester,
1557                theme,
1558                local_chip_theme_home(chip_theme_for_overrides()),
1559            );
1560            assert_chip_uses_theme(
1561                tester,
1562                Size::new(402.0, 252.0),
1563                rounded_rectangle_with_side(outline_variant),
1564            );
1565        });
1566    }
1567
1568    #[test]
1569    fn material2_chip_uses_local_chip_theme() {
1570        test_widgets(|tester| {
1571            let theme = theme_with(tester, ChipThemeData::new(), false);
1572            pump_app(
1573                tester,
1574                theme,
1575                local_chip_theme_home(chip_theme_for_overrides()),
1576            );
1577            assert_chip_uses_theme(
1578                tester,
1579                Size::new(400.0, 250.0),
1580                ShapeBorderRef::new(RoundedRectangleBorder::default()),
1581            );
1582        });
1583    }
1584
1585    #[test]
1586    fn chip_properties_overrides_chip_theme() {
1587        test_widgets(|tester| {
1588            let background_color = Color::new(0xff000000);
1589            let elevation = 6.0;
1590            let shape = RoundedRectangleBorder::new(
1591                BorderSide {
1592                    color: Color::new(0xff0000ff),
1593                    ..BorderSide::default()
1594                },
1595                waft_painting::BorderRadius::ZERO.into(),
1596            );
1597            let icon_theme = IconThemeData::new().color(Color::new(0xff00ff00));
1598            let theme = theme_with(tester, chip_theme_for_overrides(), true);
1599            let chip = avatar_chip()
1600                .background_color(background_color)
1601                .elevation(elevation)
1602                .padding(EdgeInsets::all(10.0))
1603                .label_padding(EdgeInsets::all(5.0))
1604                .label_style(TextStyle::new().font_size(20.0))
1605                .shape(shape)
1606                .icon_theme(icon_theme.clone());
1607            pump_app(tester, theme, centered_material(chip));
1608
1609            assert!(paints_rect(&material_box_ops(tester), background_color));
1610            assert_eq!(
1611                tester.get_size(only::<RawChip>(tester)),
1612                Size::new(242.0, 132.0)
1613            ); // label + padding + labelPadding
1614            assert_eq!(material_elevation(tester), elevation);
1615            assert_eq!(material_shape(tester), Some(ShapeBorderRef::new(shape)));
1616            assert_eq!(label_font_size(tester), Some(20.0));
1617            assert_eq!(icon_color(tester), Some(Color::new(0xff00ff00)));
1618        });
1619    }
1620
1621    fn assert_chip_uses_constructor_parameters(
1622        tester: &WidgetTester,
1623        background_color: Color,
1624        size: Size,
1625        shape: CircleBorder,
1626        icon_color_expected: Color,
1627    ) {
1628        assert_paints(
1629            &material_box_ops(tester),
1630            &[PaintCall::circle(Some(background_color))],
1631        );
1632        assert_eq!(tester.get_size(only::<RawChip>(tester)), size); // label + padding + labelPadding
1633        assert_eq!(material_elevation(tester), 3.0);
1634        assert_eq!(material_shape(tester), Some(ShapeBorderRef::new(shape)));
1635        assert_eq!(label_font_size(tester), Some(32.0));
1636        assert_eq!(icon_color(tester), Some(icon_color_expected));
1637    }
1638
1639    fn constructor_parameters_chip(background_color: Color, shape: CircleBorder) -> RawChip {
1640        avatar_chip()
1641            .background_color(background_color)
1642            .elevation(3.0)
1643            .padding(EdgeInsets::all(50.0))
1644            .label_padding(EdgeInsets::all(25.0))
1645            .label_style(TextStyle::new().font_size(32.0))
1646            .shape(shape)
1647            .icon_theme(IconThemeData::new().color(Color::new(0xff443322)))
1648    }
1649
1650    #[test]
1651    fn material3_chip_uses_constructor_parameters() {
1652        test_widgets(|tester| {
1653            let background_color = Color::new(0xff332211);
1654            let shape = CircleBorder::new(
1655                BorderSide {
1656                    color: Color::new(0xff0000ff),
1657                    ..BorderSide::default()
1658                },
1659                0.0,
1660            );
1661            let theme = ThemeData::new(&tester.cell.borrow());
1662            pump_app(
1663                tester,
1664                theme,
1665                centered_material(constructor_parameters_chip(background_color, shape)),
1666            );
1667            assert_chip_uses_constructor_parameters(
1668                tester,
1669                background_color,
1670                Size::new(402.0, 252.0),
1671                shape,
1672                Color::new(0xff443322),
1673            );
1674        });
1675    }
1676
1677    #[test]
1678    fn material2_chip_uses_constructor_parameters() {
1679        test_widgets(|tester| {
1680            let background_color = Color::new(0xff332211);
1681            let shape = CircleBorder::default();
1682            let theme = ThemeData::builder()
1683                .use_material3(false)
1684                .build(&tester.cell.borrow());
1685            pump_app(
1686                tester,
1687                theme,
1688                centered_material(constructor_parameters_chip(background_color, shape)),
1689            );
1690            assert_chip_uses_constructor_parameters(
1691                tester,
1692                background_color,
1693                Size::new(400.0, 250.0),
1694                shape,
1695                Color::new(0xff443322),
1696            );
1697        });
1698    }
1699
1700    fn selectable_choice_chip(selected: bool, enabled: bool) -> ChoiceChip {
1701        let mut chip = ChoiceChip::new(Text::new("Chip"), selected);
1702        if enabled {
1703            chip.on_selected = Some(Rc::new(|_app, _value| {}));
1704        }
1705        chip
1706    }
1707
1708    fn scaffold_with<K>(chip: impl IntoWidget<K>) -> WidgetRef {
1709        Scaffold::new().body(chip).into_widget()
1710    }
1711
1712    #[test]
1713    fn chip_uses_stateful_color_from_chip_theme() {
1714        test_widgets(|tester| {
1715            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
1716                .into_erased::<waft_widgets::AnyFocusNode>();
1717
1718            let pressed_color = Color::new(0x00000001);
1719            let hover_color = Color::new(0x00000002);
1720            let focused_color = Color::new(0x00000003);
1721            let default_color = Color::new(0x00000004);
1722            let selected_color = Color::new(0x00000005);
1723            let disabled_color = Color::new(0x00000006);
1724
1725            let text_color_of = move |states: &WidgetStates| {
1726                if states.contains(&WidgetState::Disabled) {
1727                    return disabled_color;
1728                }
1729                if states.contains(&WidgetState::Pressed) {
1730                    return pressed_color;
1731                }
1732                if states.contains(&WidgetState::Hovered) {
1733                    return hover_color;
1734                }
1735                if states.contains(&WidgetState::Focused) {
1736                    return focused_color;
1737                }
1738                if states.contains(&WidgetState::Selected) {
1739                    return selected_color;
1740                }
1741                default_color
1742            };
1743            let label_style = TextStyle::new().color(WidgetStateColor::resolve_with(text_color_of));
1744            let chip_widget = |tester: &WidgetTester, enabled: bool, selected: bool| {
1745                let chip_theme = ThemeData::new(&tester.cell.borrow())
1746                    .chip_theme
1747                    .copy_with()
1748                    .label_style(label_style.clone())
1749                    .secondary_label_style(label_style.clone());
1750                let theme = ThemeData::builder()
1751                    .chip_theme(chip_theme)
1752                    .build(&tester.cell.borrow());
1753                material_app(
1754                    theme,
1755                    scaffold_with(
1756                        Focus::new(selectable_choice_chip(selected, enabled))
1757                            .focus_node(focus_node.clone()),
1758                    ),
1759                )
1760            };
1761
1762            // Default, not disabled.
1763            let root = chip_widget(tester, true, false);
1764            tester.pump_widget(root);
1765            assert_eq!(tester.text_color("Chip"), default_color);
1766
1767            // Selected.
1768            let root = chip_widget(tester, true, true);
1769            tester.pump_widget(root);
1770            assert_eq!(tester.text_color("Chip"), selected_color);
1771
1772            // Focused.
1773            let chip_focus_node = focus_node.handle().children(&tester.cell.borrow())[0];
1774            chip_focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
1775            tester.pump_and_settle();
1776            assert_eq!(tester.text_color("Chip"), focused_color);
1777
1778            // Hovered.
1779            let center = tester.get_center(only::<ChoiceChip>(tester));
1780            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1781            tester.add_pointer(&mut gesture, Offset::ZERO);
1782            tester.move_to(&mut gesture, center, false);
1783            tester.pump_and_settle();
1784            assert_eq!(tester.text_color("Chip"), hover_color);
1785
1786            // Pressed.
1787            tester.down(&mut gesture, center);
1788            tester.pump_and_settle();
1789            assert_eq!(tester.text_color("Chip"), pressed_color);
1790
1791            // Disabled.
1792            let root = chip_widget(tester, false, false);
1793            tester.pump_widget(root);
1794            tester.pump_and_settle();
1795            assert_eq!(tester.text_color("Chip"), disabled_color);
1796        });
1797    }
1798
1799    /// Dart's `chipWidget({selected})` of the shape cases.
1800    fn pump_choice_chip_with_theme(tester: &mut WidgetTester, theme: ThemeData, selected: bool) {
1801        pump_app(
1802            tester,
1803            theme,
1804            scaffold_with(selectable_choice_chip(selected, true)),
1805        );
1806    }
1807
1808    fn is_stadium_shape(shape: &Option<ShapeBorderRef>) -> bool {
1809        shape
1810            .as_ref()
1811            .is_some_and(|shape| shape.as_any().downcast_ref::<StadiumBorder>().is_some())
1812    }
1813
1814    fn is_rounded_rectangle_shape(shape: &Option<ShapeBorderRef>) -> bool {
1815        shape.as_ref().is_some_and(|shape| {
1816            shape
1817                .as_any()
1818                .downcast_ref::<RoundedRectangleBorder>()
1819                .is_some()
1820        })
1821    }
1822
1823    #[test]
1824    fn material2_chip_uses_stateful_shape_from_chip_theme() {
1825        test_widgets(|tester| {
1826            let chip_theme = || {
1827                ChipThemeData::from_defaults(
1828                    Some(Brightness::Light),
1829                    None,
1830                    Colors::BLUE.primary(),
1831                    TextStyle::new(),
1832                )
1833                .shape(WidgetStateOutlinedBorder::resolve_with(|states| {
1834                    states
1835                        .contains(&WidgetState::Selected)
1836                        .then(|| OutlinedBorderRef::new(RoundedRectangleBorder::default()))
1837                }))
1838            };
1839
1840            // Default.
1841            let theme = theme_with(tester, chip_theme(), false);
1842            pump_choice_chip_with_theme(tester, theme, false);
1843            assert!(is_stadium_shape(&material_shape(tester)));
1844
1845            // Selected.
1846            let theme = theme_with(tester, chip_theme(), false);
1847            pump_choice_chip_with_theme(tester, theme, true);
1848            assert!(is_rounded_rectangle_shape(&material_shape(tester)));
1849        });
1850    }
1851
1852    #[test]
1853    fn material3_chip_uses_stateful_shape_from_chip_theme() {
1854        test_widgets(|tester| {
1855            let chip_theme = || {
1856                ChipThemeData::new().shape(WidgetStateOutlinedBorder::resolve_with(|states| {
1857                    states
1858                        .contains(&WidgetState::Selected)
1859                        .then(|| OutlinedBorderRef::new(StadiumBorder::new(BorderSide::NONE)))
1860                }))
1861            };
1862
1863            // Default.
1864            let theme = theme_with(tester, chip_theme(), true);
1865            pump_choice_chip_with_theme(tester, theme, false);
1866            assert!(is_rounded_rectangle_shape(&material_shape(tester)));
1867
1868            // Selected.
1869            let theme = theme_with(tester, chip_theme(), true);
1870            pump_choice_chip_with_theme(tester, theme, true);
1871            assert!(is_stadium_shape(&material_shape(tester)));
1872        });
1873    }
1874
1875    fn pump_raw_chip_in_material(tester: &mut WidgetTester, theme: ThemeData, chip: RawChip) {
1876        pump_app(tester, theme, Material::new().child(chip).into_widget());
1877    }
1878
1879    #[test]
1880    fn raw_chip_uses_material_state_color_from_chip_theme() {
1881        test_widgets(|tester| {
1882            let disabled_selected_color = Color::new(0xffffff00);
1883            let disabled_color = Color::new(0xff00ff00);
1884            let background_color = Color::new(0xff0000ff);
1885            let selected_color = Color::new(0xffff0000);
1886            let build_app = |tester: &mut WidgetTester, enabled: bool, selected: bool| {
1887                let chip_theme = ChipThemeData::new().color(
1888                    <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
1889                        let disabled = states.contains(&WidgetState::Disabled);
1890                        let selected = states.contains(&WidgetState::Selected);
1891                        Some(match (disabled, selected) {
1892                            (true, true) => disabled_selected_color,
1893                            (true, false) => disabled_color,
1894                            (false, true) => selected_color,
1895                            (false, false) => background_color,
1896                        })
1897                    }),
1898                );
1899                let theme = theme_with(tester, chip_theme, true);
1900                pump_raw_chip_in_material(
1901                    tester,
1902                    theme,
1903                    RawChip::new(Text::new("RawChip"))
1904                        .is_enabled(enabled)
1905                        .selected(selected),
1906                );
1907                tester.pump_and_settle();
1908            };
1909
1910            // Enabled chip should have the provided backgroundColor.
1911            build_app(tester, true, false);
1912            assert_paints(
1913                &material_box_ops(tester),
1914                &[PaintCall::rrect(Some(background_color))],
1915            );
1916
1917            // Disabled chip should have the provided disabledColor.
1918            build_app(tester, false, false);
1919            assert_paints(
1920                &material_box_ops(tester),
1921                &[PaintCall::rrect(Some(disabled_color))],
1922            );
1923
1924            // Enabled & selected chip should have the provided selectedColor.
1925            build_app(tester, true, true);
1926            assert_paints(
1927                &material_box_ops(tester),
1928                &[PaintCall::rrect(Some(selected_color))],
1929            );
1930
1931            // Disabled & selected chip should have the provided disabledSelectedColor.
1932            build_app(tester, false, true);
1933            assert_paints(
1934                &material_box_ops(tester),
1935                &[PaintCall::rrect(Some(disabled_selected_color))],
1936            );
1937        });
1938    }
1939
1940    #[test]
1941    fn raw_chip_uses_state_colors_from_chip_theme() {
1942        test_widgets(|tester| {
1943            let disabled_color = Color::new(0xadfefafe);
1944            let background_color = Color::new(0xcafefeed);
1945            let selected_color = Color::new(0xbeefcafe);
1946            let build_app = |tester: &mut WidgetTester, enabled: bool, selected: bool| {
1947                let chip_theme = ChipThemeData::new()
1948                    .disabled_color(disabled_color)
1949                    .background_color(background_color)
1950                    .selected_color(selected_color);
1951                let theme = theme_with(tester, chip_theme, true);
1952                pump_raw_chip_in_material(
1953                    tester,
1954                    theme,
1955                    RawChip::new(Text::new("RawChip"))
1956                        .is_enabled(enabled)
1957                        .selected(selected),
1958                );
1959                tester.pump_and_settle();
1960            };
1961
1962            // Enabled chip should have the provided backgroundColor.
1963            build_app(tester, true, false);
1964            assert_paints(
1965                &material_box_ops(tester),
1966                &[PaintCall::rrect(Some(background_color))],
1967            );
1968
1969            // Disabled chip should have the provided disabledColor.
1970            build_app(tester, false, false);
1971            assert_paints(
1972                &material_box_ops(tester),
1973                &[PaintCall::rrect(Some(disabled_color))],
1974            );
1975
1976            // Enabled & selected chip should have the provided selectedColor.
1977            build_app(tester, true, true);
1978            assert_paints(
1979                &material_box_ops(tester),
1980                &[PaintCall::rrect(Some(selected_color))],
1981            );
1982        });
1983    }
1984
1985    #[test]
1986    fn raw_chip_respects_checkmark_properties_from_chip_theme() {
1987        test_widgets(|tester| {
1988            let red = Color::new(0xffff0000);
1989            let build_raw_chip = |tester: &mut WidgetTester, chip_theme: ChipThemeData| {
1990                let theme = theme_with(tester, chip_theme, true);
1991                let chip = RawChip::new(SizedBox::new().width(100.0).height(100.0))
1992                    .selected(true)
1993                    .on_selected(Rc::new(|_app, _value| {}));
1994                pump_app(tester, theme, centered_material(chip));
1995            };
1996
1997            // Test that the checkmark is painted.
1998            build_raw_chip(tester, ChipThemeData::new().checkmark_color(red));
1999            assert_paints(
2000                &material_box_ops(tester),
2001                &[PaintCall::Path {
2002                    color: Some(red),
2003                    style: Some(PaintedStyle::Stroke(None)),
2004                    includes: Vec::new(),
2005                    excludes: Vec::new(),
2006                }],
2007            );
2008
2009            // Test that the checkmark is not painted when ChipThemeData.showCheckmark is false.
2010            build_raw_chip(
2011                tester,
2012                ChipThemeData::new()
2013                    .show_checkmark(false)
2014                    .checkmark_color(red),
2015            );
2016            tester.pump_and_settle();
2017            assert!(
2018                paints(
2019                    &material_box_ops(tester),
2020                    &[PaintCall::Path {
2021                        color: Some(red),
2022                        style: Some(PaintedStyle::Stroke(None)),
2023                        includes: Vec::new(),
2024                        excludes: Vec::new(),
2025                    }]
2026                )
2027                .is_err()
2028            );
2029        });
2030    }
2031
2032    #[test]
2033    fn material3_raw_chip_shapes_side_is_used_when_provided() {
2034        test_widgets(|tester| {
2035            let shape_with_side = |color: Color| {
2036                RoundedRectangleBorder::new(
2037                    BorderSide {
2038                        color,
2039                        ..BorderSide::default()
2040                    },
2041                    waft_painting::BorderRadiusGeometry::circular(7.0),
2042                )
2043            };
2044            let build_chip = |tester: &mut WidgetTester, side: Option<BorderSide>| {
2045                let mut chip_theme =
2046                    ChipThemeData::new().shape(shape_with_side(Color::new(0xffff00ff)));
2047                if let Some(side) = side {
2048                    chip_theme = chip_theme.side(side);
2049                }
2050                let theme = theme_with(tester, chip_theme, true);
2051                pump_app(
2052                    tester,
2053                    theme,
2054                    Material::new()
2055                        .child(Center::new().child(RawChip::new(Text::new("RawChip"))))
2056                        .into_widget(),
2057                );
2058            };
2059
2060            // Test [RawChip.shape] with a side.
2061            build_chip(tester, None);
2062
2063            // Chip should have the provided shape and the side from [RawChip.shape].
2064            assert_eq!(
2065                material_shape(tester),
2066                Some(ShapeBorderRef::new(shape_with_side(Color::new(0xffff00ff))))
2067            );
2068
2069            // Test [RawChip.shape] with a side and [RawChip.side].
2070            build_chip(
2071                tester,
2072                Some(BorderSide {
2073                    color: Color::new(0xfffff000),
2074                    ..BorderSide::default()
2075                }),
2076            );
2077            tester.pump_and_settle();
2078
2079            // Chip use shape from [RawChip.shape] and the side from [RawChip.side].
2080            // [RawChip.shape]'s side should be ignored.
2081            assert_eq!(
2082                material_shape(tester),
2083                Some(ShapeBorderRef::new(shape_with_side(Color::new(0xfffff000))))
2084            );
2085        });
2086    }
2087
2088    #[test]
2089    fn material3_chip_theme_data_icon_theme_respects_default_icon_theme_size() {
2090        test_widgets(|tester| {
2091            let build_chip = |tester: &mut WidgetTester, icon_theme: IconThemeData| {
2092                let theme = theme_with(tester, ChipThemeData::new().icon_theme(icon_theme), true);
2093                pump_app(tester, theme, centered_material(avatar_chip()));
2094            };
2095
2096            build_chip(tester, IconThemeData::new().color(Color::new(0xff332211)));
2097
2098            // Icon should have the default chip iconSize.
2099            assert_eq!(icon_theme_data(tester).size, Some(18.0));
2100            assert_eq!(icon_color(tester), Some(Color::new(0xff332211)));
2101
2102            // Icon should have the provided iconSize.
2103            build_chip(
2104                tester,
2105                IconThemeData::new()
2106                    .color(Color::new(0xff112233))
2107                    .size(23.0),
2108            );
2109            tester.pump_and_settle();
2110
2111            assert_eq!(icon_theme_data(tester).size, Some(23.0));
2112            assert_eq!(icon_color(tester), Some(Color::new(0xff112233)));
2113        });
2114    }
2115
2116    fn label_container() -> Container {
2117        Container::new()
2118            .width(75.0)
2119            .height(75.0)
2120            .color(Color::new(0xFFFF0000))
2121    }
2122
2123    #[test]
2124    fn chip_theme_data_avatar_box_constraints_updates_avatar_size_constraints() {
2125        test_widgets(|tester| {
2126            let border = 1.0;
2127            let icon_size = 18.0;
2128            let label_padding = 8.0;
2129            let padding = 8.0;
2130            let label_size = Size::new(75.0, 75.0);
2131
2132            // Test default avatar layout constraints.
2133            let chip_theme = ChipThemeData::new().avatar_box_constraints(
2134                BoxConstraints::tight_for_finite(f64::INFINITY, f64::INFINITY),
2135            );
2136            let theme = theme_with(tester, chip_theme, true);
2137            pump_app(
2138                tester,
2139                theme,
2140                Material::new()
2141                    .child(Center::new().child(
2142                        RawChip::new(label_container()).avatar(Icon::new(Some(Icons::favorite()))),
2143                    ))
2144                    .into_widget(),
2145            );
2146
2147            let chip_size = tester.get_size(only::<RawChip>(tester));
2148            assert_eq!(chip_size.width(), 127.0);
2149            assert_eq!(chip_size.height(), 93.0);
2150
2151            // Calculate the distance between avatar and chip edges.
2152            let chip_top_left = tester.get_rect(material_of_chip(tester)).top_left();
2153            let avatar_center =
2154                tester.get_center(tester.element(find::by_icon(&Icons::favorite()).first()));
2155            assert_eq!(
2156                chip_top_left.dx(),
2157                avatar_center.dx() - (icon_size / 2.0) - padding - border
2158            );
2159            assert_eq!(
2160                chip_top_left.dy(),
2161                avatar_center.dy() - (label_size.width() / 2.0) - padding - border
2162            );
2163
2164            // Calculate the distance between avatar and label.
2165            let label_top_left = tester.get_rect(only::<Container>(tester)).top_left();
2166            assert_eq!(
2167                label_top_left.dx(),
2168                avatar_center.dx() + (icon_size / 2.0) + label_padding
2169            );
2170        });
2171    }
2172
2173    #[test]
2174    fn chip_theme_data_delete_icon_box_constraints_updates_delete_icon_size_constraints() {
2175        test_widgets(|tester| {
2176            let border = 1.0;
2177            let icon_size = 18.0;
2178            let label_padding = 8.0;
2179            let padding = 8.0;
2180            let label_size = Size::new(75.0, 75.0);
2181
2182            // Test custom delete layout constraints.
2183            let chip_theme = ChipThemeData::new().delete_icon_box_constraints(
2184                BoxConstraints::tight_for_finite(f64::INFINITY, f64::INFINITY),
2185            );
2186            let theme = theme_with(tester, chip_theme, true);
2187            pump_app(
2188                tester,
2189                theme,
2190                Material::new()
2191                    .child(Center::new().child(
2192                        RawChip::new(label_container()).on_deleted(Listener::new(|_app| {})),
2193                    ))
2194                    .into_widget(),
2195            );
2196
2197            let chip_size = tester.get_size(only::<RawChip>(tester));
2198            assert_eq!(chip_size.width(), 127.0);
2199            assert_eq!(chip_size.height(), 93.0);
2200
2201            // Calculate the distance between delete icon and chip edges.
2202            let chip_top_right = tester.get_rect(material_of_chip(tester)).top_right();
2203            let delete_icon_center =
2204                tester.get_center(tester.element(find::by_icon(&Icons::cancel()).first()));
2205            assert_eq!(
2206                chip_top_right.dx(),
2207                delete_icon_center.dx() + (icon_size / 2.0) + padding + border
2208            );
2209            assert_eq!(
2210                chip_top_right.dy(),
2211                delete_icon_center.dy() - (label_size.width() / 2.0) - padding - border
2212            );
2213
2214            // Calculate the distance between delete icon and label.
2215            let label_top_right = tester.get_rect(only::<Container>(tester)).top_right();
2216            assert_eq!(
2217                label_top_right.dx(),
2218                delete_icon_center.dx() - (icon_size / 2.0) - label_padding
2219            );
2220        });
2221    }
2222
2223    #[test]
2224    fn chip_theme_data_icon_theme_updates_avatar_and_delete_icons() {
2225        test_widgets(|tester| {
2226            let icon_color = Color::new(0xffff0000);
2227            let icon_size = 32.0;
2228            let chip_theme = ChipThemeData::new()
2229                .icon_theme(IconThemeData::new().color(icon_color).size(icon_size));
2230            let theme = theme_with(tester, chip_theme, true);
2231            pump_app(
2232                tester,
2233                theme,
2234                Material::new()
2235                    .child(
2236                        Center::new().child(
2237                            RawChip::new(SizedBox::new().height(100.0))
2238                                .avatar(Icon::new(Some(Icons::favorite())))
2239                                .delete_icon(Icon::new(Some(Icons::delete())))
2240                                .on_deleted(Listener::new(|_app| {})),
2241                        ),
2242                    )
2243                    .into_widget(),
2244            );
2245
2246            // Test rendered icon size.
2247            let avatar_icon = tester.element(find::by_icon(&Icons::favorite()).first());
2248            let delete_icon = tester.element(find::by_icon(&Icons::delete()).first());
2249            assert_eq!(tester.get_size(avatar_icon).width(), icon_size);
2250            assert_eq!(tester.get_size(delete_icon).width(), icon_size);
2251
2252            // Test rendered icon color.
2253            assert_eq!(
2254                tester
2255                    .glyph_style(avatar_icon)
2256                    .color
2257                    .map(|color| color.color()),
2258                Some(icon_color)
2259            );
2260            assert_eq!(
2261                tester
2262                    .glyph_style(delete_icon)
2263                    .color
2264                    .map(|color| color.color()),
2265                Some(icon_color)
2266            );
2267        });
2268    }
2269
2270    #[test]
2271    fn chip_theme_data_delete_icon_color_overrides_chip_theme_data_icon_theme_color() {
2272        test_widgets(|tester| {
2273            let icon_color = Color::new(0xffff00ff);
2274            let delete_icon_color = Color::new(0xffff00ff);
2275            let build_chip = |tester: &mut WidgetTester, delete_icon_color: Option<Color>| {
2276                let mut chip_theme =
2277                    ChipThemeData::new().icon_theme(IconThemeData::new().color(icon_color));
2278                if let Some(delete_icon_color) = delete_icon_color {
2279                    chip_theme = chip_theme.delete_icon_color(delete_icon_color);
2280                }
2281                let theme = theme_with(tester, chip_theme, true);
2282                pump_app(
2283                    tester,
2284                    theme,
2285                    Material::new()
2286                        .child(
2287                            Center::new().child(
2288                                RawChip::new(SizedBox::new().height(100.0))
2289                                    .delete_icon(Icon::new(Some(Icons::delete())))
2290                                    .on_deleted(Listener::new(|_app| {})),
2291                            ),
2292                        )
2293                        .into_widget(),
2294                );
2295            };
2296            let delete_glyph_color = |tester: &WidgetTester| {
2297                tester
2298                    .glyph_style(tester.element(find::by_icon(&Icons::delete()).first()))
2299                    .color
2300                    .map(|color| color.color())
2301            };
2302
2303            build_chip(tester, None);
2304
2305            // Test rendered icon color.
2306            assert_eq!(delete_glyph_color(tester), Some(icon_color));
2307
2308            build_chip(tester, Some(delete_icon_color));
2309
2310            // Test rendered icon color.
2311            assert_eq!(delete_glyph_color(tester), Some(delete_icon_color));
2312        });
2313    }
2314
2315    // This is a regression test for https://github.com/flutter/flutter/issues/135136.
2316    #[test]
2317    fn widget_state_border_side_properly_lerp_in_chip_theme_data_side() {
2318        test_widgets(|tester| {
2319            let primary = Rc::new(Cell::new(Color::new(0)));
2320            let build_chip = |tester: &mut WidgetTester, seed_color: Color| {
2321                let color_scheme = ColorScheme::from_seed(seed_color).build();
2322                primary.set(color_scheme.primary());
2323                let side_primary = Rc::clone(&primary);
2324                let theme = ThemeData::builder()
2325                    .color_scheme(color_scheme)
2326                    .chip_theme(
2327                        ChipThemeData::new().side(WidgetStateBorderSide::resolve_with(
2328                            move |_states| {
2329                                Some(BorderSide {
2330                                    color: side_primary.get(),
2331                                    width: 4.0,
2332                                    ..BorderSide::default()
2333                                })
2334                            },
2335                        )),
2336                    )
2337                    .build(&tester.cell.borrow());
2338                pump_app(
2339                    tester,
2340                    theme,
2341                    Scaffold::new()
2342                        .body(RawChip::new(Text::new("Chip")))
2343                        .into_widget(),
2344                );
2345            };
2346
2347            build_chip(tester, Colors::RED.primary());
2348            tester.pump_and_settle();
2349            assert_paints(
2350                &raw_chip_ops(tester),
2351                &[PaintCall::drrect(Some(primary.get()))],
2352            );
2353
2354            build_chip(tester, Colors::BLUE.primary());
2355            tester.pump_by(Duration::from_millis(100));
2356            assert_paints(
2357                &raw_chip_ops(tester),
2358                &[PaintCall::drrect(Some(primary.get()))],
2359            );
2360        });
2361    }
2362    // Flutter's "Default ChipThemeData debugFillProperties".
2363    #[test]
2364    fn a_chip_theme_data_describes_nothing_by_default() {
2365        assert_eq!(
2366            waft_widgets::testing::describe_properties(|properties| {
2367                waft_foundation::Diagnosticable::debug_fill_properties(
2368                    &ChipThemeData::new(),
2369                    properties,
2370                )
2371            }),
2372            Vec::<String>::new()
2373        );
2374    }
2375}