Skip to main content

waft_material/
material_state_mixin.rs

1//! Flutter counterpart: material_ui's `material_state_mixin.dart`.
2//!
3//! [`MaterialStateMixin`] is a mixin with fields ([`MaterialStateMixinData`]) on a [`State`],
4//! which holds it under the field `material_state`.
5
6use std::rc::Rc;
7
8use waft_foundation::{
9    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, ValueChanged,
10};
11use waft_widgets::{State, WidgetState, WidgetStates};
12
13/// The fields of Dart's `MaterialStateMixin`, which a state holds under the field
14/// `material_state`.
15#[derive(Debug, Default)]
16pub struct MaterialStateMixinData {
17    /// Managed set of active [`WidgetState`] values; designed to be passed to
18    /// `WidgetStateProperty::resolve` methods.
19    ///
20    /// To mutate and have `set_state` called automatically for you, use
21    /// [`MaterialStateMixin::set_material_state`], [`MaterialStateMixin::add_material_state`],
22    /// or [`MaterialStateMixin::remove_material_state`]. Directly mutating the set is possible,
23    /// and may be necessary if you need to alter its list without calling `set_state` (and thus
24    /// triggering a re-render).
25    pub material_states: WidgetStates,
26}
27
28impl MaterialStateMixinData {
29    /// The bag of a state with no active [`WidgetState`].
30    pub fn new() -> MaterialStateMixinData {
31        MaterialStateMixinData::default()
32    }
33
34    /// Dart's `MaterialStateMixin.debugFillProperties`, shared by every state with the mixin.
35    pub(crate) fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
36        properties.add(
37            DiagnosticsProperty::<String>::new(
38                "materialStates",
39                Some(waft_widgets::widget_states(&self.material_states)),
40            )
41            .default_value(Some("{}".to_string())),
42        );
43    }
44}
45
46/// Mixin for [`State`] classes that require knowledge of changing [`WidgetState`]
47/// values for their child widgets.
48///
49/// This mixin does nothing by mere application to a [`State`] class, but is
50/// helpful when writing `build` methods that include child `InkWell`,
51/// `GestureDetector`, `MouseRegion`, or `Focus` widgets. Instead of manually
52/// creating handlers for each type of user interaction, such [`State`] classes can
53/// instead provide a `ValueChanged<bool>` function and allow [`MaterialStateMixin`]
54/// to manage the set of active [`WidgetState`]s, and the calling of `set_state`
55/// as necessary.
56///
57/// The state holds a [`MaterialStateMixinData`] under the field `material_state`.
58///
59/// ```text
60/// impl State for MyWidgetState {
61///     fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
62///         let color = self.widget(app).color.clone();
63///         InkWell::new()
64///             .on_focus_change(self.update_material_state(WidgetState::Focused, None))
65///             .child(ColoredBox::new(color.resolve(self.material_states(app))))
66///             .into_widget()
67///     }
68/// }
69/// ```
70pub trait MaterialStateMixin: State {
71    /// Mixin field access.
72    fn material_state_data(self: Handle<Self>, app: &App) -> &MaterialStateMixinData;
73
74    /// See [`material_state_data`](Self::material_state_data).
75    fn material_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut MaterialStateMixinData;
76
77    /// Dart's `materialStates`: the set of active [`WidgetState`] values.
78    fn material_states(self: Handle<Self>, app: &App) -> &WidgetStates {
79        &self.material_state_data(app).material_states
80    }
81
82    /// Callback factory which accepts a [`WidgetState`] value and returns a
83    /// closure to mutate [`material_states`](Self::material_states) and call `set_state`.
84    ///
85    /// Accepts an optional second argument, `on_changed`, which allows
86    /// arbitrary functionality to be wired through the [`MaterialStateMixin`].
87    /// If supplied, the `on_changed` function is only called when child widgets
88    /// report events that make changes to the current set of [`WidgetState`]s.
89    ///
90    /// ```text
91    /// InkWell::new().on_highlight_changed(self.update_material_state(
92    ///     WidgetState::Pressed,
93    ///     Some(Rc::new(move |app, value| {
94    ///         if value {
95    ///             self.widget(app).on_pressed();
96    ///         }
97    ///     })),
98    /// ))
99    /// ```
100    fn update_material_state(
101        self: Handle<Self>,
102        key: WidgetState,
103        on_changed: Option<ValueChanged<bool>>,
104    ) -> ValueChanged<bool> {
105        Rc::new(move |app: &mut App, value: bool| {
106            if self.material_states(app).contains(&key) == value {
107                return;
108            }
109            self.set_material_state(app, key, value);
110            if let Some(on_changed) = &on_changed {
111                on_changed(app, value);
112            }
113        })
114    }
115
116    /// Mutator to mark a [`WidgetState`] value as either active or inactive.
117    fn set_material_state(self: Handle<Self>, app: &mut App, state: WidgetState, is_set: bool) {
118        if is_set {
119            self.add_material_state(app, state)
120        } else {
121            self.remove_material_state(app, state)
122        }
123    }
124
125    /// Mutator to mark a [`WidgetState`] value as active.
126    fn add_material_state(self: Handle<Self>, app: &mut App, state: WidgetState) {
127        if self
128            .material_state_data_mut(app)
129            .material_states
130            .insert(state)
131        {
132            self.set_state(app, |_| {});
133        }
134    }
135
136    /// Mutator to mark a [`WidgetState`] value as inactive.
137    fn remove_material_state(self: Handle<Self>, app: &mut App, state: WidgetState) {
138        if self
139            .material_state_data_mut(app)
140            .material_states
141            .remove(&state)
142        {
143            self.set_state(app, |_| {});
144        }
145    }
146
147    /// Getter for whether this class considers [`WidgetState::Disabled`] to be active.
148    fn is_disabled(self: Handle<Self>, app: &App) -> bool {
149        self.material_states(app).contains(&WidgetState::Disabled)
150    }
151
152    /// Getter for whether this class considers [`WidgetState::Dragged`] to be active.
153    fn is_dragged(self: Handle<Self>, app: &App) -> bool {
154        self.material_states(app).contains(&WidgetState::Dragged)
155    }
156
157    /// Getter for whether this class considers [`WidgetState::Error`] to be active.
158    fn is_errored(self: Handle<Self>, app: &App) -> bool {
159        self.material_states(app).contains(&WidgetState::Error)
160    }
161
162    /// Getter for whether this class considers [`WidgetState::Focused`] to be active.
163    fn is_focused(self: Handle<Self>, app: &App) -> bool {
164        self.material_states(app).contains(&WidgetState::Focused)
165    }
166
167    /// Getter for whether this class considers [`WidgetState::Hovered`] to be active.
168    fn is_hovered(self: Handle<Self>, app: &App) -> bool {
169        self.material_states(app).contains(&WidgetState::Hovered)
170    }
171
172    /// Getter for whether this class considers [`WidgetState::Pressed`] to be active.
173    fn is_pressed(self: Handle<Self>, app: &App) -> bool {
174        self.material_states(app).contains(&WidgetState::Pressed)
175    }
176
177    /// Getter for whether this class considers [`WidgetState::ScrolledUnder`] to be active.
178    fn is_scrolled_under(self: Handle<Self>, app: &App) -> bool {
179        self.material_states(app)
180            .contains(&WidgetState::ScrolledUnder)
181    }
182
183    /// Getter for whether this class considers [`WidgetState::Selected`] to be active.
184    fn is_selected(self: Handle<Self>, app: &App) -> bool {
185        self.material_states(app).contains(&WidgetState::Selected)
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use std::cell::RefCell;
192    use std::fmt::{self, Debug};
193
194    use waft_embedder::Color;
195    use waft_widgets::{
196        BuildContext, ColoredBox, Container, GlobalKey, IntoWidget, StateData, StatefulWidget,
197        WidgetRef, downcast_widget,
198    };
199
200    use waft_widgets::testing::{WidgetTester, test_widgets};
201
202    use super::*;
203
204    const TRUE_COLOR: Color = Color::new(0xFFF44336);
205    const FALSE_COLOR: Color = Color::new(0xFF4CAF50);
206
207    /// What Dart's `StreamController<bool>` carries: the callback the inner widget got.
208    type Controller = Rc<RefCell<Option<ValueChanged<bool>>>>;
209
210    /// Mock widget which plays the role of a button: it hands its `on_value_changed` to the
211    /// controller, through which a test emits notifications that [`WidgetState`] values are
212    /// now in or out of play (Dart's `_InnerWidget`, whose `initState` listens to the stream).
213    struct InnerWidget {
214        on_value_changed: ValueChanged<bool>,
215        controller: Controller,
216    }
217
218    impl Debug for InnerWidget {
219        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220            f.debug_struct("InnerWidget").finish_non_exhaustive()
221        }
222    }
223
224    struct InnerWidgetState {
225        state: StateData<InnerWidget>,
226    }
227
228    impl StatefulWidget for InnerWidget {
229        type State = InnerWidgetState;
230
231        fn create_state(&self) -> InnerWidgetState {
232            InnerWidgetState {
233                state: StateData::new(),
234            }
235        }
236    }
237
238    impl State for InnerWidgetState {
239        type Widget = InnerWidget;
240        waft_widgets::state_accessors!();
241
242        fn init_state(self: Handle<Self>, app: &mut App) {
243            let widget = self.widget(app);
244            *widget.controller.borrow_mut() = Some(Rc::clone(&widget.on_value_changed));
245        }
246
247        fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
248            Container::new().into_widget()
249        }
250    }
251
252    /// Dart's `_MyWidget`.
253    struct MyWidget {
254        /// Wrapper around `MaterialStateMixin.is_pressed/is_hovered/is_focused/etc`.
255        evaluator: fn(&App, Handle<MyWidgetState>) -> bool,
256        controller: Controller,
257        /// The value we're watching in the given test.
258        material_state: WidgetState,
259        key: GlobalKey,
260    }
261
262    impl Debug for MyWidget {
263        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264            f.debug_struct("MyWidget")
265                .field("material_state", &self.material_state)
266                .finish_non_exhaustive()
267        }
268    }
269
270    struct MyWidgetState {
271        state: StateData<MyWidget>,
272        material_state: MaterialStateMixinData,
273    }
274
275    impl StatefulWidget for MyWidget {
276        type State = MyWidgetState;
277
278        fn create_state(&self) -> MyWidgetState {
279            MyWidgetState {
280                state: StateData::new(),
281                material_state: MaterialStateMixinData::new(),
282            }
283        }
284    }
285
286    impl MaterialStateMixin for MyWidgetState {
287        fn material_state_data(self: Handle<Self>, app: &App) -> &MaterialStateMixinData {
288            &app.get(self).material_state
289        }
290
291        fn material_state_data_mut(
292            self: Handle<Self>,
293            app: &mut App,
294        ) -> &mut MaterialStateMixinData {
295            &mut app.get_mut(self).material_state
296        }
297    }
298
299    impl State for MyWidgetState {
300        type Widget = MyWidget;
301        waft_widgets::state_accessors!();
302
303        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
304            let widget = self.widget(app);
305            let color = if (widget.evaluator)(app, self) {
306                TRUE_COLOR
307            } else {
308                FALSE_COLOR
309            };
310            let (controller, material_state) =
311                (Rc::clone(&widget.controller), widget.material_state);
312            ColoredBox::new(color)
313                .key(widget.key.clone().into())
314                .child(InnerWidget {
315                    on_value_changed: self.update_material_state(material_state, None),
316                    controller,
317                })
318                .into_widget()
319        }
320    }
321
322    fn colored_box_color(tester: &WidgetTester, key: &GlobalKey) -> u32 {
323        let widget = key
324            .current_widget(&tester.cell.borrow_mut())
325            .expect("mounted");
326        downcast_widget::<ColoredBox>(&*widget)
327            .expect("a ColoredBox")
328            .color
329            .to_argb32()
330    }
331
332    fn verify(evaluator: fn(&App, Handle<MyWidgetState>) -> bool, material_state: WidgetState) {
333        test_widgets(|tester| {
334            let controller = Controller::default();
335            let key = GlobalKey::new();
336            tester.pump_widget(
337                MyWidget {
338                    evaluator,
339                    controller: Rc::clone(&controller),
340                    material_state,
341                    key: key.clone(),
342                }
343                .into_widget(),
344            );
345            let emit = |tester: &mut WidgetTester, value: bool| {
346                let on_value_changed = controller.borrow().clone().expect("the inner widget ran");
347                on_value_changed(&mut tester.cell.borrow_mut(), value);
348                tester.pump_and_settle();
349            };
350
351            // Set the value to True
352            emit(tester, true);
353            assert_eq!(colored_box_color(tester, &key), TRUE_COLOR.to_argb32());
354
355            // Set the value to False
356            emit(tester, false);
357            assert_eq!(colored_box_color(tester, &key), FALSE_COLOR.to_argb32());
358        });
359    }
360
361    #[test]
362    fn widget_state_pressed_is_tracked() {
363        verify(|app, state| state.is_pressed(app), WidgetState::Pressed);
364    }
365
366    #[test]
367    fn widget_state_focused_is_tracked() {
368        verify(|app, state| state.is_focused(app), WidgetState::Focused);
369    }
370
371    #[test]
372    fn widget_state_hovered_is_tracked() {
373        verify(|app, state| state.is_hovered(app), WidgetState::Hovered);
374    }
375
376    #[test]
377    fn widget_state_disabled_is_tracked() {
378        verify(|app, state| state.is_disabled(app), WidgetState::Disabled);
379    }
380
381    #[test]
382    fn widget_state_selected_is_tracked() {
383        verify(|app, state| state.is_selected(app), WidgetState::Selected);
384    }
385
386    #[test]
387    fn widget_state_scrolled_under_is_tracked() {
388        verify(
389            |app, state| state.is_scrolled_under(app),
390            WidgetState::ScrolledUnder,
391        );
392    }
393
394    #[test]
395    fn widget_state_dragged_is_tracked() {
396        verify(|app, state| state.is_dragged(app), WidgetState::Dragged);
397    }
398
399    #[test]
400    fn widget_state_error_is_tracked() {
401        verify(|app, state| state.is_errored(app), WidgetState::Error);
402    }
403}