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
137#[cfg(not(feature = "gpui-fast"))]
138impl IntoElement for PlotAppearScope {
139 type Element = Self;
140
141 fn into_element(self) -> Self::Element {
142 self
143 }
144}
145
146impl Element for PlotAppearScope {
147 type RequestLayoutState = (Option<AnyElement>, Appeared);
148 type PrepaintState = ();
149
150 fn id(&self) -> Option<ElementId> {
151 Some(self.id.clone())
152 }
153
154 fn source_location(&self) -> Option<&'static Location<'static>> {
155 None
156 }
157
158 fn request_layout(
159 &mut self,
160 global_id: Option<&GlobalElementId>,
161 _: Option<&InspectorElementId>,
162 window: &mut Window,
163 cx: &mut App,
164 ) -> (LayoutId, Self::RequestLayoutState) {
165 let appeared: Appeared = match global_id {
166 Some(global_id) => window.with_element_state(global_id, |appeared, _| {
167 let appeared: Appeared = appeared.unwrap_or_default();
168 (appeared.clone(), appeared)
169 }),
170 None => Appeared::default(),
171 };
172 let mut child = self.child.take();
173 let layout_id = Self::within(&appeared, || match child.as_mut() {
174 Some(child) => child.request_layout(window, cx),
175 None => window.request_layout(Default::default(), None, cx),
176 });
177 (layout_id, (child, appeared))
178 }
179
180 fn prepaint(
181 &mut self,
182 _: Option<&GlobalElementId>,
183 _: Option<&InspectorElementId>,
184 _: Bounds<Pixels>,
185 (child, appeared): &mut Self::RequestLayoutState,
186 window: &mut Window,
187 cx: &mut App,
188 ) -> Self::PrepaintState {
189 if let Some(child) = child {
191 Self::within(appeared, || {
192 child.prepaint(window, cx);
193 });
194 }
195 }
196
197 fn paint(
198 &mut self,
199 _: Option<&GlobalElementId>,
200 _: Option<&InspectorElementId>,
201 _: Bounds<Pixels>,
202 (child, appeared): &mut Self::RequestLayoutState,
203 _: &mut Self::PrepaintState,
204 window: &mut Window,
205 cx: &mut App,
206 ) {
207 if let Some(child) = child {
208 Self::within(appeared, || child.paint(window, cx));
209 }
210 }
211}
212
213fn current_scope() -> Option<Appeared> {
215 SCOPES.with_borrow(|scopes| scopes.last().cloned())
216}
217
218pub(super) fn track_appear(
225 global_id: &GlobalElementId,
226 generation: u64,
227 window: &mut Window,
228 cx: &mut App,
229) -> PlotAppear {
230 let scope = current_scope();
231 if scope
232 .as_ref()
233 .is_some_and(|scope| scope.borrow().get(global_id) == Some(&generation))
234 {
235 return PlotAppear::complete();
236 }
237 let Some(policy) = cx
238 .try_global::<Theme>()
239 .map(|theme| theme.plot.motion().appear().clone())
240 else {
241 return PlotAppear::complete();
242 };
243 let easing = policy.curve().clone();
244 let sample = Presence::new((ElementId::Integer(generation), APPEAR), true)
247 .transition(policy.easing(Easing::Linear))
248 .sample(window, cx);
249 if sample.progress >= 1.
250 && let Some(scope) = scope
251 {
252 scope.borrow_mut().insert(global_id.clone(), generation);
253 }
254 PlotAppear {
255 time: sample.progress,
256 easing,
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use std::{cell::RefCell, rc::Rc, time::Duration};
263
264 use gpui::{
265 Bounds, Context, ElementId, IntoElement, ParentElement as _, Pixels, Render, Styled as _,
266 TestAppContext, WindowHandle, px, size,
267 };
268
269 use super::*;
270 use crate::{
271 PlotMotion, PlotTheme,
272 motion::Transition,
273 plot::{Plot, PlotElement},
274 };
275
276 struct Recorder {
278 samples: Rc<RefCell<Vec<f32>>>,
279 generation: Option<u64>,
280 }
281
282 impl IntoElement for Recorder {
283 type Element = PlotElement<Self>;
284
285 fn into_element(self) -> Self::Element {
286 PlotElement::new(self)
287 }
288 }
289
290 impl Plot for Recorder {
291 fn paint(&mut self, _: Bounds<Pixels>, _: &mut Window, _: &mut App) {}
292
293 fn id(&self) -> Option<ElementId> {
294 Some("recorder".into())
295 }
296
297 fn interactive(&self) -> bool {
299 false
300 }
301
302 fn appear(&mut self, appear: PlotAppear, _: &mut Window, _: &mut App) {
303 self.samples.borrow_mut().push(appear.progress());
304 }
305
306 fn appear_generation(&self) -> Option<u64> {
307 self.generation
308 }
309 }
310
311 struct RecorderView {
312 samples: Rc<RefCell<Vec<f32>>>,
313 generation: Option<u64>,
314 }
315
316 impl Render for RecorderView {
317 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
318 Recorder {
319 samples: self.samples.clone(),
320 generation: self.generation,
321 }
322 }
323 }
324
325 struct ScopedView {
328 samples: Rc<RefCell<Vec<f32>>>,
329 scope: Option<usize>,
330 mounted: bool,
331 generation: u64,
332 }
333
334 impl Render for ScopedView {
335 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
336 let plot = self.mounted.then(|| Recorder {
337 samples: self.samples.clone(),
338 generation: Some(self.generation),
339 });
340 let body = gpui::div().size_full().children(plot);
341 match self.scope {
342 Some(scope) => PlotAppearScope::new(("scope", scope), body).into_any_element(),
343 None => body.into_any_element(),
344 }
345 }
346 }
347
348 fn set_theme(cx: &mut TestAppContext) {
349 cx.update(|cx| {
350 cx.set_global(Theme::default());
351 Theme::global_mut(cx).plot = PlotTheme::new().with_motion(
352 PlotMotion::default()
353 .with_appear(Transition::new(Duration::from_millis(100)).ease(|t| t)),
354 );
355 });
356 }
357
358 fn open_scoped(
359 cx: &mut TestAppContext,
360 scope: Option<usize>,
361 ) -> (WindowHandle<ScopedView>, Rc<RefCell<Vec<f32>>>) {
362 set_theme(cx);
363 let samples = Rc::new(RefCell::new(Vec::new()));
364 let window = cx.open_window(size(px(100.), px(100.)), {
365 let samples = samples.clone();
366 move |_, _| ScopedView {
367 samples,
368 scope,
369 mounted: true,
370 generation: 0,
371 }
372 });
373 cx.run_until_parked();
374 (window, samples)
375 }
376
377 fn update_scoped(
380 window: WindowHandle<ScopedView>,
381 cx: &mut TestAppContext,
382 f: impl FnOnce(&mut ScopedView),
383 ) -> Option<f32> {
384 window
385 .update(cx, |view, _, cx| {
386 f(view);
387 view.samples.borrow_mut().clear();
388 cx.notify();
389 })
390 .unwrap();
391 cx.run_until_parked();
392 window
393 .update(cx, |view, _, _| view.samples.borrow().last().copied())
394 .unwrap()
395 }
396
397 fn finish_appear(window: WindowHandle<ScopedView>, cx: &mut TestAppContext) {
398 cx.executor().advance_clock(Duration::from_millis(100));
399 window
400 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
401 .unwrap();
402 cx.run_until_parked();
403 }
404
405 fn open(
406 cx: &mut TestAppContext,
407 generation: Option<u64>,
408 ) -> (WindowHandle<RecorderView>, Rc<RefCell<Vec<f32>>>) {
409 set_theme(cx);
410 let samples = Rc::new(RefCell::new(Vec::new()));
411 let window = cx.open_window(size(px(100.), px(100.)), {
412 let samples = samples.clone();
413 move |_, _| RecorderView {
414 samples,
415 generation,
416 }
417 });
418 cx.run_until_parked();
419 (window, samples)
420 }
421
422 fn next_frame(window: WindowHandle<RecorderView>, cx: &mut TestAppContext) -> usize {
423 let frames = window
424 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
425 .unwrap();
426 cx.run_until_parked();
427 frames
428 }
429
430 #[gpui::test]
431 fn test_plot_appears_once_over_the_theme_duration(cx: &mut TestAppContext) {
432 let (window, samples) = open(cx, Some(0));
433 assert_eq!(samples.borrow().last(), Some(&0.));
434
435 cx.executor().advance_clock(Duration::from_millis(50));
436 next_frame(window, cx);
437 assert_eq!(samples.borrow().last(), Some(&0.5));
438
439 cx.executor().advance_clock(Duration::from_millis(50));
440 next_frame(window, cx);
441 assert_eq!(samples.borrow().last(), Some(&1.));
442
443 assert_eq!(next_frame(window, cx), 0);
445 window.update(cx, |_, window, _| window.refresh()).unwrap();
446 cx.run_until_parked();
447 assert_eq!(samples.borrow().last(), Some(&1.));
448 }
449
450 #[gpui::test]
451 fn test_reduced_motion_skips_the_appear(cx: &mut TestAppContext) {
452 cx.update(|cx| cx.set_reduce_motion(true));
453 let (window, samples) = open(cx, Some(0));
454 assert_eq!(samples.borrow().first(), Some(&1.));
455 assert_eq!(next_frame(window, cx), 0);
456 }
457
458 #[gpui::test]
461 fn test_plot_without_a_generation_does_not_appear(cx: &mut TestAppContext) {
462 let (window, samples) = open(cx, None);
463 assert_eq!(samples.borrow().first(), Some(&1.));
464 assert_eq!(next_frame(window, cx), 0);
465 }
466
467 #[gpui::test]
469 fn test_new_generation_replays_the_appear(cx: &mut TestAppContext) {
470 let (window, samples) = open(cx, Some(0));
471 cx.executor().advance_clock(Duration::from_millis(100));
472 next_frame(window, cx);
473 assert_eq!(samples.borrow().last(), Some(&1.));
474
475 window
476 .update(cx, |view, _, cx| {
477 view.generation = Some(1);
478 cx.notify();
479 })
480 .unwrap();
481 cx.run_until_parked();
482 assert_eq!(samples.borrow().last(), Some(&0.));
483 }
484
485 #[gpui::test]
488 fn test_scope_keeps_a_finished_appear_across_a_remount(cx: &mut TestAppContext) {
489 let (window, samples) = open_scoped(cx, Some(0));
490 assert_eq!(samples.borrow().last(), Some(&0.));
491 finish_appear(window, cx);
492 assert_eq!(samples.borrow().last(), Some(&1.));
493
494 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
495 assert_eq!(
496 update_scoped(window, cx, |view| view.mounted = true),
497 Some(1.)
498 );
499 let frames = window
500 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
501 .unwrap();
502 assert_eq!(frames, 0);
503
504 assert_eq!(
506 update_scoped(window, cx, |view| view.generation = 1),
507 Some(0.)
508 );
509 }
510
511 #[gpui::test]
513 fn test_scope_replays_an_unfinished_appear(cx: &mut TestAppContext) {
514 let (window, _) = open_scoped(cx, Some(0));
515 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
516 assert_eq!(
517 update_scoped(window, cx, |view| view.mounted = true),
518 Some(0.)
519 );
520 }
521
522 #[gpui::test]
525 fn test_scope_forgets_when_it_goes(cx: &mut TestAppContext) {
526 let (window, _) = open_scoped(cx, Some(0));
527 finish_appear(window, cx);
528 assert_eq!(
529 update_scoped(window, cx, |view| view.scope = Some(1)),
530 Some(0.)
531 );
532
533 finish_appear(window, cx);
534 assert_eq!(
535 update_scoped(window, cx, |view| view.scope = None),
536 Some(0.)
537 );
538 finish_appear(window, cx);
539 assert_eq!(
540 update_scoped(window, cx, |view| view.scope = Some(1)),
541 Some(0.)
542 );
543 }
544
545 #[gpui::test]
547 fn test_without_a_scope_a_remount_replays(cx: &mut TestAppContext) {
548 let (window, _) = open_scoped(cx, None);
549 finish_appear(window, cx);
550 assert_eq!(update_scoped(window, cx, |view| view.mounted = false), None);
551 assert_eq!(
552 update_scoped(window, cx, |view| view.mounted = true),
553 Some(0.)
554 );
555 }
556
557 fn at(time: f32) -> PlotAppear {
558 PlotAppear {
559 time,
560 easing: Easing::Linear,
561 }
562 }
563
564 #[test]
565 fn test_complete_appear() {
566 let appear = PlotAppear::complete();
567 assert!(!appear.is_appearing());
568 assert_eq!(appear.progress(), 1.);
569 assert_eq!(appear.staggered(3, 10, 0.5), 1.);
570 }
571
572 #[test]
573 fn test_staggered_marks_share_the_appear() {
574 assert_eq!(at(0.).staggered(0, 5, 0.5), 0.);
576 assert_eq!(at(0.25).staggered(0, 5, 0.5), 0.5);
577 assert_eq!(at(0.5).staggered(4, 5, 0.5), 0.);
578 assert_eq!(at(0.75).staggered(4, 5, 0.5), 0.5);
579 for index in 0..5 {
581 assert_eq!(at(1.).staggered(index, 5, 0.5), 1.);
582 }
583 }
584
585 #[test]
586 fn test_staggered_without_spread_moves_together() {
587 assert_eq!(at(0.4).staggered(0, 3, 0.), 0.4);
588 assert_eq!(at(0.4).staggered(2, 3, 0.), 0.4);
589 assert_eq!(at(0.4).staggered(0, 1, 0.5), 0.4);
591 }
592}