flex.rs

  1use std::{any::Any, f32::INFINITY};
  2
  3use crate::{
  4    json::{self, ToJson, Value},
  5    Axis, DebugContext, Element, ElementBox, Event, EventContext, LayoutContext, PaintContext,
  6    SizeConstraint, Vector2FExt,
  7};
  8use pathfinder_geometry::{
  9    rect::RectF,
 10    vector::{vec2f, Vector2F},
 11};
 12use serde_json::json;
 13
 14pub struct Flex {
 15    axis: Axis,
 16    children: Vec<ElementBox>,
 17}
 18
 19impl Flex {
 20    pub fn new(axis: Axis) -> Self {
 21        Self {
 22            axis,
 23            children: Default::default(),
 24        }
 25    }
 26
 27    pub fn row() -> Self {
 28        Self::new(Axis::Horizontal)
 29    }
 30
 31    pub fn column() -> Self {
 32        Self::new(Axis::Vertical)
 33    }
 34
 35    fn child_flex<'b>(child: &ElementBox) -> Option<f32> {
 36        child.metadata::<FlexParentData>().map(|data| data.flex)
 37    }
 38}
 39
 40impl Extend<ElementBox> for Flex {
 41    fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
 42        self.children.extend(children);
 43    }
 44}
 45
 46impl Element for Flex {
 47    type LayoutState = ();
 48    type PaintState = ();
 49
 50    fn layout(
 51        &mut self,
 52        constraint: SizeConstraint,
 53        cx: &mut LayoutContext,
 54    ) -> (Vector2F, Self::LayoutState) {
 55        let mut total_flex = 0.0;
 56        let mut fixed_space = 0.0;
 57
 58        let cross_axis = self.axis.invert();
 59        let mut cross_axis_max: f32 = 0.0;
 60        for child in &mut self.children {
 61            if let Some(flex) = Self::child_flex(&child) {
 62                total_flex += flex;
 63            } else {
 64                let child_constraint = match self.axis {
 65                    Axis::Horizontal => SizeConstraint::new(
 66                        vec2f(0.0, constraint.min.y()),
 67                        vec2f(INFINITY, constraint.max.y()),
 68                    ),
 69                    Axis::Vertical => SizeConstraint::new(
 70                        vec2f(constraint.min.x(), 0.0),
 71                        vec2f(constraint.max.x(), INFINITY),
 72                    ),
 73                };
 74                let size = child.layout(child_constraint, cx);
 75                fixed_space += size.along(self.axis);
 76                cross_axis_max = cross_axis_max.max(size.along(cross_axis));
 77            }
 78        }
 79
 80        let mut size = if total_flex > 0.0 {
 81            if constraint.max_along(self.axis).is_infinite() {
 82                panic!("flex contains flexible children but has an infinite constraint along the flex axis");
 83            }
 84
 85            let mut remaining_space = constraint.max_along(self.axis) - fixed_space;
 86            let mut remaining_flex = total_flex;
 87            for child in &mut self.children {
 88                if let Some(flex) = Self::child_flex(&child) {
 89                    let child_max = if remaining_flex == 0.0 {
 90                        remaining_space
 91                    } else {
 92                        let space_per_flex = remaining_space / remaining_flex;
 93                        space_per_flex * flex
 94                    };
 95                    let child_constraint = match self.axis {
 96                        Axis::Horizontal => SizeConstraint::new(
 97                            vec2f(0.0, constraint.min.y()),
 98                            vec2f(child_max, constraint.max.y()),
 99                        ),
100                        Axis::Vertical => SizeConstraint::new(
101                            vec2f(constraint.min.x(), 0.0),
102                            vec2f(constraint.max.x(), child_max),
103                        ),
104                    };
105                    let child_size = child.layout(child_constraint, cx);
106                    remaining_space -= child_size.along(self.axis);
107                    remaining_flex -= flex;
108                    cross_axis_max = cross_axis_max.max(child_size.along(cross_axis));
109                }
110            }
111
112            match self.axis {
113                Axis::Horizontal => vec2f(constraint.max.x() - remaining_space, cross_axis_max),
114                Axis::Vertical => vec2f(cross_axis_max, constraint.max.y() - remaining_space),
115            }
116        } else {
117            match self.axis {
118                Axis::Horizontal => vec2f(fixed_space, cross_axis_max),
119                Axis::Vertical => vec2f(cross_axis_max, fixed_space),
120            }
121        };
122
123        if constraint.min.x().is_finite() {
124            size.set_x(size.x().max(constraint.min.x()));
125        }
126
127        if constraint.min.y().is_finite() {
128            size.set_y(size.y().max(constraint.min.y()));
129        }
130
131        (size, ())
132    }
133
134    fn paint(
135        &mut self,
136        bounds: RectF,
137        _: &mut Self::LayoutState,
138        cx: &mut PaintContext,
139    ) -> Self::PaintState {
140        let mut child_origin = bounds.origin();
141        for child in &mut self.children {
142            child.paint(child_origin, cx);
143            match self.axis {
144                Axis::Horizontal => child_origin += vec2f(child.size().x(), 0.0),
145                Axis::Vertical => child_origin += vec2f(0.0, child.size().y()),
146            }
147        }
148    }
149
150    fn dispatch_event(
151        &mut self,
152        event: &Event,
153        _: RectF,
154        _: &mut Self::LayoutState,
155        _: &mut Self::PaintState,
156        cx: &mut EventContext,
157    ) -> bool {
158        let mut handled = false;
159        for child in &mut self.children {
160            handled = child.dispatch_event(event, cx) || handled;
161        }
162        handled
163    }
164
165    fn debug(
166        &self,
167        bounds: RectF,
168        _: &Self::LayoutState,
169        _: &Self::PaintState,
170        cx: &DebugContext,
171    ) -> json::Value {
172        json!({
173            "type": "Flex",
174            "bounds": bounds.to_json(),
175            "axis": self.axis.to_json(),
176            "children": self.children.iter().map(|child| child.debug(cx)).collect::<Vec<json::Value>>()
177        })
178    }
179}
180
181struct FlexParentData {
182    flex: f32,
183}
184
185pub struct Expanded {
186    metadata: FlexParentData,
187    child: ElementBox,
188}
189
190impl Expanded {
191    pub fn new(flex: f32, child: ElementBox) -> Self {
192        Expanded {
193            metadata: FlexParentData { flex },
194            child,
195        }
196    }
197}
198
199impl Element for Expanded {
200    type LayoutState = ();
201    type PaintState = ();
202
203    fn layout(
204        &mut self,
205        constraint: SizeConstraint,
206        cx: &mut LayoutContext,
207    ) -> (Vector2F, Self::LayoutState) {
208        let size = self.child.layout(constraint, cx);
209        (size, ())
210    }
211
212    fn paint(
213        &mut self,
214        bounds: RectF,
215        _: &mut Self::LayoutState,
216        cx: &mut PaintContext,
217    ) -> Self::PaintState {
218        self.child.paint(bounds.origin(), cx)
219    }
220
221    fn dispatch_event(
222        &mut self,
223        event: &Event,
224        _: RectF,
225        _: &mut Self::LayoutState,
226        _: &mut Self::PaintState,
227        cx: &mut EventContext,
228    ) -> bool {
229        self.child.dispatch_event(event, cx)
230    }
231
232    fn metadata(&self) -> Option<&dyn Any> {
233        Some(&self.metadata)
234    }
235
236    fn debug(
237        &self,
238        _: RectF,
239        _: &Self::LayoutState,
240        _: &Self::PaintState,
241        cx: &DebugContext,
242    ) -> Value {
243        json!({
244            "type": "Expanded",
245            "flex": self.metadata.flex,
246            "child": self.child.debug(cx)
247        })
248    }
249}