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        _: RectF,
55        _: &mut Self::LayoutState,
56        _: &mut Self::PaintState,
57        cx: &mut EventContext,
58    ) -> bool {
59        for child in self.children.iter_mut().rev() {
60            if child.dispatch_event(event, cx) {
61                return true;
62            }
63        }
64        false
65    }
66
67    fn debug(
68        &self,
69        bounds: RectF,
70        _: &Self::LayoutState,
71        _: &Self::PaintState,
72        cx: &DebugContext,
73    ) -> json::Value {
74        json!({
75            "type": "Stack",
76            "bounds": bounds.to_json(),
77            "children": self.children.iter().map(|child| child.debug(cx)).collect::<Vec<json::Value>>()
78        })
79    }
80}
81
82impl Extend<ElementBox> for Stack {
83    fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
84        self.children.extend(children)
85    }
86}