Skip to main content

waft_winui/primitives/
color_transition.rs

1//! XAML `BrushTransition`: when a property's brush changes, the old colour fades to the new one over the transition's duration instead of snapping.
2
3use std::{fmt, rc::Rc, time::Duration};
4use waft_animation::{AnimationBehavior, AnimationController, ColorTween, Curves};
5use waft_embedder::Color;
6use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
7use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
8use waft_widgets::*;
9
10/// Builds the subtree for the colour currently shown.
11pub type ColorBuilder = Rc<dyn Fn(&mut App, Color) -> WidgetRef>;
12
13/// Animates from the colour last built to `color` over `duration` whenever `color` changes; XAML `BrushTransition` (linear, the transition names no easing).
14#[derive(Clone)]
15pub struct ColorTransition {
16    pub color: Color,
17    pub duration: Duration,
18    pub builder: ColorBuilder,
19}
20
21impl ColorTransition {
22    pub fn new(
23        color: Color,
24        duration: Duration,
25        builder: impl Fn(&mut App, Color) -> WidgetRef + 'static,
26    ) -> ColorTransition {
27        ColorTransition {
28            color,
29            duration,
30            builder: Rc::new(builder),
31        }
32    }
33}
34
35impl fmt::Debug for ColorTransition {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_struct("ColorTransition")
38            .field("color", &self.color)
39            .field("duration", &self.duration)
40            .finish_non_exhaustive()
41    }
42}
43
44pub struct ColorTransitionState {
45    state: StateData<ColorTransition>,
46    single_ticker_provider: SingleTickerProviderStateMixinData,
47    controller: Option<Ref<AnimationController>>,
48    tween: Option<Ref<ColorTween>>,
49    /// The colour on screen when the current transition started.
50    from: Color,
51}
52
53impl StatefulWidget for ColorTransition {
54    type State = ColorTransitionState;
55    fn create_state(&self) -> ColorTransitionState {
56        ColorTransitionState {
57            state: StateData::new(),
58            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
59            controller: None,
60            tween: None,
61            from: self.color,
62        }
63    }
64}
65
66impl SingleTickerProviderStateMixin for ColorTransitionState {
67    fn single_ticker_provider_data(
68        self: Handle<Self>,
69        app: &App,
70    ) -> &SingleTickerProviderStateMixinData {
71        &app.get(self).single_ticker_provider
72    }
73    fn single_ticker_provider_data_mut(
74        self: Handle<Self>,
75        app: &mut App,
76    ) -> &mut SingleTickerProviderStateMixinData {
77        &mut app.get_mut(self).single_ticker_provider
78    }
79}
80
81impl TickerProviderObject for ColorTransitionState {
82    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
83        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
84    }
85}
86
87impl ColorTransitionState {
88    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
89        app.get(self)
90            .controller
91            .handle()
92            .expect("created in init_state")
93    }
94
95    /// The colour at this frame of the transition.
96    fn current(self: Handle<Self>, app: &App) -> Color {
97        let controller = self.controller(app);
98        let tween = app.get(self).tween.handle().expect("created in init_state");
99        tween
100            .lerp(app, controller.value(app))
101            .unwrap_or(self.widget(app).color)
102    }
103}
104
105impl State for ColorTransitionState {
106    type Widget = ColorTransition;
107    waft_widgets::state_accessors!();
108
109    fn init_state(self: Handle<Self>, app: &mut App) {
110        let (color, duration) = {
111            let widget = self.widget(app);
112            (widget.color, widget.duration)
113        };
114        let controller = AnimationController::new(
115            app,
116            Some(1.0),
117            Some(duration),
118            None,
119            0.0,
120            1.0,
121            AnimationBehavior::Normal,
122            self,
123        );
124        controller.add_listener(app, Listener::new(move |app| self.set_state(app, |_| {})));
125        let tween = ColorTween::new(app, Some(color), Some(color));
126        let state = app.get_mut(self);
127        state.controller = Some(controller);
128        state.tween = Some(tween);
129    }
130
131    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ColorTransition) {
132        let color = self.widget(app).color;
133        if color == old_widget.color {
134            return;
135        }
136        let from = self.current(app);
137        let tween = ColorTween::new(app, Some(from), Some(color));
138        let controller = self.controller(app);
139        app.get_mut(self).tween = Some(tween);
140        app.get_mut(self).from = from;
141        controller.set_value(app, 0.0);
142        controller.animate_to(app, 1.0, None, Curves::linear());
143    }
144
145    fn activate(self: Handle<Self>, app: &mut App) {
146        SingleTickerProviderStateMixin::activate(self, app);
147    }
148
149    fn dispose(self: Handle<Self>, app: &mut App) {
150        let controller = self.controller(app);
151        controller.dispose(app);
152        SingleTickerProviderStateMixin::dispose(self, app);
153    }
154
155    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
156        let color = self.current(app);
157        let builder = self.widget(app).builder.clone();
158        builder(app, color)
159    }
160}