constrained_box.rs

 1use crate::{
 2    AfterLayoutContext, Element, ElementBox, Event, EventContext, LayoutContext, PaintContext,
 3    SizeConstraint,
 4};
 5use pathfinder_geometry::vector::Vector2F;
 6
 7pub struct ConstrainedBox {
 8    child: ElementBox,
 9    constraint: SizeConstraint,
10}
11
12impl ConstrainedBox {
13    pub fn new(child: ElementBox) -> 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    type LayoutState = ();
42    type PaintState = ();
43
44    fn layout(
45        &mut self,
46        mut constraint: SizeConstraint,
47        ctx: &mut LayoutContext,
48    ) -> (Vector2F, Self::LayoutState) {
49        constraint.min = constraint.min.max(self.constraint.min);
50        constraint.max = constraint.max.min(self.constraint.max);
51        let size = self.child.layout(constraint, ctx);
52        (size, ())
53    }
54
55    fn after_layout(
56        &mut self,
57        _: Vector2F,
58        _: &mut Self::LayoutState,
59        ctx: &mut AfterLayoutContext,
60    ) {
61        self.child.after_layout(ctx);
62    }
63
64    fn paint(
65        &mut self,
66        bounds: pathfinder_geometry::rect::RectF,
67        _: &mut Self::LayoutState,
68        ctx: &mut PaintContext,
69    ) -> Self::PaintState {
70        self.child.paint(bounds.origin(), ctx);
71    }
72
73    fn dispatch_event(
74        &mut self,
75        event: &Event,
76        _: pathfinder_geometry::rect::RectF,
77        _: &mut Self::LayoutState,
78        _: &mut Self::PaintState,
79        ctx: &mut EventContext,
80    ) -> bool {
81        self.child.dispatch_event(event, ctx)
82    }
83}