Skip to main content

gpui_base/plot/
appear.rs

1//! The appear motion shared by every [`Plot`](super::Plot): how far its data
2//! marks have drawn in since the plot was first painted.
3//!
4//! This is behavior only. A plot decides what appearing looks like — a line
5//! revealed from the left, bars growing from zero — and a styled layer
6//! projects the timing through [`PlotMotion`](crate::PlotMotion).
7//!
8//! The appear lives in the plot's element state, so a plot that stops being
9//! painted — a row a virtual list scrolled away — forgets it and draws in again
10//! when it comes back. A [`PlotAppearScope`] around the list remembers which
11//! plots have finished, for as long as the scope itself is painted.
12use 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/// How far a plot's data marks have appeared this frame, handed to
25/// [`Plot::appear`](super::Plot::appear).
26///
27/// The appear starts on the first frame a plot's id is painted and runs over
28/// the active [`PlotMotion`](crate::PlotMotion)'s appear. Base's default
29/// duration is zero, and reduced motion skips it, so a plot is then complete
30/// from its first frame.
31#[derive(Clone)]
32pub struct PlotAppear {
33    /// Linear time through the appear, from `0` to `1`.
34    time: f32,
35    easing: Easing,
36}
37
38impl PlotAppear {
39    /// A finished appear: every mark is complete.
40    pub fn complete() -> Self {
41        Self {
42            time: 1.,
43            easing: Easing::Linear,
44        }
45    }
46
47    /// How far the whole plot has appeared, from `0` to `1`, eased.
48    pub fn progress(&self) -> f32 {
49        // Charts read this per mark on every frame, long after the appear is
50        // done, so a finished appear skips sampling the curve.
51        if self.time >= 1. {
52            return 1.;
53        }
54        self.easing.sample(self.time)
55    }
56
57    /// Whether the appear is still running.
58    pub fn is_appearing(&self) -> bool {
59        self.time < 1.
60    }
61
62    /// How far mark `index` of `count` has appeared, from `0` to `1`, eased.
63    ///
64    /// The marks start one after another across the first `spread` of the
65    /// appear (`0..1`) and each runs for the rest of it, so the last mark
66    /// still finishes with the appear however many marks there are. A `spread`
67    /// of `0` moves every mark together.
68    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
79/// The element-state key of a plot's appear, within the plot's scope.
80const APPEAR: &str = "__plot-appear";
81
82/// The plots a [`PlotAppearScope`] has seen finish appearing, by global id,
83/// with the generation that finished.
84type Appeared = Rc<RefCell<HashMap<GlobalElementId, u64>>>;
85
86thread_local! {
87    /// The scopes being laid out or painted, innermost last. Only non-empty
88    /// while a [`PlotAppearScope`] is drawing its child.
89    static SCOPES: RefCell<Vec<Appeared>> = const { RefCell::new(Vec::new()) };
90}
91
92/// Remembers which plots inside it have finished appearing, so a plot that is
93/// painted again after a gap — a row a virtual list scrolled out of view and
94/// back — shows its data whole instead of drawing in again.
95///
96/// Wrap the list, or whatever region repaints its plots on and off, in one:
97///
98/// ```ignore
99/// PlotAppearScope::new(("transcript", conversation_id), list(state, render_row).flex_1())
100/// ```
101///
102/// A plot is remembered by its global element id and its
103/// [`Plot::appear_generation`](super::Plot::appear_generation), once its appear
104/// has finished; a new generation still replays it, and one taken away
105/// mid-appear draws in again from the start. The memory is the scope's own
106/// element state: it lasts while the scope is painted every frame and goes with
107/// it, so a view that is closed, or a scope whose id changes — name it after the
108/// content, such as a conversation — draws its plots in afresh. The innermost
109/// scope wins. Without one, every plot draws in each time it is painted anew.
110///
111/// The scope takes no part in layout: it hands on its child's layout, so a
112/// child that sizes itself, such as a `list`, keeps doing so.
113pub struct PlotAppearScope {
114    id: ElementId,
115    child: Option<AnyElement>,
116}
117
118impl PlotAppearScope {
119    /// Remember the appears of the plots in `child` under `id`, unique among
120    /// its siblings.
121    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    /// Run `f` with `appeared` as the innermost scope.
129    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        // A virtual list lays its rows out here, so their plots appear here.
181        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
204/// The innermost scope, if any, cloned out so no borrow outlives the lookup.
205fn current_scope() -> Option<Appeared> {
206    SCOPES.with_borrow(|scopes| scopes.last().cloned())
207}
208
209/// Sample the appear of the plot painting under the window's current element
210/// id, `global_id`. A new `generation` starts it over, and one the innermost
211/// [`PlotAppearScope`] saw finish is complete at once. Called by
212/// [`PlotElement`](super::PlotElement) within the plot's element scope on every
213/// frame, so it borrows the theme rather than cloning it and builds its key
214/// without allocating.
215pub(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    // Presence keeps the linear time so the marks can each ease over their
236    // own slice of it; see `PlotAppear::staggered`.
237    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    /// A plot that records the appear progress it is handed each frame.
268    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        // Appear motion rides on the id alone, without the interactive layer.
289        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    /// A recorder that can be taken out of the tree and put back, inside a
317    /// [`PlotAppearScope`] named `scope` or none.
318    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    /// Change the view, then return the progress the plot was handed on the
369    /// frame that follows, if it was painted.
370    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        // Once whole, the plot stops asking for frames and stays whole.
435        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    /// A plot that does not opt in is whole at once and asks for no frames,
450    /// even with an appear duration in the theme.
451    #[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    /// A new generation starts the appear over.
459    #[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    /// Inside a scope, a plot painted again after a gap is whole at once and
477    /// asks for no frames.
478    #[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        // A new generation still replays.
496        assert_eq!(
497            update_scoped(window, cx, |view| view.generation = 1),
498            Some(0.)
499        );
500    }
501
502    /// A plot taken away before its appear finished draws in again.
503    #[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    /// The memory goes with the scope: a scope under a new id, or one that
514    /// stops being painted, draws its plots in afresh.
515    #[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    /// Without a scope, a plot painted again after a gap draws in again.
537    #[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        // The first mark starts at once, the last once the spread has passed.
566        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        // Every mark finishes with the appear.
571        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        // A lone mark ignores the spread.
581        assert_eq!(at(0.4).staggered(0, 1, 0.5), 0.4);
582    }
583}