1use json::ToJson;
2use serde_json::json;
3
4use crate::{
5 geometry::{rect::RectF, vector::Vector2F},
6 json, DebugContext, Element, ElementBox, Event, EventContext, LayoutContext, PaintContext,
7 SizeConstraint,
8};
9
10pub struct ConstrainedBox {
11 child: ElementBox,
12 constraint: SizeConstraint,
13}
14
15impl ConstrainedBox {
16 pub fn new(child: ElementBox) -> Self {
17 Self {
18 child,
19 constraint: SizeConstraint {
20 min: Vector2F::zero(),
21 max: Vector2F::splat(f32::INFINITY),
22 },
23 }
24 }
25
26 pub fn with_min_width(mut self, min_width: f32) -> Self {
27 self.constraint.min.set_x(min_width);
28 self
29 }
30
31 pub fn with_max_width(mut self, max_width: f32) -> Self {
32 self.constraint.max.set_x(max_width);
33 self
34 }
35
36 pub fn with_max_height(mut self, max_height: f32) -> Self {
37 self.constraint.max.set_y(max_height);
38 self
39 }
40
41 pub fn with_width(mut self, width: f32) -> Self {
42 self.constraint.min.set_x(width);
43 self.constraint.max.set_x(width);
44 self
45 }
46
47 pub fn with_height(mut self, height: f32) -> Self {
48 self.constraint.min.set_y(height);
49 self.constraint.max.set_y(height);
50 self
51 }
52}
53
54impl Element for ConstrainedBox {
55 type LayoutState = ();
56 type PaintState = ();
57
58 fn layout(
59 &mut self,
60 mut constraint: SizeConstraint,
61 cx: &mut LayoutContext,
62 ) -> (Vector2F, Self::LayoutState) {
63 constraint.min = constraint.min.max(self.constraint.min);
64 constraint.max = constraint.max.min(self.constraint.max);
65 constraint.max = constraint.max.max(constraint.min);
66 let size = self.child.layout(constraint, cx);
67 (size, ())
68 }
69
70 fn paint(
71 &mut self,
72 bounds: RectF,
73 visible_bounds: RectF,
74 _: &mut Self::LayoutState,
75 cx: &mut PaintContext,
76 ) -> Self::PaintState {
77 self.child.paint(bounds.origin(), visible_bounds, cx);
78 }
79
80 fn dispatch_event(
81 &mut self,
82 event: &Event,
83 _: RectF,
84 _: RectF,
85 _: &mut Self::LayoutState,
86 _: &mut Self::PaintState,
87 cx: &mut EventContext,
88 ) -> bool {
89 self.child.dispatch_event(event, cx)
90 }
91
92 fn debug(
93 &self,
94 _: RectF,
95 _: &Self::LayoutState,
96 _: &Self::PaintState,
97 cx: &DebugContext,
98 ) -> json::Value {
99 json!({"type": "ConstrainedBox", "set_constraint": self.constraint.to_json(), "child": self.child.debug(cx)})
100 }
101}