deferred.rs

 1use crate::{
 2    AnyElement, Bounds, Element, GlobalElementId, IntoElement, LayoutId, Pixels, WindowContext,
 3};
 4
 5/// Builds a `Deferred` element, which delays the layout and paint of its child.
 6pub fn deferred(child: impl IntoElement) -> Deferred {
 7    Deferred {
 8        child: Some(child.into_any_element()),
 9        priority: 0,
10    }
11}
12
13/// An element which delays the painting of its child until after all of
14/// its ancestors, while keeping its layout as part of the current element tree.
15pub struct Deferred {
16    child: Option<AnyElement>,
17    priority: usize,
18}
19
20impl Deferred {
21    /// Sets the `priority` value of the `deferred` element, which
22    /// determines the drawing order relative to other deferred elements,
23    /// with higher values being drawn on top.
24    pub fn with_priority(mut self, priority: usize) -> Self {
25        self.priority = priority;
26        self
27    }
28}
29
30impl Element for Deferred {
31    type RequestLayoutState = ();
32    type PrepaintState = ();
33
34    fn id(&self) -> Option<crate::ElementId> {
35        None
36    }
37
38    fn request_layout(
39        &mut self,
40        _id: Option<&GlobalElementId>,
41        cx: &mut WindowContext,
42    ) -> (LayoutId, ()) {
43        let layout_id = self.child.as_mut().unwrap().request_layout(cx);
44        (layout_id, ())
45    }
46
47    fn prepaint(
48        &mut self,
49        _id: Option<&GlobalElementId>,
50        _bounds: Bounds<Pixels>,
51        _request_layout: &mut Self::RequestLayoutState,
52        cx: &mut WindowContext,
53    ) {
54        let child = self.child.take().unwrap();
55        let element_offset = cx.element_offset();
56        cx.defer_draw(child, element_offset, self.priority)
57    }
58
59    fn paint(
60        &mut self,
61        _id: Option<&GlobalElementId>,
62        _bounds: Bounds<Pixels>,
63        _request_layout: &mut Self::RequestLayoutState,
64        _prepaint: &mut Self::PrepaintState,
65        _cx: &mut WindowContext,
66    ) {
67    }
68}
69
70impl IntoElement for Deferred {
71    type Element = Self;
72
73    fn into_element(self) -> Self::Element {
74        self
75    }
76}
77
78impl Deferred {
79    /// Sets a priority for the element. A higher priority conceptually means painting the element
80    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
81    pub fn priority(mut self, priority: usize) -> Self {
82        self.priority = priority;
83        self
84    }
85}