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 Deferred {
19    /// Sets the `priority` value of the `deferred` element, which
20    /// determines the drawing order relative to other deferred elements,
21    /// with higher values being drawn on top.
22    pub fn with_priority(mut self, priority: usize) -> Self {
23        self.priority = priority;
24        self
25    }
26}
27
28impl Element for Deferred {
29    type RequestLayoutState = ();
30    type PrepaintState = ();
31
32    fn request_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, ()) {
33        let layout_id = self.child.as_mut().unwrap().request_layout(cx);
34        (layout_id, ())
35    }
36
37    fn prepaint(
38        &mut self,
39        _bounds: Bounds<Pixels>,
40        _request_layout: &mut Self::RequestLayoutState,
41        cx: &mut ElementContext,
42    ) {
43        let child = self.child.take().unwrap();
44        let element_offset = cx.element_offset();
45        cx.defer_draw(child, element_offset, self.priority)
46    }
47
48    fn paint(
49        &mut self,
50        _bounds: Bounds<Pixels>,
51        _request_layout: &mut Self::RequestLayoutState,
52        _prepaint: &mut Self::PrepaintState,
53        _cx: &mut ElementContext,
54    ) {
55    }
56}
57
58impl IntoElement for Deferred {
59    type Element = Self;
60
61    fn into_element(self) -> Self::Element {
62        self
63    }
64}
65
66impl Deferred {
67    /// Sets a priority for the element. A higher priority conceptually means painting the element
68    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
69    pub fn priority(mut self, priority: usize) -> Self {
70        self.priority = priority;
71        self
72    }
73}