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
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        // A virtual list lays its rows out here, so their plots appear here.
190        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
213/// The innermost scope, if any, cloned out so no borrow outlives the lookup.
214fn current_scope() -> Option<Appeared> {
215    SCOPES.with_borrow(|scopes| scopes.last().cloned())
216}
217
218/// Sample the appear of the plot painting under the window's current element
219/// id, `global_id`. A new `generation` starts it over, and one the innermost
220/// [`PlotAppearScope`] saw finish is complete at once. Called by
221/// [`PlotElement`](super::PlotElement) within the plot's element scope on every
222/// frame, so it borrows the theme rather than cloning it and builds its key
223/// without allocating.
224pub(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    // Presence keeps the linear time so the marks can each ease over their
245    // own slice of it; see `PlotAppear::staggered`.
246    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    /// A plot that records the appear progress it is handed each frame.
277    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        // Appear motion rides on the id alone, without the interactive layer.
298        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    /// A recorder that can be taken out of the tree and put back, inside a
326    /// [`PlotAppearScope`] named `scope` or none.
327    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    /// Change the view, then return the progress the plot was handed on the
378    /// frame that follows, if it was painted.
379    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        // Once whole, the plot stops asking for frames and stays whole.
444        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    /// A plot that does not opt in is whole at once and asks for no frames,
459    /// even with an appear duration in the theme.
460    #[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    /// A new generation starts the appear over.
468    #[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    /// Inside a scope, a plot painted again after a gap is whole at once and
486    /// asks for no frames.
487    #[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        // A new generation still replays.
505        assert_eq!(
506            update_scoped(window, cx, |view| view.generation = 1),
507            Some(0.)
508        );
509    }
510
511    /// A plot taken away before its appear finished draws in again.
512    #[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    /// The memory goes with the scope: a scope under a new id, or one that
523    /// stops being painted, draws its plots in afresh.
524    #[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    /// Without a scope, a plot painted again after a gap draws in again.
546    #[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        // The first mark starts at once, the last once the spread has passed.
575        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        // Every mark finishes with the appear.
580        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        // A lone mark ignores the spread.
590        assert_eq!(at(0.4).staggered(0, 1, 0.5), 0.4);
591    }
592}