1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use crate::style::{Background, BorderColor, BorderRadius, TextColor};

use super::{
    anim_val::AnimValue, AnimId, AnimPropKind, AnimState, AnimStateKind, AnimatedProp, Easing,
    EasingFn, EasingMode,
};
use std::{borrow::BorrowMut, collections::HashMap, time::Duration, time::Instant};

use floem_peniko::Color;
use floem_reactive::create_effect;

#[derive(Clone, Debug)]
pub struct Animation {
    pub(crate) id: AnimId,
    pub(crate) state: AnimState,
    pub(crate) easing: Easing,
    pub(crate) auto_reverse: bool,
    pub(crate) skip: Option<Duration>,
    pub(crate) duration: Duration,
    pub(crate) repeat_mode: RepeatMode,
    pub(crate) repeat_count: usize,
    pub(crate) animated_props: HashMap<AnimPropKind, AnimatedProp>,
}

pub(crate) fn assert_valid_time(time: f64) {
    assert!(time >= 0.0 || time <= 1.0);
}

/// The mode to specify how the animation should repeat. See also [`Animation::advance`]
#[derive(Clone, Debug)]
pub enum RepeatMode {
    // Once started, the animation will juggle between [`AnimState::PassInProgress`] and [`AnimState::PassFinished`],
    // but will never reach [`AnimState::Completed`]
    /// Repeat the animation forever
    LoopForever,
    // On every pass, we animate until `elapsed >= duration`, then we reset elapsed time to 0 and increment `repeat_count` is
    // increased by 1. This process is repeated until `repeat_count >= times`, and then the animation is set
    // to [`AnimState::Completed`].
    /// Repeat the animation the specified number of times before the animation enters a Complete state
    Times(usize),
}

pub fn animation() -> Animation {
    Animation {
        id: AnimId::next(),
        state: AnimState::Idle,
        easing: Easing::default(),
        auto_reverse: false,
        skip: None,
        duration: Duration::from_secs(1),
        repeat_mode: RepeatMode::Times(1),
        repeat_count: 0,
        animated_props: HashMap::new(),
    }
}

#[derive(Debug, Clone)]
pub enum AnimUpdateMsg {
    Prop {
        id: AnimId,
        kind: AnimPropKind,
        val: AnimValue,
    },
}

#[derive(Clone, Debug)]
pub enum SizeUnit {
    Px,
    Pct,
}

#[derive(Debug, Clone, Copy)]
pub enum AnimDirection {
    Forward,
    Backward,
}

impl Animation {
    pub fn id(&self) -> AnimId {
        self.id
    }

    pub fn duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    pub fn is_idle(&self) -> bool {
        matches!(self.state_kind(), AnimStateKind::Idle)
    }

    pub fn is_in_progress(&self) -> bool {
        matches!(self.state_kind(), AnimStateKind::PassInProgress)
    }

    pub fn is_completed(&self) -> bool {
        matches!(self.state_kind(), AnimStateKind::Completed)
    }

    pub fn is_auto_reverse(&self) -> bool {
        self.auto_reverse
    }

    // pub fn scale(self, scale: f64) -> Self {
    //     todo!()
    // }

    pub fn border_radius(self, border_radius_fn: impl Fn() -> f64 + 'static) -> Self {
        create_effect(move |_| {
            let border_radius = border_radius_fn();

            self.id
                .update_style_prop(BorderRadius, border_radius.into());
        });

        self
    }

    pub fn color(self, color_fn: impl Fn() -> Color + 'static) -> Self {
        create_effect(move |_| {
            let color = color_fn();

            self.id.update_style_prop(TextColor, Some(color));
        });

        self
    }

    pub fn border_color(self, bord_color_fn: impl Fn() -> Color + 'static) -> Self {
        create_effect(move |_| {
            let border_color = bord_color_fn();

            self.id.update_style_prop(BorderColor, border_color);
        });

        self
    }

    pub fn background(self, bg_fn: impl Fn() -> Color + 'static) -> Self {
        create_effect(move |_| {
            let background = bg_fn();

            self.id.update_style_prop(Background, Some(background));
        });

        self
    }

    pub fn width(self, width_fn: impl Fn() -> f64 + 'static) -> Self {
        create_effect(move |_| {
            let to_width = width_fn();

            self.id
                .update_prop(AnimPropKind::Width, AnimValue::Float(to_width));
        });

        self
    }

    pub fn height(self, height_fn: impl Fn() -> f64 + 'static) -> Self {
        create_effect(move |_| {
            let height = height_fn();

            self.id
                .update_prop(AnimPropKind::Height, AnimValue::Float(height));
        });

        self
    }

    pub fn auto_reverse(mut self, auto_rev: bool) -> Self {
        self.auto_reverse = auto_rev;
        self
    }

    /// Should the animation repeat forever?
    pub fn repeat(mut self, repeat: bool) -> Self {
        self.repeat_mode = if repeat {
            RepeatMode::LoopForever
        } else {
            RepeatMode::Times(1)
        };
        self
    }

    /// How many passes(loops) of the animation do we want?
    pub fn repeat_times(mut self, times: usize) -> Self {
        self.repeat_mode = RepeatMode::Times(times);
        self
    }

    pub fn easing_fn(mut self, easing_fn: EasingFn) -> Self {
        self.easing.func = easing_fn;
        self
    }

    pub fn ease_mode(mut self, mode: EasingMode) -> Self {
        self.easing.mode = mode;
        self
    }

    pub fn ease_in(self) -> Self {
        self.ease_mode(EasingMode::In)
    }

    pub fn ease_out(self) -> Self {
        self.ease_mode(EasingMode::Out)
    }

    pub fn ease_in_out(self) -> Self {
        self.ease_mode(EasingMode::InOut)
    }

    pub fn begin(&mut self) {
        self.repeat_count = 0;
        self.state = AnimState::PassInProgress {
            started_on: Instant::now(),
            elapsed: Duration::ZERO,
        }
    }

    pub fn stop(&mut self) {
        match &mut self.state {
            AnimState::Idle | AnimState::Completed { .. } | AnimState::PassFinished { .. } => {}
            AnimState::PassInProgress {
                started_on,
                elapsed,
            } => {
                let duration = Instant::now() - *started_on;
                let elapsed = *elapsed + duration;
                self.state = AnimState::Completed {
                    elapsed: Some(elapsed),
                }
            }
        }
    }

    pub fn state_kind(&self) -> AnimStateKind {
        match self.state {
            AnimState::Idle => AnimStateKind::Idle,
            AnimState::PassInProgress { .. } => AnimStateKind::PassInProgress,
            AnimState::PassFinished { .. } => AnimStateKind::PassFinished,
            AnimState::Completed { .. } => AnimStateKind::Completed,
        }
    }

    pub fn elapsed(&self) -> Option<Duration> {
        match &self.state {
            AnimState::Idle => None,
            AnimState::PassInProgress {
                started_on,
                elapsed,
            } => {
                let duration = Instant::now() - *started_on;
                Some(*elapsed + duration)
            }
            AnimState::PassFinished { elapsed } => Some(*elapsed),
            AnimState::Completed { elapsed, .. } => *elapsed,
        }
    }

    pub fn advance(&mut self) {
        match &mut self.state {
            AnimState::Idle => {
                self.begin();
            }
            AnimState::PassInProgress {
                started_on,
                mut elapsed,
            } => {
                let now = Instant::now();
                let duration = now - *started_on;
                elapsed += duration;

                if elapsed >= self.duration {
                    self.state = AnimState::PassFinished { elapsed };
                }
            }
            AnimState::PassFinished { elapsed } => match self.repeat_mode {
                RepeatMode::LoopForever => {
                    self.state = AnimState::PassInProgress {
                        started_on: Instant::now(),
                        elapsed: Duration::ZERO,
                    }
                }
                RepeatMode::Times(times) => {
                    self.repeat_count += 1;
                    if self.repeat_count >= times {
                        self.state = AnimState::Completed {
                            elapsed: Some(*elapsed),
                        }
                    } else {
                        self.state = AnimState::PassInProgress {
                            started_on: Instant::now(),
                            elapsed: Duration::ZERO,
                        }
                    }
                }
            },
            AnimState::Completed { .. } => {}
        }
    }

    pub(crate) fn props(&self) -> &HashMap<AnimPropKind, AnimatedProp> {
        &self.animated_props
    }

    pub(crate) fn props_mut(&mut self) -> &mut HashMap<AnimPropKind, AnimatedProp> {
        self.animated_props.borrow_mut()
    }

    pub(crate) fn animate_prop(&self, elapsed: Duration, prop_kind: &AnimPropKind) -> AnimValue {
        let mut elapsed = elapsed;
        let prop = self.animated_props.get(prop_kind).unwrap();

        if let Some(skip) = self.skip {
            elapsed += skip;
        }

        if self.duration == Duration::ZERO {
            return prop.from();
        }

        if elapsed > self.duration {
            elapsed = self.duration;
        }

        let time = elapsed.as_secs_f64() / self.duration.as_secs_f64();
        let time = self.easing.ease(time);
        assert_valid_time(time);

        if self.auto_reverse {
            if time > 0.5 {
                prop.animate(time * 2.0 - 1.0, AnimDirection::Backward)
            } else {
                prop.animate(time * 2.0, AnimDirection::Forward)
            }
        } else {
            prop.animate(time, AnimDirection::Forward)
        }
    }
}