deferred.rs

 1use crate::{AnyElement, Bounds, Element, ElementContext, IntoElement, LayoutId, Pixels};
 2
 3/// Builds a `Deferred` element, which delays the layout and paint of its child.
 4pub fn deferred(child: impl IntoElement) -> Deferred {
 5    Deferred {
 6        child: Some(child.into_any_element()),
 7        priority: 0,
 8    }
 9}
10
11/// An element which delays the painting of its child until after all of
12/// its ancestors, while keeping its layout as part of the current element tree.
13pub struct Deferred {
14    child: Option<AnyElement>,
15    priority: usize,
16}
17
18impl Element for Deferred {
19    type BeforeLayout = ();
20    type AfterLayout = ();
21
22    fn before_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, ()) {
23        let layout_id = self.child.as_mut().unwrap().before_layout(cx);
24        (layout_id, ())
25    }
26
27    fn after_layout(
28        &mut self,
29        _bounds: Bounds<Pixels>,
30        _before_layout: &mut Self::BeforeLayout,
31        cx: &mut ElementContext,
32    ) {
33        let child = self.child.take().unwrap();
34        let element_offset = cx.element_offset();
35        cx.defer_draw(child, element_offset, self.priority)
36    }
37
38    fn paint(
39        &mut self,
40        _bounds: Bounds<Pixels>,
41        _before_layout: &mut Self::BeforeLayout,
42        _after_layout: &mut Self::AfterLayout,
43        _cx: &mut ElementContext,
44    ) {
45    }
46}
47
48impl IntoElement for Deferred {
49    type Element = Self;
50
51    fn into_element(self) -> Self::Element {
52        self
53    }
54}
55
56impl Deferred {
57    /// Sets a priority for the element. A higher priority conceptually means painting the element
58    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
59    pub fn priority(mut self, priority: usize) -> Self {
60        self.priority = priority;
61        self
62    }
63}