stack.rs

 1use crate::{
 2    geometry::{rect::RectF, vector::Vector2F},
 3    json::{self, json, ToJson},
 4    DebugContext, Element, ElementBox, Event, EventContext, LayoutContext, PaintContext,
 5    SizeConstraint,
 6};
 7
 8pub struct Stack {
 9    children: Vec<ElementBox>,
10}
11
12impl Stack {
13    pub fn new() -> Self {
14        Stack {
15            children: Vec::new(),
16        }
17    }
18}
19
20impl Element for Stack {
21    type LayoutState = ();
22    type PaintState = ();
23
24    fn layout(
25        &mut self,
26        constraint: SizeConstraint,
27        cx: &mut LayoutContext,
28    ) -> (Vector2F, Self::LayoutState) {
29        let mut size = constraint.min;
30        for child in &mut self.children {
31            size = size.max(child.layout(constraint, cx));
32        }
33        (size, ())
34    }
35
36    fn paint(
37        &mut self,
38        bounds: RectF,
39        visible_bounds: RectF,
40        _: &mut Self::LayoutState,
41        cx: &mut PaintContext,
42    ) -> Self::PaintState {
43        for child in &mut self.children {
44            cx.scene.push_layer(None);
45            child.paint(bounds.origin(), visible_bounds, cx);
46            cx.scene.pop_layer();
47        }
48    }
49
50    fn dispatch_event(
51        &mut self,
52        event: &Event,
53        _: RectF,
54        _: &mut Self::LayoutState,
55        _: &mut Self::PaintState,
56        cx: &mut EventContext,
57    ) -> bool {
58        for child in self.children.iter_mut().rev() {
59            if child.dispatch_event(event, cx) {
60                return true;
61            }
62        }
63        false
64    }
65
66    fn debug(
67        &self,
68        bounds: RectF,
69        _: &Self::LayoutState,
70        _: &Self::PaintState,
71        cx: &DebugContext,
72    ) -> json::Value {
73        json!({
74            "type": "Stack",
75            "bounds": bounds.to_json(),
76            "children": self.children.iter().map(|child| child.debug(cx)).collect::<Vec<json::Value>>()
77        })
78    }
79}
80
81impl Extend<ElementBox> for Stack {
82    fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
83        self.children.extend(children)
84    }
85}