1use std::{any::Any, f32::INFINITY};
2
3use crate::{
4 json::{self, ToJson, Value},
5 Axis, DebugContext, Element, ElementBox, ElementStateHandle, Event, EventContext,
6 LayoutContext, MouseMovedEvent, PaintContext, RenderContext, ScrollWheelEvent, SizeConstraint,
7 Vector2FExt, View,
8};
9use pathfinder_geometry::{
10 rect::RectF,
11 vector::{vec2f, Vector2F},
12};
13use serde_json::json;
14
15#[derive(Default)]
16struct ScrollState {
17 scroll_to: Option<usize>,
18 scroll_position: f32,
19}
20
21pub struct Flex {
22 axis: Axis,
23 children: Vec<ElementBox>,
24 scroll_state: Option<ElementStateHandle<ScrollState>>,
25}
26
27impl Flex {
28 pub fn new(axis: Axis) -> Self {
29 Self {
30 axis,
31 children: Default::default(),
32 scroll_state: None,
33 }
34 }
35
36 pub fn row() -> Self {
37 Self::new(Axis::Horizontal)
38 }
39
40 pub fn column() -> Self {
41 Self::new(Axis::Vertical)
42 }
43
44 pub fn scrollable<Tag, V>(
45 mut self,
46 element_id: usize,
47 scroll_to: Option<usize>,
48 cx: &mut RenderContext<V>,
49 ) -> Self
50 where
51 Tag: 'static,
52 V: View,
53 {
54 let scroll_state = cx.element_state::<Tag, ScrollState>(element_id);
55 scroll_state.update(cx, |scroll_state, _| scroll_state.scroll_to = scroll_to);
56 self.scroll_state = Some(scroll_state);
57 self
58 }
59
60 fn layout_flex_children(
61 &mut self,
62 layout_expanded: bool,
63 constraint: SizeConstraint,
64 remaining_space: &mut f32,
65 remaining_flex: &mut f32,
66 cross_axis_max: &mut f32,
67 cx: &mut LayoutContext,
68 ) {
69 let cross_axis = self.axis.invert();
70 for child in &mut self.children {
71 if let Some(metadata) = child.metadata::<FlexParentData>() {
72 if let Some((flex, expanded)) = metadata.flex {
73 if expanded != layout_expanded {
74 continue;
75 }
76
77 let child_max = if *remaining_flex == 0.0 {
78 *remaining_space
79 } else {
80 let space_per_flex = *remaining_space / *remaining_flex;
81 space_per_flex * flex
82 };
83 let child_min = if expanded { child_max } else { 0. };
84 let child_constraint = match self.axis {
85 Axis::Horizontal => SizeConstraint::new(
86 vec2f(child_min, constraint.min.y()),
87 vec2f(child_max, constraint.max.y()),
88 ),
89 Axis::Vertical => SizeConstraint::new(
90 vec2f(constraint.min.x(), child_min),
91 vec2f(constraint.max.x(), child_max),
92 ),
93 };
94 let child_size = child.layout(child_constraint, cx);
95 *remaining_space -= child_size.along(self.axis);
96 *remaining_flex -= flex;
97 *cross_axis_max = cross_axis_max.max(child_size.along(cross_axis));
98 }
99 }
100 }
101 }
102}
103
104impl Extend<ElementBox> for Flex {
105 fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
106 self.children.extend(children);
107 }
108}
109
110impl Element for Flex {
111 type LayoutState = f32;
112 type PaintState = ();
113
114 fn layout(
115 &mut self,
116 constraint: SizeConstraint,
117 cx: &mut LayoutContext,
118 ) -> (Vector2F, Self::LayoutState) {
119 let mut total_flex = None;
120 let mut fixed_space = 0.0;
121 let mut contains_float = false;
122
123 let cross_axis = self.axis.invert();
124 let mut cross_axis_max: f32 = 0.0;
125 for child in &mut self.children {
126 let metadata = child.metadata::<FlexParentData>();
127 contains_float |= metadata.map_or(false, |metadata| metadata.float);
128
129 if let Some(flex) = metadata.and_then(|metadata| metadata.flex.map(|(flex, _)| flex)) {
130 *total_flex.get_or_insert(0.) += flex;
131 } else {
132 let child_constraint = match self.axis {
133 Axis::Horizontal => SizeConstraint::new(
134 vec2f(0.0, constraint.min.y()),
135 vec2f(INFINITY, constraint.max.y()),
136 ),
137 Axis::Vertical => SizeConstraint::new(
138 vec2f(constraint.min.x(), 0.0),
139 vec2f(constraint.max.x(), INFINITY),
140 ),
141 };
142 let size = child.layout(child_constraint, cx);
143 fixed_space += size.along(self.axis);
144 cross_axis_max = cross_axis_max.max(size.along(cross_axis));
145 }
146 }
147
148 let mut remaining_space = constraint.max_along(self.axis) - fixed_space;
149 let mut size = if let Some(mut remaining_flex) = total_flex {
150 if remaining_space.is_infinite() {
151 panic!("flex contains flexible children but has an infinite constraint along the flex axis");
152 }
153
154 self.layout_flex_children(
155 false,
156 constraint,
157 &mut remaining_space,
158 &mut remaining_flex,
159 &mut cross_axis_max,
160 cx,
161 );
162 self.layout_flex_children(
163 true,
164 constraint,
165 &mut remaining_space,
166 &mut remaining_flex,
167 &mut cross_axis_max,
168 cx,
169 );
170
171 match self.axis {
172 Axis::Horizontal => vec2f(constraint.max.x() - remaining_space, cross_axis_max),
173 Axis::Vertical => vec2f(cross_axis_max, constraint.max.y() - remaining_space),
174 }
175 } else {
176 match self.axis {
177 Axis::Horizontal => vec2f(fixed_space, cross_axis_max),
178 Axis::Vertical => vec2f(cross_axis_max, fixed_space),
179 }
180 };
181
182 if contains_float {
183 match self.axis {
184 Axis::Horizontal => size.set_x(size.x().max(constraint.max.x())),
185 Axis::Vertical => size.set_y(size.y().max(constraint.max.y())),
186 }
187 }
188
189 if constraint.min.x().is_finite() {
190 size.set_x(size.x().max(constraint.min.x()));
191 }
192 if constraint.min.y().is_finite() {
193 size.set_y(size.y().max(constraint.min.y()));
194 }
195
196 if size.x() > constraint.max.x() {
197 size.set_x(constraint.max.x());
198 }
199 if size.y() > constraint.max.y() {
200 size.set_y(constraint.max.y());
201 }
202
203 if let Some(scroll_state) = self.scroll_state.as_ref() {
204 scroll_state.update(cx, |scroll_state, _| {
205 if let Some(scroll_to) = scroll_state.scroll_to.take() {
206 let visible_start = scroll_state.scroll_position;
207 let visible_end = visible_start + size.along(self.axis);
208 if let Some(child) = self.children.get(scroll_to) {
209 let child_start: f32 = self.children[..scroll_to]
210 .iter()
211 .map(|c| c.size().along(self.axis))
212 .sum();
213 let child_end = child_start + child.size().along(self.axis);
214 if child_start < visible_start {
215 scroll_state.scroll_position = child_start;
216 } else if child_end > visible_end {
217 scroll_state.scroll_position = child_end - size.along(self.axis);
218 }
219 }
220 }
221
222 scroll_state.scroll_position =
223 scroll_state.scroll_position.min(-remaining_space).max(0.);
224 });
225 }
226
227 (size, remaining_space)
228 }
229
230 fn paint(
231 &mut self,
232 bounds: RectF,
233 visible_bounds: RectF,
234 remaining_space: &mut Self::LayoutState,
235 cx: &mut PaintContext,
236 ) -> Self::PaintState {
237 let mut remaining_space = *remaining_space;
238
239 let overflowing = remaining_space < 0.;
240 if overflowing {
241 cx.scene.push_layer(Some(bounds));
242 }
243
244 let mut child_origin = bounds.origin();
245 if let Some(scroll_state) = self.scroll_state.as_ref() {
246 let scroll_position = scroll_state.read(cx).scroll_position;
247 match self.axis {
248 Axis::Horizontal => child_origin.set_x(child_origin.x() - scroll_position),
249 Axis::Vertical => child_origin.set_y(child_origin.y() - scroll_position),
250 }
251 }
252
253 for child in &mut self.children {
254 if remaining_space > 0. {
255 if let Some(metadata) = child.metadata::<FlexParentData>() {
256 if metadata.float {
257 match self.axis {
258 Axis::Horizontal => child_origin += vec2f(remaining_space, 0.0),
259 Axis::Vertical => child_origin += vec2f(0.0, remaining_space),
260 }
261 remaining_space = 0.;
262 }
263 }
264 }
265 child.paint(child_origin, visible_bounds, cx);
266 match self.axis {
267 Axis::Horizontal => child_origin += vec2f(child.size().x(), 0.0),
268 Axis::Vertical => child_origin += vec2f(0.0, child.size().y()),
269 }
270 }
271
272 if overflowing {
273 cx.scene.pop_layer();
274 }
275 }
276
277 fn dispatch_event(
278 &mut self,
279 event: &Event,
280 bounds: RectF,
281 _: RectF,
282 remaining_space: &mut Self::LayoutState,
283 _: &mut Self::PaintState,
284 cx: &mut EventContext,
285 ) -> bool {
286 let mut handled = false;
287 for child in &mut self.children {
288 handled = child.dispatch_event(event, cx) || handled;
289 }
290 if !handled {
291 if let &Event::ScrollWheel(ScrollWheelEvent {
292 position,
293 delta,
294 precise,
295 }) = event
296 {
297 if *remaining_space < 0. && bounds.contains_point(position) {
298 if let Some(scroll_state) = self.scroll_state.as_ref() {
299 scroll_state.update(cx, |scroll_state, cx| {
300 let mut delta = match self.axis {
301 Axis::Horizontal => {
302 if delta.x() != 0. {
303 delta.x()
304 } else {
305 delta.y()
306 }
307 }
308 Axis::Vertical => delta.y(),
309 };
310 if !precise {
311 delta *= 20.;
312 }
313
314 scroll_state.scroll_position -= delta;
315
316 handled = true;
317 cx.notify();
318 });
319 }
320 }
321 }
322 }
323
324 if !handled {
325 if let &Event::MouseMoved(MouseMovedEvent { position, .. }) = event {
326 // If this is a scrollable flex, and the mouse is over it, eat the scroll event to prevent
327 // propogating it to the element below.
328 if self.scroll_state.is_some() && bounds.contains_point(position) {
329 handled = true;
330 }
331 }
332 }
333
334 handled
335 }
336
337 fn debug(
338 &self,
339 bounds: RectF,
340 _: &Self::LayoutState,
341 _: &Self::PaintState,
342 cx: &DebugContext,
343 ) -> json::Value {
344 json!({
345 "type": "Flex",
346 "bounds": bounds.to_json(),
347 "axis": self.axis.to_json(),
348 "children": self.children.iter().map(|child| child.debug(cx)).collect::<Vec<json::Value>>()
349 })
350 }
351}
352
353struct FlexParentData {
354 flex: Option<(f32, bool)>,
355 float: bool,
356}
357
358pub struct FlexItem {
359 metadata: FlexParentData,
360 child: ElementBox,
361}
362
363impl FlexItem {
364 pub fn new(child: ElementBox) -> Self {
365 FlexItem {
366 metadata: FlexParentData {
367 flex: None,
368 float: false,
369 },
370 child,
371 }
372 }
373
374 pub fn flex(mut self, flex: f32, expanded: bool) -> Self {
375 self.metadata.flex = Some((flex, expanded));
376 self
377 }
378
379 pub fn float(mut self) -> Self {
380 self.metadata.float = true;
381 self
382 }
383}
384
385impl Element for FlexItem {
386 type LayoutState = ();
387 type PaintState = ();
388
389 fn layout(
390 &mut self,
391 constraint: SizeConstraint,
392 cx: &mut LayoutContext,
393 ) -> (Vector2F, Self::LayoutState) {
394 let size = self.child.layout(constraint, cx);
395 (size, ())
396 }
397
398 fn paint(
399 &mut self,
400 bounds: RectF,
401 visible_bounds: RectF,
402 _: &mut Self::LayoutState,
403 cx: &mut PaintContext,
404 ) -> Self::PaintState {
405 self.child.paint(bounds.origin(), visible_bounds, cx)
406 }
407
408 fn dispatch_event(
409 &mut self,
410 event: &Event,
411 _: RectF,
412 _: RectF,
413 _: &mut Self::LayoutState,
414 _: &mut Self::PaintState,
415 cx: &mut EventContext,
416 ) -> bool {
417 self.child.dispatch_event(event, cx)
418 }
419
420 fn metadata(&self) -> Option<&dyn Any> {
421 Some(&self.metadata)
422 }
423
424 fn debug(
425 &self,
426 _: RectF,
427 _: &Self::LayoutState,
428 _: &Self::PaintState,
429 cx: &DebugContext,
430 ) -> Value {
431 json!({
432 "type": "Flexible",
433 "flex": self.metadata.flex,
434 "child": self.child.debug(cx)
435 })
436 }
437}