Skip to main content

waft_widgets/widgets/
toggleable.rs

1//! Flutter counterpart: `widgets/toggleable.dart`.
2//!
3//! [`ToggleableStateMixin`] is a mixin with fields ([`ToggleableStateMixinData`]) on a state
4//! that is also a [`TickerProviderStateMixin`]; where Dart types a field or parameter as the
5//! mixin, it is the erased [`AnyToggleableState`]. [`ToggleablePainter`] is a base class whose
6//! fields are [`ToggleablePainterData`]; a painter is an arena `ChangeNotifier` and a
7//! `CustomPaint` reaches it through [`ToggleablePainterRef`]. The tap's `TapSemanticEvent` and
8//! the detector's `excludeFromSemantics` wait with accessibility.
9
10use std::any::{Any, TypeId};
11use std::collections::HashMap;
12use std::fmt::{self, Debug};
13use std::rc::Rc;
14use std::time::Duration;
15
16use waft_animation::{
17    AnimationBehavior, AnimationController, AnimationRef, AnyAnimation, CurvedAnimation, Curves,
18};
19use waft_embedder::{Canvas, Color, Offset, Paint, Size};
20use waft_foundation::{
21    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Listenable, Listener,
22    OptionRetained, ValueChanged,
23};
24use waft_gestures::{TapDownDetails, TapUpDetails};
25use waft_rendering::CustomPainter;
26use waft_scheduler::TickerProviderObject;
27use waft_services::{MouseCursorRef, SystemMouseCursors};
28
29use crate::framework::{BuildContext, IntoWidget, State, WidgetRef};
30use crate::widgets::actions::{ActionRef, ActivateIntent, CallbackAction, FocusableActionDetector};
31use crate::widgets::basic::{CustomPaint, Semantics};
32use crate::widgets::focus_manager::FocusNodeRef;
33use crate::widgets::gesture_detector::GestureDetector;
34use crate::widgets::ticker_provider::TickerProviderStateMixin;
35use crate::widgets::widget_state::{WidgetState, WidgetStatePropertyRef, WidgetStates};
36use waft_foundation::Ref;
37
38// Duration of the animation that moves the toggle from one state to another.
39const K_TOGGLE_DURATION: Duration = Duration::from_millis(200);
40
41// Duration of the fade animation for the reaction when focus and hover occur.
42const K_REACTION_FADE_DURATION: Duration = Duration::from_millis(50);
43
44// Default duration of the radial reaction animation.
45const K_REACTION_ANIMATION_DURATION: Duration = Duration::from_millis(100);
46
47/// The fields of Dart's `ToggleableStateMixin`, which a state holds under the field
48/// `toggleable`.
49///
50/// The animations and the action are arena objects, created in
51/// [`ToggleableStateMixin::init_state`] (Dart's `late` fields and `late final _actionMap`).
52#[derive(Default)]
53pub struct ToggleableStateMixinData {
54    position_controller: Option<Ref<AnimationController>>,
55    position: Option<Ref<CurvedAnimation>>,
56    reaction_controller: Option<Ref<AnimationController>>,
57    reaction: Option<Ref<CurvedAnimation>>,
58    reaction_hover_fade: Option<Ref<CurvedAnimation>>,
59    reaction_hover_fade_controller: Option<Ref<AnimationController>>,
60    reaction_focus_fade: Option<Ref<CurvedAnimation>>,
61    reaction_focus_fade_controller: Option<Ref<AnimationController>>,
62    action_map: HashMap<TypeId, ActionRef>,
63    down_position: Option<Offset>,
64    focused: bool,
65    hovering: bool,
66}
67
68impl ToggleableStateMixinData {
69    /// The bag of a state whose `init_state` has not run yet.
70    pub fn new() -> ToggleableStateMixinData {
71        ToggleableStateMixinData::default()
72    }
73}
74
75/// A mixin for `StatefulWidget`s that implement toggleable controls with toggle animations
76/// (e.g. `Switch`es, `CupertinoSwitch`es, `Checkbox`es, `CupertinoCheckbox`es, `Radio`s, and
77/// `CupertinoRadio`s).
78///
79/// The mixin implements the logic for toggling the control (e.g. when tapped) and provides a
80/// series of animation controllers to transition the control from one state to another. It
81/// does not have any opinion about the visual representation of the toggleable widget. The
82/// visuals are defined by a [`CustomPainter`] passed to the
83/// [`build_toggleable`](Self::build_toggleable). [`State`](crate::State) objects using this
84/// mixin should call that method from their `build` method.
85///
86/// The state holds a [`ToggleableStateMixinData`] under the field `toggleable`, and its
87/// `init_state` and `dispose` call this mixin's where Dart's `super` calls reach it:
88/// [`init_state`](Self::init_state) first, then [`dispose`](Self::dispose) followed by
89/// [`TickerProviderStateMixin::dispose`].
90pub trait ToggleableStateMixin: TickerProviderStateMixin + TickerProviderObject {
91    /// Mixin field access.
92    fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData;
93
94    /// See [`toggleable_data`](Self::toggleable_data).
95    fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData;
96
97    /// This state as the erased [`AnyToggleableState`] — what to pass where a Dart API takes a
98    /// `ToggleableStateMixin`.
99    fn as_toggleable_state(self: Handle<Self>) -> AnyToggleableState {
100        AnyToggleableState {
101            id: self.id(),
102            vtable: const { &ToggleableStateVTable::of::<Self>() },
103        }
104    }
105
106    /// Used by subclasses to manipulate the visual value of the control.
107    ///
108    /// Some controls respond to user input by updating their visual value. For example, the
109    /// thumb of a switch moves from one position to another when dragged. These controls
110    /// manipulate this animation controller to update their [`position`](Self::position) and
111    /// eventually trigger an [`on_changed`](Self::on_changed) callback when the animation
112    /// reaches either 0.0 or 1.0.
113    fn position_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
114        self.toggleable_data(app)
115            .position_controller
116            .handle()
117            .expect("created in init_state")
118    }
119
120    /// The visual value of the control.
121    ///
122    /// When the control is inactive, the [`value`](Self::value) is false and this animation
123    /// has the value 0.0. When the control is active, the value is either true or tristate is
124    /// true and the value is null. When the control is active the animation has a value of
125    /// 1.0. When the control is changing from inactive to active (or vice versa),
126    /// [`value`](Self::value) is the target value and this animation gradually updates from
127    /// 0.0 to 1.0 (or vice versa).
128    fn position(self: Handle<Self>, app: &App) -> &Ref<CurvedAnimation> {
129        self.toggleable_data(app)
130            .position
131            .as_ref()
132            .expect("created in init_state")
133    }
134
135    /// Used by subclasses to control the radial reaction animation.
136    ///
137    /// Some controls have a radial ink reaction to user input. This animation controller can
138    /// be used to start or stop these ink reactions.
139    ///
140    /// To paint the actual radial reaction, [`ToggleablePainter::paint_radial_reaction`] may
141    /// be used.
142    fn reaction_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
143        self.toggleable_data(app)
144            .reaction_controller
145            .handle()
146            .expect("created in init_state")
147    }
148
149    /// The visual value of the radial reaction animation.
150    ///
151    /// Some controls have a radial ink reaction to user input. This animation controls the
152    /// progress of these ink reactions.
153    ///
154    /// To paint the actual radial reaction, [`ToggleablePainter::paint_radial_reaction`] may
155    /// be used.
156    fn reaction(self: Handle<Self>, app: &App) -> &Ref<CurvedAnimation> {
157        self.toggleable_data(app)
158            .reaction
159            .as_ref()
160            .expect("created in init_state")
161    }
162
163    /// Controls the radial reaction's opacity animation for hover changes.
164    ///
165    /// Some controls have a radial ink reaction to pointer hover. This animation controls
166    /// these ink reaction fade-ins and fade-outs.
167    ///
168    /// To paint the actual radial reaction, [`ToggleablePainter::paint_radial_reaction`] may
169    /// be used.
170    fn reaction_hover_fade(self: Handle<Self>, app: &App) -> &Ref<CurvedAnimation> {
171        self.toggleable_data(app)
172            .reaction_hover_fade
173            .as_ref()
174            .expect("created in init_state")
175    }
176
177    /// Controls the radial reaction's opacity animation for focus changes.
178    ///
179    /// Some controls have a radial ink reaction to focus. This animation controls these ink
180    /// reaction fade-ins and fade-outs.
181    ///
182    /// To paint the actual radial reaction, [`ToggleablePainter::paint_radial_reaction`] may
183    /// be used.
184    fn reaction_focus_fade(self: Handle<Self>, app: &App) -> &Ref<CurvedAnimation> {
185        self.toggleable_data(app)
186            .reaction_focus_fade
187            .as_ref()
188            .expect("created in init_state")
189    }
190
191    /// The amount of time a circular ink response should take to expand to its full size if a
192    /// radial reaction is drawn using [`ToggleablePainter::paint_radial_reaction`].
193    fn reaction_animation_duration(self: Handle<Self>, app: &App) -> Option<Duration> {
194        let _ = app;
195        Some(K_REACTION_ANIMATION_DURATION)
196    }
197
198    /// Whether [`value`](Self::value) of this control can be changed by user interaction.
199    ///
200    /// The control is considered interactive if the [`on_changed`](Self::on_changed) callback
201    /// is non-null. If the callback is null, then the control is disabled, and
202    /// non-interactive. A disabled checkbox, for example, is displayed using a grey color and
203    /// its value cannot be changed.
204    fn is_interactive(self: Handle<Self>, app: &App) -> bool {
205        self.on_changed(app).is_some()
206    }
207
208    /// Called when the control changes value.
209    ///
210    /// If the control is tapped, [`on_changed`](Self::on_changed) is called immediately with
211    /// the new value.
212    ///
213    /// The control is considered interactive (see [`is_interactive`](Self::is_interactive)) if
214    /// this callback is non-null. If the callback is null, then the control is disabled, and
215    /// non-interactive. A disabled checkbox, for example, is displayed using a grey color and
216    /// its value cannot be changed.
217    fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>>;
218
219    /// False if this control is "inactive" (not checked, off, or unselected).
220    ///
221    /// If value is true then the control "active" (checked, on, or selected). If tristate is
222    /// true and value is null, then the control is considered to be in its third or
223    /// "indeterminate" state.
224    ///
225    /// When the value changes, this object starts the
226    /// [`position_controller`](Self::position_controller) and [`position`](Self::position)
227    /// animations to animate the visual appearance of the control to the new value.
228    fn value(self: Handle<Self>, app: &App) -> Option<bool>;
229
230    /// If true, [`value`](Self::value) can be true, false, or null, otherwise
231    /// [`value`](Self::value) must be true or false.
232    ///
233    /// When [`tristate`](Self::tristate) is true and [`value`](Self::value) is null, then the
234    /// control is considered to be in its third or "indeterminate" state.
235    fn tristate(self: Handle<Self>, app: &App) -> bool;
236
237    /// The mixin's part of `State::init_state`; the state calls it first, where Dart's
238    /// `super.initState()` reaches the mixin.
239    fn init_state(self: Handle<Self>, app: &mut App) {
240        let position_value = if self.value(app) == Some(false) {
241            0.0
242        } else {
243            1.0
244        };
245        let position_controller = AnimationController::new(
246            app,
247            Some(position_value),
248            Some(K_TOGGLE_DURATION),
249            None,
250            0.0,
251            1.0,
252            AnimationBehavior::Normal,
253            self,
254        );
255        let position = CurvedAnimation::new(
256            app,
257            position_controller.erase(),
258            Curves::ease_in(),
259            Some(Curves::ease_out()),
260        );
261        let reaction_duration = self
262            .reaction_animation_duration(app)
263            .unwrap_or(K_REACTION_ANIMATION_DURATION);
264        let reaction_controller = AnimationController::new(
265            app,
266            None,
267            Some(reaction_duration),
268            None,
269            0.0,
270            1.0,
271            AnimationBehavior::Normal,
272            self,
273        );
274        let reaction = CurvedAnimation::new(
275            app,
276            reaction_controller.erase(),
277            Curves::fast_out_slow_in(),
278            None,
279        );
280        let fade_value = {
281            let data = self.toggleable_data(app);
282            if data.hovering || data.focused {
283                1.0
284            } else {
285                0.0
286            }
287        };
288        let reaction_hover_fade_controller = AnimationController::new(
289            app,
290            Some(fade_value),
291            Some(K_REACTION_FADE_DURATION),
292            None,
293            0.0,
294            1.0,
295            AnimationBehavior::Normal,
296            self,
297        );
298        let reaction_hover_fade = CurvedAnimation::new(
299            app,
300            reaction_hover_fade_controller.erase(),
301            Curves::fast_out_slow_in(),
302            None,
303        );
304        let reaction_focus_fade_controller = AnimationController::new(
305            app,
306            Some(fade_value),
307            Some(K_REACTION_FADE_DURATION),
308            None,
309            0.0,
310            1.0,
311            AnimationBehavior::Normal,
312            self,
313        );
314        let reaction_focus_fade = CurvedAnimation::new(
315            app,
316            reaction_focus_fade_controller.erase(),
317            Curves::fast_out_slow_in(),
318            None,
319        );
320        let activate = CallbackAction::<ActivateIntent>::new(
321            app,
322            Rc::new(move |app: &mut App, _intent: &ActivateIntent| {
323                self.handle_tap(app);
324                None
325            }),
326        );
327        let data = self.toggleable_data_mut(app);
328        data.position_controller = Some(position_controller);
329        data.position = Some(position);
330        data.reaction_controller = Some(reaction_controller);
331        data.reaction = Some(reaction);
332        data.reaction_hover_fade_controller = Some(reaction_hover_fade_controller);
333        data.reaction_hover_fade = Some(reaction_hover_fade);
334        data.reaction_focus_fade_controller = Some(reaction_focus_fade_controller);
335        data.reaction_focus_fade = Some(reaction_focus_fade);
336        data.action_map
337            .insert(TypeId::of::<ActivateIntent>(), activate.erase());
338    }
339
340    /// Runs the [`position`](Self::position) animation to transition the Toggleable's
341    /// appearance to match [`value`](Self::value).
342    ///
343    /// This method must be called whenever [`value`](Self::value) changes to ensure that the
344    /// visual representation of the Toggleable matches the current [`value`](Self::value).
345    fn animate_to_value(self: Handle<Self>, app: &mut App) {
346        let position_controller = self.position_controller(app);
347        let value = self.value(app);
348        if self.tristate(app) {
349            if value.is_none() {
350                position_controller.set_value(app, 0.0);
351            }
352            if value.unwrap_or(true) {
353                position_controller.forward(app, None);
354            } else {
355                position_controller.reverse(app, None);
356            }
357        } else if value.unwrap_or(false) {
358            position_controller.forward(app, None);
359        } else {
360            position_controller.reverse(app, None);
361        }
362    }
363
364    /// The mixin's part of `State::dispose`; the state calls it where Dart's `super.dispose()`
365    /// reaches the mixin, then [`TickerProviderStateMixin::dispose`].
366    fn dispose(self: Handle<Self>, app: &mut App) {
367        let data = self.toggleable_data(app);
368        let pairs = [
369            (data.position_controller.handle(), data.position.handle()),
370            (data.reaction_controller.handle(), data.reaction.handle()),
371            (
372                data.reaction_hover_fade_controller.handle(),
373                data.reaction_hover_fade.handle(),
374            ),
375            (
376                data.reaction_focus_fade_controller.handle(),
377                data.reaction_focus_fade.handle(),
378            ),
379        ];
380        for (controller, animation) in pairs {
381            controller.expect("created in init_state").dispose(app);
382            animation.expect("created in init_state").dispose(app);
383        }
384    }
385
386    /// The most recent [`Offset`] at which a pointer touched the Toggleable.
387    ///
388    /// This is null if currently no pointer is touching the Toggleable or if
389    /// [`is_interactive`](Self::is_interactive) is false.
390    fn down_position(self: Handle<Self>, app: &App) -> Option<Offset> {
391        self.toggleable_data(app).down_position
392    }
393
394    /// Describes the current [`WidgetState`] of the Toggleable.
395    ///
396    /// The returned set will include:
397    ///
398    ///  * [`WidgetState::Disabled`], if [`is_interactive`](Self::is_interactive) is false
399    ///  * [`WidgetState::Hovered`], if a pointer is hovering over the Toggleable
400    ///  * [`WidgetState::Focused`], if the Toggleable has input focus
401    ///  * [`WidgetState::Selected`], if [`value`](Self::value) is true or null
402    fn states(self: Handle<Self>, app: &App) -> WidgetStates {
403        let mut states = WidgetStates::new();
404        if !self.is_interactive(app) {
405            states.insert(WidgetState::Disabled);
406        }
407        if self.toggleable_data(app).hovering {
408            states.insert(WidgetState::Hovered);
409        }
410        if self.toggleable_data(app).focused {
411            states.insert(WidgetState::Focused);
412        }
413        if self.value(app).unwrap_or(true) {
414            states.insert(WidgetState::Selected);
415        }
416        states
417    }
418
419    /// Typically wraps a `painter` that draws the actual visuals of the Toggleable with logic
420    /// to toggle it.
421    ///
422    /// Use [`build_toggleable_with_child`](Self::build_toggleable_with_child) if one would
423    /// like to provide a widget instead of [`CustomPainter`].
424    ///
425    /// If drawing a radial ink reaction is desired (in Material Design for example), consider
426    /// providing a [`ToggleablePainter`] as a `painter`, which implements logic to draw a
427    /// radial ink reaction for this control. The painter is usually configured with the
428    /// [`reaction`](Self::reaction), [`position`](Self::position),
429    /// [`reaction_hover_fade`](Self::reaction_hover_fade), and
430    /// [`reaction_focus_fade`](Self::reaction_focus_fade) animation provided by this mixin. It
431    /// is expected to draw the visuals of the Toggleable based on the current value of these
432    /// animations. The animations are triggered by this mixin to transition the Toggleable
433    /// from one state to another.
434    ///
435    /// Material Toggleables must provide a `mouse_cursor` which resolves to a mouse cursor
436    /// based on the current [`WidgetState`] of the Toggleable. Cupertino Toggleables may not
437    /// provide a `mouse_cursor`. If no `mouse_cursor` is provided,
438    /// [`SystemMouseCursors::BASIC`] will be used as the `mouse_cursor` across all
439    /// [`WidgetState`]s.
440    ///
441    /// This method must be called from the `build` method of the state that uses this mixin.
442    /// The returned widget must be returned from the build method - potentially after wrapping
443    /// it in other widgets.
444    #[allow(clippy::too_many_arguments)]
445    fn build_toggleable(
446        self: Handle<Self>,
447        app: &mut App,
448        focus_node: Option<FocusNodeRef>,
449        on_focus_change: Option<ValueChanged<bool>>,
450        autofocus: bool,
451        mouse_cursor: Option<WidgetStatePropertyRef<MouseCursorRef>>,
452        size: Size,
453        painter: impl CustomPainter,
454    ) -> WidgetRef {
455        self.build_toggleable_with_child(
456            app,
457            focus_node,
458            on_focus_change,
459            autofocus,
460            mouse_cursor,
461            CustomPaint::new().size(size).painter(painter).into_widget(),
462        )
463    }
464
465    /// Typically wraps a child that draws the actual visuals of the Toggleable with logic to
466    /// toggle it.
467    ///
468    /// If drawing a radial ink reaction is desired (in Material Design for example), consider
469    /// providing a [`CustomPaint`] with a [`ToggleablePainter`] as its painter, which
470    /// implements logic to draw a radial ink reaction for this control. The painter is usually
471    /// configured with the [`reaction`](Self::reaction), [`position`](Self::position),
472    /// [`reaction_hover_fade`](Self::reaction_hover_fade), and
473    /// [`reaction_focus_fade`](Self::reaction_focus_fade) animation provided by this mixin. It
474    /// is expected to draw the visuals of the Toggleable based on the current value of these
475    /// animations. The animations are triggered by this mixin to transition the Toggleable
476    /// from one state to another.
477    ///
478    /// Material Toggleables must provide a `mouse_cursor` which resolves to a mouse cursor
479    /// based on the current [`WidgetState`] of the Toggleable. Cupertino Toggleables may not
480    /// provide a `mouse_cursor`. If no `mouse_cursor` is provided,
481    /// [`SystemMouseCursors::BASIC`] will be used as the `mouse_cursor` across all
482    /// [`WidgetState`]s.
483    ///
484    /// This method must be called from the `build` method of the state that uses this mixin.
485    /// The returned widget must be returned from the build method - potentially after wrapping
486    /// it in other widgets.
487    fn build_toggleable_with_child(
488        self: Handle<Self>,
489        app: &mut App,
490        focus_node: Option<FocusNodeRef>,
491        on_focus_change: Option<ValueChanged<bool>>,
492        autofocus: bool,
493        mouse_cursor: Option<WidgetStatePropertyRef<MouseCursorRef>>,
494        child: WidgetRef,
495    ) -> WidgetRef {
496        let is_interactive = self.is_interactive(app);
497        let effective_mouse_cursor = match mouse_cursor {
498            Some(mouse_cursor) => mouse_cursor.resolve(&self.states(app)),
499            None => SystemMouseCursors::BASIC.into(),
500        };
501        let mut detector = FocusableActionDetector::new(
502            self.tap_detector(app)
503                .child(Semantics::new().enabled(is_interactive).child(child)),
504        )
505        .actions(self.toggleable_data(app).action_map.clone())
506        .autofocus(autofocus)
507        .enabled(is_interactive)
508        .on_show_focus_highlight(move |app, focused| {
509            self.handle_focus_highlight_changed(app, focused)
510        })
511        .on_show_hover_highlight(move |app, hovering| self.handle_hover_changed(app, hovering))
512        .mouse_cursor(effective_mouse_cursor);
513        if let Some(focus_node) = focus_node {
514            detector = detector.focus_node(focus_node);
515        }
516        if let Some(on_focus_change) = on_focus_change {
517            detector = detector.on_focus_change(move |app, focused| on_focus_change(app, focused));
518        }
519        detector.into_widget()
520    }
521}
522
523/// Dart's private members of `ToggleableStateMixin`.
524trait ToggleableStateMixinPrivate: ToggleableStateMixin {
525    /// The `GestureDetector` Dart builds inline: the tap handlers only while interactive.
526    fn tap_detector(self: Handle<Self>, app: &App) -> GestureDetector {
527        if !self.is_interactive(app) {
528            return GestureDetector::new();
529        }
530        GestureDetector::new()
531            .on_tap_down(Rc::new(move |app: &mut App, details| {
532                self.handle_tap_down(app, details)
533            }))
534            .on_tap(Listener::new(move |app| self.handle_tap(app)))
535            .on_tap_up(Rc::new(move |app: &mut App, details| {
536                self.handle_tap_end(app, Some(details))
537            }))
538            .on_tap_cancel(Listener::new(move |app| self.handle_tap_end(app, None)))
539    }
540
541    fn handle_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
542        if self.is_interactive(app) {
543            self.toggleable_data_mut(app).down_position = Some(details.local_position);
544            self.set_state(app, |_| {});
545            self.reaction_controller(app).forward(app, None);
546        }
547    }
548
549    fn handle_tap(self: Handle<Self>, app: &mut App) {
550        if !self.is_interactive(app) {
551            return;
552        }
553        let on_changed = self.on_changed(app).expect("an interactive toggleable");
554        match self.value(app) {
555            Some(false) => on_changed(app, Some(true)),
556            Some(true) => {
557                let new_value = if self.tristate(app) {
558                    None
559                } else {
560                    Some(false)
561                };
562                on_changed(app, new_value);
563            }
564            None => on_changed(app, Some(false)),
565        }
566        // `sendSemanticsEvent(const TapSemanticEvent())` waits with accessibility.
567    }
568
569    fn handle_tap_end(self: Handle<Self>, app: &mut App, _details: Option<TapUpDetails>) {
570        if self.toggleable_data(app).down_position.is_some() {
571            self.toggleable_data_mut(app).down_position = None;
572            self.set_state(app, |_| {});
573        }
574        self.reaction_controller(app).reverse(app, None);
575    }
576
577    fn handle_focus_highlight_changed(self: Handle<Self>, app: &mut App, focused: bool) {
578        if focused != self.toggleable_data(app).focused {
579            self.toggleable_data_mut(app).focused = focused;
580            self.set_state(app, |_| {});
581            let controller = self
582                .toggleable_data(app)
583                .reaction_focus_fade_controller
584                .handle()
585                .expect("created in init_state");
586            if focused {
587                controller.forward(app, None);
588            } else {
589                controller.reverse(app, None);
590            }
591        }
592    }
593
594    fn handle_hover_changed(self: Handle<Self>, app: &mut App, hovering: bool) {
595        if hovering != self.toggleable_data(app).hovering {
596            self.toggleable_data_mut(app).hovering = hovering;
597            self.set_state(app, |_| {});
598            let controller = self
599                .toggleable_data(app)
600                .reaction_hover_fade_controller
601                .handle()
602                .expect("created in init_state");
603            if hovering {
604                controller.forward(app, None);
605            } else {
606                controller.reverse(app, None);
607            }
608        }
609    }
610}
611
612impl<S: ToggleableStateMixin> ToggleableStateMixinPrivate for S {}
613
614/// The vtable of an erased [`AnyToggleableState`]: one `&'static` table per leaf type.
615struct ToggleableStateVTable {
616    type_name: fn() -> &'static str,
617    context: fn(&App, HandleId) -> BuildContext,
618    mounted: fn(&App, HandleId) -> bool,
619    position_controller: fn(&App, HandleId) -> Handle<AnimationController>,
620    position: fn(&App, HandleId) -> &Ref<CurvedAnimation>,
621    reaction_controller: fn(&App, HandleId) -> Handle<AnimationController>,
622    reaction: fn(&App, HandleId) -> &Ref<CurvedAnimation>,
623    reaction_hover_fade: fn(&App, HandleId) -> &Ref<CurvedAnimation>,
624    reaction_focus_fade: fn(&App, HandleId) -> &Ref<CurvedAnimation>,
625    reaction_animation_duration: fn(&App, HandleId) -> Option<Duration>,
626    is_interactive: fn(&App, HandleId) -> bool,
627    on_changed: fn(&App, HandleId) -> Option<ValueChanged<Option<bool>>>,
628    value: fn(&App, HandleId) -> Option<bool>,
629    tristate: fn(&App, HandleId) -> bool,
630    animate_to_value: fn(&mut App, HandleId),
631    down_position: fn(&App, HandleId) -> Option<Offset>,
632    states: fn(&App, HandleId) -> WidgetStates,
633    #[allow(clippy::type_complexity)]
634    build_toggleable_with_child: fn(
635        &mut App,
636        HandleId,
637        Option<FocusNodeRef>,
638        Option<ValueChanged<bool>>,
639        bool,
640        Option<WidgetStatePropertyRef<MouseCursorRef>>,
641        WidgetRef,
642    ) -> WidgetRef,
643}
644
645/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
646fn resolve<S: 'static>(id: HandleId) -> Handle<S> {
647    Handle::from_id(id)
648}
649
650impl ToggleableStateVTable {
651    const fn of<S: ToggleableStateMixin>() -> ToggleableStateVTable {
652        ToggleableStateVTable {
653            type_name: std::any::type_name::<S>,
654            context: |app, id| <S as State>::context(resolve(id), app),
655            mounted: |app, id| <S as State>::mounted(resolve(id), app),
656            position_controller: |app, id| {
657                <S as ToggleableStateMixin>::position_controller(resolve(id), app)
658            },
659            position: |app, id| <S as ToggleableStateMixin>::position(resolve(id), app),
660            reaction_controller: |app, id| {
661                <S as ToggleableStateMixin>::reaction_controller(resolve(id), app)
662            },
663            reaction: |app, id| <S as ToggleableStateMixin>::reaction(resolve(id), app),
664            reaction_hover_fade: |app, id| {
665                <S as ToggleableStateMixin>::reaction_hover_fade(resolve(id), app)
666            },
667            reaction_focus_fade: |app, id| {
668                <S as ToggleableStateMixin>::reaction_focus_fade(resolve(id), app)
669            },
670            reaction_animation_duration: |app, id| {
671                <S as ToggleableStateMixin>::reaction_animation_duration(resolve(id), app)
672            },
673            is_interactive: |app, id| <S as ToggleableStateMixin>::is_interactive(resolve(id), app),
674            on_changed: |app, id| <S as ToggleableStateMixin>::on_changed(resolve(id), app),
675            value: |app, id| <S as ToggleableStateMixin>::value(resolve(id), app),
676            tristate: |app, id| <S as ToggleableStateMixin>::tristate(resolve(id), app),
677            animate_to_value: |app, id| {
678                <S as ToggleableStateMixin>::animate_to_value(resolve(id), app)
679            },
680            down_position: |app, id| <S as ToggleableStateMixin>::down_position(resolve(id), app),
681            states: |app, id| <S as ToggleableStateMixin>::states(resolve(id), app),
682            build_toggleable_with_child: |app,
683                                          id,
684                                          focus_node,
685                                          on_focus_change,
686                                          autofocus,
687                                          mouse_cursor,
688                                          child| {
689                <S as ToggleableStateMixin>::build_toggleable_with_child(
690                    resolve(id),
691                    app,
692                    focus_node,
693                    on_focus_change,
694                    autofocus,
695                    mouse_cursor,
696                    child,
697                )
698            },
699        }
700    }
701}
702
703/// Erased [`ToggleableStateMixin`]: one identity and a static vtable.
704///
705/// This is what a field or parameter Dart types as `ToggleableStateMixin` becomes, such as the
706/// state a `RawRadio` hands its [`RadioBuilder`](crate::RadioBuilder). Equality is Dart's `==` on
707/// an object reference.
708#[derive(Clone, Copy)]
709pub struct AnyToggleableState {
710    id: HandleId,
711    vtable: &'static ToggleableStateVTable,
712}
713
714impl PartialEq for AnyToggleableState {
715    fn eq(&self, other: &AnyToggleableState) -> bool {
716        self.id == other.id
717    }
718}
719
720impl Eq for AnyToggleableState {}
721
722impl Debug for AnyToggleableState {
723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
725    }
726}
727
728impl AnyToggleableState {
729    /// The arena id behind this handle.
730    pub fn id(self) -> HandleId {
731        self.id
732    }
733
734    /// See [`State::context`].
735    pub fn context(self, app: &App) -> BuildContext {
736        (self.vtable.context)(app, self.id)
737    }
738
739    /// See [`State::mounted`].
740    pub fn mounted(self, app: &App) -> bool {
741        (self.vtable.mounted)(app, self.id)
742    }
743
744    /// See [`ToggleableStateMixin::position_controller`].
745    pub fn position_controller(self, app: &App) -> Handle<AnimationController> {
746        (self.vtable.position_controller)(app, self.id)
747    }
748
749    /// See [`ToggleableStateMixin::position`].
750    pub fn position(self, app: &App) -> &Ref<CurvedAnimation> {
751        (self.vtable.position)(app, self.id)
752    }
753
754    /// See [`ToggleableStateMixin::reaction_controller`].
755    pub fn reaction_controller(self, app: &App) -> Handle<AnimationController> {
756        (self.vtable.reaction_controller)(app, self.id)
757    }
758
759    /// See [`ToggleableStateMixin::reaction`].
760    pub fn reaction(self, app: &App) -> &Ref<CurvedAnimation> {
761        (self.vtable.reaction)(app, self.id)
762    }
763
764    /// See [`ToggleableStateMixin::reaction_hover_fade`].
765    pub fn reaction_hover_fade(self, app: &App) -> &Ref<CurvedAnimation> {
766        (self.vtable.reaction_hover_fade)(app, self.id)
767    }
768
769    /// See [`ToggleableStateMixin::reaction_focus_fade`].
770    pub fn reaction_focus_fade(self, app: &App) -> &Ref<CurvedAnimation> {
771        (self.vtable.reaction_focus_fade)(app, self.id)
772    }
773
774    /// See [`ToggleableStateMixin::reaction_animation_duration`].
775    pub fn reaction_animation_duration(self, app: &App) -> Option<Duration> {
776        (self.vtable.reaction_animation_duration)(app, self.id)
777    }
778
779    /// See [`ToggleableStateMixin::is_interactive`].
780    pub fn is_interactive(self, app: &App) -> bool {
781        (self.vtable.is_interactive)(app, self.id)
782    }
783
784    /// See [`ToggleableStateMixin::on_changed`].
785    pub fn on_changed(self, app: &App) -> Option<ValueChanged<Option<bool>>> {
786        (self.vtable.on_changed)(app, self.id)
787    }
788
789    /// See [`ToggleableStateMixin::value`].
790    pub fn value(self, app: &App) -> Option<bool> {
791        (self.vtable.value)(app, self.id)
792    }
793
794    /// See [`ToggleableStateMixin::tristate`].
795    pub fn tristate(self, app: &App) -> bool {
796        (self.vtable.tristate)(app, self.id)
797    }
798
799    /// See [`ToggleableStateMixin::animate_to_value`].
800    pub fn animate_to_value(self, app: &mut App) {
801        (self.vtable.animate_to_value)(app, self.id);
802    }
803
804    /// See [`ToggleableStateMixin::down_position`].
805    pub fn down_position(self, app: &App) -> Option<Offset> {
806        (self.vtable.down_position)(app, self.id)
807    }
808
809    /// See [`ToggleableStateMixin::states`].
810    pub fn states(self, app: &App) -> WidgetStates {
811        (self.vtable.states)(app, self.id)
812    }
813
814    /// See [`ToggleableStateMixin::build_toggleable`].
815    #[allow(clippy::too_many_arguments)]
816    pub fn build_toggleable(
817        self,
818        app: &mut App,
819        focus_node: Option<FocusNodeRef>,
820        on_focus_change: Option<ValueChanged<bool>>,
821        autofocus: bool,
822        mouse_cursor: Option<WidgetStatePropertyRef<MouseCursorRef>>,
823        size: Size,
824        painter: impl CustomPainter,
825    ) -> WidgetRef {
826        self.build_toggleable_with_child(
827            app,
828            focus_node,
829            on_focus_change,
830            autofocus,
831            mouse_cursor,
832            CustomPaint::new().size(size).painter(painter).into_widget(),
833        )
834    }
835
836    /// See [`ToggleableStateMixin::build_toggleable_with_child`].
837    pub fn build_toggleable_with_child(
838        self,
839        app: &mut App,
840        focus_node: Option<FocusNodeRef>,
841        on_focus_change: Option<ValueChanged<bool>>,
842        autofocus: bool,
843        mouse_cursor: Option<WidgetStatePropertyRef<MouseCursorRef>>,
844        child: WidgetRef,
845    ) -> WidgetRef {
846        (self.vtable.build_toggleable_with_child)(
847            app,
848            self.id,
849            focus_node,
850            on_focus_change,
851            autofocus,
852            mouse_cursor,
853            child,
854        )
855    }
856}
857
858/// The fields of Dart's `ToggleablePainter`, which a painter holds under the field
859/// `toggleable_painter`. Dart's `late` getters read them with a `!`; here
860/// [`ToggleablePainter`]'s getters panic on a field no setter has written.
861#[derive(Default)]
862pub struct ToggleablePainterData {
863    position: Option<AnimationRef<f64>>,
864    reaction: Option<AnimationRef<f64>>,
865    reaction_focus_fade: Option<AnimationRef<f64>>,
866    reaction_hover_fade: Option<AnimationRef<f64>>,
867    active_color: Option<Color>,
868    inactive_color: Option<Color>,
869    inactive_reaction_color: Option<Color>,
870    reaction_color: Option<Color>,
871    hover_color: Option<Color>,
872    focus_color: Option<Color>,
873    splash_radius: Option<f64>,
874    down_position: Option<Offset>,
875    is_focused: Option<bool>,
876    is_hovered: Option<bool>,
877    is_active: Option<bool>,
878}
879
880impl ToggleablePainterData {
881    /// The bag of a painter no setter has configured yet.
882    pub fn new() -> ToggleablePainterData {
883        ToggleablePainterData::default()
884    }
885}
886
887/// A base class for a [`CustomPainter`] that may be passed to
888/// [`ToggleableStateMixin::build_toggleable`] to draw the visual representation of a
889/// Toggleable.
890///
891/// Implementors must implement the [`paint`](Self::paint) method to draw the actual visuals of
892/// the Toggleable.
893///
894/// If drawing a radial ink reaction is desired (in Material Design for example),
895/// implementors may call [`paint_radial_reaction`](Self::paint_radial_reaction) in their
896/// [`paint`](Self::paint) method.
897///
898/// A painter is an arena `ChangeNotifier` holding a [`ToggleablePainterData`] under the field
899/// `toggleable_painter`; a `CustomPaint` holds it as a [`ToggleablePainterRef`]. A painter
900/// that overrides `dispose` ends its own by calling this trait's
901/// [`dispose`](Self::dispose), Dart's `super.dispose()`.
902pub trait ToggleablePainter: ChangeNotifier {
903    /// Base class field access.
904    fn toggleable_painter_data(self: Handle<Self>, app: &App) -> &ToggleablePainterData;
905
906    /// See [`toggleable_painter_data`](Self::toggleable_painter_data).
907    fn toggleable_painter_data_mut(self: Handle<Self>, app: &mut App)
908    -> &mut ToggleablePainterData;
909
910    /// The visual value of the control.
911    ///
912    /// Usually set to [`ToggleableStateMixin::position`].
913    fn position(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
914        self.toggleable_painter_data(app)
915            .position
916            .handle()
917            .expect("set before painting")
918    }
919
920    /// Sets [`position`](Self::position).
921    fn set_position(self: Handle<Self>, app: &mut App, value: AnimationRef<f64>) {
922        let old = self.toggleable_painter_data(app).position.handle();
923        if old == Some(value.handle()) {
924            return;
925        }
926        let notify = Listener::handle_method(self, Handle::<Self>::notify_listeners);
927        if let Some(old) = old {
928            old.remove_listener(app, &notify);
929        }
930        value.add_listener(app, notify);
931        self.toggleable_painter_data_mut(app).position = Some(value);
932        self.notify_listeners(app);
933    }
934
935    /// The visual value of the radial reaction animation.
936    ///
937    /// Usually set to [`ToggleableStateMixin::reaction`].
938    fn reaction(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
939        self.toggleable_painter_data(app)
940            .reaction
941            .handle()
942            .expect("set before painting")
943    }
944
945    /// Sets [`reaction`](Self::reaction).
946    fn set_reaction(self: Handle<Self>, app: &mut App, value: AnimationRef<f64>) {
947        let old = self.toggleable_painter_data(app).reaction.handle();
948        if old == Some(value.handle()) {
949            return;
950        }
951        let notify = Listener::handle_method(self, Handle::<Self>::notify_listeners);
952        if let Some(old) = old {
953            old.remove_listener(app, &notify);
954        }
955        value.add_listener(app, notify);
956        self.toggleable_painter_data_mut(app).reaction = Some(value);
957        self.notify_listeners(app);
958    }
959
960    /// Controls the radial reaction's opacity animation for focus changes.
961    ///
962    /// Usually set to [`ToggleableStateMixin::reaction_focus_fade`].
963    fn reaction_focus_fade(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
964        self.toggleable_painter_data(app)
965            .reaction_focus_fade
966            .handle()
967            .expect("set before painting")
968    }
969
970    /// Sets [`reaction_focus_fade`](Self::reaction_focus_fade).
971    fn set_reaction_focus_fade(self: Handle<Self>, app: &mut App, value: AnimationRef<f64>) {
972        let old = self
973            .toggleable_painter_data(app)
974            .reaction_focus_fade
975            .handle();
976        if old == Some(value.handle()) {
977            return;
978        }
979        let notify = Listener::handle_method(self, Handle::<Self>::notify_listeners);
980        if let Some(old) = old {
981            old.remove_listener(app, &notify);
982        }
983        value.add_listener(app, notify);
984        self.toggleable_painter_data_mut(app).reaction_focus_fade = Some(value);
985        self.notify_listeners(app);
986    }
987
988    /// Controls the radial reaction's opacity animation for hover changes.
989    ///
990    /// Usually set to [`ToggleableStateMixin::reaction_hover_fade`].
991    fn reaction_hover_fade(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
992        self.toggleable_painter_data(app)
993            .reaction_hover_fade
994            .handle()
995            .expect("set before painting")
996    }
997
998    /// Sets [`reaction_hover_fade`](Self::reaction_hover_fade).
999    fn set_reaction_hover_fade(self: Handle<Self>, app: &mut App, value: AnimationRef<f64>) {
1000        let old = self
1001            .toggleable_painter_data(app)
1002            .reaction_hover_fade
1003            .handle();
1004        if old == Some(value.handle()) {
1005            return;
1006        }
1007        let notify = Listener::handle_method(self, Handle::<Self>::notify_listeners);
1008        if let Some(old) = old {
1009            old.remove_listener(app, &notify);
1010        }
1011        value.add_listener(app, notify);
1012        self.toggleable_painter_data_mut(app).reaction_hover_fade = Some(value);
1013        self.notify_listeners(app);
1014    }
1015
1016    /// The color that should be used in the active state (i.e., when
1017    /// [`ToggleableStateMixin::value`] is true).
1018    ///
1019    /// For example, a checkbox should use this color when checked.
1020    fn active_color(self: Handle<Self>, app: &App) -> Color {
1021        self.toggleable_painter_data(app)
1022            .active_color
1023            .expect("set before painting")
1024    }
1025
1026    /// Sets [`active_color`](Self::active_color).
1027    fn set_active_color(self: Handle<Self>, app: &mut App, value: Color) {
1028        if self.toggleable_painter_data(app).active_color == Some(value) {
1029            return;
1030        }
1031        self.toggleable_painter_data_mut(app).active_color = Some(value);
1032        self.notify_listeners(app);
1033    }
1034
1035    /// The color that should be used in the inactive state (i.e., when
1036    /// [`ToggleableStateMixin::value`] is false).
1037    ///
1038    /// For example, a checkbox should use this color when unchecked.
1039    fn inactive_color(self: Handle<Self>, app: &App) -> Color {
1040        self.toggleable_painter_data(app)
1041            .inactive_color
1042            .expect("set before painting")
1043    }
1044
1045    /// Sets [`inactive_color`](Self::inactive_color).
1046    fn set_inactive_color(self: Handle<Self>, app: &mut App, value: Color) {
1047        if self.toggleable_painter_data(app).inactive_color == Some(value) {
1048            return;
1049        }
1050        self.toggleable_painter_data_mut(app).inactive_color = Some(value);
1051        self.notify_listeners(app);
1052    }
1053
1054    /// The color that should be used for the reaction when the toggleable is inactive.
1055    ///
1056    /// Used when the toggleable needs to change the reaction color/transparency that is
1057    /// displayed when the toggleable is inactive and tapped.
1058    fn inactive_reaction_color(self: Handle<Self>, app: &App) -> Color {
1059        self.toggleable_painter_data(app)
1060            .inactive_reaction_color
1061            .expect("set before painting")
1062    }
1063
1064    /// Sets [`inactive_reaction_color`](Self::inactive_reaction_color).
1065    fn set_inactive_reaction_color(self: Handle<Self>, app: &mut App, value: Color) {
1066        if self.toggleable_painter_data(app).inactive_reaction_color == Some(value) {
1067            return;
1068        }
1069        self.toggleable_painter_data_mut(app)
1070            .inactive_reaction_color = Some(value);
1071        self.notify_listeners(app);
1072    }
1073
1074    /// The color that should be used for the reaction when the toggleable is active.
1075    ///
1076    /// Used when the toggleable needs to change the reaction color/transparency that is
1077    /// displayed when the toggleable is active and tapped.
1078    fn reaction_color(self: Handle<Self>, app: &App) -> Color {
1079        self.toggleable_painter_data(app)
1080            .reaction_color
1081            .expect("set before painting")
1082    }
1083
1084    /// Sets [`reaction_color`](Self::reaction_color).
1085    fn set_reaction_color(self: Handle<Self>, app: &mut App, value: Color) {
1086        if self.toggleable_painter_data(app).reaction_color == Some(value) {
1087            return;
1088        }
1089        self.toggleable_painter_data_mut(app).reaction_color = Some(value);
1090        self.notify_listeners(app);
1091    }
1092
1093    /// The color that should be used for the reaction when [`is_hovered`](Self::is_hovered)
1094    /// is true.
1095    ///
1096    /// Used when the toggleable needs to change the reaction color/transparency, when it is
1097    /// being hovered over.
1098    fn hover_color(self: Handle<Self>, app: &App) -> Color {
1099        self.toggleable_painter_data(app)
1100            .hover_color
1101            .expect("set before painting")
1102    }
1103
1104    /// Sets [`hover_color`](Self::hover_color).
1105    fn set_hover_color(self: Handle<Self>, app: &mut App, value: Color) {
1106        if self.toggleable_painter_data(app).hover_color == Some(value) {
1107            return;
1108        }
1109        self.toggleable_painter_data_mut(app).hover_color = Some(value);
1110        self.notify_listeners(app);
1111    }
1112
1113    /// The color that should be used for the reaction when [`is_focused`](Self::is_focused)
1114    /// is true.
1115    ///
1116    /// Used when the toggleable needs to change the reaction color/transparency, when it has
1117    /// focus.
1118    fn focus_color(self: Handle<Self>, app: &App) -> Color {
1119        self.toggleable_painter_data(app)
1120            .focus_color
1121            .expect("set before painting")
1122    }
1123
1124    /// Sets [`focus_color`](Self::focus_color).
1125    fn set_focus_color(self: Handle<Self>, app: &mut App, value: Color) {
1126        if self.toggleable_painter_data(app).focus_color == Some(value) {
1127            return;
1128        }
1129        self.toggleable_painter_data_mut(app).focus_color = Some(value);
1130        self.notify_listeners(app);
1131    }
1132
1133    /// The splash radius for the radial reaction.
1134    fn splash_radius(self: Handle<Self>, app: &App) -> f64 {
1135        self.toggleable_painter_data(app)
1136            .splash_radius
1137            .expect("set before painting")
1138    }
1139
1140    /// Sets [`splash_radius`](Self::splash_radius).
1141    fn set_splash_radius(self: Handle<Self>, app: &mut App, value: f64) {
1142        if self.toggleable_painter_data(app).splash_radius == Some(value) {
1143            return;
1144        }
1145        self.toggleable_painter_data_mut(app).splash_radius = Some(value);
1146        self.notify_listeners(app);
1147    }
1148
1149    /// The [`Offset`] within the Toggleable at which a pointer touched the Toggleable.
1150    ///
1151    /// This is null if currently no pointer is touching the Toggleable.
1152    ///
1153    /// Usually set to [`ToggleableStateMixin::down_position`].
1154    fn down_position(self: Handle<Self>, app: &App) -> Option<Offset> {
1155        self.toggleable_painter_data(app).down_position
1156    }
1157
1158    /// Sets [`down_position`](Self::down_position).
1159    fn set_down_position(self: Handle<Self>, app: &mut App, value: Option<Offset>) {
1160        if self.toggleable_painter_data(app).down_position == value {
1161            return;
1162        }
1163        self.toggleable_painter_data_mut(app).down_position = value;
1164        self.notify_listeners(app);
1165    }
1166
1167    /// True if this toggleable has the input focus.
1168    fn is_focused(self: Handle<Self>, app: &App) -> bool {
1169        self.toggleable_painter_data(app)
1170            .is_focused
1171            .expect("set before painting")
1172    }
1173
1174    /// Sets [`is_focused`](Self::is_focused).
1175    fn set_is_focused(self: Handle<Self>, app: &mut App, value: Option<bool>) {
1176        if self.toggleable_painter_data(app).is_focused == value {
1177            return;
1178        }
1179        self.toggleable_painter_data_mut(app).is_focused = value;
1180        self.notify_listeners(app);
1181    }
1182
1183    /// True if this toggleable is being hovered over by a pointer.
1184    fn is_hovered(self: Handle<Self>, app: &App) -> bool {
1185        self.toggleable_painter_data(app)
1186            .is_hovered
1187            .expect("set before painting")
1188    }
1189
1190    /// Sets [`is_hovered`](Self::is_hovered).
1191    fn set_is_hovered(self: Handle<Self>, app: &mut App, value: Option<bool>) {
1192        if self.toggleable_painter_data(app).is_hovered == value {
1193            return;
1194        }
1195        self.toggleable_painter_data_mut(app).is_hovered = value;
1196        self.notify_listeners(app);
1197    }
1198
1199    /// Determines whether the toggleable shows as active.
1200    fn is_active(self: Handle<Self>, app: &App) -> bool {
1201        self.toggleable_painter_data(app)
1202            .is_active
1203            .expect("set before painting")
1204    }
1205
1206    /// Sets [`is_active`](Self::is_active).
1207    fn set_is_active(self: Handle<Self>, app: &mut App, value: Option<bool>) {
1208        if self.toggleable_painter_data(app).is_active == value {
1209            return;
1210        }
1211        self.toggleable_painter_data_mut(app).is_active = value;
1212        self.notify_listeners(app);
1213    }
1214
1215    /// Draws the Toggleable into `size`; Dart's abstract `CustomPainter.paint`.
1216    fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size);
1217
1218    /// Used by implementors to paint the radial ink reaction for this control.
1219    ///
1220    /// The reaction is painted on the given canvas at the given offset. The origin is the
1221    /// center point of the reaction (usually distinct from the
1222    /// [`down_position`](Self::down_position) at which the user interacted with the control).
1223    fn paint_radial_reaction(
1224        self: Handle<Self>,
1225        app: &App,
1226        canvas: &mut Canvas,
1227        offset: Offset,
1228        origin: Offset,
1229    ) {
1230        let reaction = self.reaction(app);
1231        let reaction_focus_fade = self.reaction_focus_fade(app);
1232        let reaction_hover_fade = self.reaction_hover_fade(app);
1233        if !reaction.is_dismissed(app)
1234            || !reaction_focus_fade.is_dismissed(app)
1235            || !reaction_hover_fade.is_dismissed(app)
1236        {
1237            let reaction_color = Color::lerp(
1238                Color::lerp(
1239                    Color::lerp(
1240                        Some(self.inactive_reaction_color(app)),
1241                        Some(self.reaction_color(app)),
1242                        self.position(app).value(app),
1243                    ),
1244                    Some(self.hover_color(app)),
1245                    reaction_hover_fade.value(app),
1246                ),
1247                Some(self.focus_color(app)),
1248                reaction_focus_fade.value(app),
1249            )
1250            .expect("lerping non-null colors");
1251            let reaction_paint = Paint::from_color(reaction_color.into());
1252            let splash_radius = self.splash_radius(app);
1253            // Dart's `Tween<double>(begin: 0.0, end: splashRadius).evaluate(reaction)`.
1254            let reaction_radius = if self.is_focused(app) || self.is_hovered(app) {
1255                splash_radius
1256            } else {
1257                splash_radius * reaction.value(app)
1258            };
1259            if reaction_radius > 0.0 {
1260                canvas.draw_circle(origin + offset, reaction_radius as f32, &reaction_paint);
1261            }
1262        }
1263    }
1264
1265    /// Removes the listeners the animation setters added; Dart's `ToggleablePainter.dispose`,
1266    /// which a painter's own `dispose` calls last.
1267    fn dispose(self: Handle<Self>, app: &mut App) {
1268        let notify = Listener::handle_method(self, Handle::<Self>::notify_listeners);
1269        let data = self.toggleable_painter_data(app);
1270        let animations = [
1271            data.position.handle(),
1272            data.reaction.handle(),
1273            data.reaction_focus_fade.handle(),
1274            data.reaction_hover_fade.handle(),
1275        ];
1276        for animation in animations.into_iter().flatten() {
1277            animation.remove_listener(app, &notify);
1278        }
1279        ChangeNotifierData::dispose(app, self);
1280    }
1281}
1282
1283/// A [`ToggleablePainter`] as the [`CustomPainter`] a `CustomPaint` holds: the painter is an
1284/// arena object, so the value the widget carries is its handle plus the [`Listenable`] the
1285/// render object subscribes to (Dart's painter is its own `repaint`).
1286pub struct ToggleablePainterRef<P: ToggleablePainter> {
1287    painter: Ref<P>,
1288    repaint: Rc<dyn Listenable>,
1289}
1290
1291impl<P: ToggleablePainter> ToggleablePainterRef<P> {
1292    /// Wraps a [`ToggleablePainter`] as a [`CustomPainter`].
1293    pub fn new(painter: Ref<P>) -> ToggleablePainterRef<P> {
1294        ToggleablePainterRef {
1295            repaint: Rc::new(painter.clone()),
1296            painter,
1297        }
1298    }
1299
1300    /// The painter itself.
1301    pub fn painter(&self) -> Handle<P> {
1302        self.painter.handle()
1303    }
1304}
1305
1306impl<P: ToggleablePainter> CustomPainter for ToggleablePainterRef<P> {
1307    fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
1308        Some(&self.repaint)
1309    }
1310
1311    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1312        ToggleablePainter::paint(self.painter.handle(), app, canvas, size);
1313    }
1314
1315    fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
1316        true
1317    }
1318
1319    fn as_any(&self) -> &dyn Any {
1320        self
1321    }
1322}
1323
1324impl<P: ToggleablePainter> Debug for ToggleablePainterRef<P> {
1325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1326        write!(f, "{}#{:?}", std::any::type_name::<P>(), self.painter.id())
1327    }
1328}