1use std::{cell::RefCell, collections::HashMap, panic::Location, rc::Rc};
13
14use gpui::{
15 AnyElement, App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
16 LayoutId, Pixels, Window,
17};
18
19use crate::{
20 Theme,
21 motion::{Easing, Presence},
22};
23
24#[derive(Clone)]
32pub struct PlotAppear {
33 time: f32,
35 easing: Easing,
36}
37
38impl PlotAppear {
39 pub fn complete() -> Self {
41 Self {
42 time: 1.,
43 easing: Easing::Linear,
44 }
45 }
46
47 pub fn progress(&self) -> f32 {
49 if self.time >= 1. {
52 return 1.;
53 }
54 self.easing.sample(self.time)
55 }
56
57 pub fn is_appearing(&self) -> bool {
59 self.time < 1.
60 }
61
62 pub fn staggered(&self, index: usize, count: usize, spread: f32) -> f32 {
69 if count <= 1 || self.time >= 1. {
70 return self.progress();
71 }
72 let spread = spread.clamp(0., 0.95);
73 let start = spread * index.min(count - 1) as f32 / (count - 1) as f32;
74 let time = ((self.time - start) / (1. - spread)).clamp(0., 1.);
75 self.easing.sample(time)
76 }
77}
78
79const APPEAR: &str = "__plot-appear";
81
82type Appeared = Rc<RefCell<HashMap<GlobalElementId, u64>>>;
85
86thread_local! {
87 static SCOPES: RefCell<Vec<Appeared>> = const { RefCell::new(Vec::new()) };
90}
91
92pub struct PlotAppearScope {
114 id: ElementId,
115 child: Option<AnyElement>,
116}
117
118impl PlotAppearScope {
119 pub fn new(id: impl Into<ElementId>, child: impl IntoElement) -> Self {
122 Self {
123 id: id.into(),
124 child: Some(child.into_any_element()),
125 }
126 }
127
128 fn within<R>(appeared: &Appeared, f: impl FnOnce() -> R) -> R {
130 SCOPES.with_borrow_mut(|scopes| scopes.push(appeared.clone()));
131 let result = f();
132 SCOPES.with_borrow_mut(|scopes| scopes.pop());
133 result
134 }
135}
136
137impl Element for PlotAppearScope {
138 type RequestLayoutState = (Option<AnyElement>, Appeared);
139 type PrepaintState = ();
140
141 fn id(&self) -> Option<ElementId> {
142 Some(self.id.clone())
143 }
144
145 fn source_location(&self) -> Option<&'static Location<'static>> {
146 None
147 }
148
149 fn request_layout(
150 &mut self,
151 global_id: Option<&GlobalElementId>,
152 _: Option<&InspectorElementId>,
153 window: &mut Window,
154 cx: &mut App,
155 ) -> (LayoutId, Self::RequestLayoutState) {
156 let appeared: Appeared = match global_id {
157 Some(global_id) => window.with_element_state(global_id, |appeared, _| {
158 let appeared: Appeared = appeared.unwrap_or_default();
159 (appeared.clone(), appeared)
160 }),
161 None => Appeared::default(),
162 };
163 let mut child = self.child.take();
164 let layout_id = Self::within(&appeared, || match child.as_mut() {
165 Some(child) => child.request_layout(window, cx),
166 None => window.request_layout(Default::default(), None, cx),
167 });
168 (layout_id, (child, appeared))
169 }
170
171 fn prepaint(
172 &mut self,
173 _: Option<&GlobalElementId>,
174 _: Option<&InspectorElementId>,
175 _: Bounds<Pixels>,
176 (child, appeared): &mut Self::RequestLayoutState,
177 window: &mut Window,
178 cx: &mut App,
179 ) -> Self::PrepaintState {
180 if let Some(child) = child {
182 Self::within(appeared, || {
183 child.prepaint(window, cx);
184 });
185 }
186 }
187
188 fn paint(
189 &mut self,
190 _: Option<&GlobalElementId>,
191 _: Option<&InspectorElementId>,
192 _: Bounds<Pixels>,
193 (child, appeared): &mut Self::RequestLayoutState,
194 _: &mut Self::PrepaintState,
195 window: &mut Window,
196 cx: &mut App,
197 ) {
198 if let Some(child) = child {
199 Self::within(appeared, || child.paint(window, cx));
200 }
201 }
202}
203
204fn current_scope() -> Option<Appeared> {
206 SCOPES.with_borrow(|scopes| scopes.last().cloned())
207}
208
209pub(super) fn track_appear(
216 global_id: &GlobalElementId,
217 generation: u64,
218 window: &mut Window,
219 cx: &mut App,
220) -> PlotAppear {
221 let scope = current_scope();
222 if scope
223 .as_ref()
224 .is_some_and(|scope| scope.borrow().get(global_id) == Some(&generation))
225 {
226 return PlotAppear::complete();
227 }
228 let Some(policy) = cx
229 .try_global::<Theme>()
230 .map(|theme| theme.plot.motion().appear().clone())
231 else {
232 return PlotAppear::complete();
233 };
234 let easing = policy.curve().clone();
235 let sample = Presence::new((ElementId::Integer(generation), APPEAR), true)
238 .transition(policy.easing(Easing::Linear))
239 .sample(window, cx);
240 if sample.progress >= 1.
241 && let Some(scope) = scope
242 {
243 scope.borrow_mut().insert(global_id.clone(), generation);
244 }
245 PlotAppear {
246 time: sample.progress,
247 easing,
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use std::{cell::RefCell, rc::Rc, time::Duration};
254
255 use gpui::{
256 Bounds, Context, ElementId, IntoElement, ParentElement as _, Pixels, Render, Styled as _,
257 TestAppContext, WindowHandle, px, size,
258 };
259
260 use super::*;
261 use crate::{
262 PlotMotion, PlotTheme,
263 motion::Transition,
264 plot::{Plot, PlotElement},
265 };
266
267 struct Recorder {
269 samples: Rc<RefCell<Vec<f32>>>,
270 generation: Option<u64>,
271 }
272
273 impl IntoElement for Recorder {
274 type Element = PlotElement<Self>;
275
276 fn into_element(self) -> Self::Element {
277 PlotElement::new(self)
278 }
279 }
280
281 impl Plot for Recorder {
282 fn paint(&mut self, _: Bounds<Pixels>, _: &mut Window, _: &mut App) {}
283
284 fn id(&self) -> Option<ElementId> {
285 Some("recorder".into())
286 }
287
288 fn interactive(&self) -> bool {
290 false
291 }
292
293 fn appear(&mut self, appear: PlotAppear, _: &mut Window, _: &mut App) {
294 self.samples.borrow_mut().push(appear.progress());
295 }
296
297 fn appear_generation(&self) -> Option<u64> {
298 self.generation
299 }
300 }
301
302 struct RecorderView {
303 samples: Rc<RefCell<Vec<f32>>>,
304 generation: Option<u64>,
305 }
306
307 impl Render for RecorderView {
308 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
309 Recorder {
310 samples: self.samples.clone(),
311 generation: self.generation,
312 }
313 }
314 }
315
316 struct ScopedView {
319 samples: Rc<RefCell<Vec<f32>>>,
320 scope: Option<usize>,
321 mounted: bool,
322 generation: u64,
323 }
324
325 impl Render for ScopedView {
326 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
327 let plot = self.mounted.then(|| Recorder {
328 samples: self.samples.clone(),
329 generation: Some(self.generation),
330 });
331 let body = gpui::div().size_full().children(plot);
332 match self.scope {
333 Some(scope) => PlotAppearScope::new(("scope", scope), body).into_any_element(),
334 None => body.into_any_element(),
335 }
336 }
337 }
338
339 fn set_theme(cx: &mut TestAppContext) {
340 cx.update(|cx| {
341 cx.set_global(Theme::default());
342 Theme::global_mut(cx).plot = PlotTheme::new().with_motion(
343 PlotMotion::default()
344 .with_appear(Transition::new(Duration::from_millis(100)).ease(|t| t)),
345 );
346 });
347 }
348
349 fn open_scoped(
350 cx: &mut TestAppContext,
351 scope: Option<usize>,
352 ) -> (WindowHandle<ScopedView>, Rc<RefCell<Vec<f32>>>) {
353 set_theme(cx);
354 let samples = Rc::new(RefCell::new(Vec::new()));
355 let window = cx.open_window(size(px(100.), px(100.)), {
356 let samples = samples.clone();
357 move |_, _| ScopedView {
358 samples,
359 scope,
360 mounted: true,
361 generation: 0,
362 }
363 });
364 cx.run_until_parked();
365 (window, samples)
366 }
367
368 fn update_scoped(
371 window: WindowHandle<ScopedView>,
372 cx: &mut TestAppContext,
373 f: impl FnOnce(&mut ScopedView),
374 ) -> Option<f32> {
375 window
376 .update(cx, |view, _, cx| {
377 f(view);
378 view.samples.borrow_mut().clear();
379 cx.notify();
380 })
381 .unwrap();
382 cx.run_until_parked();
383 window
384 .update(cx, |view, _, _| view.samples.borrow().last().copied())
385 .unwrap()
386 }
387
388 fn finish_appear(window: WindowHandle<ScopedView>, cx: &mut TestAppContext) {
389 cx.executor().advance_clock(Duration::from_millis(100));
390 window
391 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
392 .unwrap();
393 cx.run_until_parked();
394 }
395
396 fn open(
397 cx: &mut TestAppContext,
398 generation: Option<u64>,
399 ) -> (WindowHandle<RecorderView>, Rc<RefCell<Vec<f32>>>) {
400 set_theme(cx);
401 let samples = Rc::new(RefCell::new(Vec::new()));
402 let window = cx.open_window(size(px(100.), px(100.)), {
403 let samples = samples.clone();
404 move |_, _| RecorderView {
405 samples,
406 generation,
407 }
408 });
409 cx.run_until_parked();
410 (window, samples)
411 }
412
413 fn next_frame(window: WindowHandle<RecorderView>, cx: &mut TestAppContext) -> usize {
414 let frames = window
415 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
416 .unwrap();
417 cx.run_until_parked();
418 frames
419 }
420
421 #[gpui::test]
422 fn test_plot_appears_once_over_the_theme_duration(cx: &mut TestAppContext) {
423 let (window, samples) = open(cx, Some(0));
424 assert_eq!(samples.borrow().last(), Some(&0.));
425
426 cx.executor().advance_clock(Duration::from_millis(50));
427 next_frame(window, cx);
428 assert_eq!(samples.borrow().last(), Some(&0.5));
429
430 cx.executor().advance_clock(Duration::from_millis(50));
431 next_frame(window, cx);
432 assert_eq!(samples.borrow().last(), Some(&1.));
433
434 assert_eq!(next_frame(window, cx), 0);
436 window.update(cx, |_, window, _| window.refresh()).unwrap();
437 cx.run_until_parked();
438 assert_eq!(samples.borrow().last(), Some(&1.));
439 }
440
441 #[gpui::test]
442 fn test_reduced_motion_skips_the_appear(cx: &mut TestAppContext) {
443 cx.update(|cx| cx.set_reduce_motion(true));
444 let (window, samples) = open(cx, Some(0));
445 assert_eq!(samples.borrow().first(), Some(&1.));
446 assert_eq!(next_frame(window, cx), 0);
447 }
448
449 #[gpui::test]
452 fn test_plot_without_a_generation_does_not_appear(cx: &mut TestAppContext) {
453 let (window, samples) = open(cx, None);
454 assert_eq!(samples.borrow().first(), Some(&1.));
455 assert_eq!(next_frame(window, cx), 0);
456 }
457
458 #[gpui::test]
460 fn test_new_generation_replays_the_appear(cx: &mut TestAppContext) {
461 let (window, samples) = open(cx, Some(0));
462 cx.executor().advance_clock(Duration::from_millis(100));
463 next_frame(window, cx);
464 assert_eq!(samples.borrow().last(), Some(&1.));
465
466 window
467 .update(cx, |view, _, cx| {
468 view.generation = Some(1);
469 cx.notify();
470 })
471 .unwrap();
472 cx.run_until_parked();
473 assert_eq!(samples.borrow().last(), Some(&0.));
474 }
475
476 #[gpui::test]
479 fn test_scope_keeps_a_finished_appear_across_a_remount(cx: &mut TestAppContext) {
480 let (window, samples) = open_scoped(cx, Some(0));
481 assert_eq!(samples.borrow().last(), Some(&0.));
482 finish_appear(window, cx);
483 assert_eq!(samples.borrow().last(), Some(&1.));
484
485 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
486 assert_eq!(
487 update_scoped(window, cx, |view| view.mounted = true),
488 Some(1.)
489 );
490 let frames = window
491 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
492 .unwrap();
493 assert_eq!(frames, 0);
494
495 assert_eq!(
497 update_scoped(window, cx, |view| view.generation = 1),
498 Some(0.)
499 );
500 }
501
502 #[gpui::test]
504 fn test_scope_replays_an_unfinished_appear(cx: &mut TestAppContext) {
505 let (window, _) = open_scoped(cx, Some(0));
506 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
507 assert_eq!(
508 update_scoped(window, cx, |view| view.mounted = true),
509 Some(0.)
510 );
511 }
512
513 #[gpui::test]
516 fn test_scope_forgets_when_it_goes(cx: &mut TestAppContext) {
517 let (window, _) = open_scoped(cx, Some(0));
518 finish_appear(window, cx);
519 assert_eq!(
520 update_scoped(window, cx, |view| view.scope = Some(1)),
521 Some(0.)
522 );
523
524 finish_appear(window, cx);
525 assert_eq!(
526 update_scoped(window, cx, |view| view.scope = None),
527 Some(0.)
528 );
529 finish_appear(window, cx);
530 assert_eq!(
531 update_scoped(window, cx, |view| view.scope = Some(1)),
532 Some(0.)
533 );
534 }
535
536 #[gpui::test]
538 fn test_without_a_scope_a_remount_replays(cx: &mut TestAppContext) {
539 let (window, _) = open_scoped(cx, None);
540 finish_appear(window, cx);
541 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
542 assert_eq!(
543 update_scoped(window, cx, |view| view.mounted = true),
544 Some(0.)
545 );
546 }
547
548 fn at(time: f32) -> PlotAppear {
549 PlotAppear {
550 time,
551 easing: Easing::Linear,
552 }
553 }
554
555 #[test]
556 fn test_complete_appear() {
557 let appear = PlotAppear::complete();
558 assert!(!appear.is_appearing());
559 assert_eq!(appear.progress(), 1.);
560 assert_eq!(appear.staggered(3, 10, 0.5), 1.);
561 }
562
563 #[test]
564 fn test_staggered_marks_share_the_appear() {
565 assert_eq!(at(0.).staggered(0, 5, 0.5), 0.);
567 assert_eq!(at(0.25).staggered(0, 5, 0.5), 0.5);
568 assert_eq!(at(0.5).staggered(4, 5, 0.5), 0.);
569 assert_eq!(at(0.75).staggered(4, 5, 0.5), 0.5);
570 for index in 0..5 {
572 assert_eq!(at(1.).staggered(index, 5, 0.5), 1.);
573 }
574 }
575
576 #[test]
577 fn test_staggered_without_spread_moves_together() {
578 assert_eq!(at(0.4).staggered(0, 3, 0.), 0.4);
579 assert_eq!(at(0.4).staggered(2, 3, 0.), 0.4);
580 assert_eq!(at(0.4).staggered(0, 1, 0.5), 0.4);
582 }
583}