stack.rs

 1use crate::{
 2    geometry::{rect::RectF, vector::Vector2F},
 3    json::{self, json, ToJson},
 4    AfterLayoutContext, DebugContext, Element, ElementBox, Event, EventContext, LayoutContext,
 5    PaintContext, 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 after_layout(
37        &mut self,
38        _: Vector2F,
39        _: &mut Self::LayoutState,
40        cx: &mut AfterLayoutContext,
41    ) {
42        for child in &mut self.children {
43            child.after_layout(cx);
44        }
45    }
46
47    fn paint(
48        &mut self,
49        bounds: RectF,
50        _: &mut Self::LayoutState,
51        cx: &mut PaintContext,
52    ) -> Self::PaintState {
53        for child in &mut self.children {
54            cx.scene.push_layer(None);
55            child.paint(bounds.origin(), cx);
56            cx.scene.pop_layer();
57        }
58    }
59
60    fn dispatch_event(
61        &mut self,
62        event: &Event,
63        _: RectF,
64        _: &mut Self::LayoutState,
65        _: &mut Self::PaintState,
66        cx: &mut EventContext,
67    ) -> bool {
68        for child in self.children.iter_mut().rev() {
69            if child.dispatch_event(event, cx) {
70                return true;
71            }
72        }
73        false
74    }
75
76    fn debug(
77        &self,
78        bounds: RectF,
79        _: &Self::LayoutState,
80        _: &Self::PaintState,
81        cx: &DebugContext,
82    ) -> json::Value {
83        json!({
84            "type": "Stack",
85            "bounds": bounds.to_json(),
86            "children": self.children.iter().map(|child| child.debug(cx)).collect::<Vec<json::Value>>()
87        })
88    }
89}
90
91impl Extend<ElementBox> for Stack {
92    fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
93        self.children.extend(children)
94    }
95}