expanded.rs

 1use std::ops::Range;
 2
 3use crate::{
 4    geometry::{rect::RectF, vector::Vector2F},
 5    json, AnyElement, Element, LayoutContext, PaintContext, SceneBuilder, SizeConstraint, View,
 6    ViewContext,
 7};
 8use serde_json::json;
 9
10pub struct Expanded<V: View> {
11    child: AnyElement<V>,
12    full_width: bool,
13    full_height: bool,
14}
15
16impl<V: View> Expanded<V> {
17    pub fn new(child: impl Element<V>) -> Self {
18        Self {
19            child: child.into_any(),
20            full_width: true,
21            full_height: true,
22        }
23    }
24
25    pub fn full_width(mut self) -> Self {
26        self.full_width = true;
27        self.full_height = false;
28        self
29    }
30
31    pub fn full_height(mut self) -> Self {
32        self.full_width = false;
33        self.full_height = true;
34        self
35    }
36}
37
38impl<V: View> Element<V> for Expanded<V> {
39    type LayoutState = ();
40    type PaintState = ();
41
42    fn layout(
43        &mut self,
44        mut constraint: SizeConstraint,
45        view: &mut V,
46        cx: &mut LayoutContext<V>,
47    ) -> (Vector2F, Self::LayoutState) {
48        if self.full_width {
49            constraint.min.set_x(constraint.max.x());
50        }
51        if self.full_height {
52            constraint.min.set_y(constraint.max.y());
53        }
54        let size = self.child.layout(constraint, view, cx);
55        (size, ())
56    }
57
58    fn paint(
59        &mut self,
60        scene: &mut SceneBuilder,
61        bounds: RectF,
62        visible_bounds: RectF,
63        _: &mut Self::LayoutState,
64        view: &mut V,
65        cx: &mut PaintContext<V>,
66    ) -> Self::PaintState {
67        self.child
68            .paint(scene, bounds.origin(), visible_bounds, view, cx);
69    }
70
71    fn rect_for_text_range(
72        &self,
73        range_utf16: Range<usize>,
74        _: RectF,
75        _: RectF,
76        _: &Self::LayoutState,
77        _: &Self::PaintState,
78        view: &V,
79        cx: &ViewContext<V>,
80    ) -> Option<RectF> {
81        self.child.rect_for_text_range(range_utf16, view, cx)
82    }
83
84    fn debug(
85        &self,
86        _: RectF,
87        _: &Self::LayoutState,
88        _: &Self::PaintState,
89        view: &V,
90        cx: &ViewContext<V>,
91    ) -> json::Value {
92        json!({
93            "type": "Expanded",
94            "full_width": self.full_width,
95            "full_height": self.full_height,
96            "child": self.child.debug(view, cx)
97        })
98    }
99}