1use std::{any::Any, cell::Cell, f32::INFINITY, ops::Range, rc::Rc};
2
3use crate::{
4 json::{self, ToJson, Value},
5 presenter::MeasurementContext,
6 Axis, DebugContext, Element, ElementBox, ElementStateHandle, LayoutContext, PaintContext,
7 RenderContext, SizeConstraint, 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: Cell<Option<usize>>,
18 scroll_position: Cell<f32>,
19}
20
21pub struct Flex {
22 axis: Axis,
23 children: Vec<ElementBox>,
24 scroll_state: Option<(ElementStateHandle<Rc<ScrollState>>, usize)>,
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.default_element_state::<Tag, Rc<ScrollState>>(element_id);
55 scroll_state.read(cx).scroll_to.set(scroll_to);
56 self.scroll_state = Some((scroll_state, cx.handle().id()));
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.0.update(cx, |scroll_state, _| {
205 if let Some(scroll_to) = scroll_state.scroll_to.take() {
206 let visible_start = scroll_state.scroll_position.get();
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.set(child_start);
216 } else if child_end > visible_end {
217 scroll_state
218 .scroll_position
219 .set(child_end - size.along(self.axis));
220 }
221 }
222 }
223
224 scroll_state.scroll_position.set(
225 scroll_state
226 .scroll_position
227 .get()
228 .min(-remaining_space)
229 .max(0.),
230 );
231 });
232 }
233
234 (size, remaining_space)
235 }
236
237 fn paint(
238 &mut self,
239 bounds: RectF,
240 visible_bounds: RectF,
241 remaining_space: &mut Self::LayoutState,
242 cx: &mut PaintContext,
243 ) -> Self::PaintState {
244 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
245
246 let mut remaining_space = *remaining_space;
247 let overflowing = remaining_space < 0.;
248 if overflowing {
249 cx.scene.push_layer(Some(visible_bounds));
250 }
251
252 if let Some(scroll_state) = &self.scroll_state {
253 cx.scene.push_mouse_region(
254 crate::MouseRegion::new::<Self>(scroll_state.1, 0, bounds)
255 .on_scroll({
256 let scroll_state = scroll_state.0.read(cx).clone();
257 let axis = self.axis;
258 move |e, cx| {
259 if remaining_space < 0. {
260 let scroll_delta = e.delta.raw();
261
262 let mut delta = match axis {
263 Axis::Horizontal => {
264 if scroll_delta.x().abs() >= scroll_delta.y().abs() {
265 scroll_delta.x()
266 } else {
267 scroll_delta.y()
268 }
269 }
270 Axis::Vertical => scroll_delta.y(),
271 };
272 if !e.delta.precise() {
273 delta *= 20.;
274 }
275
276 scroll_state
277 .scroll_position
278 .set(scroll_state.scroll_position.get() - delta);
279
280 cx.notify();
281 } else {
282 cx.propagate_event();
283 }
284 }
285 })
286 .on_move(|_, _| { /* Capture move events */ }),
287 )
288 }
289
290 let mut child_origin = bounds.origin();
291 if let Some(scroll_state) = self.scroll_state.as_ref() {
292 let scroll_position = scroll_state.0.read(cx).scroll_position.get();
293 match self.axis {
294 Axis::Horizontal => child_origin.set_x(child_origin.x() - scroll_position),
295 Axis::Vertical => child_origin.set_y(child_origin.y() - scroll_position),
296 }
297 }
298
299 for child in &mut self.children {
300 if remaining_space > 0. {
301 if let Some(metadata) = child.metadata::<FlexParentData>() {
302 if metadata.float {
303 match self.axis {
304 Axis::Horizontal => child_origin += vec2f(remaining_space, 0.0),
305 Axis::Vertical => child_origin += vec2f(0.0, remaining_space),
306 }
307 remaining_space = 0.;
308 }
309 }
310 }
311 child.paint(child_origin, visible_bounds, cx);
312 match self.axis {
313 Axis::Horizontal => child_origin += vec2f(child.size().x(), 0.0),
314 Axis::Vertical => child_origin += vec2f(0.0, child.size().y()),
315 }
316 }
317
318 if overflowing {
319 cx.scene.pop_layer();
320 }
321 }
322
323 fn rect_for_text_range(
324 &self,
325 range_utf16: Range<usize>,
326 _: RectF,
327 _: RectF,
328 _: &Self::LayoutState,
329 _: &Self::PaintState,
330 cx: &MeasurementContext,
331 ) -> Option<RectF> {
332 self.children
333 .iter()
334 .find_map(|child| child.rect_for_text_range(range_utf16.clone(), cx))
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 rect_for_text_range(
409 &self,
410 range_utf16: Range<usize>,
411 _: RectF,
412 _: RectF,
413 _: &Self::LayoutState,
414 _: &Self::PaintState,
415 cx: &MeasurementContext,
416 ) -> Option<RectF> {
417 self.child.rect_for_text_range(range_utf16, 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}