constrained_box.rs

 1use crate::{
 2    AfterLayoutContext, AppContext, Element, Event, EventContext, LayoutContext, MutableAppContext,
 3    PaintContext, SizeConstraint,
 4};
 5use pathfinder_geometry::vector::Vector2F;
 6
 7pub struct ConstrainedBox {
 8    child: Box<dyn Element>,
 9    constraint: SizeConstraint,
10}
11
12impl ConstrainedBox {
13    pub fn new(child: Box<dyn Element>) -> Self {
14        Self {
15            child,
16            constraint: SizeConstraint {
17                min: Vector2F::zero(),
18                max: Vector2F::splat(f32::INFINITY),
19            },
20        }
21    }
22
23    pub fn with_max_width(mut self, max_width: f32) -> Self {
24        self.constraint.max.set_x(max_width);
25        self
26    }
27
28    pub fn with_max_height(mut self, max_height: f32) -> Self {
29        self.constraint.max.set_y(max_height);
30        self
31    }
32
33    pub fn with_height(mut self, height: f32) -> Self {
34        self.constraint.min.set_y(height);
35        self.constraint.max.set_y(height);
36        self
37    }
38}
39
40impl Element for ConstrainedBox {
41    fn layout(
42        &mut self,
43        mut constraint: SizeConstraint,
44        ctx: &mut LayoutContext,
45        app: &AppContext,
46    ) -> Vector2F {
47        constraint.min = constraint.min.max(self.constraint.min);
48        constraint.max = constraint.max.min(self.constraint.max);
49        self.child.layout(constraint, ctx, app)
50    }
51
52    fn after_layout(&mut self, ctx: &mut AfterLayoutContext, app: &mut MutableAppContext) {
53        self.child.after_layout(ctx, app);
54    }
55
56    fn paint(&mut self, origin: Vector2F, ctx: &mut PaintContext, app: &AppContext) {
57        self.child.paint(origin, ctx, app);
58    }
59
60    fn dispatch_event(&self, event: &Event, ctx: &mut EventContext, app: &AppContext) -> bool {
61        self.child.dispatch_event(event, ctx, app)
62    }
63
64    fn size(&self) -> Option<Vector2F> {
65        self.child.size()
66    }
67}