Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Add synced repeating animations and phase-lock spinners (#62332)

Agus Zubiaga4ed3738c4068
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 1ce553011d1..5e09d6905ae 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -764,6 +764,8 @@ pub struct App {
pub(crate) mode: GpuiMode,
pub(crate) cursor_hide_mode: CursorHideMode,
pub(crate) reduce_motion: bool,
+ /// Origin of the shared clock that phase-locks synced repeating animations.
+ pub(crate) synced_animation_epoch: Instant,
/// Whether the app was created by [`Application::new_inaccessible`]. No
/// accesskit APIs will be called when this flag is set.
pub(crate) accessibility_force_disabled: bool,
@@ -791,6 +793,7 @@ impl App {
background_executor.is_main_thread(),
"must construct App on main thread"
);
+ let synced_animation_epoch = background_executor.now();
let text_system = Arc::new(TextSystem::new(platform.text_system()));
let entities = EntityMap::new();
@@ -858,6 +861,7 @@ impl App {
quitting: false,
cursor_hide_mode: CursorHideMode::default(),
reduce_motion: false,
+ synced_animation_epoch,
accessibility_force_disabled: false,
#[cfg(any(test, feature = "test-support", debug_assertions))]
diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rs
index 0a3c0c300ba..ba09d35191b 100644
--- a/crates/gpui/src/elements/animation.rs
+++ b/crates/gpui/src/elements/animation.rs
@@ -16,6 +16,8 @@ pub struct Animation {
pub duration: Duration,
/// Whether to repeat this animation when it finishes
pub oneshot: bool,
+ /// Whether to derive the phase from a shared clock. See [`Animation::repeat_synced`].
+ pub synced: bool,
/// A function that takes a delta between 0 and 1 and returns a new delta
/// between 0 and 1 based on the given easing function.
pub easing: Rc<dyn Fn(f32) -> f32>,
@@ -28,6 +30,7 @@ impl Animation {
Self {
duration,
oneshot: true,
+ synced: false,
easing: Rc::new(linear),
}
}
@@ -38,6 +41,13 @@ impl Animation {
self
}
+ /// Set the animation to loop when it finishes, phase-locked to a clock shared by the whole [`App`].
+ pub fn repeat_synced(mut self) -> Self {
+ self.oneshot = false;
+ self.synced = true;
+ self
+ }
+
/// Set the easing function to use for this animation.
/// The easing function will take a time delta between 0 and 1 and return a new delta
/// between 0 and 1
@@ -168,9 +178,16 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
(animation_ix, delta, true)
} else {
let animation_ix = state.animation_ix;
+ let duration = self.animations[animation_ix].duration;
- let mut delta = state.start.elapsed().as_secs_f32()
- / self.animations[animation_ix].duration.as_secs_f32();
+ let elapsed = if self.animations[animation_ix].synced && !duration.is_zero() {
+ let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
+ // Reduce modulo the duration before f32 conversion, which loses sub-second precision at scale.
+ Duration::from_nanos((elapsed.as_nanos() % duration.as_nanos()) as u64)
+ } else {
+ state.start.elapsed()
+ };
+ let mut delta = elapsed.as_secs_f32() / duration.as_secs_f32();
let mut done = false;
if delta > 1.0 {
@@ -303,6 +320,37 @@ mod tests {
rendered_deltas: Rc<RefCell<Vec<f32>>>,
}
+ struct SyncedAnimationTestView {
+ show_second: bool,
+ first_deltas: Rc<RefCell<Vec<f32>>>,
+ second_deltas: Rc<RefCell<Vec<f32>>>,
+ }
+
+ impl Render for SyncedAnimationTestView {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {
+ move |this, delta| {
+ deltas.borrow_mut().push(delta);
+ this
+ }
+ };
+ div()
+ .size_full()
+ .child(div().with_animation(
+ "first-synced-animation",
+ Animation::new(Duration::from_secs(1)).repeat_synced(),
+ record_deltas(self.first_deltas.clone()),
+ ))
+ .when(self.show_second, |this| {
+ this.child(div().with_animation(
+ "second-synced-animation",
+ Animation::new(Duration::from_secs(1)).repeat_synced(),
+ record_deltas(self.second_deltas.clone()),
+ ))
+ })
+ }
+ }
+
impl Render for AnimationTestView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let rendered_deltas = self.rendered_deltas.clone();
@@ -329,10 +377,7 @@ mod tests {
(rendered_deltas, window)
}
- fn simulate_next_frame(
- window: &WindowHandle<AnimationTestView>,
- cx: &mut TestAppContext,
- ) -> usize {
+ fn simulate_next_frame<V: Render>(window: &WindowHandle<V>, cx: &mut TestAppContext) -> usize {
let callback_count = window
.update(cx, |_, window, cx| window.simulate_next_frame(cx))
.unwrap();
@@ -373,6 +418,59 @@ mod tests {
}
}
+ #[gpui::test]
+ fn test_synced_animations_share_phase_across_elements(cx: &mut TestAppContext) {
+ let first_deltas = Rc::new(RefCell::new(Vec::new()));
+ let second_deltas = Rc::new(RefCell::new(Vec::new()));
+ let window = cx.open_window(size(px(100.), px(100.)), {
+ let first_deltas = first_deltas.clone();
+ let second_deltas = second_deltas.clone();
+ move |_, _| SyncedAnimationTestView {
+ show_second: false,
+ first_deltas,
+ second_deltas,
+ }
+ });
+ cx.run_until_parked();
+
+ assert_eq!(*first_deltas.borrow(), vec![0.0]);
+
+ cx.executor().advance_clock(Duration::from_millis(250));
+ simulate_next_frame(&window, cx);
+ assert_eq!(*first_deltas.borrow(), vec![0.0, 0.25]);
+
+ // The second element mounts a quarter through the cycle, yet renders
+ // the shared phase rather than starting at zero.
+ window
+ .update(cx, |view, _, cx| {
+ view.show_second = true;
+ cx.notify();
+ })
+ .unwrap();
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_millis(250));
+ simulate_next_frame(&window, cx);
+
+ assert_eq!(*second_deltas.borrow().last().unwrap(), 0.5);
+ assert_eq!(
+ *first_deltas.borrow().last().unwrap(),
+ *second_deltas.borrow().last().unwrap()
+ );
+ assert!(second_deltas.borrow().iter().all(|delta| *delta > 0.0));
+
+ // The phase wraps around each full cycle.
+ cx.executor().advance_clock(Duration::from_millis(2250));
+ simulate_next_frame(&window, cx);
+ assert_eq!(*first_deltas.borrow().last().unwrap(), 0.75);
+
+ // Sub-second precision survives months of uptime: converting the raw
+ // elapsed time to f32 would round 0.25 away entirely.
+ cx.executor()
+ .advance_clock(Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(500));
+ simulate_next_frame(&window, cx);
+ assert_eq!(*first_deltas.borrow().last().unwrap(), 0.25);
+ }
+
#[gpui::test]
fn test_reduce_motion_renders_single_static_frame(cx: &mut TestAppContext) {
cx.update(|cx| cx.set_reduce_motion(true));
diff --git a/crates/ui/src/traits/animation_ext.rs b/crates/ui/src/traits/animation_ext.rs
index 4907c71ff2a..64cdd4f9c9a 100644
--- a/crates/ui/src/traits/animation_ext.rs
+++ b/crates/ui/src/traits/animation_ext.rs
@@ -33,7 +33,7 @@ pub trait CommonAnimationExt: AnimationExt {
{
self.with_animation(
id,
- Animation::new(Duration::from_secs(duration)).repeat(),
+ Animation::new(Duration::from_secs(duration)).repeat_synced(),
|component, delta| component.transform(Transformation::rotate(percentage(delta))),
)
}