Skip to main content

waft_material/
material_state.rs

1//! Flutter counterpart: material_ui's `material_state.dart`.
2//!
3//! The deprecated Material names of the widgets layer's `widget_state.rs` types, as Dart's
4//! typedefs are. `MaterialStateProperty` is the erased property type
5//! `dyn WidgetStateProperty<T>`: Rust has no stable alias of a trait, so a type implements
6//! [`WidgetStateProperty`] by that name. The input borders that are also properties
7//! (`MaterialStateOutlineInputBorder`, `MaterialStateUnderlineInputBorder`,
8//! `WidgetStateInputBorder`) implement [`InputBorder`] by delegating to the plain border their
9//! Dart class extends.
10
11use std::any::Any;
12use std::fmt::{self, Debug};
13use std::rc::Rc;
14
15use waft_embedder::{Canvas, Paint, Path, Rect};
16use waft_painting::{BorderSide, EdgeInsetsGeometry, ShapeBorder, ShapeBorderRef, TextDirection};
17use waft_widgets::{
18    WidgetPropertyResolver, WidgetState, WidgetStateBorderSide, WidgetStateColor, WidgetStateMap,
19    WidgetStateMapper, WidgetStateMouseCursor, WidgetStateOutlinedBorder, WidgetStateProperty,
20    WidgetStatePropertyAll, WidgetStateTextStyle, WidgetStates, WidgetStatesController,
21};
22
23use crate::input_border::{InputBorder, InputBorderRef, OutlineInputBorder, UnderlineInputBorder};
24
25/// Interactive states that some of the Material widgets can take on when
26/// receiving input from the user.
27///
28/// States are defined by <https://material.io/design/interaction/states.html#usage>.
29///
30/// Some Material widgets track their current state in a `Set<MaterialState>`.
31///
32/// See also:
33///
34///  * [`WidgetState`], a general non-Material version that can be used
35///    interchangeably with `MaterialState`. They functionally work the same,
36///    except [`WidgetState`] can be used outside of Material.
37///  * [`MaterialStateProperty`], an interface for objects that "resolve" to
38///    different values depending on a widget's material state.
39///  * [`MaterialStateColor`], a `Color` that implements `MaterialStateProperty`
40///    which is used in APIs that need to accept either a `Color` or a
41///    `MaterialStateProperty<Color>`.
42///  * [`MaterialStateMouseCursor`], a `MouseCursor` that implements
43///    `MaterialStateProperty` which is used in APIs that need to accept either
44///    a `MouseCursor` or a `MaterialStateProperty<MouseCursor>`.
45///  * [`MaterialStateOutlinedBorder`], an `OutlinedBorder` that implements
46///    `MaterialStateProperty` which is used in APIs that need to accept either
47///    an `OutlinedBorder` or a `MaterialStateProperty<OutlinedBorder>`.
48///  * `MaterialStateOutlineInputBorder`, an `OutlineInputBorder` that implements
49///    `MaterialStateProperty` which is used in APIs that need to accept either
50///    an `OutlineInputBorder` or a `MaterialStateProperty<OutlineInputBorder>`.
51///  * `MaterialStateUnderlineInputBorder`, an `UnderlineInputBorder` that implements
52///    `MaterialStateProperty` which is used in APIs that need to accept either
53///    an `UnderlineInputBorder` or a `MaterialStateProperty<UnderlineInputBorder>`.
54///  * [`MaterialStateBorderSide`], a `BorderSide` that implements
55///    `MaterialStateProperty` which is used in APIs that need to accept either
56///    a `BorderSide` or a `MaterialStateProperty<BorderSide>`.
57///  * [`MaterialStateTextStyle`], a `TextStyle` that implements
58///    `MaterialStateProperty` which is used in APIs that need to accept either
59///    a `TextStyle` or a `MaterialStateProperty<TextStyle>`.
60#[deprecated(
61    note = "Use WidgetState instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
62)]
63pub type MaterialState = WidgetState;
64
65/// Signature for the function that returns a value of type `T` based on a given
66/// set of states.
67///
68/// See also:
69///
70///  * [`WidgetPropertyResolver`], the non-Material form of `MaterialPropertyResolver`
71///    that can be used interchangeably with `MaterialPropertyResolver`.
72#[deprecated(
73    note = "Use WidgetPropertyResolver instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
74)]
75pub type MaterialPropertyResolver<T> = WidgetPropertyResolver<T>;
76
77/// Defines a `Color` that is also a [`MaterialStateProperty`].
78///
79/// This class exists to enable widgets with `Color` valued properties
80/// to also accept `MaterialStateProperty<Color>` values. A material
81/// state color property represents a color which depends on
82/// a widget's "interactive state". This state is represented as a
83/// set of [`MaterialState`]s, like [`WidgetState::Pressed`],
84/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
85///
86/// [`MaterialStateColor`] should only be used with widgets that document
87/// their support, like `TimePickerThemeData.dayPeriodColor`.
88///
89/// To use a [`MaterialStateColor`], use [`WidgetStateColor::resolve_with`] and pass in a
90/// callback that will be used to resolve the color in the given states.
91///
92/// If a [`MaterialStateColor`] is used for a property or a parameter that doesn't
93/// support resolving `MaterialStateProperty<Color>`s, then its default color
94/// value will be used for all states.
95///
96/// See also
97///
98///  * [`WidgetStateColor`], the non-Material version that can be used
99///    interchangeably with `MaterialStateColor`.
100#[deprecated(
101    note = "Use WidgetStateColor instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
102)]
103pub type MaterialStateColor = WidgetStateColor;
104
105/// Defines a `MouseCursor` whose value depends on a set of [`MaterialState`]s which
106/// represent the interactive state of a component.
107///
108/// This kind of `MouseCursor` is useful when the set of interactive
109/// actions a widget supports varies with its state. For example, a
110/// mouse pointer hovering over a disabled `ListTile` should not
111/// display `SystemMouseCursors.click`, since a disabled list tile
112/// doesn't respond to mouse clicks. `ListTile`'s default mouse cursor
113/// is a [`WidgetStateMouseCursor::clickable`], which resolves to
114/// `SystemMouseCursors.basic` when the button is disabled.
115///
116/// This class should only be used for parameters which are documented to take
117/// [`MaterialStateMouseCursor`], otherwise only the default state will be used.
118///
119/// See also:
120///
121///  * [`WidgetStateMouseCursor`], the non-Material version that can be used
122///    interchangeably with `MaterialStateMouseCursor`.
123///  * `MouseCursor` for introduction on the mouse cursor system.
124///  * `SystemMouseCursors`, which defines cursors that are supported by
125///    native platforms.
126#[deprecated(
127    note = "Use WidgetStateMouseCursor instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
128)]
129pub type MaterialStateMouseCursor = WidgetStateMouseCursor;
130
131/// Defines a `BorderSide` whose value depends on a set of [`MaterialState`]s
132/// which represent the interactive state of a component.
133///
134/// This class enables existing widget implementations with `BorderSide`
135/// properties to be extended to also effectively support `MaterialStateProperty<BorderSide>`
136/// property values. [`MaterialStateBorderSide`] should only be used with widgets that document
137/// their support, like `ActionChip.side`.
138///
139/// This class should only be used for parameters which are documented to take
140/// [`MaterialStateBorderSide`], otherwise only the default state will be used.
141///
142/// See also:
143///
144///  * [`WidgetStateBorderSide`], the non-Material version that can be used
145///    interchangeably with `MaterialStateBorderSide`.
146#[deprecated(
147    note = "Use WidgetStateBorderSide instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
148)]
149pub type MaterialStateBorderSide = WidgetStateBorderSide;
150
151/// Defines an `OutlinedBorder` whose value depends on a set of [`MaterialState`]s
152/// which represent the interactive state of a component.
153///
154/// This class should only be used for parameters which are documented to take
155/// [`MaterialStateOutlinedBorder`], otherwise only the default state will be used.
156///
157/// See also:
158///
159///  * [`WidgetStateOutlinedBorder`], the non-Material version that can be used
160///    interchangeably with `MaterialStateOutlinedBorder`.
161///  * `ShapeBorder` the base class for shape outlines.
162#[deprecated(
163    note = "Use WidgetStateOutlinedBorder instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
164)]
165pub type MaterialStateOutlinedBorder = WidgetStateOutlinedBorder;
166
167/// Defines a `TextStyle` that is also a [`MaterialStateProperty`].
168///
169/// This class exists to enable widgets with `TextStyle` valued properties
170/// to also accept `MaterialStateProperty<TextStyle>` values. A material
171/// state text style property represents a text style which depends on
172/// a widget's "interactive state". This state is represented as a
173/// set of [`MaterialState`]s, like [`WidgetState::Pressed`],
174/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
175///
176/// [`MaterialStateTextStyle`] should only be used with widgets that document
177/// their support, like `InputDecoration.labelStyle`.
178///
179/// To use a [`MaterialStateTextStyle`], use [`WidgetStateTextStyle::resolve_with`] and pass
180/// in a callback that will be used to resolve the color in the given states.
181///
182/// If a [`MaterialStateTextStyle`] is used for a property or a parameter that doesn't
183/// support resolving `MaterialStateProperty<TextStyle>`s, then its default color
184/// value will be used for all states.
185///
186/// See also:
187///
188///  * [`WidgetStateTextStyle`], the non-Material version that can be used
189///    interchangeably with `MaterialStateTextStyle`.
190#[deprecated(
191    note = "Use WidgetStateTextStyle instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
192)]
193pub type MaterialStateTextStyle = WidgetStateTextStyle;
194
195/// The `ShapeBorder` and `InputBorder` members of an input border that is also a
196/// `WidgetStateProperty<InputBorder>`: those of the plain border Dart's class extends,
197/// held in `self.border`, with `as_widget_state_property` answering the type itself.
198macro_rules! state_input_border {
199    ($name:ty, $debug:literal) => {
200        #[allow(deprecated)]
201        impl ShapeBorder for $name {
202            fn dimensions(&self) -> EdgeInsetsGeometry {
203                self.border.dimensions()
204            }
205
206            fn scale(&self, t: f64) -> ShapeBorderRef {
207                ShapeBorder::scale(&self.border, t)
208            }
209
210            fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
211                self.border.lerp_from(a, t)
212            }
213
214            fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
215                self.border.lerp_to(b, t)
216            }
217
218            fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
219                self.border.get_outer_path(rect, text_direction)
220            }
221
222            fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
223                self.border.get_inner_path(rect, text_direction)
224            }
225
226            fn paint_interior(
227                &self,
228                canvas: &mut Canvas,
229                rect: Rect,
230                paint: &Paint,
231                text_direction: Option<TextDirection>,
232            ) {
233                self.border
234                    .paint_interior(canvas, rect, paint, text_direction);
235            }
236
237            fn prefer_paint_interior(&self) -> bool {
238                self.border.prefer_paint_interior()
239            }
240
241            fn paint(
242                &self,
243                canvas: &mut Canvas,
244                rect: Rect,
245                text_direction: Option<TextDirection>,
246            ) {
247                ShapeBorder::paint(&self.border, canvas, rect, text_direction);
248            }
249
250            fn as_any(&self) -> &dyn Any {
251                self
252            }
253
254            fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
255                other
256                    .as_any()
257                    .downcast_ref::<$name>()
258                    .is_some_and(|other| self.eq_subclass(other))
259            }
260        }
261
262        #[allow(deprecated)]
263        impl InputBorder for $name {
264            fn border_side(&self) -> BorderSide {
265                self.border.border_side
266            }
267
268            fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
269                InputBorder::copy_with(&self.border, border_side)
270            }
271
272            fn is_outline(&self) -> bool {
273                self.border.is_outline()
274            }
275
276            fn paint(
277                &self,
278                canvas: &mut Canvas,
279                rect: Rect,
280                gap_start: Option<f64>,
281                gap_extent: f64,
282                gap_percentage: f64,
283                text_direction: Option<TextDirection>,
284            ) {
285                InputBorder::paint(
286                    &self.border,
287                    canvas,
288                    rect,
289                    gap_start,
290                    gap_extent,
291                    gap_percentage,
292                    text_direction,
293                );
294            }
295
296            fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<InputBorderRef>> {
297                Some(self)
298            }
299        }
300
301        #[allow(deprecated)]
302        impl Debug for $name {
303            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304                f.write_str($debug)
305            }
306        }
307    };
308}
309
310/// Defines a [`OutlineInputBorder`] that is also a [`MaterialStateProperty`].
311///
312/// This class exists to enable widgets with [`OutlineInputBorder`] valued properties
313/// to also accept `MaterialStateProperty<OutlineInputBorder>` values. A material
314/// state input border property represents an input border which depends on
315/// a widget's "interactive state". This state is represented as a
316/// set of [`MaterialState`]s, like [`WidgetState::Pressed`],
317/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
318///
319/// [`MaterialStateOutlineInputBorder`] should only be used with widgets that document
320/// their support, like `InputDecoration.border`.
321///
322/// To use a [`MaterialStateOutlineInputBorder`], use
323/// [`MaterialStateOutlineInputBorder::resolve_with`] and pass in a callback that
324/// will be used to resolve the color in the given states.
325///
326/// If a [`MaterialStateOutlineInputBorder`] is used for a property or a parameter that doesn't
327/// support resolving `MaterialStateProperty<OutlineInputBorder>`s, then its default color
328/// value will be used for all states.
329///
330/// It is itself an [`InputBorder`]: the default `OutlineInputBorder()` it extends in Dart.
331#[deprecated(
332    note = "Use WidgetStateInputBorder instead. Renamed to match other WidgetStateProperty objects. This feature was deprecated after v3.26.0-0.1.pre."
333)]
334#[derive(Clone)]
335pub struct MaterialStateOutlineInputBorder {
336    /// Dart's `_MaterialStateOutlineInputBorder._resolve`.
337    resolve: WidgetPropertyResolver<InputBorderRef>,
338    /// Dart's `super`: `MaterialStateOutlineInputBorder extends OutlineInputBorder`.
339    border: OutlineInputBorder,
340}
341
342#[allow(deprecated)]
343impl MaterialStateOutlineInputBorder {
344    /// Creates a [`MaterialStateOutlineInputBorder`] from a
345    /// `MaterialPropertyResolver<InputBorder>` callback function.
346    ///
347    /// If used as a regular input border, the border resolved in the default state (the
348    /// empty set of states) will be used.
349    ///
350    /// The given callback parameter must return a non-null text style in the default
351    /// state.
352    #[deprecated(
353        note = "Use WidgetStateInputBorder.resolveWith() instead. Renamed to match other WidgetStateProperty objects. This feature was deprecated after v3.26.0-0.1.pre."
354    )]
355    pub fn resolve_with(
356        callback: impl Fn(&WidgetStates) -> InputBorderRef + 'static,
357    ) -> MaterialStateOutlineInputBorder {
358        MaterialStateOutlineInputBorder {
359            resolve: Rc::new(callback),
360            border: OutlineInputBorder::new(),
361        }
362    }
363
364    // Dart's `OutlineInputBorder.==`: the same runtime type and fields.
365    fn eq_subclass(&self, other: &MaterialStateOutlineInputBorder) -> bool {
366        self.border == other.border
367    }
368}
369
370/// Returns a [`InputBorder`] that's to be used when a Material component is in the
371/// specified state.
372#[allow(deprecated)]
373impl WidgetStateProperty<InputBorderRef> for MaterialStateOutlineInputBorder {
374    fn resolve(&self, states: &WidgetStates) -> InputBorderRef {
375        (self.resolve)(states)
376    }
377
378    fn as_any(&self) -> &dyn Any {
379        self
380    }
381
382    fn eq_property(&self, other: &dyn WidgetStateProperty<InputBorderRef>) -> bool {
383        other
384            .as_any()
385            .downcast_ref::<Self>()
386            .is_some_and(|other| self.eq_subclass(other))
387    }
388}
389
390state_input_border!(
391    MaterialStateOutlineInputBorder,
392    "_MaterialStateOutlineInputBorder()"
393);
394
395/// Defines a [`UnderlineInputBorder`] that is also a [`MaterialStateProperty`].
396///
397/// This class exists to enable widgets with [`UnderlineInputBorder`] valued properties
398/// to also accept `MaterialStateProperty<UnderlineInputBorder>` values. A material
399/// state input border property represents an input border which depends on
400/// a widget's "interactive state". This state is represented as a
401/// set of [`MaterialState`]s, like [`WidgetState::Pressed`],
402/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
403///
404/// [`MaterialStateUnderlineInputBorder`] should only be used with widgets that document
405/// their support, like `InputDecoration.border`.
406///
407/// To use a [`MaterialStateUnderlineInputBorder`], use
408/// [`MaterialStateUnderlineInputBorder::resolve_with`] and pass in a callback that
409/// will be used to resolve the color in the given states.
410///
411/// If a [`MaterialStateUnderlineInputBorder`] is used for a property or a parameter that doesn't
412/// support resolving `MaterialStateProperty<UnderlineInputBorder>`s, then its default color
413/// value will be used for all states.
414///
415/// It is itself an [`InputBorder`]: the default `UnderlineInputBorder()` it extends in Dart.
416#[deprecated(
417    note = "Use WidgetStateInputBorder instead. Renamed to match other WidgetStateProperty objects. This feature was deprecated after v3.26.0-0.1.pre."
418)]
419#[derive(Clone)]
420pub struct MaterialStateUnderlineInputBorder {
421    /// Dart's `_MaterialStateUnderlineInputBorder._resolve`.
422    resolve: WidgetPropertyResolver<InputBorderRef>,
423    /// Dart's `super`: `MaterialStateUnderlineInputBorder extends UnderlineInputBorder`.
424    border: UnderlineInputBorder,
425}
426
427#[allow(deprecated)]
428impl MaterialStateUnderlineInputBorder {
429    /// Creates a [`MaterialStateUnderlineInputBorder`] from a
430    /// `MaterialPropertyResolver<InputBorder>` callback function.
431    ///
432    /// If used as a regular input border, the border resolved in the default state (the
433    /// empty set of states) will be used.
434    ///
435    /// The given callback parameter must return a non-null text style in the default
436    /// state.
437    #[deprecated(
438        note = "Use WidgetStateInputBorder.resolveWith() instead. Renamed to match other WidgetStateProperty objects. This feature was deprecated after v3.26.0-0.1.pre."
439    )]
440    pub fn resolve_with(
441        callback: impl Fn(&WidgetStates) -> InputBorderRef + 'static,
442    ) -> MaterialStateUnderlineInputBorder {
443        MaterialStateUnderlineInputBorder {
444            resolve: Rc::new(callback),
445            border: UnderlineInputBorder::new(),
446        }
447    }
448
449    // Dart's `UnderlineInputBorder.==`: the same runtime type and fields.
450    fn eq_subclass(&self, other: &MaterialStateUnderlineInputBorder) -> bool {
451        self.border == other.border
452    }
453}
454
455/// Returns a [`InputBorder`] that's to be used when a Material component is in the
456/// specified state.
457#[allow(deprecated)]
458impl WidgetStateProperty<InputBorderRef> for MaterialStateUnderlineInputBorder {
459    fn resolve(&self, states: &WidgetStates) -> InputBorderRef {
460        (self.resolve)(states)
461    }
462
463    fn as_any(&self) -> &dyn Any {
464        self
465    }
466
467    fn eq_property(&self, other: &dyn WidgetStateProperty<InputBorderRef>) -> bool {
468        other
469            .as_any()
470            .downcast_ref::<Self>()
471            .is_some_and(|other| self.eq_subclass(other))
472    }
473}
474
475state_input_border!(
476    MaterialStateUnderlineInputBorder,
477    "_MaterialStateUnderlineInputBorder()"
478);
479
480/// Defines an [`InputBorder`] that is also a [`WidgetStateProperty`].
481///
482/// This class exists to enable widgets with [`InputBorder`] valued properties
483/// to also accept [`WidgetStateProperty`] objects.
484///
485/// [`WidgetStateInputBorder`] should only be used with widgets that document
486/// their support, like `InputDecoration.border`.
487///
488/// A [`WidgetStateInputBorder`] can be created by:
489///  1. Using [`WidgetStateInputBorder::resolve_with`] with a callback that
490///     resolves the input border in the given states.
491///  2. Using [`WidgetStateInputBorder::from_map`] to assign a border with a
492///     [`WidgetStateMap`].
493///
494/// It is itself an [`InputBorder`]: the default `OutlineInputBorder()` that Dart's
495/// `_WidgetStateInputBorder` extends, for a map-built one too.
496#[derive(Clone)]
497pub struct WidgetStateInputBorder {
498    subclass: InputBorderSubclass,
499    /// Dart's `super`: `_WidgetStateInputBorder extends OutlineInputBorder`.
500    border: OutlineInputBorder,
501}
502
503/// Dart's two private implementations of `WidgetStateInputBorder`.
504#[derive(Clone)]
505enum InputBorderSubclass {
506    /// `_WidgetStateInputBorder`.
507    ResolveWith(WidgetPropertyResolver<InputBorderRef>),
508    /// `_WidgetInputBorderMapper`.
509    Mapper(Rc<WidgetStateMapper<InputBorderRef>>),
510}
511
512impl WidgetStateInputBorder {
513    /// Creates a [`WidgetStateInputBorder`] using a [`WidgetPropertyResolver`]
514    /// callback.
515    ///
516    /// This constructor should only be used for fields that support
517    /// [`WidgetStateInputBorder`], such as `InputDecoration.border`
518    /// (if used as a regular [`InputBorder`], it acts the same as
519    /// an empty `OutlineInputBorder()` constructor).
520    pub fn resolve_with(
521        callback: impl Fn(&WidgetStates) -> InputBorderRef + 'static,
522    ) -> WidgetStateInputBorder {
523        WidgetStateInputBorder {
524            subclass: InputBorderSubclass::ResolveWith(Rc::new(callback)),
525            border: OutlineInputBorder::new(),
526        }
527    }
528
529    /// Creates a [`WidgetStateInputBorder`] from a [`WidgetStateMap`].
530    ///
531    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
532    /// entry whose key is satisfied by the set of states, and returns its associated value.
533    /// It should only be used for fields that support [`WidgetStateInputBorder`]
534    /// objects, such as `InputDecoration.border`.
535    pub fn from_map(map: WidgetStateMap<InputBorderRef>) -> WidgetStateInputBorder {
536        WidgetStateInputBorder {
537            subclass: InputBorderSubclass::Mapper(Rc::new(WidgetStateMapper::new(map))),
538            border: OutlineInputBorder::new(),
539        }
540    }
541
542    // `_WidgetStateInputBorder` has `OutlineInputBorder.==` (the same runtime type and
543    // fields); the mapper has `WidgetStateMapper.==`, which compares maps.
544    fn eq_subclass(&self, other: &WidgetStateInputBorder) -> bool {
545        match (&self.subclass, &other.subclass) {
546            (InputBorderSubclass::ResolveWith(_), InputBorderSubclass::ResolveWith(_)) => {
547                self.border == other.border
548            }
549            (InputBorderSubclass::Mapper(mine), InputBorderSubclass::Mapper(theirs)) => {
550                mine == theirs
551            }
552            _ => false,
553        }
554    }
555}
556
557impl WidgetStateProperty<InputBorderRef> for WidgetStateInputBorder {
558    fn resolve(&self, states: &WidgetStates) -> InputBorderRef {
559        match &self.subclass {
560            InputBorderSubclass::ResolveWith(resolve) => resolve(states),
561            InputBorderSubclass::Mapper(mapper) => mapper.resolve(states),
562        }
563    }
564
565    fn as_any(&self) -> &dyn Any {
566        self
567    }
568
569    fn as_mapper(&self) -> Option<&WidgetStateMapper<InputBorderRef>> {
570        match &self.subclass {
571            InputBorderSubclass::Mapper(mapper) => Some(mapper.as_ref()),
572            InputBorderSubclass::ResolveWith(_) => None,
573        }
574    }
575
576    fn eq_property(&self, other: &dyn WidgetStateProperty<InputBorderRef>) -> bool {
577        if let InputBorderSubclass::Mapper(mapper) = &self.subclass {
578            return mapper.eq_property(other);
579        }
580        other
581            .as_any()
582            .downcast_ref::<Self>()
583            .is_some_and(|other| self.eq_subclass(other))
584    }
585}
586
587state_input_border!(WidgetStateInputBorder, "_WidgetStateInputBorder()");
588
589/// Interface for classes that [`resolve`](WidgetStateProperty::resolve) to a value of
590/// type `T` based on a widget's interactive "state", which is defined as a set
591/// of [`MaterialState`]s.
592///
593/// Material state properties represent values that depend on a widget's material
594/// "state". The state is encoded as a set of [`MaterialState`] values, like
595/// [`WidgetState::Focused`], [`WidgetState::Hovered`], [`WidgetState::Pressed`]. For
596/// example the `InkWell.overlayColor` defines the color that fills the ink well
597/// when it's pressed (the "splash color"), focused, or hovered. The `InkWell`
598/// uses the overlay color's [`resolve`](WidgetStateProperty::resolve) method to compute
599/// the color for the ink well's current state.
600///
601/// `ButtonStyle`, which is used to configure the appearance of
602/// buttons like `TextButton`, `ElevatedButton`, and `OutlinedButton`,
603/// has many material state properties. The button widgets keep track
604/// of their current material state and [`resolve`](WidgetStateProperty::resolve) the
605/// button style's material state properties when their value is needed.
606///
607/// This is the erased property, `dyn WidgetStateProperty<T>`: Dart's static members are
608/// reached through it (`<MaterialStateProperty<Color>>::resolve_with(..)`), and a type
609/// implements [`WidgetStateProperty`] itself.
610///
611/// See also:
612///
613///  * [`WidgetStateProperty`], the non-Material version that can be used
614///    interchangeably with `MaterialStateProperty`.
615#[deprecated(
616    note = "Use WidgetStateProperty instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
617)]
618pub type MaterialStateProperty<T> = dyn WidgetStateProperty<T>;
619
620/// Convenience class for creating a [`MaterialStateProperty`] that
621/// resolves to the given value for all states.
622///
623/// See also:
624///
625///  * [`WidgetStatePropertyAll`], the non-Material version that can be used
626///    interchangeably with `MaterialStatePropertyAll`.
627#[deprecated(
628    note = "Use WidgetStatePropertyAll instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
629)]
630pub type MaterialStatePropertyAll<T> = WidgetStatePropertyAll<T>;
631
632/// Manages a set of [`MaterialState`]s and notifies listeners of changes.
633///
634/// Used by widgets that expose their internal state for the sake of
635/// extensions that add support for additional states. See
636/// `TextButton` for an example.
637///
638/// The controller's [`value`](WidgetStatesController::value) is its current set of
639/// states. Listeners are notified whenever the
640/// [`value`](WidgetStatesController::value) changes. The
641/// [`value`](WidgetStatesController::value) should only be changed with
642/// [`update`](WidgetStatesController::update); it should not be modified directly.
643///
644/// The controller's [`value`](WidgetStatesController::value) represents the set of
645/// states that a widget's visual properties, typically [`MaterialStateProperty`]
646/// values, are resolved against. It is _not_ the intrinsic state of
647/// the widget. The widget is responsible for ensuring that the
648/// controller's [`value`](WidgetStatesController::value) tracks its intrinsic state.
649/// For example one cannot request the keyboard focus for a widget by adding
650/// [`WidgetState::Focused`] to its controller. When the widget gains or loses the
651/// focus it will [`update`](WidgetStatesController::update) its controller's
652/// [`value`](WidgetStatesController::value) and notify listeners of the change.
653///
654/// When calling `set_state` in a [`MaterialStatesController`] listener, use the
655/// `SchedulerBinding::add_post_frame_callback` to delay the call to `set_state` after
656/// the frame has been rendered. It's generally prudent to use the
657/// `SchedulerBinding::add_post_frame_callback` because some of the widgets that
658/// depend on [`MaterialStatesController`] may call
659/// [`update`](WidgetStatesController::update) in their build method.
660/// In such cases, listener's that call `set_state` - during the build phase - will cause
661/// an error.
662///
663/// See also:
664///
665///  * [`WidgetStatesController`], the non-Material version that can be used
666///    interchangeably with `MaterialStatesController`.
667#[deprecated(
668    note = "Use WidgetStatesController instead. Moved to the Widgets layer to make code available outside of Material. This feature was deprecated after v3.19.0-0.3.pre."
669)]
670pub type MaterialStatesController = WidgetStatesController;
671
672#[cfg(test)]
673#[allow(deprecated)]
674mod tests {
675    use std::cell::Cell;
676    use std::rc::Rc;
677
678    use waft_embedder::Color;
679    use waft_foundation::{AppCell, ChangeNotifier, Listenable, Listener};
680    use waft_painting::TextStyle;
681    use waft_widgets::WidgetStates;
682
683    use super::*;
684
685    const EVERY_STATE: [MaterialState; 7] = [
686        MaterialState::Hovered,
687        MaterialState::Focused,
688        MaterialState::Pressed,
689        MaterialState::Dragged,
690        MaterialState::Selected,
691        MaterialState::Disabled,
692        MaterialState::Error,
693    ];
694
695    fn states(states: impl IntoIterator<Item = MaterialState>) -> WidgetStates {
696        states.into_iter().collect()
697    }
698
699    // material_state_property_test.dart 'MaterialStateProperty.resolveWith()'.
700    #[test]
701    fn resolve_with_resolves_through_the_callback() {
702        let value: Rc<MaterialStateProperty<MaterialState>> =
703            <MaterialStateProperty<MaterialState>>::resolve_with(|states| {
704                states.iter().next().copied().expect("one state")
705            });
706        for state in EVERY_STATE {
707            assert_eq!(value.resolve(&states([state])), state);
708        }
709    }
710
711    // material_state_property_test.dart 'MaterialStateProperty.all()'.
712    #[test]
713    fn all_resolves_to_its_value_for_every_state() {
714        let value: Rc<MaterialStateProperty<i32>> = <MaterialStateProperty<i32>>::all(123);
715        for state in EVERY_STATE {
716            assert_eq!(value.resolve(&states([state])), 123);
717        }
718    }
719
720    // material_state_property_test.dart 'MaterialStatePropertyAll'.
721    #[test]
722    fn material_state_property_all_resolves_to_its_value_for_every_state() {
723        let value = MaterialStatePropertyAll::new(123);
724        assert_eq!(value.resolve(&WidgetStates::new()), 123);
725        for state in EVERY_STATE {
726            assert_eq!(value.resolve(&states([state])), 123);
727        }
728    }
729
730    // material_state_property_test.dart 'toString formats correctly'.
731    #[test]
732    fn a_material_state_property_all_prints_as_a_widget_state_property_all() {
733        let color_property = MaterialStatePropertyAll::new(Some(Color::new(0xFFFFFFFF)));
734        assert_eq!(
735            format!("{color_property:?}"),
736            format!("WidgetStatePropertyAll({:?})", Some(Color::new(0xffffffff)))
737        );
738    }
739
740    // material_state_property_test.dart "Can interpolate between two MaterialStateProperty's".
741    #[test]
742    fn lerp_interpolates_the_resolved_values() {
743        let enabled = WidgetStates::new();
744        let text_style_1: Rc<MaterialStateProperty<TextStyle>> = Rc::new(
745            MaterialStatePropertyAll::new(TextStyle::new().font_size(14.0)),
746        );
747        let text_style_2: Rc<MaterialStateProperty<TextStyle>> = Rc::new(
748            MaterialStatePropertyAll::new(TextStyle::new().font_size(20.0)),
749        );
750        let lerp = |t: f64| {
751            <MaterialStateProperty<TextStyle>>::lerp(
752                Some(Rc::clone(&text_style_1)),
753                Some(Rc::clone(&text_style_2)),
754                t,
755                |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
756            )
757            .expect("one side")
758            .resolve(&enabled)
759            .expect("both sides")
760            .font_size
761        };
762        assert_eq!(lerp(0.0), Some(14.0));
763        assert_eq!(lerp(0.5), Some(17.0));
764        assert_eq!(lerp(1.0), Some(20.0));
765    }
766
767    // material_states_controller_test.dart 'MaterialStatesController constructor'.
768    #[test]
769    fn controller_starts_with_the_given_states() {
770        let cell = AppCell::new();
771        let mut app = cell.borrow_mut();
772        let none = MaterialStatesController::new(&mut app, None);
773        assert_eq!(*app.get(&none).value(), WidgetStates::new());
774        let empty = MaterialStatesController::new(&mut app, Some(WidgetStates::new()));
775        assert_eq!(*app.get(&empty).value(), WidgetStates::new());
776        let selected =
777            MaterialStatesController::new(&mut app, Some(states([MaterialState::Selected])));
778        assert_eq!(
779            *app.get(&selected).value(),
780            states([MaterialState::Selected])
781        );
782    }
783
784    // material_states_controller_test.dart 'MaterialStatesController update, listener'.
785    #[test]
786    fn controller_update_notifies_only_on_change() {
787        let cell = AppCell::new();
788        let mut app = cell.borrow_mut();
789        let count = Rc::new(Cell::new(0));
790        let value_changed = Listener::new({
791            let count = Rc::clone(&count);
792            move |_app| count.set(count.get() + 1)
793        });
794
795        let controller = MaterialStatesController::new(&mut app, None);
796        controller.add_listener(&mut app, value_changed.clone());
797
798        let expect = |app: &waft_foundation::App, expected: &[MaterialState], expected_count| {
799            assert_eq!(
800                *app.get(&controller).value(),
801                states(expected.iter().copied())
802            );
803            assert_eq!(count.get(), expected_count);
804        };
805
806        controller.update(&mut app, MaterialState::Selected, true);
807        expect(&app, &[MaterialState::Selected], 1);
808        controller.update(&mut app, MaterialState::Selected, true);
809        expect(&app, &[MaterialState::Selected], 1);
810
811        controller.update(&mut app, MaterialState::Hovered, false);
812        expect(&app, &[MaterialState::Selected], 1);
813        controller.update(&mut app, MaterialState::Selected, false);
814        expect(&app, &[], 2);
815
816        controller.update(&mut app, MaterialState::Hovered, true);
817        expect(&app, &[MaterialState::Hovered], 3);
818        controller.update(&mut app, MaterialState::Hovered, true);
819        expect(&app, &[MaterialState::Hovered], 3);
820        controller.update(&mut app, MaterialState::Pressed, true);
821        expect(&app, &[MaterialState::Hovered, MaterialState::Pressed], 4);
822        controller.update(&mut app, MaterialState::Selected, true);
823        expect(
824            &app,
825            &[
826                MaterialState::Hovered,
827                MaterialState::Pressed,
828                MaterialState::Selected,
829            ],
830            5,
831        );
832        controller.update(&mut app, MaterialState::Selected, false);
833        expect(&app, &[MaterialState::Hovered, MaterialState::Pressed], 6);
834        controller.update(&mut app, MaterialState::Selected, false);
835        expect(&app, &[MaterialState::Hovered, MaterialState::Pressed], 6);
836        controller.update(&mut app, MaterialState::Pressed, false);
837        expect(&app, &[MaterialState::Hovered], 7);
838        controller.update(&mut app, MaterialState::Hovered, false);
839        expect(&app, &[], 8);
840
841        controller.remove_listener(&mut app, &value_changed);
842        controller.update(&mut app, MaterialState::Selected, true);
843        expect(&app, &[MaterialState::Selected], 8);
844    }
845
846    // material_states_controller_test.dart 'MaterialStatesController const initial value'.
847    #[test]
848    fn controller_with_an_initial_value_notifies_only_on_change() {
849        let cell = AppCell::new();
850        let mut app = cell.borrow_mut();
851        let count = Rc::new(Cell::new(0));
852        let controller =
853            MaterialStatesController::new(&mut app, Some(states([MaterialState::Selected])));
854        controller.add_listener(&mut app, {
855            let count = Rc::clone(&count);
856            Listener::new(move |_app| count.set(count.get() + 1))
857        });
858
859        controller.update(&mut app, MaterialState::Selected, true);
860        assert_eq!(
861            *app.get(&controller).value(),
862            states([MaterialState::Selected])
863        );
864        assert_eq!(count.get(), 0);
865
866        controller.update(&mut app, MaterialState::Selected, false);
867        assert_eq!(*app.get(&controller).value(), WidgetStates::new());
868        assert_eq!(count.get(), 1);
869
870        controller.dispose(&mut app);
871        assert!(!app.get(&controller).change_notifier_data().has_listeners());
872    }
873}