stack.rs

 1use std::ops::Range;
 2
 3use crate::{
 4    geometry::{rect::RectF, vector::Vector2F},
 5    json::{self, json, ToJson},
 6    presenter::MeasurementContext,
 7    DebugContext, Element, ElementBox, LayoutContext, PaintContext, SizeConstraint,
 8};
 9
10#[derive(Default)]
11pub struct Stack {
12    children: Vec<ElementBox>,
13}
14
15impl Stack {
16    pub fn new() -> Self {
17        Self::default()
18    }
19}
20
21impl Element for Stack {
22    type LayoutState = ();
23    type PaintState = ();
24
25    fn layout(
26        &mut self,
27        constraint: SizeConstraint,
28        cx: &mut LayoutContext,
29    ) -> (Vector2F, Self::LayoutState) {
30        let mut size = constraint.min;
31        for child in &mut self.children {
32            size = size.max(child.layout(constraint, cx));
33        }
34        (size, ())
35    }
36
37    fn paint(
38        &mut self,
39        bounds: RectF,
40        visible_bounds: RectF,
41        _: &mut Self::LayoutState,
42        cx: &mut PaintContext,
43    ) -> Self::PaintState {
44        for child in &mut self.children {
45            cx.paint_layer(None, |cx| {
46                child.paint(bounds.origin(), visible_bounds, cx);
47            });
48        }
49    }
50
51    fn rect_for_text_range(
52        &self,
53        range_utf16: Range<usize>,
54        _: RectF,
55        _: RectF,
56        _: &Self::LayoutState,
57        _: &Self::PaintState,
58        cx: &MeasurementContext,
59    ) -> Option<RectF> {
60        self.children
61            .iter()
62            .rev()
63            .find_map(|child| child.rect_for_text_range(range_utf16.clone(), cx))
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}