Skip to content

Visual Studio Code, rebuilt in Rust

Rust
6.1 KB
Raw Blame
//! CSS `transition`s for the port's elements: a value that moves to each new target over a duration and timing
//! curve, starting from the value shown when the target changed, and the element that keeps a view drawing while it
//! moves.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::hash::Hash;
use std::time::{Duration, Instant};

use gpui::{IntoElement, Rgba, Styled, canvas};

#[derive(Clone, Copy)]
pub(super) struct Transition<const N: usize> {
    from: [f32; N],
    to: [f32; N],
    at: Instant,
    duration: Duration,
    curve: fn(f32) -> f32,
}

impl<const N: usize> Transition<N> {
    pub fn new(value: [f32; N], duration: Duration, curve: fn(f32) -> f32, now: Instant) -> Self {
        Self { from: value, to: value, at: now, duration, curve }
    }

    /// Moves to `target` from the value at `now`, or jumps there without `animate` (reduced motion, also when it
    /// turns on mid-move).
    pub fn set(&mut self, target: [f32; N], now: Instant, animate: bool) {
        if !animate {
            (self.from, self.to) = (target, target);
            return;
        }
        if target == self.to {
            return;
        }
        self.from = self.value(now);
        self.to = target;
        self.at = now;
    }

    pub fn value(&self, now: Instant) -> [f32; N] {
        let progress = (now.saturating_duration_since(self.at).as_secs_f32() / self.duration.as_secs_f32()).min(1.);
        let eased = (self.curve)(progress);
        std::array::from_fn(|index| self.from[index] + (self.to[index] - self.from[index]) * eased)
    }

    pub fn target(&self) -> [f32; N] {
        self.to
    }

    pub fn moving(&self, now: Instant) -> bool {
        self.from != self.to && now < self.at + self.duration
    }
}

/// The value of the transition in `cell` after it moves to `target`, and whether it still moves. The first target
/// shows at once.
pub(super) fn follow<const N: usize>(cell: &Cell<Option<Transition<N>>>, target: [f32; N], duration: Duration, curve: fn(f32) -> f32, animate: bool) -> ([f32; N], bool) {
    let now = Instant::now();
    let mut transition = cell.get().unwrap_or_else(|| Transition::new(target, duration, curve, now));
    transition.set(target, now, animate);
    cell.set(Some(transition));
    (transition.value(now), transition.moving(now))
}

/// The 0 to 1 transition of `key` toward 1 while `on` and back to 0 after, with whether it still moves; `None`
/// once it is back at 0, when `transitions` drops it.
pub(super) fn toggle<K: Hash + Eq>(transitions: &RefCell<HashMap<K, Transition<1>>>, key: K, on: bool, duration: Duration, curve: fn(f32) -> f32, animate: bool) -> Option<(f32, bool)> {
    let now = Instant::now();
    let mut transitions = transitions.borrow_mut();
    let transition = match transitions.entry(key) {
        Entry::Vacant(_) if !on => return None,
        Entry::Vacant(entry) => entry.insert(Transition::new([0.], duration, curve, now)),
        Entry::Occupied(entry) => entry.into_mut(),
    };
    transition.set([if on { 1. } else { 0. }], now, animate);
    let ([value], moving) = (transition.value(now), transition.moving(now));
    if !on && !moving {
        transitions.retain(|_, transition| transition.target() == [1.] || transition.moving(now));
        return None;
    }
    Some((value, moving))
}

pub(super) fn rgba_values(color: Rgba) -> [f32; 4] {
    [color.r, color.g, color.b, color.a]
}

pub(super) fn values_rgba([r, g, b, a]: [f32; 4]) -> Rgba {
    Rgba { r, g, b, a }
}

/// Draws the view again on the next frame, for a render that has no `Window` to ask with.
pub(super) fn next_frame() -> impl IntoElement {
    canvas(|_, window, _| window.request_animation_frame(), |_, _, _, _| {}).absolute()
}

/// A CSS `cubic-bezier(x1, y1, x2, y2)` at `x`: the curve's parameter for `x` found by bisection, then its y.
pub(super) fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
    if x <= 0. || x >= 1. {
        return x.clamp(0., 1.);
    }
    let bezier = |p1: f32, p2: f32, t: f32| 3. * p1 * t * (1. - t).powi(2) + 3. * p2 * t * t * (1. - t) + t.powi(3);
    let (mut low, mut high) = (0., 1.);
    for _ in 0..24 {
        let mid = (low + high) / 2.;
        if bezier(x1, x2, mid) < x { low = mid } else { high = mid }
    }
    bezier(y1, y2, (low + high) / 2.)
}

pub(super) fn ease_out(x: f32) -> f32 {
    cubic_bezier(0., 0., 0.58, 1., x)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_new_target_moves_from_the_value_shown_then() {
        let start = Instant::now();
        let ms = |millis| start + Duration::from_millis(millis);
        let mut transition = Transition::new([0.], Duration::from_millis(100), |progress| progress, start);
        transition.set([1.], start, true);
        assert!((transition.value(ms(40))[0] - 0.4).abs() < 1e-5);
        transition.set([0.], ms(40), true);
        assert!((transition.value(ms(90))[0] - 0.2).abs() < 1e-5, "back from 0.4, half way");
        assert_eq!(transition.value(ms(140)), [0.]);
        assert!(!transition.moving(ms(140)));
        transition.set([1.], ms(150), false);
        assert_eq!(transition.value(ms(150)), [1.]);
        assert!(!transition.moving(ms(150)));
    }

    #[test]
    fn a_toggle_fades_out_after_off_then_forgets_its_key() {
        let transitions = RefCell::new(HashMap::new());
        let toggle = |on, animate| toggle(&transitions, "sash", on, Duration::from_millis(50), |progress| progress, animate);
        assert_eq!(toggle(false, true), None, "never on: nothing to fade");
        assert_eq!(toggle(true, false), Some((1., false)));
        let (value, moving) = toggle(false, true).expect("fading out");
        assert!(value > 0.9 && moving);
        assert_eq!(toggle(false, false), None, "reduced motion: gone at once");
        assert!(transitions.borrow().is_empty());
    }

    #[test]
    fn ease_out_is_css_ease_out() {
        assert_eq!(ease_out(0.), 0.);
        assert!((ease_out(1.) - 1.).abs() < 1e-5);
        // cubic-bezier(0, 0, 0.58, 1) at x 0.5: t 0.6258, y 0.6847 (by hand from the curve's polynomials).
        assert!((ease_out(0.5) - 0.6847).abs() < 2e-3, "{}", ease_out(0.5));
    }
}