use std::time::Duration;
use arc_tokens::{ArcMotionTokens, CubicBezierSpec};
use gpui_kit::{
App, ElementId, Window,
base::{MotionStatus, PresencePhase, TransitionId},
};
use crate::{bezier::CubicBezier, clock::motion_now};
#[derive(Clone, Copy, Debug)]
pub struct ArcPresenceConfig {
pub enter_duration: Duration,
pub enter_ease: CubicBezierSpec,
pub exit_duration: Duration,
pub exit_ease: CubicBezierSpec,
pub fade_on_reduced_motion: bool,
}
impl Default for ArcPresenceConfig {
fn default() -> Self {
let tokens = ArcMotionTokens::DEFAULT;
Self {
enter_duration: tokens.duration.standard,
enter_ease: tokens.ease.enter,
exit_duration: tokens.duration.exit,
exit_ease: tokens.ease.exit,
fade_on_reduced_motion: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ArcPresenceSample {
pub phase: PresencePhase,
pub progress: f32,
pub status: MotionStatus,
}
impl ArcPresenceSample {
pub const fn should_render(self) -> bool {
!matches!(self.phase, PresencePhase::Absent)
}
pub const fn is_exiting(self) -> bool {
matches!(self.phase, PresencePhase::Exiting)
}
}
#[derive(Clone, Copy, Debug)]
struct PresenceState {
from: f32,
target: f32,
started_at_secs: f64,
duration_secs: f64,
ease: CubicBezier,
}
pub struct ArcPresence {
id: TransitionId,
present: bool,
config: ArcPresenceConfig,
animate_initial: bool,
}
impl ArcPresence {
pub fn new(id: impl Into<TransitionId>, present: bool) -> Self {
Self {
id: id.into(),
present,
config: ArcPresenceConfig::default(),
animate_initial: true,
}
}
pub fn config(mut self, config: ArcPresenceConfig) -> Self {
self.config = config;
self
}
pub fn enter(mut self, duration: Duration, ease: CubicBezierSpec) -> Self {
self.config.enter_duration = duration;
self.config.enter_ease = ease;
self
}
pub fn exit(mut self, duration: Duration, ease: CubicBezierSpec) -> Self {
self.config.exit_duration = duration;
self.config.exit_ease = ease;
self
}
pub fn animate_initial(mut self, animate_initial: bool) -> Self {
self.animate_initial = animate_initial;
self
}
pub fn sample(self, window: &mut Window, cx: &mut App) -> ArcPresenceSample {
let element_id =
ElementId::NamedChild(ElementId::from(self.id).into(), "__arc-presence".into());
let now = motion_now(cx);
let target = if self.present { 1.0 } else { 0.0 };
let reduced = cx.reduce_motion();
let (duration, ease) = if self.present {
(
if reduced && self.config.fade_on_reduced_motion {
ArcMotionTokens::DEFAULT.duration.instant
} else {
self.config.enter_duration
},
CubicBezier::from_spec(self.config.enter_ease),
)
} else {
(
if reduced && self.config.fade_on_reduced_motion {
ArcMotionTokens::DEFAULT.duration.instant
} else {
self.config.exit_duration
},
CubicBezier::from_spec(self.config.exit_ease),
)
};
let initial_from = if self.animate_initial { 0.0 } else { target };
let state = window.use_keyed_state(element_id, cx, |_, _| PresenceState {
from: initial_from,
target,
started_at_secs: now,
duration_secs: duration.as_secs_f64(),
ease,
});
let snapshot = *state.read(cx);
if (reduced && !self.config.fade_on_reduced_motion) || duration.is_zero() {
if snapshot.from != target || snapshot.target != target {
state.update(cx, |s, _| {
s.from = target;
s.target = target;
s.started_at_secs = now;
s.duration_secs = 0.0;
s.ease = ease;
});
}
return stable(self.present);
}
let elapsed = (now - snapshot.started_at_secs).max(0.0);
let raw_t = if snapshot.duration_secs <= 0.0 {
1.0
} else {
(elapsed / snapshot.duration_secs).clamp(0.0, 1.0)
};
let eased = snapshot.ease.sample(raw_t as f32);
let sampled = snapshot.from + (snapshot.target - snapshot.from) * eased;
if (snapshot.target - target).abs() > 1e-6 {
let remaining_fraction = (target - sampled).abs().clamp(0.05, 1.0) as f64;
let next_duration = duration.as_secs_f64() * remaining_fraction;
state.update(cx, |s, _| {
s.from = sampled;
s.target = target;
s.started_at_secs = now;
s.duration_secs = next_duration;
s.ease = ease;
});
window.request_animation_frame();
return ArcPresenceSample {
phase: if self.present {
PresencePhase::Entering
} else {
PresencePhase::Exiting
},
progress: sampled,
status: MotionStatus::Running,
};
}
if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
stable(self.present)
} else {
window.request_animation_frame();
ArcPresenceSample {
phase: if self.present {
PresencePhase::Entering
} else {
PresencePhase::Exiting
},
progress: sampled,
status: MotionStatus::Running,
}
}
}
}
fn stable(present: bool) -> ArcPresenceSample {
ArcPresenceSample {
phase: if present {
PresencePhase::Present
} else {
PresencePhase::Absent
},
progress: if present { 1.0 } else { 0.0 },
status: MotionStatus::Finished,
}
}
#[cfg(test)]
mod tests {
use gpui_kit::{Context, IntoElement, Render, TestAppContext, div, test::TestWindowExt as _};
use super::*;
struct PresenceHost {
present: bool,
last: Option<ArcPresenceSample>,
}
impl Render for PresenceHost {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let sample = ArcPresence::new(("host", "panel"), self.present).sample(window, cx);
self.last = Some(sample);
div()
}
}
#[gpui_kit::test]
fn presence_enters_exits_and_reverses_mid_flight(cx: &mut TestAppContext) {
let (view, cx) = cx.add_window_view(|_, _| PresenceHost {
present: true,
last: None,
});
let first = cx.update(|window, cx| {
window.render_frame(cx);
view.read(cx).last.unwrap()
});
assert_eq!(first.phase, PresencePhase::Entering);
assert!(first.should_render());
cx.executor().advance_clock(Duration::from_millis(300));
let settled = cx.update(|window, cx| {
window.render_frame(cx);
view.read(cx).last.unwrap()
});
assert_eq!(settled.phase, PresencePhase::Present);
assert_eq!(settled.progress, 1.0);
view.update(cx, |v, cx| {
v.present = false;
cx.notify();
});
cx.update(|window, cx| window.render_frame(cx));
cx.executor().advance_clock(Duration::from_millis(90));
let mid_exit = cx.update(|window, cx| {
window.render_frame(cx);
view.read(cx).last.unwrap()
});
assert_eq!(mid_exit.phase, PresencePhase::Exiting);
assert!(mid_exit.progress > 0.0 && mid_exit.progress < 1.0);
view.update(cx, |v, cx| {
v.present = true;
cx.notify();
});
let reversed = cx.update(|window, cx| {
window.render_frame(cx);
view.read(cx).last.unwrap()
});
assert_eq!(reversed.phase, PresencePhase::Entering);
assert!((reversed.progress - mid_exit.progress).abs() < 0.05);
}
}