use std::time::{Duration, Instant};
use gpui::{App, ElementId, Styled, Window};
use super::{reduced_motion, Easing, Interpolate, Keyframes};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Transition {
pub duration: Duration,
pub easing: Easing,
}
impl Transition {
#[must_use]
pub fn new(duration: Duration, easing: Easing) -> Self {
Self { duration, easing }
}
#[must_use]
pub fn ease_out(milliseconds: u64) -> Self {
Self::new(Duration::from_millis(milliseconds), Easing::EaseOut)
}
#[must_use]
pub fn ease_in_out(milliseconds: u64) -> Self {
Self::new(Duration::from_millis(milliseconds), Easing::EaseInOut)
}
#[must_use]
pub fn linear(milliseconds: u64) -> Self {
Self::new(Duration::from_millis(milliseconds), Easing::Linear)
}
#[must_use]
pub fn spring() -> Self {
Self::new(Duration::from_millis(500), Easing::Spring { damping: 0.6 })
}
}
impl Default for Transition {
fn default() -> Self {
Self::ease_out(200)
}
}
struct Tween<T> {
from: T,
to: T,
started: Instant,
}
pub fn use_transition<T: Interpolate + PartialEq + 'static>(
key: impl Into<ElementId>,
window: &mut Window,
cx: &mut App,
target: T,
transition: Transition,
) -> T {
let state = window.use_keyed_state(key, cx, |_, _| Tween {
from: target,
to: target,
started: Instant::now(),
});
let now = Instant::now();
let value_at = |tween: &Tween<T>, now: Instant| -> (T, bool) {
if reduced_motion() || transition.duration.is_zero() {
return (tween.to, true);
}
let elapsed = now.duration_since(tween.started).as_secs_f32();
let t = elapsed / transition.duration.as_secs_f32();
if t >= 1. {
(tween.to, true)
} else {
(
tween.from.interpolate(tween.to, transition.easing.apply(t)),
false,
)
}
};
if state.read(cx).to != target {
let (current, _) = value_at(state.read(cx), now);
state.update(cx, |tween, _| {
tween.from = current;
tween.to = target;
tween.started = now;
});
}
let (value, finished) = value_at(state.read(cx), now);
if !finished {
window.request_animation_frame();
}
value
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Presence {
progress: f32,
present: bool,
}
impl Presence {
#[must_use]
pub fn is_mounted(&self) -> bool {
self.present || self.progress > 0.001
}
#[must_use]
pub fn progress(&self) -> f32 {
self.progress
}
#[must_use]
pub fn is_present(&self) -> bool {
self.present
}
pub fn apply<E: Styled>(&self, element: E, keyframes: &Keyframes) -> E {
keyframes.apply(element, self.progress)
}
}
pub fn use_presence(
key: impl Into<ElementId>,
window: &mut Window,
cx: &mut App,
present: bool,
transition: Transition,
) -> Presence {
let target = if present { 1. } else { 0. };
let progress = use_transition(key, window, cx, target, transition);
Presence { progress, present }
}