Skip to main content

waft_widgets/widgets/
widget_state.rs

1//! Flutter counterpart: `widgets/widget_state.dart`.
2
3use std::any::{Any, type_name};
4use std::collections::HashSet;
5use std::fmt::{self, Debug};
6use std::ops::{BitAnd, BitOr, Deref, Not};
7use std::rc::Rc;
8
9use waft_embedder::{Canvas, Color, Offset, Paint, Path, Rect, Size};
10use waft_foundation::Ref;
11use waft_foundation::{
12    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsProperty,
13    Handle, K_IS_WEB, describe_enum, describe_identity,
14};
15use waft_painting::{
16    AnyBorderSide, AnyColor, AnyTextStyle, BorderSide, BorderSideExtension, ColorExtension,
17    EdgeInsetsGeometry, OutlinedBorder, OutlinedBorderRef, RoundedRectangleBorder, ShapeBorder,
18    ShapeBorderRef, TextDirection, TextStyle, TextStyleExtension,
19};
20use waft_services::{MouseCursor, MouseCursorRef, MouseCursorSession, SystemMouseCursors};
21
22/// Dart's `Set<WidgetState>`: the interactive states a widget is in.
23pub type WidgetStates = HashSet<WidgetState>;
24
25/// This mixin allows [`WidgetState`] enum values to be combined
26/// using the `&`, `|`, and `~` operators.
27///
28/// A map with [`WidgetStatesConstraint`] objects as keys can be used
29/// in the `<dyn WidgetStateProperty<T>>::from_map` constructor
30/// to resolve to one of its values, based on the first key that
31/// [`is_satisfied_by`](Self::is_satisfied_by) the current set of states.
32///
33/// A constraint is stored erased as a [`WidgetStatesConstraintRef`], which the operators
34/// produce; `constraint.into()` erases a value by hand.
35pub trait WidgetStatesConstraint: Debug + 'static {
36    /// Whether the provided `states` satisfy this object's criteria.
37    ///
38    /// If the constraint is a single [`WidgetState`] object,
39    /// it's satisfied by the set if the set contains the object.
40    ///
41    /// The constraint can also be created using one or more operators, for example:
42    ///
43    /// ```text
44    /// let constraint = WidgetState::Focused | WidgetState::Hovered;
45    /// ```
46    ///
47    /// In the above case, `constraint.is_satisfied_by(&states)` is equivalent to:
48    ///
49    /// ```text
50    /// states.contains(&WidgetState::Focused) || states.contains(&WidgetState::Hovered)
51    /// ```
52    fn is_satisfied_by(&self, states: &WidgetStates) -> bool;
53
54    /// Downcast support for Dart's `is` checks between constraint classes.
55    fn as_any(&self) -> &dyn Any;
56
57    /// Dart's `==`. Identity unless a class overrides it, as the combinators do.
58    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
59        std::ptr::addr_eq(
60            self as *const Self,
61            other as *const dyn WidgetStatesConstraint,
62        )
63    }
64}
65
66impl PartialEq for dyn WidgetStatesConstraint {
67    fn eq(&self, other: &dyn WidgetStatesConstraint) -> bool {
68        self.eq_constraint(other)
69    }
70}
71
72/// A shared, erased [`WidgetStatesConstraint`] (a Dart object reference).
73///
74/// The `&`, `|`, and `~` operators of the Dart mixin live here and on [`WidgetState`], and
75/// produce this type: `WidgetState::Hovered & WidgetState::Focused`, `~WidgetState::Disabled`.
76/// It derefs to the constraint for [`is_satisfied_by`](WidgetStatesConstraint::is_satisfied_by).
77#[derive(Clone)]
78pub struct WidgetStatesConstraintRef(Rc<dyn WidgetStatesConstraint>);
79
80impl WidgetStatesConstraintRef {
81    /// Erases a constraint.
82    pub fn new(constraint: impl WidgetStatesConstraint) -> WidgetStatesConstraintRef {
83        WidgetStatesConstraintRef(Rc::new(constraint))
84    }
85}
86
87impl<C: WidgetStatesConstraint> From<C> for WidgetStatesConstraintRef {
88    fn from(constraint: C) -> WidgetStatesConstraintRef {
89        WidgetStatesConstraintRef::new(constraint)
90    }
91}
92
93impl Deref for WidgetStatesConstraintRef {
94    type Target = dyn WidgetStatesConstraint;
95
96    fn deref(&self) -> &dyn WidgetStatesConstraint {
97        &*self.0
98    }
99}
100
101impl PartialEq for WidgetStatesConstraintRef {
102    fn eq(&self, other: &WidgetStatesConstraintRef) -> bool {
103        self.0.eq_constraint(&*other.0)
104    }
105}
106
107impl Debug for WidgetStatesConstraintRef {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        self.0.fmt(f)
110    }
111}
112
113impl fmt::Display for WidgetStatesConstraintRef {
114    /// Dart's `toString` of the constraint classes: `WidgetState.hovered`,
115    /// `WidgetState.any`, `(a & b)`, `(a | b)` and `~a`.
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        let constraint = self.as_any();
118        if let Some(state) = constraint.downcast_ref::<WidgetState>() {
119            return write!(f, "WidgetState.{}", describe_enum(state));
120        }
121        if constraint.is::<AnyWidgetStates>() {
122            return f.write_str("WidgetState.any");
123        }
124        if let Some(and) = constraint.downcast_ref::<WidgetStateAnd>() {
125            return write!(f, "({} & {})", and.first, and.second);
126        }
127        if let Some(or) = constraint.downcast_ref::<WidgetStateOr>() {
128            return write!(f, "({} | {})", or.first, or.second);
129        }
130        if let Some(not) = constraint.downcast_ref::<WidgetStateNot>() {
131            return write!(f, "~{}", not.value);
132        }
133        write!(f, "{self:?}")
134    }
135}
136
137/// The operators of Dart's `WidgetStatesConstraint` mixin, for a type that implements it.
138macro_rules! widget_states_constraint_operators {
139    ($constraint:ty) => {
140        impl<R: Into<WidgetStatesConstraintRef>> BitAnd<R> for $constraint {
141            type Output = WidgetStatesConstraintRef;
142
143            /// Combines two [`WidgetStatesConstraint`] values using logical "and".
144            fn bitand(self, other: R) -> WidgetStatesConstraintRef {
145                WidgetStatesConstraintRef::new(WidgetStateAnd {
146                    first: self.into(),
147                    second: other.into(),
148                })
149            }
150        }
151
152        impl<R: Into<WidgetStatesConstraintRef>> BitOr<R> for $constraint {
153            type Output = WidgetStatesConstraintRef;
154
155            /// Combines two [`WidgetStatesConstraint`] values using logical "or".
156            fn bitor(self, other: R) -> WidgetStatesConstraintRef {
157                WidgetStatesConstraintRef::new(WidgetStateOr {
158                    first: self.into(),
159                    second: other.into(),
160                })
161            }
162        }
163
164        impl Not for $constraint {
165            type Output = WidgetStatesConstraintRef;
166
167            /// Takes a [`WidgetStatesConstraint`] and applies the logical "not".
168            fn not(self) -> WidgetStatesConstraintRef {
169                WidgetStatesConstraintRef::new(WidgetStateNot { value: self.into() })
170            }
171        }
172    };
173}
174
175widget_states_constraint_operators!(WidgetStatesConstraintRef);
176
177// Dart's `_WidgetStateCombo` is the `first` / `second` pair the two combinators share.
178
179struct WidgetStateAnd {
180    first: WidgetStatesConstraintRef,
181    second: WidgetStatesConstraintRef,
182}
183
184impl WidgetStatesConstraint for WidgetStateAnd {
185    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
186        self.first.is_satisfied_by(states) && self.second.is_satisfied_by(states)
187    }
188
189    fn as_any(&self) -> &dyn Any {
190        self
191    }
192
193    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
194        other
195            .as_any()
196            .downcast_ref::<WidgetStateAnd>()
197            .is_some_and(|other| other.first == self.first && other.second == self.second)
198    }
199}
200
201impl Debug for WidgetStateAnd {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        write!(f, "({:?} & {:?})", self.first, self.second)
204    }
205}
206
207struct WidgetStateOr {
208    first: WidgetStatesConstraintRef,
209    second: WidgetStatesConstraintRef,
210}
211
212impl WidgetStatesConstraint for WidgetStateOr {
213    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
214        self.first.is_satisfied_by(states) || self.second.is_satisfied_by(states)
215    }
216
217    fn as_any(&self) -> &dyn Any {
218        self
219    }
220
221    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
222        other
223            .as_any()
224            .downcast_ref::<WidgetStateOr>()
225            .is_some_and(|other| other.first == self.first && other.second == self.second)
226    }
227}
228
229impl Debug for WidgetStateOr {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        write!(f, "({:?} | {:?})", self.first, self.second)
232    }
233}
234
235struct WidgetStateNot {
236    value: WidgetStatesConstraintRef,
237}
238
239impl WidgetStatesConstraint for WidgetStateNot {
240    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
241        !self.value.is_satisfied_by(states)
242    }
243
244    fn as_any(&self) -> &dyn Any {
245        self
246    }
247
248    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
249        other
250            .as_any()
251            .downcast_ref::<WidgetStateNot>()
252            .is_some_and(|other| other.value == self.value)
253    }
254}
255
256impl Debug for WidgetStateNot {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        write!(f, "~{:?}", self.value)
259    }
260}
261
262/// A private class, used to create [`WidgetState::any`]. Every instance is equal, as Dart's
263/// `const` one is canonical.
264struct AnyWidgetStates;
265
266impl WidgetStatesConstraint for AnyWidgetStates {
267    fn is_satisfied_by(&self, _states: &WidgetStates) -> bool {
268        true
269    }
270
271    fn as_any(&self) -> &dyn Any {
272        self
273    }
274
275    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
276        other.as_any().is::<AnyWidgetStates>()
277    }
278}
279
280impl Debug for AnyWidgetStates {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.write_str("WidgetState.any")
283    }
284}
285
286/// Interactive states that some of the widgets can take on when receiving input
287/// from the user.
288///
289/// States are defined by <https://m3.material.io/foundations/interaction/states>,
290/// but are not limited to the Material design system or library.
291///
292/// Some widgets track their current state in a [`WidgetStates`] set.
293///
294/// See also:
295///
296///  * `MaterialState`, the Material specific version of `WidgetState`.
297///  * [`WidgetStateProperty`], an interface for objects that "resolve" to
298///    different values depending on a widget's state.
299///  * [`WidgetStateColor`], a `Color` that implements `WidgetStateProperty`
300///    which is used in APIs that need to accept either a `Color` or a
301///    `WidgetStateProperty<Color>`.
302///  * [`WidgetStateMouseCursor`], a `MouseCursor` that implements
303///    `WidgetStateProperty` which is used in APIs that need to accept either
304///    a `MouseCursor` or a `WidgetStateProperty<MouseCursor>`.
305///  * `WidgetStateOutlinedBorder`, an `OutlinedBorder` that implements
306///    `WidgetStateProperty` which is used in APIs that need to accept either
307///    an `OutlinedBorder` or a `WidgetStateProperty<OutlinedBorder>`.
308///  * `WidgetStateBorderSide`, a `BorderSide` that implements
309///    `WidgetStateProperty` which is used in APIs that need to accept either
310///    a `BorderSide` or a `WidgetStateProperty<BorderSide>`.
311///  * `WidgetStateTextStyle`, a `TextStyle` that implements
312///    `WidgetStateProperty` which is used in APIs that need to accept either
313///    a `TextStyle` or a `WidgetStateProperty<TextStyle>`.
314#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
315pub enum WidgetState {
316    /// The state when the user drags their mouse cursor over the given widget.
317    ///
318    /// See: <https://material.io/design/interaction/states.html#hover>.
319    Hovered,
320
321    /// The state when the user navigates with the keyboard to a given widget.
322    ///
323    /// This can also sometimes be triggered when a widget is tapped. For example,
324    /// when a `TextField` is tapped, it becomes [`Focused`](Self::Focused).
325    ///
326    /// See: <https://material.io/design/interaction/states.html#focus>.
327    Focused,
328
329    /// The state when the user is actively pressing down on the given widget.
330    ///
331    /// See: <https://material.io/design/interaction/states.html#pressed>.
332    Pressed,
333
334    /// The state when this widget is being dragged from one place to another by
335    /// the user.
336    ///
337    /// <https://material.io/design/interaction/states.html#dragged>.
338    Dragged,
339
340    /// The state when this item has been selected.
341    ///
342    /// This applies to things that can be toggled (such as chips and checkboxes)
343    /// and things that are selected from a set of options (such as tabs and radio buttons).
344    ///
345    /// See: <https://material.io/design/interaction/states.html#selected>.
346    Selected,
347
348    /// The state when this widget overlaps the content of a scrollable below.
349    ///
350    /// Used by `AppBar` to indicate that the primary scrollable's
351    /// content has scrolled up and behind the app bar.
352    ScrolledUnder,
353
354    /// The state when this widget is disabled and cannot be interacted with.
355    ///
356    /// Disabled widgets should not respond to hover, focus, press, or drag
357    /// interactions.
358    ///
359    /// See: <https://material.io/design/interaction/states.html#disabled>.
360    Disabled,
361
362    /// The state when the widget has entered some form of invalid state.
363    ///
364    /// See <https://material.io/design/interaction/states.html#usage>.
365    Error,
366}
367
368impl WidgetState {
369    /// To prevent a situation where each [`WidgetStatesConstraint`]
370    /// isn't satisfied by the given set of states, consider adding
371    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
372    pub fn any() -> WidgetStatesConstraintRef {
373        WidgetStatesConstraintRef::new(AnyWidgetStates)
374    }
375}
376
377/// Dart's `Set<WidgetState>.toString`, as `{WidgetState.disabled, WidgetState.hovered}`. A
378/// Rust set has no insertion order, so the states are sorted to keep a dump stable.
379pub fn widget_states(states: &WidgetStates) -> String {
380    let mut names: Vec<String> = states
381        .iter()
382        .map(|state| format!("WidgetState.{}", describe_enum(state)))
383        .collect();
384    names.sort();
385    format!("{{{}}}", names.join(", "))
386}
387
388impl WidgetStatesConstraint for WidgetState {
389    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
390        states.contains(self)
391    }
392
393    fn as_any(&self) -> &dyn Any {
394        self
395    }
396
397    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
398        other.as_any().downcast_ref::<WidgetState>() == Some(self)
399    }
400}
401
402widget_states_constraint_operators!(WidgetState);
403
404/// Signature for the function that returns a value of type `T` based on a given
405/// set of states.
406pub type WidgetPropertyResolver<T> = Rc<dyn Fn(&WidgetStates) -> T>;
407
408/// Defines a `Color` that is also a [`WidgetStateProperty`].
409///
410/// This class exists to enable widgets with `Color` valued properties
411/// to also accept `WidgetStateProperty<Color>` values. A widget
412/// state color property represents a color which depends on
413/// a widget's "interactive state". This state is represented as a
414/// set of [`WidgetState`]s, like [`WidgetState::Pressed`],
415/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
416///
417/// [`WidgetStateColor`] should only be used with widgets that document
418/// their support, like `TimePickerThemeData.dayPeriodColor`.
419///
420/// A [`WidgetStateColor`] can be created in one of the following ways:
421///   1. Use [`WidgetStateColor::resolve_with`] and pass in a callback that
422///      will be used to resolve the color in the given states.
423///   2. Use [`WidgetStateColor::from_map`] to assign a value using a [`WidgetStateMap`].
424///
425/// It is the `Color` it is in Dart once erased with [`into_any`](Self::into_any) (or
426/// `.into()`): an [`AnyColor`] whose value is the color resolved in the default state (the
427/// empty set of states), Dart's `super(defaultValue)`, and whose extension is this object,
428/// recovered with `color.extension::<WidgetStateColor>()`.
429pub struct WidgetStateColor {
430    subclass: ColorSubclass,
431}
432
433/// Dart's three private subclasses of `WidgetStateColor`.
434enum ColorSubclass {
435    /// `_WidgetStateColor`.
436    ResolveWith(WidgetPropertyResolver<Color>),
437    /// `_WidgetStateColorTransparent`.
438    Transparent,
439    /// `_WidgetStateColorMapper`.
440    Mapper(WidgetStateMapper<Color>),
441}
442
443impl WidgetStateColor {
444    /// Creates a [`WidgetStateColor`] from a [`WidgetPropertyResolver<Color>`]
445    /// callback function.
446    ///
447    /// If used as a regular color, the color resolved in the default state (the
448    /// empty set of states) will be used.
449    ///
450    /// The given callback parameter must return a non-null color in the default
451    /// state.
452    pub fn resolve_with(callback: impl Fn(&WidgetStates) -> Color + 'static) -> WidgetStateColor {
453        WidgetStateColor {
454            subclass: ColorSubclass::ResolveWith(Rc::new(callback)),
455        }
456    }
457
458    /// Creates a [`WidgetStateColor`] from a [`WidgetStateMap<Color>`].
459    ///
460    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
461    /// entry whose key is satisfied by the set of states, and returns its associated value.
462    /// It should only be used with widgets that document support for
463    /// [`WidgetStateColor`] (panics if used as a normal `Color` with no key satisfied by
464    /// the empty set of states).
465    ///
466    /// To prevent a situation where each [`WidgetStatesConstraint`]
467    /// isn't satisfied by the given set of states, consider adding
468    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
469    pub fn from_map(map: WidgetStateMap<Color>) -> WidgetStateColor {
470        WidgetStateColor {
471            subclass: ColorSubclass::Mapper(WidgetStateMapper::new(map)),
472        }
473    }
474
475    /// A constant whose value is transparent for all states.
476    pub fn transparent() -> WidgetStateColor {
477        WidgetStateColor {
478            subclass: ColorSubclass::Transparent,
479        }
480    }
481
482    /// The color as the `Color` it is in Dart: the default-state value, carrying this
483    /// object as the extension.
484    pub fn into_any(self) -> AnyColor {
485        let default_value = self.resolve(&WidgetStates::new());
486        AnyColor::with_shared(default_value, Rc::new(self))
487    }
488}
489
490impl WidgetStateProperty<Color> for WidgetStateColor {
491    /// Returns a `Color` that's to be used when a component is in the specified
492    /// state.
493    fn resolve(&self, states: &WidgetStates) -> Color {
494        match &self.subclass {
495            ColorSubclass::ResolveWith(resolve) => resolve(states),
496            ColorSubclass::Transparent => Color::new(0x00000000),
497            ColorSubclass::Mapper(mapper) => mapper.resolve(states),
498        }
499    }
500
501    fn as_any(&self) -> &dyn Any {
502        self
503    }
504
505    fn as_mapper(&self) -> Option<&WidgetStateMapper<Color>> {
506        match &self.subclass {
507            ColorSubclass::Mapper(mapper) => Some(mapper),
508            _ => None,
509        }
510    }
511
512    // Dart's `Color.==`: the same runtime type and value; the mapper subclass has
513    // `WidgetStateMapper.==`.
514    fn eq_property(&self, other: &dyn WidgetStateProperty<Color>) -> bool {
515        if let ColorSubclass::Mapper(mapper) = &self.subclass {
516            return mapper.eq_property(other);
517        }
518        let default_states = WidgetStates::new();
519        other
520            .as_any()
521            .downcast_ref::<WidgetStateColor>()
522            .is_some_and(|other| {
523                self.eq_extension(other)
524                    && self.resolve(&default_states) == other.resolve(&default_states)
525            })
526    }
527}
528
529impl ColorExtension for WidgetStateColor {
530    fn as_any(&self) -> &dyn Any {
531        self
532    }
533
534    // Dart's `Color.==` compares runtime types (values are already equal here); the mapper
535    // subclass compares maps instead.
536    fn eq_extension(&self, other: &dyn ColorExtension) -> bool {
537        other
538            .as_any()
539            .downcast_ref::<WidgetStateColor>()
540            .is_some_and(|other| match (&self.subclass, &other.subclass) {
541                (ColorSubclass::ResolveWith(_), ColorSubclass::ResolveWith(_))
542                | (ColorSubclass::Transparent, ColorSubclass::Transparent) => true,
543                (ColorSubclass::Mapper(mine), ColorSubclass::Mapper(theirs)) => mine == theirs,
544                _ => false,
545            })
546    }
547}
548
549impl Debug for WidgetStateColor {
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        match &self.subclass {
552            ColorSubclass::ResolveWith(_) => f.write_str("WidgetStateColor.resolveWith"),
553            ColorSubclass::Transparent => f.write_str("WidgetStateColor.transparent"),
554            ColorSubclass::Mapper(mapper) => mapper.fmt(f),
555        }
556    }
557}
558
559impl From<WidgetStateColor> for AnyColor {
560    fn from(color: WidgetStateColor) -> AnyColor {
561        color.into_any()
562    }
563}
564
565impl MaybeWidgetStateProperty<Color> for AnyColor {
566    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Color>> {
567        self.extension::<WidgetStateColor>()
568            .map(|color| color as &dyn WidgetStateProperty<Color>)
569    }
570
571    fn from_resolved(value: Color) -> AnyColor {
572        AnyColor::new(value)
573    }
574}
575
576/// Defines a `MouseCursor` whose value depends on a set of [`WidgetState`]s which
577/// represent the interactive state of a component.
578///
579/// This kind of `MouseCursor` is useful when the set of interactive
580/// actions a widget supports varies with its state. For example, a
581/// mouse pointer hovering over a disabled `ListTile` should not
582/// display [`SystemMouseCursors::CLICK`], since a disabled list tile
583/// doesn't respond to mouse clicks. `ListTile`'s default mouse cursor
584/// is a [`WidgetStateMouseCursor::clickable`], which resolves to
585/// [`SystemMouseCursors::BASIC`] when the button is disabled.
586///
587/// This class should only be used for parameters that document their support
588/// for [`WidgetStateMouseCursor`].
589///
590/// A [`WidgetStateMouseCursor`] can be created in one of the following ways:
591///   1. Use [`WidgetStateMouseCursor::resolve_with`] and pass in a callback that
592///      will be used to resolve the color in the given states.
593///   2. Use [`WidgetStateMouseCursor::from_map`] to assign a value using a [`WidgetStateMap`].
594///
595/// This example defines a mouse cursor that resolves to
596/// [`SystemMouseCursors::FORBIDDEN`] when its widget is disabled.
597///
598/// ```text
599/// let cursor = WidgetStateMouseCursor::resolve_with(
600///     |states| {
601///         if states.contains(&WidgetState::Disabled) {
602///             return SystemMouseCursors::FORBIDDEN.into();
603///         }
604///         SystemMouseCursors::CLICK.into()
605///     },
606///     None,
607/// );
608/// ```
609///
610/// It is the `MouseCursor` it is in Dart once erased with `.into()`: a [`MouseCursorRef`]
611/// recovered with `cursor.as_any().downcast_ref::<WidgetStateMouseCursor>()`.
612///
613/// See also:
614///
615///  * [`MouseCursor`] for introduction on the mouse cursor system.
616///  * [`SystemMouseCursors`], which defines cursors that are supported by
617///    native platforms.
618pub struct WidgetStateMouseCursor {
619    subclass: MouseCursorSubclass,
620}
621
622/// Dart's two private subclasses of `WidgetStateMouseCursor`.
623enum MouseCursorSubclass {
624    /// `_WidgetStateMouseCursor`.
625    ResolveWith {
626        resolve: WidgetPropertyResolver<MouseCursorRef>,
627        debug_description: String,
628    },
629    /// `_WidgetMouseCursorMapper`.
630    Mapper(WidgetStateMapper<MouseCursorRef>),
631}
632
633impl WidgetStateMouseCursor {
634    /// Creates a [`WidgetStateMouseCursor`] using a [`WidgetPropertyResolver`]
635    /// callback.
636    ///
637    /// A `debug_description` may optionally be provided (Dart's default is
638    /// `'WidgetStateMouseCursor()'`).
639    ///
640    /// If used as a regular `MouseCursor`, the cursor resolved
641    /// in the default state (the empty set of states) will be used.
642    pub fn resolve_with(
643        callback: impl Fn(&WidgetStates) -> MouseCursorRef + 'static,
644        debug_description: Option<&str>,
645    ) -> WidgetStateMouseCursor {
646        WidgetStateMouseCursor {
647            subclass: MouseCursorSubclass::ResolveWith {
648                resolve: Rc::new(callback),
649                debug_description: debug_description
650                    .unwrap_or("WidgetStateMouseCursor()")
651                    .to_owned(),
652            },
653        }
654    }
655
656    /// Creates a [`WidgetStateMouseCursor`] from a [`WidgetStateMap`].
657    ///
658    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
659    /// entry whose key is satisfied by the set of states, and returns its associated value.
660    /// It should only be used with classes that document support for
661    /// [`WidgetStateMouseCursor`] (panics if used as a regular
662    /// `MouseCursor` with no key satisfied by the empty set of states).
663    pub fn from_map(map: WidgetStateMap<MouseCursorRef>) -> WidgetStateMouseCursor {
664        WidgetStateMouseCursor {
665            subclass: MouseCursorSubclass::Mapper(WidgetStateMapper::new(map)),
666        }
667    }
668
669    /// A mouse cursor for clickable widgets, which resolves differently when the
670    /// widget is disabled.
671    ///
672    /// By default this cursor resolves to [`SystemMouseCursors::CLICK`]. If the widget is
673    /// disabled, the cursor resolves to [`SystemMouseCursors::BASIC`].
674    pub fn clickable() -> WidgetStateMouseCursor {
675        thread_local! {
676            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
677                Rc::new(WidgetStateMouseCursor::resolve_clickable);
678        }
679        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(clickable)")
680    }
681
682    fn resolve_clickable(states: &WidgetStates) -> MouseCursorRef {
683        if states.contains(&WidgetState::Disabled) {
684            return SystemMouseCursors::BASIC.into();
685        }
686        SystemMouseCursors::CLICK.into()
687    }
688
689    /// A platform-adaptive mouse cursor for clickable widgets, which resolves
690    /// differently based on the widget's state and the platform.
691    ///
692    /// On web platforms, this cursor resolves to [`SystemMouseCursors::CLICK`] by
693    /// default. If the widget is disabled, it resolves to
694    /// [`SystemMouseCursors::BASIC`].
695    ///
696    /// On non-web platforms, this cursor always resolves to
697    /// [`SystemMouseCursors::BASIC`].
698    ///
699    /// This cursor is commonly used for interactive widgets like buttons. The
700    /// difference in behavior across platforms reflects native conventions (e.g.,
701    /// web uses a hand pointer for buttons, while desktop platforms do not).
702    pub fn adaptive_clickable() -> WidgetStateMouseCursor {
703        thread_local! {
704            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
705                Rc::new(WidgetStateMouseCursor::resolve_adaptive_clickable);
706        }
707        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(adaptiveClickable)")
708    }
709
710    fn resolve_adaptive_clickable(states: &WidgetStates) -> MouseCursorRef {
711        if states.contains(&WidgetState::Disabled) {
712            return SystemMouseCursors::BASIC.into();
713        }
714        if K_IS_WEB {
715            SystemMouseCursors::CLICK.into()
716        } else {
717            SystemMouseCursors::BASIC.into()
718        }
719    }
720
721    /// A mouse cursor for widgets related to text, which resolves differently
722    /// when the widget is disabled.
723    ///
724    /// By default this cursor resolves to [`SystemMouseCursors::TEXT`]. If the widget is
725    /// disabled, the cursor resolves to [`SystemMouseCursors::BASIC`].
726    ///
727    /// This cursor is the default for many widgets.
728    pub fn textable() -> WidgetStateMouseCursor {
729        thread_local! {
730            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
731                Rc::new(WidgetStateMouseCursor::resolve_textable);
732        }
733        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(textable)")
734    }
735
736    /// One of Dart's `static const` cursors: every call shares the one resolver, so the
737    /// cursors compare equal as Dart's one canonical object does.
738    fn canonical(
739        resolve: &'static std::thread::LocalKey<WidgetPropertyResolver<MouseCursorRef>>,
740        debug_description: &str,
741    ) -> WidgetStateMouseCursor {
742        WidgetStateMouseCursor {
743            subclass: MouseCursorSubclass::ResolveWith {
744                resolve: resolve.with(Rc::clone),
745                debug_description: debug_description.to_owned(),
746            },
747        }
748    }
749
750    /// Dart's identity of a `_WidgetStateMouseCursor`: a cursor is the object its resolver
751    /// was made for, so two share a resolver only when they are one of the canonical cursors.
752    fn same_resolver(&self, other: &WidgetStateMouseCursor) -> bool {
753        match (&self.subclass, &other.subclass) {
754            (
755                MouseCursorSubclass::ResolveWith { resolve: mine, .. },
756                MouseCursorSubclass::ResolveWith {
757                    resolve: theirs, ..
758                },
759            ) => Rc::ptr_eq(mine, theirs),
760            _ => false,
761        }
762    }
763
764    fn resolve_textable(states: &WidgetStates) -> MouseCursorRef {
765        if states.contains(&WidgetState::Disabled) {
766            return SystemMouseCursors::BASIC.into();
767        }
768        SystemMouseCursors::TEXT.into()
769    }
770}
771
772impl MouseCursor for WidgetStateMouseCursor {
773    fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession> {
774        self.resolve(&WidgetStates::new()).create_session(device)
775    }
776
777    fn debug_description(&self) -> String {
778        match &self.subclass {
779            MouseCursorSubclass::ResolveWith {
780                debug_description, ..
781            } => debug_description.clone(),
782            MouseCursorSubclass::Mapper(mapper) => format!("{mapper:?}"),
783        }
784    }
785
786    fn as_any(&self) -> &dyn Any {
787        self
788    }
789
790    // Identity, except that the mapper subclass compares maps (Dart's `WidgetStateMapper.==`).
791    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
792        let Some(other) = other.as_any().downcast_ref::<WidgetStateMouseCursor>() else {
793            return false;
794        };
795        match (&self.subclass, &other.subclass) {
796            (MouseCursorSubclass::Mapper(mine), MouseCursorSubclass::Mapper(theirs)) => {
797                mine == theirs
798            }
799            _ => self.same_resolver(other),
800        }
801    }
802}
803
804impl WidgetStateProperty<MouseCursorRef> for WidgetStateMouseCursor {
805    /// Returns a `MouseCursor` that's to be used when a component is in the
806    /// specified state.
807    fn resolve(&self, states: &WidgetStates) -> MouseCursorRef {
808        match &self.subclass {
809            MouseCursorSubclass::ResolveWith { resolve, .. } => resolve(states),
810            MouseCursorSubclass::Mapper(mapper) => mapper.resolve(states),
811        }
812    }
813
814    fn as_any(&self) -> &dyn Any {
815        self
816    }
817
818    fn as_mapper(&self) -> Option<&WidgetStateMapper<MouseCursorRef>> {
819        match &self.subclass {
820            MouseCursorSubclass::Mapper(mapper) => Some(mapper),
821            MouseCursorSubclass::ResolveWith { .. } => None,
822        }
823    }
824
825    // Identity, except that the mapper subclass has `WidgetStateMapper.==`.
826    fn eq_property(&self, other: &dyn WidgetStateProperty<MouseCursorRef>) -> bool {
827        match &self.subclass {
828            MouseCursorSubclass::Mapper(mapper) => mapper.eq_property(other),
829            MouseCursorSubclass::ResolveWith { .. } => other
830                .as_any()
831                .downcast_ref::<WidgetStateMouseCursor>()
832                .is_some_and(|other| self.same_resolver(other)),
833        }
834    }
835}
836
837impl Debug for WidgetStateMouseCursor {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        f.write_str(&self.debug_description())
840    }
841}
842
843impl From<WidgetStateMouseCursor> for MouseCursorRef {
844    fn from(cursor: WidgetStateMouseCursor) -> MouseCursorRef {
845        Rc::new(cursor)
846    }
847}
848
849impl MaybeWidgetStateProperty<MouseCursorRef> for MouseCursorRef {
850    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<MouseCursorRef>> {
851        self.as_any()
852            .downcast_ref::<WidgetStateMouseCursor>()
853            .map(|cursor| cursor as &dyn WidgetStateProperty<MouseCursorRef>)
854    }
855
856    fn from_resolved(value: MouseCursorRef) -> MouseCursorRef {
857        value
858    }
859}
860
861/// Defines a `BorderSide` whose value depends on a set of [`WidgetState`]s which represent
862/// the interactive state of a component.
863///
864/// To use a [`WidgetStateBorderSide`], you can either:
865///   1. Create a subclass of [`WidgetStateBorderSide`] and implement the abstract
866///      `resolve` method.
867///   2. Use [`WidgetStateBorderSide::resolve_with`] and pass in a callback that will be used
868///      to resolve the color in the given states.
869///   3. Use [`WidgetStateBorderSide::from_map`] to assign a value using a [`WidgetStateMap`].
870///
871/// If a [`WidgetStateBorderSide`] is used for a property or a parameter that doesn't
872/// support resolving [`WidgetStateProperty<Option<BorderSide>>`]s, then its default value
873/// will be used for all states.
874///
875/// It is the `BorderSide` it is in Dart once erased with [`into_any`](Self::into_any) (or
876/// `.into()`): an [`AnyBorderSide`] whose value is Dart's `super` value, the default
877/// `BorderSide`, and whose extension is this object, recovered with
878/// `side.extension::<WidgetStateBorderSide>()`.
879pub struct WidgetStateBorderSide {
880    subclass: BorderSideSubclass,
881}
882
883/// Dart's two private subclasses of `WidgetStateBorderSide`.
884enum BorderSideSubclass {
885    /// `_WidgetStateBorderSide`.
886    ResolveWith(WidgetPropertyResolver<Option<BorderSide>>),
887    /// `_WidgetBorderSideMapper`.
888    Mapper(WidgetStateMapper<Option<BorderSide>>),
889}
890
891impl WidgetStateBorderSide {
892    /// Creates a [`WidgetStateBorderSide`] from a [`WidgetPropertyResolver<Option<BorderSide>>`]
893    /// callback function.
894    ///
895    /// If used as a regular `BorderSide`, its behavior matches an empty `BorderSide()`
896    /// constructor.
897    pub fn resolve_with(
898        callback: impl Fn(&WidgetStates) -> Option<BorderSide> + 'static,
899    ) -> WidgetStateBorderSide {
900        WidgetStateBorderSide {
901            subclass: BorderSideSubclass::ResolveWith(Rc::new(callback)),
902        }
903    }
904
905    /// Creates a [`WidgetStateBorderSide`] from a [`WidgetStateMap`].
906    ///
907    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
908    /// entry whose key is satisfied by the set of states, and returns its associated value.
909    pub fn from_map(map: WidgetStateMap<Option<BorderSide>>) -> WidgetStateBorderSide {
910        WidgetStateBorderSide {
911            subclass: BorderSideSubclass::Mapper(WidgetStateMapper::new(map)),
912        }
913    }
914
915    /// The side as the `BorderSide` it is in Dart: the default `BorderSide`, carrying this
916    /// object as the extension.
917    pub fn into_any(self) -> AnyBorderSide {
918        AnyBorderSide::with_shared(BorderSide::default(), Rc::new(self))
919    }
920
921    /// Linearly interpolate between two [`WidgetStateProperty`]s of `BorderSide`.
922    pub fn lerp(
923        a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
924        b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
925        t: f64,
926    ) -> Option<WidgetStatePropertyRef<Option<BorderSide>>> {
927        // Avoid creating a _LerpSides object for a common case.
928        if a.is_none() && b.is_none() {
929            return None;
930        }
931        if let (Some(a), Some(b)) = (&a, &b)
932            && Rc::ptr_eq(a, b)
933        {
934            return Some(Rc::clone(a));
935        }
936        Some(Rc::new(LerpSides { a, b, t }))
937    }
938}
939
940impl WidgetStateProperty<Option<BorderSide>> for WidgetStateBorderSide {
941    fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
942        match &self.subclass {
943            BorderSideSubclass::ResolveWith(resolve) => resolve(states),
944            BorderSideSubclass::Mapper(mapper) => mapper.resolve(states),
945        }
946    }
947
948    fn as_any(&self) -> &dyn Any {
949        self
950    }
951
952    fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<BorderSide>>> {
953        match &self.subclass {
954            BorderSideSubclass::Mapper(mapper) => Some(mapper),
955            BorderSideSubclass::ResolveWith(_) => None,
956        }
957    }
958
959    // Dart's `BorderSide.==`; the mapper subclass has `WidgetStateMapper.==`.
960    fn eq_property(&self, other: &dyn WidgetStateProperty<Option<BorderSide>>) -> bool {
961        if let BorderSideSubclass::Mapper(mapper) = &self.subclass {
962            return mapper.eq_property(other);
963        }
964        other
965            .as_any()
966            .downcast_ref::<WidgetStateBorderSide>()
967            .is_some_and(|other| self.eq_extension(other))
968    }
969}
970
971impl BorderSideExtension for WidgetStateBorderSide {
972    fn as_any(&self) -> &dyn Any {
973        self
974    }
975
976    // Dart's `BorderSide.==` compares runtime types (values are already equal here); the
977    // mapper subclass compares maps instead.
978    fn eq_extension(&self, other: &dyn BorderSideExtension) -> bool {
979        other
980            .as_any()
981            .downcast_ref::<WidgetStateBorderSide>()
982            .is_some_and(|other| match (&self.subclass, &other.subclass) {
983                (BorderSideSubclass::ResolveWith(_), BorderSideSubclass::ResolveWith(_)) => true,
984                (BorderSideSubclass::Mapper(mine), BorderSideSubclass::Mapper(theirs)) => {
985                    mine == theirs
986                }
987                _ => false,
988            })
989    }
990}
991
992impl Debug for WidgetStateBorderSide {
993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
994        match &self.subclass {
995            BorderSideSubclass::ResolveWith(_) => f.write_str("WidgetStateBorderSide.resolveWith"),
996            BorderSideSubclass::Mapper(mapper) => mapper.fmt(f),
997        }
998    }
999}
1000
1001impl From<WidgetStateBorderSide> for AnyBorderSide {
1002    fn from(side: WidgetStateBorderSide) -> AnyBorderSide {
1003        side.into_any()
1004    }
1005}
1006
1007/// Dart's `T?` is `BorderSide?`: a `WidgetStateBorderSide` resolves to an optional side.
1008impl MaybeWidgetStateProperty<Option<BorderSide>> for Option<AnyBorderSide> {
1009    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Option<BorderSide>>> {
1010        self.as_ref()
1011            .and_then(|side| side.extension::<WidgetStateBorderSide>())
1012            .map(|side| side as &dyn WidgetStateProperty<Option<BorderSide>>)
1013    }
1014
1015    fn from_resolved(value: Option<BorderSide>) -> Option<AnyBorderSide> {
1016        value.map(AnyBorderSide::new)
1017    }
1018}
1019
1020/// Dart's `_LerpSides`.
1021struct LerpSides {
1022    a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
1023    b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
1024    t: f64,
1025}
1026
1027impl WidgetStateProperty<Option<BorderSide>> for LerpSides {
1028    fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
1029        let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
1030        let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
1031        match (resolved_a, resolved_b) {
1032            (None, None) => None,
1033            (None, Some(resolved_b)) => Some(BorderSide::lerp(
1034                BorderSide {
1035                    width: 0.0,
1036                    color: resolved_b.color.with_alpha(0),
1037                    ..BorderSide::default()
1038                },
1039                resolved_b,
1040                self.t,
1041            )),
1042            (Some(resolved_a), None) => Some(BorderSide::lerp(
1043                resolved_a,
1044                BorderSide {
1045                    width: 0.0,
1046                    color: resolved_a.color.with_alpha(0),
1047                    ..BorderSide::default()
1048                },
1049                self.t,
1050            )),
1051            (Some(resolved_a), Some(resolved_b)) => {
1052                Some(BorderSide::lerp(resolved_a, resolved_b, self.t))
1053            }
1054        }
1055    }
1056
1057    fn as_any(&self) -> &dyn Any {
1058        self
1059    }
1060}
1061
1062impl Debug for LerpSides {
1063    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1064        write!(f, "_LerpSides({:?}, {:?}, {})", self.a, self.b, self.t)
1065    }
1066}
1067
1068/// Defines an `OutlinedBorder` whose value depends on a set of [`WidgetState`]s which
1069/// represent the interactive state of a component.
1070///
1071/// To use a [`WidgetStateOutlinedBorder`], you should create a subclass of a
1072/// [`WidgetStateOutlinedBorder`] and override the abstract `resolve` method, or use
1073/// [`WidgetStateOutlinedBorder::resolve_with`] or [`WidgetStateOutlinedBorder::from_map`].
1074///
1075/// If a [`WidgetStateOutlinedBorder`] is used for a property or a parameter that doesn't
1076/// support resolving [`WidgetStateProperty<Option<OutlinedBorderRef>>`]s, then its
1077/// default value, Dart's `RoundedRectangleBorder()`, will be used for all states.
1078///
1079/// It is itself an `OutlinedBorder`, as `OutlinedBorder` is a trait here: it is recovered
1080/// from an `OutlinedBorderRef` with
1081/// `border.as_any().downcast_ref::<WidgetStateOutlinedBorder>()`.
1082#[derive(Clone)]
1083pub struct WidgetStateOutlinedBorder {
1084    subclass: OutlinedBorderSubclass,
1085    /// Dart's `super`: `_WidgetStateOutlinedBorder extends RoundedRectangleBorder`.
1086    border: RoundedRectangleBorder,
1087}
1088
1089/// Dart's two private subclasses of `WidgetStateOutlinedBorder`.
1090#[derive(Clone)]
1091enum OutlinedBorderSubclass {
1092    /// `_WidgetStateOutlinedBorder`.
1093    ResolveWith(WidgetPropertyResolver<Option<OutlinedBorderRef>>),
1094    /// `_WidgetOutlinedBorderMapper`.
1095    Mapper(Rc<WidgetStateMapper<Option<OutlinedBorderRef>>>),
1096}
1097
1098impl WidgetStateOutlinedBorder {
1099    /// Creates a [`WidgetStateOutlinedBorder`] from a [`WidgetPropertyResolver`] callback
1100    /// function.
1101    ///
1102    /// If used as a regular `OutlinedBorder`, it acts the same as an empty
1103    /// `RoundedRectangleBorder()` constructor.
1104    pub fn resolve_with(
1105        callback: impl Fn(&WidgetStates) -> Option<OutlinedBorderRef> + 'static,
1106    ) -> WidgetStateOutlinedBorder {
1107        WidgetStateOutlinedBorder {
1108            subclass: OutlinedBorderSubclass::ResolveWith(Rc::new(callback)),
1109            border: RoundedRectangleBorder::default(),
1110        }
1111    }
1112
1113    /// Creates a [`WidgetStateOutlinedBorder`] from a [`WidgetStateMap`].
1114    ///
1115    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
1116    /// entry whose key is satisfied by the set of states, and returns its associated value.
1117    pub fn from_map(map: WidgetStateMap<Option<OutlinedBorderRef>>) -> WidgetStateOutlinedBorder {
1118        WidgetStateOutlinedBorder {
1119            subclass: OutlinedBorderSubclass::Mapper(Rc::new(WidgetStateMapper::new(map))),
1120            border: RoundedRectangleBorder::default(),
1121        }
1122    }
1123}
1124
1125impl WidgetStateProperty<Option<OutlinedBorderRef>> for WidgetStateOutlinedBorder {
1126    fn resolve(&self, states: &WidgetStates) -> Option<OutlinedBorderRef> {
1127        match &self.subclass {
1128            OutlinedBorderSubclass::ResolveWith(resolve) => resolve(states),
1129            OutlinedBorderSubclass::Mapper(mapper) => mapper.resolve(states),
1130        }
1131    }
1132
1133    fn as_any(&self) -> &dyn Any {
1134        self
1135    }
1136
1137    fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<OutlinedBorderRef>>> {
1138        match &self.subclass {
1139            OutlinedBorderSubclass::Mapper(mapper) => Some(mapper.as_ref()),
1140            OutlinedBorderSubclass::ResolveWith(_) => None,
1141        }
1142    }
1143
1144    // Dart's `RoundedRectangleBorder.==`; the mapper subclass has `WidgetStateMapper.==`.
1145    fn eq_property(&self, other: &dyn WidgetStateProperty<Option<OutlinedBorderRef>>) -> bool {
1146        if let OutlinedBorderSubclass::Mapper(mapper) = &self.subclass {
1147            return mapper.eq_property(other);
1148        }
1149        other
1150            .as_any()
1151            .downcast_ref::<WidgetStateOutlinedBorder>()
1152            .is_some_and(|other| self.eq_shape(other))
1153    }
1154}
1155
1156impl Debug for WidgetStateOutlinedBorder {
1157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158        match &self.subclass {
1159            OutlinedBorderSubclass::ResolveWith(_) => {
1160                f.write_str("WidgetStateOutlinedBorder.resolveWith")
1161            }
1162            OutlinedBorderSubclass::Mapper(mapper) => mapper.fmt(f),
1163        }
1164    }
1165}
1166
1167/// `_WidgetStateOutlinedBorder extends RoundedRectangleBorder`: every `ShapeBorder` member is
1168/// the default rounded rectangle's.
1169impl ShapeBorder for WidgetStateOutlinedBorder {
1170    fn dimensions(&self) -> EdgeInsetsGeometry {
1171        self.border.dimensions()
1172    }
1173
1174    fn scale(&self, t: f64) -> ShapeBorderRef {
1175        ShapeBorder::scale(&self.border, t)
1176    }
1177
1178    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1179        self.border.lerp_from(a, t)
1180    }
1181
1182    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1183        self.border.lerp_to(b, t)
1184    }
1185
1186    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1187        self.border.get_outer_path(rect, text_direction)
1188    }
1189
1190    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1191        self.border.get_inner_path(rect, text_direction)
1192    }
1193
1194    fn hit_test(
1195        &self,
1196        rect: Rect,
1197        position: Offset,
1198        text_direction: Option<TextDirection>,
1199    ) -> bool {
1200        self.border.hit_test(rect, position, text_direction)
1201    }
1202
1203    fn paint_interior(
1204        &self,
1205        canvas: &mut Canvas,
1206        rect: Rect,
1207        paint: &Paint,
1208        text_direction: Option<TextDirection>,
1209    ) {
1210        self.border
1211            .paint_interior(canvas, rect, paint, text_direction);
1212    }
1213
1214    fn prefer_paint_interior(&self) -> bool {
1215        self.border.prefer_paint_interior()
1216    }
1217
1218    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
1219        self.border.paint(canvas, rect, text_direction);
1220    }
1221
1222    fn as_any(&self) -> &dyn Any {
1223        self
1224    }
1225
1226    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1227        Some(self)
1228    }
1229
1230    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1231        Some(self)
1232    }
1233
1234    // Dart's `RoundedRectangleBorder.==`: the same runtime type and fields; the mapper
1235    // compares maps.
1236    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1237        other
1238            .as_any()
1239            .downcast_ref::<WidgetStateOutlinedBorder>()
1240            .is_some_and(|other| {
1241                self.border.eq_shape(&other.border)
1242                    && match (&self.subclass, &other.subclass) {
1243                        (
1244                            OutlinedBorderSubclass::ResolveWith(_),
1245                            OutlinedBorderSubclass::ResolveWith(_),
1246                        ) => true,
1247                        (
1248                            OutlinedBorderSubclass::Mapper(mine),
1249                            OutlinedBorderSubclass::Mapper(theirs),
1250                        ) => mine == theirs,
1251                        _ => false,
1252                    }
1253            })
1254    }
1255}
1256
1257impl OutlinedBorder for WidgetStateOutlinedBorder {
1258    fn side(&self) -> BorderSide {
1259        self.border.side()
1260    }
1261
1262    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
1263        OutlinedBorder::copy_with(&self.border, side)
1264    }
1265}
1266
1267/// Dart's `T?` is `OutlinedBorder?`: a `WidgetStateOutlinedBorder` resolves to an optional
1268/// border.
1269impl MaybeWidgetStateProperty<Option<OutlinedBorderRef>> for Option<OutlinedBorderRef> {
1270    fn as_widget_state_property(
1271        &self,
1272    ) -> Option<&dyn WidgetStateProperty<Option<OutlinedBorderRef>>> {
1273        self.as_ref()
1274            .and_then(|border| border.as_any().downcast_ref::<WidgetStateOutlinedBorder>())
1275            .map(|border| border as &dyn WidgetStateProperty<Option<OutlinedBorderRef>>)
1276    }
1277
1278    fn from_resolved(value: Option<OutlinedBorderRef>) -> Option<OutlinedBorderRef> {
1279        value
1280    }
1281}
1282
1283/// Defines a `TextStyle` that is also a [`WidgetStateProperty`].
1284///
1285/// This class exists to enable widgets with `TextStyle` valued properties to also accept
1286/// `WidgetStateProperty<TextStyle>` values. A widget state text style property represents a
1287/// text style which depends on a widget's "interactive state". This state is represented as
1288/// a set of [`WidgetState`]s, like [`WidgetState::Pressed`], [`WidgetState::Focused`] and
1289/// [`WidgetState::Hovered`].
1290///
1291/// [`WidgetStateTextStyle`] should only be used with widgets that document their support,
1292/// like `InputDecoration.labelStyle`.
1293///
1294/// It is the `TextStyle` it is in Dart once erased with [`into_any`](Self::into_any) (or
1295/// `.into()`): an [`AnyTextStyle`] whose value is Dart's `super` value, the empty
1296/// `TextStyle()`, and whose extension is this object, recovered with
1297/// `style.extension::<WidgetStateTextStyle>()`.
1298pub struct WidgetStateTextStyle {
1299    subclass: TextStyleSubclass,
1300}
1301
1302/// Dart's two private subclasses of `WidgetStateTextStyle`.
1303enum TextStyleSubclass {
1304    /// `_WidgetStateTextStyle`.
1305    ResolveWith(WidgetPropertyResolver<TextStyle>),
1306    /// `_WidgetTextStyleMapper`.
1307    Mapper(WidgetStateMapper<TextStyle>),
1308}
1309
1310impl WidgetStateTextStyle {
1311    /// Creates a [`WidgetStateTextStyle`] from a [`WidgetPropertyResolver<TextStyle>`]
1312    /// callback function.
1313    ///
1314    /// If used as a regular text style, the style resolved in the default state (the empty
1315    /// set of states) will be used.
1316    ///
1317    /// The given callback parameter must return a non-null text style in the default state.
1318    pub fn resolve_with(
1319        callback: impl Fn(&WidgetStates) -> TextStyle + 'static,
1320    ) -> WidgetStateTextStyle {
1321        WidgetStateTextStyle {
1322            subclass: TextStyleSubclass::ResolveWith(Rc::new(callback)),
1323        }
1324    }
1325
1326    /// Creates a [`WidgetStateTextStyle`] from a [`WidgetStateMap<TextStyle>`].
1327    ///
1328    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
1329    /// entry whose key is satisfied by the set of states, and returns its associated value.
1330    pub fn from_map(map: WidgetStateMap<TextStyle>) -> WidgetStateTextStyle {
1331        WidgetStateTextStyle {
1332            subclass: TextStyleSubclass::Mapper(WidgetStateMapper::new(map)),
1333        }
1334    }
1335
1336    /// The style as the `TextStyle` it is in Dart: the empty style, carrying this object as
1337    /// the extension.
1338    pub fn into_any(self) -> AnyTextStyle {
1339        AnyTextStyle::with_shared(TextStyle::new(), Rc::new(self))
1340    }
1341}
1342
1343impl WidgetStateProperty<TextStyle> for WidgetStateTextStyle {
1344    fn resolve(&self, states: &WidgetStates) -> TextStyle {
1345        match &self.subclass {
1346            TextStyleSubclass::ResolveWith(resolve) => resolve(states),
1347            TextStyleSubclass::Mapper(mapper) => mapper.resolve(states),
1348        }
1349    }
1350
1351    fn as_any(&self) -> &dyn Any {
1352        self
1353    }
1354
1355    fn as_mapper(&self) -> Option<&WidgetStateMapper<TextStyle>> {
1356        match &self.subclass {
1357            TextStyleSubclass::Mapper(mapper) => Some(mapper),
1358            TextStyleSubclass::ResolveWith(_) => None,
1359        }
1360    }
1361
1362    // Dart's `TextStyle.==`; the mapper subclass has `WidgetStateMapper.==`.
1363    fn eq_property(&self, other: &dyn WidgetStateProperty<TextStyle>) -> bool {
1364        if let TextStyleSubclass::Mapper(mapper) = &self.subclass {
1365            return mapper.eq_property(other);
1366        }
1367        other
1368            .as_any()
1369            .downcast_ref::<WidgetStateTextStyle>()
1370            .is_some_and(|other| self.eq_extension(other))
1371    }
1372}
1373
1374impl TextStyleExtension for WidgetStateTextStyle {
1375    fn as_any(&self) -> &dyn Any {
1376        self
1377    }
1378
1379    // Dart's `TextStyle.==` compares runtime types (values are already equal here); the
1380    // mapper subclass compares maps instead.
1381    fn eq_extension(&self, other: &dyn TextStyleExtension) -> bool {
1382        other
1383            .as_any()
1384            .downcast_ref::<WidgetStateTextStyle>()
1385            .is_some_and(|other| match (&self.subclass, &other.subclass) {
1386                (TextStyleSubclass::ResolveWith(_), TextStyleSubclass::ResolveWith(_)) => true,
1387                (TextStyleSubclass::Mapper(mine), TextStyleSubclass::Mapper(theirs)) => {
1388                    mine == theirs
1389                }
1390                _ => false,
1391            })
1392    }
1393}
1394
1395impl Debug for WidgetStateTextStyle {
1396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397        match &self.subclass {
1398            TextStyleSubclass::ResolveWith(_) => f.write_str("WidgetStateTextStyle.resolveWith"),
1399            TextStyleSubclass::Mapper(mapper) => mapper.fmt(f),
1400        }
1401    }
1402}
1403
1404impl From<WidgetStateTextStyle> for AnyTextStyle {
1405    fn from(style: WidgetStateTextStyle) -> AnyTextStyle {
1406        style.into_any()
1407    }
1408}
1409
1410impl MaybeWidgetStateProperty<TextStyle> for AnyTextStyle {
1411    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<TextStyle>> {
1412        self.extension::<WidgetStateTextStyle>()
1413            .map(|style| style as &dyn WidgetStateProperty<TextStyle>)
1414    }
1415
1416    fn from_resolved(value: TextStyle) -> AnyTextStyle {
1417        AnyTextStyle::new(value)
1418    }
1419}
1420
1421/// Interface for classes that [`resolve`] to a value of type `T` based
1422/// on a widget's interactive "state", which is defined as a set
1423/// of [`WidgetState`]s.
1424///
1425/// Widget state properties represent values that depend on a widget's "state".
1426/// The state is encoded as a set of [`WidgetState`] values, like
1427/// [`WidgetState::Focused`], [`WidgetState::Hovered`], [`WidgetState::Pressed`]. For
1428/// example the `InkWell.overlayColor` defines the color that fills the ink well
1429/// when it's pressed (the "splash color"), focused, or hovered. The `InkWell`
1430/// uses the overlay color's [`resolve`] method to compute the color for the
1431/// ink well's current state.
1432///
1433/// `ButtonStyle`, which is used to configure the appearance of
1434/// buttons like `TextButton`, `ElevatedButton`, and `OutlinedButton`,
1435/// has many material state properties. The button widgets keep track
1436/// of their current material state and [`resolve`] the button style's
1437/// material state properties when their value is needed.
1438///
1439/// ## Performance Consideration
1440///
1441/// In order for constructed [`WidgetStateProperty`] objects to be recognized as
1442/// equivalent, they need to have overrides for `==`
1443/// ([`eq_property`](WidgetStateProperty::eq_property)).
1444///
1445/// This comes into play when, for instance, two `ThemeData` objects are being
1446/// compared for equality.
1447///
1448/// For a concrete `WidgetStateProperty` object that supports stable
1449/// equality checks, consider using [`WidgetStateMapper`].
1450///
1451/// A property is stored erased as a [`WidgetStatePropertyRef`], whose `==` is Dart's;
1452/// Dart's static members (`from_map`, `resolve_as`, `resolve_with`, `all`, `lerp`) are on
1453/// `<dyn WidgetStateProperty<T>>`.
1454///
1455/// See also:
1456///
1457///  * `MaterialStateProperty`, the Material specific version of
1458///    `WidgetStateProperty`.
1459///  * [`WidgetStateColor`] and [`WidgetStateMouseCursor`], the value types that
1460///    implement it.
1461///
1462/// [`resolve`]: WidgetStateProperty::resolve
1463pub trait WidgetStateProperty<T>: Debug + 'static {
1464    /// Returns a value of type `T` that depends on `states`.
1465    ///
1466    /// Widgets like `TextButton` and `ElevatedButton` apply this method to their
1467    /// current [`WidgetState`]s to compute colors and other visual parameters
1468    /// at build time.
1469    fn resolve(&self, states: &WidgetStates) -> T;
1470
1471    /// Downcast support for Dart's `is` checks in `==`.
1472    fn as_any(&self) -> &dyn Any;
1473
1474    /// Dart's `WidgetStateProperty.debugFillProperties`, from `Diagnosticable`: a property
1475    /// adds its own fields.
1476    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1477        let _ = properties;
1478    }
1479
1480    /// Dart's `other is WidgetStateMapper<T>`: the mapper this property is, if it is one,
1481    /// as the private mapper subclasses of `WidgetStateColor` and the rest are.
1482    fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
1483        None
1484    }
1485
1486    /// Dart's `==`. Identity unless a class overrides it, as [`WidgetStatePropertyAll`] and
1487    /// [`WidgetStateMapper`] do.
1488    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1489        std::ptr::addr_eq(
1490            self as *const Self,
1491            other as *const dyn WidgetStateProperty<T>,
1492        )
1493    }
1494}
1495
1496impl<T: 'static> PartialEq for dyn WidgetStateProperty<T> {
1497    fn eq(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1498        self.eq_property(other)
1499    }
1500}
1501
1502/// A shared, erased [`WidgetStateProperty`] (a Dart object reference).
1503pub type WidgetStatePropertyRef<T> = Rc<dyn WidgetStateProperty<T>>;
1504
1505/// The value a [`WidgetStateProperty`] resolves to, printed as Dart's `toString` and named
1506/// as Dart names it inside `_WidgetStatePropertyWith<T>`.
1507pub trait WidgetStatePropertyValue {
1508    /// The value's Dart `toString`.
1509    fn state_property_value(&self) -> String;
1510
1511    /// The value's Dart type, as `_WidgetStatePropertyWith<T>` prints it.
1512    const DART_TYPE: &'static str;
1513}
1514
1515macro_rules! display_state_value {
1516    ($($t:ty),* $(,)?) => {
1517        $(
1518            impl WidgetStatePropertyValue for Option<$t> {
1519                const DART_TYPE: &'static str = concat!(stringify!($t), "?");
1520
1521                fn state_property_value(&self) -> String {
1522                    match self {
1523                        Some(value) => value.to_string(),
1524                        None => "null".to_string(),
1525                    }
1526                }
1527            }
1528        )*
1529    };
1530}
1531
1532display_state_value!(
1533    Color,
1534    Size,
1535    EdgeInsetsGeometry,
1536    BorderSide,
1537    ShapeBorderRef,
1538    TextStyle
1539);
1540
1541impl WidgetStatePropertyValue for Option<bool> {
1542    const DART_TYPE: &'static str = "bool?";
1543
1544    fn state_property_value(&self) -> String {
1545        match self {
1546            Some(value) => value.to_string(),
1547            None => "null".to_string(),
1548        }
1549    }
1550}
1551
1552impl WidgetStatePropertyValue for Option<f64> {
1553    const DART_TYPE: &'static str = "double?";
1554
1555    fn state_property_value(&self) -> String {
1556        waft_foundation::debug_format_double(*self)
1557    }
1558}
1559
1560impl WidgetStatePropertyValue for f64 {
1561    const DART_TYPE: &'static str = "double";
1562
1563    fn state_property_value(&self) -> String {
1564        waft_foundation::debug_format_double(Some(*self))
1565    }
1566}
1567
1568impl WidgetStatePropertyValue for Option<OutlinedBorderRef> {
1569    const DART_TYPE: &'static str = "OutlinedBorder?";
1570
1571    fn state_property_value(&self) -> String {
1572        match self {
1573            Some(value) => format!("{value:?}"),
1574            None => "null".to_string(),
1575        }
1576    }
1577}
1578
1579impl WidgetStatePropertyValue for Option<MouseCursorRef> {
1580    const DART_TYPE: &'static str = "MouseCursor?";
1581
1582    fn state_property_value(&self) -> String {
1583        match self {
1584            Some(value) => value.debug_description(),
1585            None => "null".to_string(),
1586        }
1587    }
1588}
1589
1590impl WidgetStatePropertyValue for Option<crate::WidgetRef> {
1591    const DART_TYPE: &'static str = "Widget?";
1592
1593    fn state_property_value(&self) -> String {
1594        match self {
1595            Some(widget) => widget.to_string_short(),
1596            None => "null".to_string(),
1597        }
1598    }
1599}
1600
1601impl WidgetStatePropertyValue for Option<Rc<crate::Icon>> {
1602    const DART_TYPE: &'static str = "Icon?";
1603
1604    fn state_property_value(&self) -> String {
1605        match self {
1606            Some(icon) => match &icon.icon {
1607                Some(icon_data) => {
1608                    format!("Icon(IconData(U+{:05X}))", icon_data.code_point)
1609                }
1610                None => "Icon".to_string(),
1611            },
1612            None => "null".to_string(),
1613        }
1614    }
1615}
1616
1617impl WidgetStatePropertyValue for Option<crate::IconThemeData> {
1618    const DART_TYPE: &'static str = "IconThemeData?";
1619
1620    fn state_property_value(&self) -> String {
1621        match self {
1622            Some(value) => value.to_string(),
1623            None => "null".to_string(),
1624        }
1625    }
1626}
1627
1628/// A value that may be a [`WidgetStateProperty`] in disguise: Dart's
1629/// `value is WidgetStateProperty<T>` in `<dyn WidgetStateProperty<T>>::resolve_as`.
1630///
1631/// [`AnyColor`] answers through its [`WidgetStateColor`] extension, [`MouseCursorRef`]
1632/// through `as_any`, and an `Option` of either through its content (Dart's `T?`).
1633pub trait MaybeWidgetStateProperty<T>: Clone {
1634    /// The property this value is, if it is one.
1635    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>>;
1636
1637    /// A resolved value as this type (Dart's `T` is both).
1638    fn from_resolved(value: T) -> Self;
1639}
1640
1641impl<T, V: MaybeWidgetStateProperty<T>> MaybeWidgetStateProperty<T> for Option<V> {
1642    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>> {
1643        self.as_ref().and_then(V::as_widget_state_property)
1644    }
1645
1646    fn from_resolved(value: T) -> Option<V> {
1647        Some(V::from_resolved(value))
1648    }
1649}
1650
1651impl<T: 'static> dyn WidgetStateProperty<T> {
1652    /// Dart's `WidgetStateProperty.toString`: `WidgetStatePropertyAll(value)` for one, the
1653    /// mapper's own text, `Instance of '_WidgetStatePropertyWith<T>'` for a `resolveWith`, and
1654    /// the property's `Debug` for another implementation.
1655    #[allow(
1656        clippy::inherent_to_string,
1657        reason = "Dart's toString needs a value bound Rust's Display cannot carry here"
1658    )]
1659    pub fn to_string(&self) -> String
1660    where
1661        T: WidgetStatePropertyValue + Debug,
1662    {
1663        if let Some(all) = self.as_any().downcast_ref::<WidgetStatePropertyAll<T>>() {
1664            return format!(
1665                "WidgetStatePropertyAll({})",
1666                all.value.state_property_value()
1667            );
1668        }
1669        if self.as_any().is::<WidgetStatePropertyWith<T>>() {
1670            return format!("Instance of '_WidgetStatePropertyWith<{}>'", T::DART_TYPE);
1671        }
1672        if let Some(mapper) = self.as_mapper() {
1673            return mapper.to_string();
1674        }
1675        format!("{self:?}")
1676    }
1677
1678    /// Creates a property that resolves using a [`WidgetStateMap`].
1679    ///
1680    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
1681    /// entry whose key is satisfied by the set of states, and returns its associated value.
1682    ///
1683    /// Panics if no keys match (see [`WidgetStateMapper`]).
1684    /// To prevent a situation where each [`WidgetStatesConstraint`]
1685    /// isn't satisfied by the given set of states, consider adding
1686    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
1687    pub fn from_map(map: WidgetStateMap<T>) -> WidgetStatePropertyRef<T>
1688    where
1689        T: Clone + Debug + PartialEq,
1690    {
1691        Rc::new(WidgetStateMapper::new(map))
1692    }
1693
1694    /// Resolves the value for the given set of states if `value` is a
1695    /// [`WidgetStateProperty`], otherwise returns the value itself.
1696    ///
1697    /// This is useful for widgets that have parameters which can optionally be a
1698    /// [`WidgetStateProperty`]. For example, `InkWell.mouseCursor` can be a
1699    /// `MouseCursor` or a `WidgetStateProperty<MouseCursor>`.
1700    ///
1701    /// Dart's `T` is the value's own type here (`AnyColor` for a `Color`,
1702    /// [`MouseCursorRef`] for a `MouseCursor`, or an `Option` of one):
1703    /// `<dyn WidgetStateProperty<Color>>::resolve_as(&color, &states)`.
1704    pub fn resolve_as<V: MaybeWidgetStateProperty<T>>(value: &V, states: &WidgetStates) -> V {
1705        if let Some(property) = value.as_widget_state_property() {
1706            return V::from_resolved(property.resolve(states));
1707        }
1708        value.clone()
1709    }
1710
1711    /// Convenience method for creating a [`WidgetStateProperty`] from a
1712    /// [`WidgetPropertyResolver`] function alone.
1713    pub fn resolve_with(
1714        callback: impl Fn(&WidgetStates) -> T + 'static,
1715    ) -> WidgetStatePropertyRef<T> {
1716        Rc::new(WidgetStatePropertyWith {
1717            resolve: Rc::new(callback),
1718        })
1719    }
1720
1721    /// Convenience method for creating a [`WidgetStateProperty`] that resolves
1722    /// to a single value for all states.
1723    ///
1724    /// Prefer using [`WidgetStatePropertyAll`] directly.
1725    pub fn all(value: T) -> WidgetStatePropertyRef<T>
1726    where
1727        T: Clone + Debug + PartialEq,
1728    {
1729        Rc::new(WidgetStatePropertyAll::new(value))
1730    }
1731
1732    /// Linearly interpolate between two [`WidgetStateProperty`]s.
1733    pub fn lerp(
1734        a: Option<WidgetStatePropertyRef<T>>,
1735        b: Option<WidgetStatePropertyRef<T>>,
1736        t: f64,
1737        lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
1738    ) -> Option<WidgetStatePropertyRef<Option<T>>> {
1739        // Avoid creating a LerpProperties object for a common case.
1740        if a.is_none() && b.is_none() {
1741            return None;
1742        }
1743        Some(Rc::new(LerpProperties {
1744            a,
1745            b,
1746            t,
1747            lerp_function: Rc::new(lerp_function),
1748        }))
1749    }
1750}
1751
1752/// Dart's `T? Function(T?, T?, double)` argument of `WidgetStateProperty.lerp`.
1753type LerpFunction<T> = Rc<dyn Fn(Option<T>, Option<T>, f64) -> Option<T>>;
1754
1755struct LerpProperties<T> {
1756    a: Option<WidgetStatePropertyRef<T>>,
1757    b: Option<WidgetStatePropertyRef<T>>,
1758    t: f64,
1759    lerp_function: LerpFunction<T>,
1760}
1761
1762impl<T: 'static> WidgetStateProperty<Option<T>> for LerpProperties<T> {
1763    fn resolve(&self, states: &WidgetStates) -> Option<T> {
1764        let resolved_a = self.a.as_ref().map(|a| a.resolve(states));
1765        let resolved_b = self.b.as_ref().map(|b| b.resolve(states));
1766        (self.lerp_function)(resolved_a, resolved_b, self.t)
1767    }
1768
1769    fn as_any(&self) -> &dyn Any {
1770        self
1771    }
1772}
1773
1774impl<T> Debug for LerpProperties<T> {
1775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1776        write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
1777    }
1778}
1779
1780impl<T: 'static> dyn WidgetStateProperty<Option<T>> {
1781    /// Linearly interpolate between two [`WidgetStateProperty`]s of a nullable value.
1782    ///
1783    /// This is Dart's `WidgetStateProperty.lerp<T>` with `T` nullable, such as the
1784    /// `WidgetStateProperty<Color?>` fields of a `ButtonStyle`: Dart's `T??` is `T?`, so the
1785    /// lerped property resolves to `Option<T>`, where [`lerp`](Self::lerp) over
1786    /// `Option<T>` would resolve to `Option<Option<T>>`. A side that resolves to `None` is
1787    /// handed to `lerp_function` as `None`, as Dart hands it `null`.
1788    pub fn lerp_optional(
1789        a: Option<WidgetStatePropertyRef<Option<T>>>,
1790        b: Option<WidgetStatePropertyRef<Option<T>>>,
1791        t: f64,
1792        lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
1793    ) -> Option<WidgetStatePropertyRef<Option<T>>> {
1794        // Avoid creating a LerpProperties object for a common case.
1795        if a.is_none() && b.is_none() {
1796            return None;
1797        }
1798        Some(Rc::new(LerpOptionalProperties {
1799            a,
1800            b,
1801            t,
1802            lerp_function: Rc::new(lerp_function),
1803        }))
1804    }
1805}
1806
1807/// Dart's `_LerpProperties<T>` with `T` nullable, which `lerp_optional` makes.
1808struct LerpOptionalProperties<T> {
1809    a: Option<WidgetStatePropertyRef<Option<T>>>,
1810    b: Option<WidgetStatePropertyRef<Option<T>>>,
1811    t: f64,
1812    lerp_function: LerpFunction<T>,
1813}
1814
1815impl<T: 'static> WidgetStateProperty<Option<T>> for LerpOptionalProperties<T> {
1816    fn resolve(&self, states: &WidgetStates) -> Option<T> {
1817        let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
1818        let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
1819        (self.lerp_function)(resolved_a, resolved_b, self.t)
1820    }
1821
1822    fn as_any(&self) -> &dyn Any {
1823        self
1824    }
1825}
1826
1827impl<T> Debug for LerpOptionalProperties<T> {
1828    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829        write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
1830    }
1831}
1832
1833struct WidgetStatePropertyWith<T> {
1834    resolve: WidgetPropertyResolver<T>,
1835}
1836
1837impl<T: 'static> WidgetStateProperty<T> for WidgetStatePropertyWith<T> {
1838    fn resolve(&self, states: &WidgetStates) -> T {
1839        (self.resolve)(states)
1840    }
1841
1842    fn as_any(&self) -> &dyn Any {
1843        self
1844    }
1845}
1846
1847impl<T> Debug for WidgetStatePropertyWith<T> {
1848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1849        f.write_str("WidgetStateProperty.resolveWith")
1850    }
1851}
1852
1853/// A map used to resolve to a single value of type `T` based on
1854/// the current set of Widget states.
1855///
1856/// Dart's `Map<WidgetStatesConstraint, T>`, kept as its entries in insertion order.
1857///
1858/// Example:
1859///
1860/// ```text
1861/// // This WidgetStateMap<Option<Color>> resolves to None if no keys match.
1862/// <dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
1863///     (WidgetState::Error.into(), Some(RED)),
1864///     (WidgetState::Hovered & WidgetState::Focused, Some(BLUE_ACCENT)),
1865///     (WidgetState::Focused.into(), Some(BLUE)),
1866///     (~WidgetState::Disabled, Some(BLACK)),
1867///     (WidgetState::any(), None),
1868/// ]);
1869///
1870/// // The same can be accomplished with a WidgetPropertyResolver,
1871/// // but it's more verbose:
1872/// <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
1873///     if states.contains(&WidgetState::Error) {
1874///         Some(RED)
1875///     } else if states.contains(&WidgetState::Hovered) && states.contains(&WidgetState::Focused) {
1876///         Some(BLUE_ACCENT)
1877///     } else if states.contains(&WidgetState::Focused) {
1878///         Some(BLUE)
1879///     } else if !states.contains(&WidgetState::Disabled) {
1880///         Some(BLACK)
1881///     } else {
1882///         None
1883///     }
1884/// });
1885/// ```
1886///
1887/// A widget state combination can be stored in a variable,
1888/// and [`WidgetState::any`] can be used for non-nullable types to ensure
1889/// that there's a match:
1890///
1891/// ```text
1892/// let selected_error = WidgetState::Selected & WidgetState::Error;
1893///
1894/// let color = <dyn WidgetStateProperty<Color>>::from_map(vec![
1895///     (selected_error.clone() & WidgetState::Hovered, RED_ACCENT),
1896///     (selected_error, RED),
1897///     (WidgetState::any(), BLACK),
1898/// ]);
1899///
1900/// // The (more verbose) WidgetPropertyResolver implementation:
1901/// let color_resolve_with = <dyn WidgetStateProperty<Color>>::resolve_with(|states| {
1902///     if states.contains(&WidgetState::Selected) && states.contains(&WidgetState::Error) {
1903///         if states.contains(&WidgetState::Hovered) {
1904///             return RED_ACCENT;
1905///         }
1906///         return RED;
1907///     }
1908///     BLACK
1909/// });
1910/// ```
1911pub type WidgetStateMap<T> = Vec<(WidgetStatesConstraintRef, T)>;
1912
1913/// Uses a [`WidgetStateMap`] to resolve to a single value of type `T` based on
1914/// the current set of Widget states.
1915///
1916/// Classes that hold a [`WidgetStateMapper`] can implement any other interface,
1917/// but should only be used for fields that document their support for
1918/// [`WidgetStateProperty`] objects.
1919///
1920/// For example, a [`WidgetStateColor::from_map`] object can be passed anywhere that
1921/// accepts either a `Color` or a [`WidgetStateProperty`] object.
1922///
1923/// [`resolve`](WidgetStateProperty::resolve) panics when no key is satisfied, whatever
1924/// `T`; a map that should resolve to `None` ends with `(WidgetState::any(), None)`.
1925#[derive(Clone)]
1926pub struct WidgetStateMapper<T> {
1927    map: WidgetStateMap<T>,
1928}
1929
1930impl<T> WidgetStateMapper<T> {
1931    /// Creates a [`WidgetStateProperty`] object that can resolve
1932    /// to a value of type `T` using the provided `map`.
1933    pub fn new(map: WidgetStateMap<T>) -> WidgetStateMapper<T> {
1934        WidgetStateMapper { map }
1935    }
1936}
1937
1938impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStateMapper<T> {
1939    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1940        properties.add(DiagnosticsProperty::<String>::new(
1941            "map",
1942            Some(format!("{:?}", self.map)),
1943        ));
1944    }
1945
1946    fn resolve(&self, states: &WidgetStates) -> T {
1947        for (key, value) in &self.map {
1948            if key.is_satisfied_by(states) {
1949                return value.clone();
1950            }
1951        }
1952
1953        panic!(
1954            "The current set of widget states is {states:?}.\n\
1955             None of the provided map keys matched this set, \
1956             and the type \"{t}\" is non-nullable.\n\
1957             Consider using \"WidgetStateMapper<Option<{t}>>\" with a final \
1958             \"WidgetState::any()\" key mapped to None, \
1959             or adding the \"WidgetState::any()\" key to this map.",
1960            t = type_name::<T>()
1961        );
1962    }
1963
1964    fn as_any(&self) -> &dyn Any {
1965        self
1966    }
1967
1968    fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
1969        Some(self)
1970    }
1971
1972    // Dart's `other is WidgetStateMapper<T> && mapEquals(_map, other._map)`.
1973    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1974        other.as_mapper().is_some_and(|other| self == other)
1975    }
1976}
1977
1978impl<T: PartialEq> PartialEq for WidgetStateMapper<T> {
1979    // Dart's `mapEquals`: the same entries, looked up by key equality.
1980    fn eq(&self, other: &WidgetStateMapper<T>) -> bool {
1981        self.map.len() == other.map.len()
1982            && self.map.iter().all(|(key, value)| {
1983                other
1984                    .map
1985                    .iter()
1986                    .any(|(other_key, other_value)| other_key == key && other_value == value)
1987            })
1988    }
1989}
1990
1991impl<T: WidgetStatePropertyValue + Debug> WidgetStateMapper<T> {
1992    /// Dart's `WidgetStateMapper.toString`: the type and the map.
1993    #[allow(
1994        clippy::inherent_to_string,
1995        reason = "Dart's toString needs Dart's value formatting, not Display"
1996    )]
1997    pub fn to_string(&self) -> String {
1998        let entries: Vec<String> = self
1999            .map
2000            .iter()
2001            .map(|(key, value)| format!("{key}: {}", value.state_property_value()))
2002            .collect();
2003        format!(
2004            "WidgetStateMapper<{}>({{{}}})",
2005            T::DART_TYPE,
2006            entries.join(", ")
2007        )
2008    }
2009}
2010
2011impl<T: Debug> Debug for WidgetStateMapper<T> {
2012    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2013        write!(f, "WidgetStateMapper<{}>({:?})", type_name::<T>(), self.map)
2014    }
2015}
2016
2017/// Convenience class for creating a [`WidgetStateProperty`] that
2018/// resolves to the given value for all states.
2019///
2020/// See also:
2021///
2022///  * `MaterialStatePropertyAll`, the Material specific version of
2023///    `WidgetStatePropertyAll`.
2024#[derive(Clone, PartialEq)]
2025pub struct WidgetStatePropertyAll<T> {
2026    /// The value of the property that will be used for all states.
2027    pub value: T,
2028}
2029
2030impl<T> WidgetStatePropertyAll<T> {
2031    /// Constructs a [`WidgetStateProperty`] that always resolves to the given
2032    /// value.
2033    pub const fn new(value: T) -> WidgetStatePropertyAll<T> {
2034        WidgetStatePropertyAll { value }
2035    }
2036}
2037
2038impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStatePropertyAll<T> {
2039    fn resolve(&self, _states: &WidgetStates) -> T {
2040        self.value.clone()
2041    }
2042
2043    fn as_any(&self) -> &dyn Any {
2044        self
2045    }
2046
2047    // Dart's `other is WidgetStatePropertyAll<T> && other.runtimeType == runtimeType &&
2048    // other.value == value`.
2049    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
2050        other
2051            .as_any()
2052            .downcast_ref::<WidgetStatePropertyAll<T>>()
2053            .is_some_and(|other| other.value == self.value)
2054    }
2055}
2056
2057impl<T: Debug> Debug for WidgetStatePropertyAll<T> {
2058    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2059        write!(f, "WidgetStatePropertyAll({:?})", self.value)
2060    }
2061}
2062
2063/// Manages a set of [`WidgetState`]s and notifies listeners of changes.
2064///
2065/// Used by widgets that expose their internal state for the sake of
2066/// extensions that add support for additional states. See
2067/// `TextButton` for an example.
2068///
2069/// The controller's [`value`] is its current set of states. Listeners
2070/// are notified whenever the [`value`] changes. The [`value`] should only be
2071/// changed with [`update`]; it should not be modified directly.
2072///
2073/// The controller's [`value`] represents the set of states that a
2074/// widget's visual properties, typically [`WidgetStateProperty`]
2075/// values, are resolved against. It is _not_ the intrinsic state of
2076/// the widget. The widget is responsible for ensuring that the
2077/// controller's [`value`] tracks its intrinsic state. For example one
2078/// cannot request the keyboard focus for a widget by adding
2079/// [`WidgetState::Focused`] to its controller. When the widget gains the
2080/// or loses the focus it will [`update`] its controller's [`value`] and
2081/// notify listeners of the change.
2082///
2083/// When calling `set_state` in a [`WidgetStatesController`] listener, use the
2084/// `SchedulerBinding::add_post_frame_callback` to delay the call to `set_state` after
2085/// the frame has been rendered. It's generally prudent to use the
2086/// `SchedulerBinding::add_post_frame_callback` because some of the widgets that
2087/// depend on [`WidgetStatesController`] may call [`update`] in their build method.
2088/// In such cases, listener's that call `set_state` - during the build phase - will cause
2089/// an error.
2090///
2091/// Dart's `ValueNotifier<Set<WidgetState>>` superclass is the `change_notifier` and `value`
2092/// fields here, with its [`value`] / [`set_value`] / [`dispose`]; the handle is a
2093/// `Listenable`.
2094///
2095/// See also:
2096///
2097///  * `MaterialStatesController`, the Material specific version of
2098///    `WidgetStatesController`.
2099///
2100/// [`value`]: WidgetStatesController::value
2101/// [`set_value`]: WidgetStatesController::set_value
2102/// [`dispose`]: WidgetStatesController::dispose
2103/// [`update`]: WidgetStatesController::update
2104#[derive(Debug)]
2105pub struct WidgetStatesController {
2106    change_notifier: ChangeNotifierData,
2107    value: WidgetStates,
2108}
2109
2110impl WidgetStatesController {
2111    /// Creates a WidgetStatesController.
2112    pub fn new(app: &mut App, value: Option<WidgetStates>) -> Ref<WidgetStatesController> {
2113        app.create(WidgetStatesController {
2114            change_notifier: ChangeNotifierData::new(),
2115            value: value.unwrap_or_default(),
2116        })
2117    }
2118
2119    /// The current set of states.
2120    pub fn value(&self) -> &WidgetStates {
2121        &self.value
2122    }
2123
2124    /// Replaces the current set of states, notifying listeners when it differs
2125    /// (`ValueNotifier`'s setter). Prefer [`update`](Self::update).
2126    pub fn set_value(self: Handle<Self>, app: &mut App, new_value: WidgetStates) {
2127        if app.get(self).value == new_value {
2128            return;
2129        }
2130        app.get_mut(self).value = new_value;
2131        self.notify_listeners(app);
2132    }
2133
2134    /// Discards any resources used by the object; see [`ChangeNotifierData::dispose`].
2135    pub fn dispose(self: Handle<Self>, app: &mut App) {
2136        ChangeNotifierData::dispose(app, self);
2137    }
2138
2139    /// Dart's `WidgetStatesController.toString`, which it inherits from
2140    /// `ValueNotifier<Set<WidgetState>>`: the identity and the set.
2141    pub fn to_string(self: Handle<Self>, app: &App) -> String {
2142        format!(
2143            "{}({})",
2144            describe_identity("WidgetStatesController", self.id().identity_hash()),
2145            widget_states(app.get(self).value())
2146        )
2147    }
2148
2149    /// Adds `state` to [`value`](Self::value) if `add` is true, and removes it otherwise,
2150    /// and notifies listeners if [`value`](Self::value) has changed.
2151    pub fn update(self: Handle<Self>, app: &mut App, state: WidgetState, add: bool) {
2152        let value = &mut app.get_mut(self).value;
2153        let value_changed = if add {
2154            value.insert(state)
2155        } else {
2156            value.remove(&state)
2157        };
2158        if value_changed {
2159            self.notify_listeners(app);
2160        }
2161    }
2162}
2163
2164impl ChangeNotifier for WidgetStatesController {
2165    fn change_notifier_data(&self) -> &ChangeNotifierData {
2166        &self.change_notifier
2167    }
2168
2169    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2170        &mut self.change_notifier
2171    }
2172}
2173
2174#[cfg(test)]
2175mod tests {
2176    use std::cell::Cell;
2177    use waft_foundation::AppCell;
2178
2179    use waft_foundation::{Listenable, Listener};
2180    use waft_painting::TextStyle;
2181
2182    use super::*;
2183
2184    const WHITE: Color = Color::new(0xFFFFFFFF);
2185    const BLACK: Color = Color::new(0xFF000000);
2186    const RED: Color = Color::new(0xFFFF0000);
2187
2188    fn states(states: impl IntoIterator<Item = WidgetState>) -> WidgetStates {
2189        states.into_iter().collect()
2190    }
2191
2192    fn cursor(cursor: MouseCursorRef) -> MouseCursorRef {
2193        cursor
2194    }
2195
2196    // widget_state_property_test.dart 'WidgetStateProperty.resolveWith()'.
2197    #[test]
2198    fn resolve_with_resolves_through_the_callback() {
2199        let value = <dyn WidgetStateProperty<WidgetState>>::resolve_with(|states| {
2200            states.iter().next().copied().expect("one state")
2201        });
2202        for state in [
2203            WidgetState::Hovered,
2204            WidgetState::Focused,
2205            WidgetState::Pressed,
2206            WidgetState::Dragged,
2207            WidgetState::Selected,
2208            WidgetState::Disabled,
2209            WidgetState::Error,
2210        ] {
2211            assert_eq!(value.resolve(&states([state])), state);
2212        }
2213    }
2214
2215    // widget_state_property_test.dart 'WidgetStateProperty.map()'.
2216    #[test]
2217    fn a_map_resolves_to_the_first_satisfied_key_through_the_combinators() {
2218        let active = WidgetState::Hovered | WidgetState::Focused | WidgetState::Pressed;
2219        let value = <dyn WidgetStateProperty<Option<&str>>>::from_map(vec![
2220            (active.clone() & WidgetState::Error, Some("active error")),
2221            (
2222                WidgetState::Disabled | WidgetState::Error,
2223                Some("kinda sus"),
2224            ),
2225            (
2226                !(WidgetState::Dragged | WidgetState::Selected) & !active.clone(),
2227                Some("this is boring"),
2228            ),
2229            (active, Some("active")),
2230            (WidgetState::any(), None),
2231        ]);
2232        assert_eq!(
2233            value.resolve(&states([WidgetState::Focused, WidgetState::Error])),
2234            Some("active error")
2235        );
2236        assert_eq!(
2237            value.resolve(&states([WidgetState::ScrolledUnder])),
2238            Some("this is boring")
2239        );
2240        assert_eq!(
2241            value.resolve(&states([WidgetState::Disabled])),
2242            Some("kinda sus")
2243        );
2244        assert_eq!(
2245            value.resolve(&states([WidgetState::Hovered])),
2246            Some("active")
2247        );
2248        assert_eq!(value.resolve(&states([WidgetState::Dragged])), None);
2249    }
2250
2251    #[test]
2252    fn any_is_satisfied_by_every_set_and_a_constraint_prints_as_dart_does() {
2253        assert!(WidgetState::any().is_satisfied_by(&WidgetStates::new()));
2254        assert!(WidgetState::any().is_satisfied_by(&states([WidgetState::Disabled])));
2255        assert_eq!(WidgetState::any(), WidgetState::any());
2256        assert_eq!(format!("{:?}", WidgetState::any()), "WidgetState.any");
2257        assert_eq!(
2258            format!("{:?}", !(WidgetState::Hovered & WidgetState::Focused)),
2259            "~(Hovered & Focused)"
2260        );
2261        assert_eq!(
2262            WidgetState::Hovered | WidgetState::Focused,
2263            WidgetState::Hovered | WidgetState::Focused
2264        );
2265        assert_ne!(
2266            WidgetState::Hovered | WidgetState::Focused,
2267            WidgetState::Focused | WidgetState::Hovered
2268        );
2269        assert_ne!(
2270            WidgetState::Hovered | WidgetState::Focused,
2271            WidgetState::Hovered & WidgetState::Focused
2272        );
2273    }
2274
2275    #[test]
2276    #[should_panic(expected = "None of the provided map keys matched this set")]
2277    fn a_map_with_no_satisfied_key_panics_with_darts_message() {
2278        let value = WidgetStateMapper::new(vec![(WidgetState::Hovered.into(), 1)]);
2279        value.resolve(&states([WidgetState::Focused]));
2280    }
2281
2282    // widget_state_property_test.dart 'WidgetStateProperty.all()' and 'WidgetStatePropertyAll'.
2283    #[test]
2284    fn all_resolves_to_its_value_for_every_state() {
2285        let value = <dyn WidgetStateProperty<i32>>::all(123);
2286        let constant = WidgetStatePropertyAll::new(123);
2287        assert_eq!(constant.resolve(&WidgetStates::new()), 123);
2288        for state in [
2289            WidgetState::Hovered,
2290            WidgetState::Focused,
2291            WidgetState::Pressed,
2292            WidgetState::Dragged,
2293            WidgetState::Selected,
2294            WidgetState::Disabled,
2295            WidgetState::Error,
2296        ] {
2297            assert_eq!(value.resolve(&states([state])), 123);
2298            assert_eq!(constant.resolve(&states([state])), 123);
2299        }
2300        assert_eq!(
2301            format!("{:?}", WidgetStatePropertyAll::new(Some(WHITE))),
2302            format!("WidgetStatePropertyAll({:?})", Some(WHITE))
2303        );
2304        assert_eq!(
2305            WidgetStatePropertyAll::new(1),
2306            WidgetStatePropertyAll::new(1)
2307        );
2308        assert_ne!(
2309            WidgetStatePropertyAll::new(1),
2310            WidgetStatePropertyAll::new(2)
2311        );
2312    }
2313
2314    // widget_state_property_test.dart "Can interpolate between two WidgetStateProperty's".
2315    #[test]
2316    fn lerp_interpolates_the_resolved_values() {
2317        let enabled = WidgetStates::new();
2318        let text_style_1: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
2319            TextStyle::new().font_size(14.0),
2320        ));
2321        let text_style_2: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
2322            TextStyle::new().font_size(20.0),
2323        ));
2324        let lerp = |t: f64| {
2325            <dyn WidgetStateProperty<TextStyle>>::lerp(
2326                Some(Rc::clone(&text_style_1)),
2327                Some(Rc::clone(&text_style_2)),
2328                t,
2329                |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
2330            )
2331            .expect("one side")
2332            .resolve(&enabled)
2333            .expect("both sides")
2334            .font_size
2335        };
2336        assert_eq!(lerp(0.0), Some(14.0));
2337        assert_eq!(lerp(0.5), Some(17.0));
2338        assert_eq!(lerp(1.0), Some(20.0));
2339        assert!(
2340            <dyn WidgetStateProperty<TextStyle>>::lerp(None, None, 0.5, |_, _, _| None).is_none()
2341        );
2342    }
2343
2344    #[test]
2345    fn lerp_optional_interpolates_nullable_values_and_hands_a_none_side_on() {
2346        let enabled = WidgetStates::new();
2347        let some: WidgetStatePropertyRef<Option<f64>> =
2348            Rc::new(WidgetStatePropertyAll::new(Some(10.0)));
2349        let none: WidgetStatePropertyRef<Option<f64>> = Rc::new(WidgetStatePropertyAll::new(None));
2350        let lerp = |a: &WidgetStatePropertyRef<Option<f64>>,
2351                    b: Option<&WidgetStatePropertyRef<Option<f64>>>,
2352                    t: f64| {
2353            <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(
2354                Some(Rc::clone(a)),
2355                b.cloned(),
2356                t,
2357                |a, b, t| match (a, b) {
2358                    (Some(a), Some(b)) => Some(a + (b - a) * t),
2359                    (Some(a), None) => Some(a * (1.0 - t)),
2360                    (None, Some(b)) => Some(b * t),
2361                    (None, None) => None,
2362                },
2363            )
2364            .expect("one side")
2365            .resolve(&enabled)
2366        };
2367        let twenty: WidgetStatePropertyRef<Option<f64>> =
2368            Rc::new(WidgetStatePropertyAll::new(Some(20.0)));
2369        assert_eq!(lerp(&some, Some(&twenty), 0.5), Some(15.0));
2370        assert_eq!(lerp(&some, Some(&none), 0.5), Some(5.0));
2371        assert_eq!(lerp(&some, None, 0.5), Some(5.0));
2372        assert_eq!(lerp(&none, Some(&none), 0.5), None);
2373        assert!(
2374            <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(None, None, 0.5, |_, _, _| None)
2375                .is_none()
2376        );
2377    }
2378
2379    #[test]
2380    fn a_widget_state_color_resolves_per_state_and_travels_through_a_text_style() {
2381        let color = WidgetStateColor::resolve_with(|states| {
2382            if states.contains(&WidgetState::Pressed) {
2383                return RED;
2384            }
2385            BLACK
2386        });
2387        assert_eq!(color.resolve(&states([WidgetState::Pressed])), RED);
2388        assert_eq!(color.resolve(&WidgetStates::new()), BLACK);
2389
2390        let style = TextStyle::new().color(color);
2391        let color = style.color.clone().expect("set above");
2392        assert_eq!(color.color(), BLACK, "the default-state value is the Color");
2393        let property = color
2394            .extension::<WidgetStateColor>()
2395            .expect("the extension survives the style");
2396        assert_eq!(property.resolve(&states([WidgetState::Pressed])), RED);
2397
2398        assert_eq!(
2399            <dyn WidgetStateProperty<Color>>::resolve_as(&color, &states([WidgetState::Pressed])),
2400            AnyColor::new(RED)
2401        );
2402        assert_eq!(
2403            <dyn WidgetStateProperty<Color>>::resolve_as(
2404                &Some(color),
2405                &states([WidgetState::Pressed])
2406            ),
2407            Some(AnyColor::new(RED))
2408        );
2409    }
2410
2411    #[test]
2412    fn resolve_as_returns_a_plain_color_unchanged() {
2413        let plain = AnyColor::new(RED);
2414        assert_eq!(
2415            <dyn WidgetStateProperty<Color>>::resolve_as(&plain, &states([WidgetState::Pressed])),
2416            plain
2417        );
2418        assert_eq!(
2419            <dyn WidgetStateProperty<Color>>::resolve_as(
2420                &None::<AnyColor>,
2421                &states([WidgetState::Pressed])
2422            ),
2423            None
2424        );
2425    }
2426
2427    #[test]
2428    fn transparent_resolves_transparent_and_a_from_map_color_resolves_its_first_key() {
2429        let transparent = WidgetStateColor::transparent().into_any();
2430        assert_eq!(transparent.color(), Color::new(0x00000000));
2431        assert_eq!(
2432            transparent
2433                .extension::<WidgetStateColor>()
2434                .expect("a WidgetStateColor")
2435                .resolve(&states([WidgetState::Pressed])),
2436            Color::new(0x00000000)
2437        );
2438        assert_eq!(transparent, WidgetStateColor::transparent().into_any());
2439
2440        let color = WidgetStateColor::from_map(vec![
2441            (WidgetState::Focused | WidgetState::Hovered, WHITE),
2442            (WidgetState::any(), BLACK),
2443        ]);
2444        assert_eq!(color.resolve(&states([WidgetState::Hovered])), WHITE);
2445        assert_eq!(color.resolve(&states([WidgetState::Pressed])), BLACK);
2446        assert_eq!(color.into_any().color(), BLACK);
2447    }
2448
2449    // widget_state_property_test.dart '.fromMap() constructors perform accurate equality checks'.
2450    #[test]
2451    fn from_map_constructors_perform_accurate_equality_checks() {
2452        let color_1 = WidgetStateColor::from_map(vec![
2453            (WidgetState::Focused | WidgetState::Hovered, WHITE),
2454            (WidgetState::any(), BLACK),
2455        ])
2456        .into_any();
2457        let color_2 = WidgetStateColor::from_map(vec![
2458            (WidgetState::Focused | WidgetState::Hovered, WHITE),
2459            (WidgetState::any(), BLACK),
2460        ])
2461        .into_any();
2462        let color_3 = WidgetStateColor::from_map(vec![
2463            (WidgetState::Focused | WidgetState::Hovered, BLACK),
2464            (WidgetState::any(), WHITE),
2465        ])
2466        .into_any();
2467        assert!(color_1 == color_2);
2468        assert!(color_1 != color_3);
2469
2470        let cursor_1 = cursor(
2471            WidgetStateMouseCursor::from_map(vec![
2472                (
2473                    WidgetState::Focused | WidgetState::Hovered,
2474                    <dyn MouseCursor>::defer(),
2475                ),
2476                (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
2477            ])
2478            .into(),
2479        );
2480        let cursor_2 = cursor(
2481            WidgetStateMouseCursor::from_map(vec![
2482                (
2483                    WidgetState::Focused | WidgetState::Hovered,
2484                    <dyn MouseCursor>::defer(),
2485                ),
2486                (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
2487            ])
2488            .into(),
2489        );
2490        let cursor_3 = cursor(
2491            WidgetStateMouseCursor::from_map(vec![
2492                (
2493                    WidgetState::Focused | WidgetState::Hovered,
2494                    <dyn MouseCursor>::uncontrolled(),
2495                ),
2496                (WidgetState::any(), <dyn MouseCursor>::defer()),
2497            ])
2498            .into(),
2499        );
2500        assert!(*cursor_1 == *cursor_2);
2501        assert!(*cursor_1 != *cursor_3);
2502
2503        let white_border = BorderSide {
2504            color: WHITE,
2505            ..BorderSide::default()
2506        };
2507        let black_border = BorderSide::default();
2508        let side = |first: BorderSide, rest: BorderSide| {
2509            WidgetStateBorderSide::from_map(vec![
2510                (WidgetState::Focused | WidgetState::Hovered, Some(first)),
2511                (WidgetState::any(), Some(rest)),
2512            ])
2513            .into_any()
2514        };
2515        assert!(side(white_border, black_border) == side(white_border, black_border));
2516        assert!(side(white_border, black_border) != side(black_border, white_border));
2517
2518        let rrect = |side: BorderSide| -> OutlinedBorderRef {
2519            OutlinedBorderRef::new(RoundedRectangleBorder {
2520                side,
2521                ..RoundedRectangleBorder::default()
2522            })
2523        };
2524        let border = |first: BorderSide, rest: BorderSide| {
2525            WidgetStateOutlinedBorder::from_map(vec![
2526                (
2527                    WidgetState::Focused | WidgetState::Hovered,
2528                    Some(rrect(first)),
2529                ),
2530                (WidgetState::any(), Some(rrect(rest))),
2531            ])
2532        };
2533        assert!(border(white_border, black_border).eq_shape(&border(white_border, black_border)));
2534        assert!(!border(white_border, black_border).eq_shape(&border(black_border, white_border)));
2535
2536        let text = |first: Color, rest: Color| {
2537            WidgetStateTextStyle::from_map(vec![
2538                (
2539                    WidgetState::Focused | WidgetState::Hovered,
2540                    TextStyle::new().color(first),
2541                ),
2542                (WidgetState::any(), TextStyle::new().color(rest)),
2543            ])
2544            .into_any()
2545        };
2546        assert!(text(WHITE, BLACK) == text(WHITE, BLACK));
2547        assert!(text(WHITE, BLACK) != text(BLACK, WHITE));
2548    }
2549
2550    /// Not a Dart case: the `==` overrides of `widget_state.dart`, read through the erased
2551    /// property a theme stores.
2552    #[test]
2553    fn erased_properties_compare_as_darts_equality_overrides_do() {
2554        let all = |value: f64| <dyn WidgetStateProperty<f64>>::all(value);
2555        assert!(*all(1.0) == *all(1.0));
2556        assert!(*all(1.0) != *all(2.0));
2557
2558        let map = |first: Color, rest: Color| {
2559            <dyn WidgetStateProperty<Color>>::from_map(vec![
2560                (WidgetState::Disabled.into(), first),
2561                (WidgetState::any(), rest),
2562            ])
2563        };
2564        assert!(*map(WHITE, BLACK) == *map(WHITE, BLACK));
2565        assert!(*map(WHITE, BLACK) != *map(BLACK, WHITE));
2566        let mapped_color: WidgetStatePropertyRef<Color> =
2567            Rc::new(WidgetStateColor::from_map(vec![
2568                (WidgetState::Disabled.into(), WHITE),
2569                (WidgetState::any(), BLACK),
2570            ]));
2571        assert!(*map(WHITE, BLACK) == *mapped_color);
2572        assert!(*mapped_color == *map(WHITE, BLACK));
2573        assert!(*map(WHITE, BLACK) != *<dyn WidgetStateProperty<Color>>::all(WHITE));
2574
2575        let resolved = <dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0);
2576        assert!(*resolved == *Rc::clone(&resolved));
2577        assert!(*resolved != *<dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0));
2578
2579        let color = |value: Color| -> WidgetStatePropertyRef<Color> {
2580            Rc::new(WidgetStateColor::resolve_with(move |_| value))
2581        };
2582        assert!(*color(WHITE) == *color(WHITE));
2583        assert!(*color(WHITE) != *color(BLACK));
2584
2585        // Dart's `WidgetStatePropertyAll<Widget?>`: widgets compare by identity.
2586        use crate::framework::{IntoWidget, WidgetRef};
2587        let icon: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
2588        let widget = |widget: &WidgetRef| {
2589            <dyn WidgetStateProperty<Option<WidgetRef>>>::all(Some(Rc::clone(widget)))
2590        };
2591        assert!(*widget(&icon) == *widget(&icon));
2592        let other: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
2593        assert!(*widget(&icon) != *widget(&other));
2594    }
2595
2596    // widget_state_property_test.dart 'WidgetStateBorderSide.lerp()'.
2597    #[test]
2598    fn border_side_lerp_interpolates_the_resolved_sides() {
2599        let side_1: WidgetStatePropertyRef<Option<BorderSide>> =
2600            Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
2601                color: Color::new(0xffff0000),
2602                width: 4.0,
2603                ..BorderSide::default()
2604            })));
2605        let side_2: WidgetStatePropertyRef<Option<BorderSide>> =
2606            Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
2607                color: Color::new(0xff0000ff),
2608                width: 12.0,
2609                ..BorderSide::default()
2610            })));
2611        let lerp = |t: f64| {
2612            WidgetStateBorderSide::lerp(Some(Rc::clone(&side_1)), Some(Rc::clone(&side_2)), t)
2613                .expect("two sides")
2614                .resolve(&WidgetStates::new())
2615                .expect("a side")
2616        };
2617        assert_eq!(lerp(0.0).color, Color::new(0xffff0000));
2618        assert_eq!(lerp(0.0).width, 4.0);
2619        // Dart's `isSameColorAs` allows a rounding step per channel.
2620        #[allow(deprecated)]
2621        let (red, blue) = (lerp(0.5).color.red(), lerp(0.5).color.blue());
2622        assert!(
2623            (red - 0x7f).abs() <= 1 && (blue - 0x7f).abs() <= 1,
2624            "{:?}",
2625            lerp(0.5).color
2626        );
2627        assert_eq!(lerp(0.5).width, 8.0);
2628        assert_eq!(lerp(1.0).color, Color::new(0xff0000ff));
2629        assert_eq!(lerp(1.0).width, 12.0);
2630        assert!(WidgetStateBorderSide::lerp(None, None, 0.5).is_none());
2631    }
2632
2633    /// A widget-state side, border or style passed where Dart takes the plain value is the
2634    /// default value there and resolves through `resolve_as`.
2635    #[test]
2636    fn the_widget_state_values_are_their_default_and_resolve_through_resolve_as() {
2637        let pressed = states([WidgetState::Pressed]);
2638        let red_side = BorderSide {
2639            color: RED,
2640            ..BorderSide::default()
2641        };
2642        let side: Option<AnyBorderSide> = Some(
2643            WidgetStateBorderSide::resolve_with(move |states| {
2644                states.contains(&WidgetState::Pressed).then_some(red_side)
2645            })
2646            .into(),
2647        );
2648        assert_eq!(
2649            *side.as_ref().expect("a side").value(),
2650            BorderSide::default()
2651        );
2652        let resolved = <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &pressed);
2653        assert_eq!(resolved, Some(AnyBorderSide::new(red_side)));
2654        let resolved =
2655            <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &WidgetStates::new());
2656        assert_eq!(resolved, None);
2657
2658        let style: AnyTextStyle = WidgetStateTextStyle::resolve_with(|states| {
2659            TextStyle::new().font_size(if states.contains(&WidgetState::Pressed) {
2660                20.0
2661            } else {
2662                10.0
2663            })
2664        })
2665        .into();
2666        assert_eq!(*style.value(), TextStyle::new());
2667        let resolved = <dyn WidgetStateProperty<TextStyle>>::resolve_as(&style, &pressed);
2668        assert_eq!(resolved.font_size, Some(20.0));
2669
2670        let border: Option<OutlinedBorderRef> = Some(OutlinedBorderRef::new(
2671            WidgetStateOutlinedBorder::resolve_with(|states| {
2672                states.contains(&WidgetState::Pressed).then(|| {
2673                    OutlinedBorderRef::new(RoundedRectangleBorder {
2674                        side: BorderSide {
2675                            width: 3.0,
2676                            ..BorderSide::default()
2677                        },
2678                        ..RoundedRectangleBorder::default()
2679                    })
2680                })
2681            }),
2682        ));
2683        assert_eq!(
2684            border.as_ref().expect("a border").side(),
2685            RoundedRectangleBorder::default().side,
2686            "as a plain border it is the default rounded rectangle"
2687        );
2688        let resolved =
2689            <dyn WidgetStateProperty<Option<OutlinedBorderRef>>>::resolve_as(&border, &pressed)
2690                .expect("a border");
2691        assert_eq!(resolved.side().width, 3.0);
2692    }
2693
2694    #[test]
2695    fn clickable_resolves_to_basic_when_disabled_and_is_a_mouse_cursor() {
2696        let clickable = WidgetStateMouseCursor::clickable();
2697        assert!(
2698            *clickable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::CLICK.into())
2699        );
2700        assert!(
2701            *clickable.resolve(&states([WidgetState::Disabled]))
2702                == *cursor(SystemMouseCursors::BASIC.into())
2703        );
2704        assert_eq!(
2705            clickable.debug_description(),
2706            "WidgetStateMouseCursor(clickable)"
2707        );
2708
2709        let textable = WidgetStateMouseCursor::textable();
2710        assert!(
2711            *textable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::TEXT.into())
2712        );
2713
2714        // Dart's `static const` cursors are one object each, so they compare equal; a
2715        // `resolve_with` cursor is equal only to itself.
2716        let as_property =
2717            |cursor: WidgetStateMouseCursor| -> WidgetStatePropertyRef<MouseCursorRef> {
2718                Rc::new(cursor)
2719            };
2720        assert!(
2721            *as_property(WidgetStateMouseCursor::clickable())
2722                == *as_property(WidgetStateMouseCursor::clickable())
2723        );
2724        assert!(
2725            *as_property(WidgetStateMouseCursor::clickable())
2726                != *as_property(WidgetStateMouseCursor::textable())
2727        );
2728        let as_cursor = |cursor: WidgetStateMouseCursor| -> MouseCursorRef { Rc::new(cursor) };
2729        assert!(
2730            *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
2731                == *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
2732        );
2733        let resolve_click =
2734            |_: &WidgetStates| -> MouseCursorRef { SystemMouseCursors::CLICK.into() };
2735        assert!(
2736            *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
2737                != *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
2738        );
2739        assert!(
2740            *textable.resolve(&states([WidgetState::Disabled]))
2741                == *cursor(SystemMouseCursors::BASIC.into())
2742        );
2743
2744        // Used as a plain cursor, the session is the default-state cursor's.
2745        let session = clickable.create_session(1);
2746        assert!(*session.cursor() == *cursor(SystemMouseCursors::CLICK.into()));
2747        assert_eq!(session.device(), 1);
2748
2749        let erased: MouseCursorRef = clickable.into();
2750        assert!(erased.as_any().is::<WidgetStateMouseCursor>());
2751        assert!(
2752            *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
2753                &erased,
2754                &states([WidgetState::Disabled])
2755            ) == *cursor(SystemMouseCursors::BASIC.into())
2756        );
2757        assert!(
2758            *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
2759                &Some(Rc::clone(&erased)),
2760                &states([WidgetState::Disabled])
2761            )
2762            .expect("some")
2763                == *cursor(SystemMouseCursors::BASIC.into())
2764        );
2765        let plain = cursor(SystemMouseCursors::GRAB.into());
2766        assert!(Rc::ptr_eq(
2767            &<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&plain, &WidgetStates::new()),
2768            &plain
2769        ));
2770    }
2771
2772    // widget_state_mouse_cursor.0.dart: a cursor that is forbidden when disabled.
2773    #[test]
2774    fn a_resolve_with_cursor_can_forbid_when_disabled() {
2775        let cursor = WidgetStateMouseCursor::resolve_with(
2776            |states| {
2777                if states.contains(&WidgetState::Disabled) {
2778                    return SystemMouseCursors::FORBIDDEN.into();
2779                }
2780                SystemMouseCursors::CLICK.into()
2781            },
2782            None,
2783        );
2784        assert!(
2785            *cursor.resolve(&states([WidgetState::Disabled]))
2786                == *MouseCursorRef::from(SystemMouseCursors::FORBIDDEN)
2787        );
2788        assert!(
2789            *cursor.resolve(&WidgetStates::new())
2790                == *MouseCursorRef::from(SystemMouseCursors::CLICK)
2791        );
2792        assert_eq!(cursor.debug_description(), "WidgetStateMouseCursor()");
2793    }
2794
2795    // widget_states_controller_test.dart 'WidgetStatesController constructor'.
2796    #[test]
2797    fn controller_starts_with_the_given_states() {
2798        let cell = AppCell::new();
2799        let mut app = cell.borrow_mut();
2800        let empty = WidgetStatesController::new(&mut app, None);
2801        assert_eq!(*app.get(&empty).value(), WidgetStates::new());
2802        let selected = WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
2803        assert_eq!(*app.get(&selected).value(), states([WidgetState::Selected]));
2804    }
2805
2806    // widget_states_controller_test.dart 'WidgetStatesController update, listener'.
2807    #[test]
2808    fn controller_update_notifies_only_on_change() {
2809        let cell = AppCell::new();
2810        let mut app = cell.borrow_mut();
2811        let count = Rc::new(Cell::new(0));
2812        let value_changed = Listener::new({
2813            let count = Rc::clone(&count);
2814            move |_app| count.set(count.get() + 1)
2815        });
2816
2817        let controller = WidgetStatesController::new(&mut app, None);
2818        controller.add_listener(&mut app, value_changed.clone());
2819
2820        let expect = |app: &App, expected: &[WidgetState], expected_count: i32| {
2821            assert_eq!(
2822                *app.get(&controller).value(),
2823                states(expected.iter().copied())
2824            );
2825            assert_eq!(count.get(), expected_count);
2826        };
2827
2828        controller.update(&mut app, WidgetState::Selected, true);
2829        expect(&app, &[WidgetState::Selected], 1);
2830        controller.update(&mut app, WidgetState::Selected, true);
2831        expect(&app, &[WidgetState::Selected], 1);
2832
2833        controller.update(&mut app, WidgetState::Hovered, false);
2834        expect(&app, &[WidgetState::Selected], 1);
2835        controller.update(&mut app, WidgetState::Selected, false);
2836        expect(&app, &[], 2);
2837
2838        controller.update(&mut app, WidgetState::Hovered, true);
2839        expect(&app, &[WidgetState::Hovered], 3);
2840        controller.update(&mut app, WidgetState::Hovered, true);
2841        expect(&app, &[WidgetState::Hovered], 3);
2842        controller.update(&mut app, WidgetState::Pressed, true);
2843        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 4);
2844        controller.update(&mut app, WidgetState::Selected, true);
2845        expect(
2846            &app,
2847            &[
2848                WidgetState::Hovered,
2849                WidgetState::Pressed,
2850                WidgetState::Selected,
2851            ],
2852            5,
2853        );
2854        controller.update(&mut app, WidgetState::Selected, false);
2855        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
2856        controller.update(&mut app, WidgetState::Selected, false);
2857        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
2858        controller.update(&mut app, WidgetState::Pressed, false);
2859        expect(&app, &[WidgetState::Hovered], 7);
2860        controller.update(&mut app, WidgetState::Hovered, false);
2861        expect(&app, &[], 8);
2862
2863        controller.remove_listener(&mut app, &value_changed);
2864        controller.update(&mut app, WidgetState::Selected, true);
2865        expect(&app, &[WidgetState::Selected], 8);
2866    }
2867
2868    // widget_states_controller_test.dart 'WidgetStatesController const initial value'.
2869    #[test]
2870    fn controller_with_an_initial_value_notifies_only_on_change() {
2871        let cell = AppCell::new();
2872        let mut app = cell.borrow_mut();
2873        let count = Rc::new(Cell::new(0));
2874        let controller =
2875            WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
2876        controller.add_listener(&mut app, {
2877            let count = Rc::clone(&count);
2878            Listener::new(move |_app| count.set(count.get() + 1))
2879        });
2880
2881        controller.update(&mut app, WidgetState::Selected, true);
2882        assert_eq!(
2883            *app.get(&controller).value(),
2884            states([WidgetState::Selected])
2885        );
2886        assert_eq!(count.get(), 0);
2887
2888        controller.update(&mut app, WidgetState::Selected, false);
2889        assert_eq!(*app.get(&controller).value(), WidgetStates::new());
2890        assert_eq!(count.get(), 1);
2891
2892        controller.set_value(&mut app, states([WidgetState::Hovered]));
2893        assert_eq!(count.get(), 2);
2894        controller.set_value(&mut app, states([WidgetState::Hovered]));
2895        assert_eq!(count.get(), 2);
2896
2897        controller.dispose(&mut app);
2898        assert!(!app.get(&controller).change_notifier_data().has_listeners());
2899    }
2900}