Skip to main content

native_gui_core/layout/
flex.rs

1//! Constrained flex layout engine supporting single-line and multi-line wrapping.
2//!
3//! Provides:
4//! - Single-line flex layout (`FlexDirection::Row`, `Column`, `RowReverse`, `ColumnReverse`).
5//! - Multi-line flex wrapping (`FlexWrap::Wrap`, `FlexWrap::WrapReverse`, FIX-WRP-001, FIX-WRP-002, FIX-WRP-003).
6//! - Line formation with strict fractional breakpoint handling (FIX-WRP-005).
7//! - Cross-axis line distribution (`AlignContent::Start`, `End`, `Center`, `Stretch`, `SpaceBetween`, `SpaceAround`, `SpaceEvenly`, FIX-WRP-004).
8//! - Reverse cross-line stacking under `FlexWrap::WrapReverse` (FIX-WRP-003).
9//! - Flex basis determination (explicit `flex_basis`, main-axis `size`, or auto content size).
10//! - Iterative constrained grow with max-size clamp freezing (FIX-FLX-003).
11//! - Iterative constrained shrink with min-size floor freezing and zero-shrink items (FIX-FLX-004, FIX-FLX-005).
12//! - Gaps along main and cross axes (`gap.width`, `gap.height`, FIX-FLX-001, FIX-FLX-002).
13//! - Reverse flow positioning (`RowReverse`, `ColumnReverse`, FIX-FLX-006, FIX-FLX-007).
14//! - Content justification (`Start`, `End`, `Center`, `SpaceBetween`, `SpaceAround`, `SpaceEvenly`, FIX-FLX-008, FIX-FLX-009).
15//! - Cross-axis alignment (`Start`, `End`, `Center`, `Stretch`, `Baseline`) and per-item `align_self` override (FIX-FLX-010, FIX-FLX-011).
16//! - Asymmetric padding insets and margin offsets (FIX-FLX-012).
17//! - Parent-local coordinate placement with strict numerical invariants.
18
19use crate::error::GuiResult;
20use crate::layout::box_sizing::{
21    resolve_dimension, resolve_margin, BoxConstraints, STRICT_TOLERANCE_PX,
22};
23use crate::layout::{
24    AlignContent, AlignItems, AlignSelf, AvailableSpace, Dimension, Display, FlexDirection,
25    FlexWrap, JustifyContent, LayoutNodeId, LayoutRect, LengthPercentage, Point, Rect, Size, Style,
26};
27
28/// Converts container [`AlignItems`] to equivalent item [`AlignSelf`].
29pub fn to_align_self(align: AlignItems) -> AlignSelf {
30    match align {
31        AlignItems::Start => AlignSelf::Start,
32        AlignItems::End => AlignSelf::End,
33        AlignItems::Center => AlignSelf::Center,
34        AlignItems::Baseline => AlignSelf::Baseline,
35        AlignItems::Stretch => AlignSelf::Stretch,
36    }
37}
38
39/// A single flex item being resolved within a flex container.
40#[derive(Debug, Clone)]
41pub struct FlexItem {
42    /// Node identifier.
43    pub id: LayoutNodeId,
44    /// Layout style.
45    pub style: Style,
46    /// Flex basis in logical pixels.
47    pub basis: f32,
48    /// Minimum size constraint along main axis.
49    pub min_main: f32,
50    /// Maximum size constraint along main axis (or f32::INFINITY).
51    pub max_main: f32,
52    /// Resolved target main size.
53    pub target_main: f32,
54    /// Minimum size constraint along cross axis.
55    pub min_cross: f32,
56    /// Maximum size constraint along cross axis (or f32::INFINITY).
57    pub max_cross: f32,
58    /// Resolved target cross size.
59    pub target_cross: f32,
60    /// Resolved margins in logical pixels.
61    pub margin: Rect<f32>,
62    /// Whether this item has frozen its main size during iterative constraint resolution.
63    pub frozen: bool,
64    /// Hypothetical / intrinsic content size.
65    pub hypothetical: Size<f32>,
66}
67
68/// Computes flex layout for a container and its in-flow children,
69/// automatically handling single-line or multi-line wrapping according to `container_style.flex_wrap`.
70pub fn compute_flex(
71    container_style: &Style,
72    container_inner: Size<f32>,
73    available_space: Size<AvailableSpace>,
74    children: &[(LayoutNodeId, Style, Size<f32>)],
75    content_origin: Point<f32>,
76) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
77    match container_style.flex_wrap {
78        FlexWrap::NoWrap => compute_single_line_flex(
79            container_style,
80            container_inner,
81            available_space,
82            children,
83            content_origin,
84        ),
85        FlexWrap::Wrap | FlexWrap::WrapReverse => compute_multi_line_flex(
86            container_style,
87            container_inner,
88            available_space,
89            children,
90            content_origin,
91        ),
92    }
93}
94
95/// Computes single-line flex layout for a container and its in-flow children.
96pub fn compute_single_line_flex(
97    container_style: &Style,
98    container_inner: Size<f32>,
99    available_space: Size<AvailableSpace>,
100    children: &[(LayoutNodeId, Style, Size<f32>)],
101    content_origin: Point<f32>,
102) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
103    if children.is_empty() {
104        return Ok(Vec::new());
105    }
106
107    if children.iter().any(|(_, s, _)| s.display == Display::None) {
108        let mut active = Vec::with_capacity(children.len());
109        let mut hidden_indices = std::collections::HashSet::new();
110        for (i, item) in children.iter().enumerate() {
111            if item.1.display == Display::None {
112                hidden_indices.insert(i);
113            } else {
114                active.push(item.clone());
115            }
116        }
117        let active_placements = compute_single_line_flex(
118            container_style,
119            container_inner,
120            available_space,
121            &active,
122            content_origin,
123        )?;
124        let mut active_iter = active_placements.into_iter();
125        let mut results = Vec::with_capacity(children.len());
126        for (i, (id, _, _)) in children.iter().enumerate() {
127            if hidden_indices.contains(&i) {
128                results.push((
129                    *id,
130                    LayoutRect::new(content_origin.x, content_origin.y, 0.0, 0.0),
131                ));
132            } else if let Some(placed) = active_iter.next() {
133                results.push(placed);
134            }
135        }
136        return Ok(results);
137    }
138
139    let is_row = matches!(
140        container_style.flex_direction,
141        FlexDirection::Row | FlexDirection::RowReverse
142    );
143    let is_reverse = matches!(
144        container_style.flex_direction,
145        FlexDirection::RowReverse | FlexDirection::ColumnReverse
146    );
147
148    let (inner_main, inner_cross) = if is_row {
149        (container_inner.width, container_inner.height)
150    } else {
151        (container_inner.height, container_inner.width)
152    };
153
154    let inner_avail = Size::new(
155        if is_row {
156            AvailableSpace::Definite(inner_main)
157        } else {
158            AvailableSpace::Definite(inner_cross)
159        },
160        if is_row {
161            AvailableSpace::Definite(inner_cross)
162        } else {
163            AvailableSpace::Definite(inner_main)
164        },
165    );
166
167    let (gap_main, _gap_cross) = resolve_gaps(container_style, inner_main, inner_cross, is_row);
168
169    // 1. Build flex items with basis and min/max clamps
170    let mut items = Vec::with_capacity(children.len());
171    for &(id, ref style, hypothetical) in children {
172        let margin = resolve_margin(&style.margin, inner_avail);
173
174        let (hypo_main, hypo_cross) = if is_row {
175            (hypothetical.width, hypothetical.height)
176        } else {
177            (hypothetical.height, hypothetical.width)
178        };
179
180        let (basis, min_main, max_main) =
181            resolve_main_constraints(style, inner_main, is_row, hypo_main);
182
183        let (min_cross, max_cross) = resolve_cross_constraints(style, inner_cross, is_row);
184
185        let target_main = BoxConstraints::clamp_dimension(
186            basis,
187            Some(min_main),
188            if max_main.is_finite() {
189                Some(max_main)
190            } else {
191                None
192            },
193        );
194
195        items.push(FlexItem {
196            id,
197            style: style.clone(),
198            basis,
199            min_main,
200            max_main,
201            target_main,
202            min_cross,
203            max_cross,
204            target_cross: hypo_cross,
205            margin,
206            frozen: false,
207            hypothetical,
208        });
209    }
210
211    // 2. Iterative grow / shrink resolution
212    resolve_flexible_lengths(&mut items, inner_main, gap_main);
213
214    // 3. Cross-axis sizing
215    resolve_cross_axis_sizes(
216        &mut items,
217        container_style,
218        inner_cross,
219        is_row,
220        available_space,
221    );
222
223    // 4. Main-axis positioning and alignment
224    let placements = position_flex_items(
225        &items,
226        container_style,
227        inner_main,
228        inner_cross,
229        gap_main,
230        content_origin,
231        is_row,
232        is_reverse,
233    );
234
235    Ok(placements)
236}
237
238/// Computes multi-line flex layout (`FlexWrap::Wrap` or `FlexWrap::WrapReverse`).
239pub fn compute_multi_line_flex(
240    container_style: &Style,
241    container_inner: Size<f32>,
242    available_space: Size<AvailableSpace>,
243    children: &[(LayoutNodeId, Style, Size<f32>)],
244    content_origin: Point<f32>,
245) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
246    if children.is_empty() {
247        return Ok(Vec::new());
248    }
249
250    if children.iter().any(|(_, s, _)| s.display == Display::None) {
251        let mut active = Vec::with_capacity(children.len());
252        let mut hidden_indices = std::collections::HashSet::new();
253        for (i, item) in children.iter().enumerate() {
254            if item.1.display == Display::None {
255                hidden_indices.insert(i);
256            } else {
257                active.push(item.clone());
258            }
259        }
260        let active_placements = compute_multi_line_flex(
261            container_style,
262            container_inner,
263            available_space,
264            &active,
265            content_origin,
266        )?;
267        let mut active_iter = active_placements.into_iter();
268        let mut results = Vec::with_capacity(children.len());
269        for (i, (id, _, _)) in children.iter().enumerate() {
270            if hidden_indices.contains(&i) {
271                results.push((
272                    *id,
273                    LayoutRect::new(content_origin.x, content_origin.y, 0.0, 0.0),
274                ));
275            } else if let Some(placed) = active_iter.next() {
276                results.push(placed);
277            }
278        }
279        return Ok(results);
280    }
281
282    let is_row = matches!(
283        container_style.flex_direction,
284        FlexDirection::Row | FlexDirection::RowReverse
285    );
286    let is_reverse = matches!(
287        container_style.flex_direction,
288        FlexDirection::RowReverse | FlexDirection::ColumnReverse
289    );
290    let is_wrap_reverse = container_style.flex_wrap == FlexWrap::WrapReverse;
291
292    let (inner_main_raw, inner_cross_raw) = if is_row {
293        (container_inner.width, container_inner.height)
294    } else {
295        (container_inner.height, container_inner.width)
296    };
297
298    let inner_main = if inner_main_raw > 0.0 {
299        inner_main_raw
300    } else {
301        let avail_main = if is_row {
302            available_space.width
303        } else {
304            available_space.height
305        };
306        match avail_main {
307            AvailableSpace::Definite(val) => val,
308            _ => f32::INFINITY,
309        }
310    };
311
312    let inner_cross = if inner_cross_raw > 0.0 {
313        inner_cross_raw
314    } else {
315        let avail_cross = if is_row {
316            available_space.height
317        } else {
318            available_space.width
319        };
320        match avail_cross {
321            AvailableSpace::Definite(val) => val,
322            _ => 0.0,
323        }
324    };
325
326    let inner_avail = Size::new(
327        if is_row {
328            AvailableSpace::Definite(inner_main)
329        } else {
330            AvailableSpace::Definite(inner_cross)
331        },
332        if is_row {
333            AvailableSpace::Definite(inner_cross)
334        } else {
335            AvailableSpace::Definite(inner_main)
336        },
337    );
338
339    let (gap_main, gap_cross) = resolve_gaps(container_style, inner_main, inner_cross, is_row);
340
341    // 1. Build initial flex items with basis and constraints
342    let mut items = Vec::with_capacity(children.len());
343    for &(id, ref style, hypothetical) in children {
344        let margin = resolve_margin(&style.margin, inner_avail);
345
346        let (hypo_main, hypo_cross) = if is_row {
347            (hypothetical.width, hypothetical.height)
348        } else {
349            (hypothetical.height, hypothetical.width)
350        };
351
352        let (basis, min_main, max_main) =
353            resolve_main_constraints(style, inner_main, is_row, hypo_main);
354
355        let (min_cross, max_cross) = resolve_cross_constraints(style, inner_cross, is_row);
356
357        let target_main = BoxConstraints::clamp_dimension(
358            basis,
359            Some(min_main),
360            if max_main.is_finite() {
361                Some(max_main)
362            } else {
363                None
364            },
365        );
366
367        items.push(FlexItem {
368            id,
369            style: style.clone(),
370            basis,
371            min_main,
372            max_main,
373            target_main,
374            min_cross,
375            max_cross,
376            target_cross: hypo_cross,
377            margin,
378            frozen: false,
379            hypothetical,
380        });
381    }
382
383    // 2. Line formation: group items into lines based on available main space
384    let mut lines: Vec<Vec<FlexItem>> = Vec::new();
385    let mut current_line: Vec<FlexItem> = Vec::new();
386    let mut current_line_main = 0.0;
387
388    for item in items {
389        let margin_main = if is_row {
390            item.margin.left + item.margin.right
391        } else {
392            item.margin.top + item.margin.bottom
393        };
394        let item_outer_main = item.target_main + margin_main;
395
396        if current_line.is_empty() {
397            current_line.push(item);
398            current_line_main = item_outer_main;
399        } else {
400            let needed = gap_main + item_outer_main;
401            // 1e-4 tolerance protects against float inaccuracies while correctly breaking at
402            // strict 0.01 fractional breakpoints (e.g. FIX-WRP-005: 50.005 + 50.005 = 100.010 > 100.000).
403            if current_line_main + needed <= inner_main + 1e-4 {
404                current_line.push(item);
405                current_line_main += needed;
406            } else {
407                lines.push(current_line);
408                current_line = vec![item];
409                current_line_main = item_outer_main;
410            }
411        }
412    }
413    if !current_line.is_empty() {
414        lines.push(current_line);
415    }
416
417    if lines.is_empty() {
418        return Ok(Vec::new());
419    }
420
421    // 3. For each line, resolve flexible lengths (grow/shrink) and determine un-stretched line cross size
422    let num_lines = lines.len();
423    let mut line_cross_sizes = Vec::with_capacity(num_lines);
424
425    for line in &mut lines {
426        resolve_flexible_lengths(line, inner_main, gap_main);
427
428        // Determine item cross sizes and find max outer cross size of the line
429        let mut max_line_cross = 0.0f32;
430        for item in line.iter_mut() {
431            let cross_dim = if is_row {
432                item.style.size.height
433            } else {
434                item.style.size.width
435            };
436            if !cross_dim.is_auto() {
437                let resolved = resolve_dimension(cross_dim, AvailableSpace::Definite(inner_cross));
438                if let Some(val) = resolved {
439                    item.target_cross = BoxConstraints::clamp_dimension(
440                        val,
441                        Some(item.min_cross),
442                        if item.max_cross.is_finite() {
443                            Some(item.max_cross)
444                        } else {
445                            None
446                        },
447                    );
448                } else {
449                    item.target_cross = BoxConstraints::clamp_dimension(
450                        if is_row {
451                            item.hypothetical.height
452                        } else {
453                            item.hypothetical.width
454                        },
455                        Some(item.min_cross),
456                        if item.max_cross.is_finite() {
457                            Some(item.max_cross)
458                        } else {
459                            None
460                        },
461                    );
462                }
463            } else {
464                item.target_cross = BoxConstraints::clamp_dimension(
465                    if is_row {
466                        item.hypothetical.height
467                    } else {
468                        item.hypothetical.width
469                    },
470                    Some(item.min_cross),
471                    if item.max_cross.is_finite() {
472                        Some(item.max_cross)
473                    } else {
474                        None
475                    },
476                );
477            }
478
479            let margin_cross = if is_row {
480                item.margin.top + item.margin.bottom
481            } else {
482                item.margin.left + item.margin.right
483            };
484            max_line_cross = max_line_cross.max(item.target_cross + margin_cross);
485        }
486        line_cross_sizes.push(max_line_cross);
487    }
488
489    // 4. Align lines along the cross axis (align_content)
490    let total_lines_cross: f32 = line_cross_sizes.iter().sum();
491    let total_line_gaps = (num_lines.saturating_sub(1) as f32) * gap_cross;
492    let free_cross = inner_cross - total_lines_cross - total_line_gaps;
493
494    let align_content = container_style
495        .align_content
496        .unwrap_or(AlignContent::Stretch);
497
498    // If align_content is Stretch and there is positive free cross space, distribute to lines
499    if align_content == AlignContent::Stretch
500        && free_cross > STRICT_TOLERANCE_PX
501        && inner_cross > 0.0
502    {
503        let extra_per_line = free_cross / num_lines as f32;
504        for sz in &mut line_cross_sizes {
505            *sz += extra_per_line;
506        }
507    }
508
509    let (cross_offset, extra_line_gap) = match align_content {
510        AlignContent::Start | AlignContent::Stretch => (0.0, 0.0),
511        AlignContent::End => (free_cross.max(0.0), 0.0),
512        AlignContent::Center => (free_cross.max(0.0) / 2.0, 0.0),
513        AlignContent::SpaceBetween => {
514            if num_lines > 1 && free_cross > 0.0 {
515                (0.0, free_cross / (num_lines - 1) as f32)
516            } else {
517                (0.0, 0.0)
518            }
519        }
520        AlignContent::SpaceAround => {
521            if num_lines > 0 && free_cross > 0.0 {
522                let share = free_cross / num_lines as f32;
523                (share / 2.0, share)
524            } else {
525                (0.0, 0.0)
526            }
527        }
528        AlignContent::SpaceEvenly => {
529            if num_lines > 0 && free_cross > 0.0 {
530                let share = free_cross / (num_lines + 1) as f32;
531                (share, share)
532            } else {
533                (0.0, 0.0)
534            }
535        }
536    };
537
538    let effective_line_gap = gap_cross + extra_line_gap;
539    let mut line_cross_positions = Vec::with_capacity(num_lines);
540    let mut cursor = cross_offset;
541    for &sz in &line_cross_sizes {
542        line_cross_positions.push(cursor);
543        cursor += sz + effective_line_gap;
544    }
545
546    // Invert line cross positions for WrapReverse
547    if is_wrap_reverse {
548        let total_extent = if inner_cross > 0.0 {
549            inner_cross
550        } else {
551            total_lines_cross + total_line_gaps
552        };
553        for i in 0..num_lines {
554            line_cross_positions[i] =
555                (total_extent - (line_cross_positions[i] + line_cross_sizes[i])).max(0.0);
556        }
557    }
558
559    // 5. Position items within each line
560    let mut results = Vec::with_capacity(children.len());
561
562    for (line_idx, line) in lines.iter_mut().enumerate() {
563        let line_cross_pos = line_cross_positions[line_idx];
564        let line_cross_sz = line_cross_sizes[line_idx];
565
566        // Apply item cross stretch within this line
567        for item in line.iter_mut() {
568            let item_align = effective_align_self(&item.style, container_style);
569            let cross_dim = if is_row {
570                item.style.size.height
571            } else {
572                item.style.size.width
573            };
574
575            if cross_dim.is_auto()
576                && item.style.aspect_ratio.is_none()
577                && (has_explicit_stretch_alignment(&item.style, container_style)
578                    || item.target_cross <= 0.0)
579                && item_align == AlignSelf::Stretch
580                && line_cross_sz > 0.0
581            {
582                let margin_cross = if is_row {
583                    item.margin.top + item.margin.bottom
584                } else {
585                    item.margin.left + item.margin.right
586                };
587                let stretched = (line_cross_sz - margin_cross).max(0.0);
588                item.target_cross = BoxConstraints::clamp_dimension(
589                    stretched,
590                    Some(item.min_cross),
591                    if item.max_cross.is_finite() {
592                        Some(item.max_cross)
593                    } else {
594                        None
595                    },
596                );
597            }
598        }
599
600        // Calculate main-axis positions on this line
601        let main_positions = calculate_main_axis_positions(
602            line,
603            container_style,
604            inner_main,
605            gap_main,
606            is_row,
607            is_reverse,
608        );
609
610        // Position each item in line
611        for (item_idx, item) in line.iter().enumerate() {
612            let pos_main = main_positions[item_idx];
613
614            let (c_start, c_end) = if is_row {
615                (item.margin.top, item.margin.bottom)
616            } else {
617                (item.margin.left, item.margin.right)
618            };
619
620            let align = effective_align_self(&item.style, container_style);
621            let pos_in_line = if !is_wrap_reverse {
622                match align {
623                    AlignSelf::Start | AlignSelf::Stretch | AlignSelf::Baseline => c_start,
624                    AlignSelf::End => (line_cross_sz - c_end - item.target_cross).max(0.0),
625                    AlignSelf::Center => {
626                        c_start + (line_cross_sz - item.target_cross - c_start - c_end) / 2.0
627                    }
628                }
629            } else {
630                match align {
631                    AlignSelf::Start | AlignSelf::Stretch | AlignSelf::Baseline => {
632                        (line_cross_sz - c_end - item.target_cross).max(0.0)
633                    }
634                    AlignSelf::End => c_start,
635                    AlignSelf::Center => {
636                        c_start + (line_cross_sz - item.target_cross - c_start - c_end) / 2.0
637                    }
638                }
639            };
640
641            let total_cross = line_cross_pos + pos_in_line;
642
643            let rect = if is_row {
644                LayoutRect::new(
645                    content_origin.x + pos_main,
646                    content_origin.y + total_cross,
647                    item.target_main,
648                    item.target_cross,
649                )
650            } else {
651                LayoutRect::new(
652                    content_origin.x + total_cross,
653                    content_origin.y + pos_main,
654                    item.target_cross,
655                    item.target_main,
656                )
657            };
658
659            results.push((item.id, rect));
660        }
661    }
662
663    Ok(results)
664}
665
666fn resolve_gaps(style: &Style, inner_main: f32, inner_cross: f32, is_row: bool) -> (f32, f32) {
667    let gap_w = match style.gap.width {
668        LengthPercentage::Length(px) => px.max(0.0),
669        LengthPercentage::Percent(p) => {
670            (if is_row { inner_main } else { inner_cross } * p).max(0.0)
671        }
672    };
673    let gap_h = match style.gap.height {
674        LengthPercentage::Length(px) => px.max(0.0),
675        LengthPercentage::Percent(p) => {
676            (if is_row { inner_cross } else { inner_main } * p).max(0.0)
677        }
678    };
679
680    if is_row {
681        (gap_w, gap_h)
682    } else {
683        (gap_h, gap_w)
684    }
685}
686
687fn resolve_main_constraints(
688    style: &Style,
689    inner_main: f32,
690    is_row: bool,
691    hypothetical_main: f32,
692) -> (f32, f32, f32) {
693    // Flex basis
694    let basis = match style.flex_basis {
695        Dimension::Length(px) => px.max(0.0),
696        Dimension::Percent(p) => (inner_main * p).max(0.0),
697        Dimension::Auto => {
698            let main_dim = if is_row {
699                style.size.width
700            } else {
701                style.size.height
702            };
703            match main_dim {
704                Dimension::Length(px) => px.max(0.0),
705                Dimension::Percent(p) => (inner_main * p).max(0.0),
706                Dimension::Auto => hypothetical_main,
707            }
708        }
709    };
710
711    // Min main
712    let min_dim = if is_row {
713        style.min_size.width
714    } else {
715        style.min_size.height
716    };
717    let min_main = match min_dim {
718        Dimension::Length(px) => px.max(0.0),
719        Dimension::Percent(p) => (inner_main * p).max(0.0),
720        Dimension::Auto => 0.0,
721    };
722
723    // Max main
724    let max_dim = if is_row {
725        style.max_size.width
726    } else {
727        style.max_size.height
728    };
729    let max_main = match max_dim {
730        Dimension::Length(px) => px.max(0.0),
731        Dimension::Percent(p) => (inner_main * p).max(0.0),
732        Dimension::Auto => f32::INFINITY,
733    };
734
735    let (clamped_min, clamped_max) = if min_main > max_main {
736        (min_main, min_main)
737    } else {
738        (min_main, max_main)
739    };
740
741    (basis, clamped_min, clamped_max)
742}
743
744fn resolve_cross_constraints(style: &Style, inner_cross: f32, is_row: bool) -> (f32, f32) {
745    let min_dim = if is_row {
746        style.min_size.height
747    } else {
748        style.min_size.width
749    };
750    let min_cross = match min_dim {
751        Dimension::Length(px) => px.max(0.0),
752        Dimension::Percent(p) => (inner_cross * p).max(0.0),
753        Dimension::Auto => 0.0,
754    };
755
756    let max_dim = if is_row {
757        style.max_size.height
758    } else {
759        style.max_size.width
760    };
761    let max_cross = match max_dim {
762        Dimension::Length(px) => px.max(0.0),
763        Dimension::Percent(p) => (inner_cross * p).max(0.0),
764        Dimension::Auto => f32::INFINITY,
765    };
766
767    if min_cross > max_cross {
768        (min_cross, min_cross)
769    } else {
770        (min_cross, max_cross)
771    }
772}
773
774fn resolve_flexible_lengths(items: &mut [FlexItem], inner_main: f32, gap_main: f32) {
775    let count = items.len();
776    if count == 0 {
777        return;
778    }
779
780    let total_gaps = (count.saturating_sub(1) as f32) * gap_main;
781    let sum_target: f32 = items.iter().map(|item| item.target_main).sum();
782
783    let free_space = inner_main - sum_target - total_gaps;
784
785    if free_space > STRICT_TOLERANCE_PX {
786        // GROW
787        let mut remaining_free = free_space;
788        let mut loop_count = 0;
789        while remaining_free > STRICT_TOLERANCE_PX && loop_count < count * 2 {
790            loop_count += 1;
791            let sum_grow: f32 = items
792                .iter()
793                .filter(|item| !item.frozen && item.style.flex_grow > 0.0)
794                .map(|item| item.style.flex_grow)
795                .sum();
796
797            if sum_grow <= 0.0 {
798                break;
799            }
800
801            let mut any_newly_frozen = false;
802            for item in items.iter_mut() {
803                if !item.frozen && item.style.flex_grow > 0.0 {
804                    let share = remaining_free * (item.style.flex_grow / sum_grow);
805                    let prospective = item.target_main + share;
806                    if prospective >= item.max_main {
807                        item.target_main = item.max_main;
808                        item.frozen = true;
809                        any_newly_frozen = true;
810                    }
811                }
812            }
813
814            if any_newly_frozen {
815                let current_sum: f32 = items.iter().map(|item| item.target_main).sum();
816                remaining_free = inner_main - current_sum - total_gaps;
817            } else {
818                for item in items.iter_mut() {
819                    if !item.frozen && item.style.flex_grow > 0.0 {
820                        let share = remaining_free * (item.style.flex_grow / sum_grow);
821                        item.target_main += share;
822                    }
823                }
824                break;
825            }
826        }
827    } else if free_space < -STRICT_TOLERANCE_PX {
828        // SHRINK
829        let mut overflow = -free_space;
830
831        for item in items.iter_mut() {
832            if item.style.flex_shrink <= 0.0 || item.target_main <= item.min_main {
833                item.frozen = true;
834            }
835        }
836
837        let mut loop_count = 0;
838        while overflow > STRICT_TOLERANCE_PX && loop_count < count * 2 {
839            loop_count += 1;
840            let sum_scaled_shrink: f32 = items
841                .iter()
842                .filter(|item| !item.frozen && item.style.flex_shrink > 0.0)
843                .map(|item| item.style.flex_shrink * item.basis)
844                .sum();
845
846            if sum_scaled_shrink <= 0.0 {
847                break;
848            }
849
850            let mut any_newly_frozen = false;
851            for item in items.iter_mut() {
852                if !item.frozen && item.style.flex_shrink > 0.0 {
853                    let scaled = item.style.flex_shrink * item.basis;
854                    let share = overflow * (scaled / sum_scaled_shrink);
855                    let prospective = item.target_main - share;
856                    if prospective <= item.min_main {
857                        item.target_main = item.min_main;
858                        item.frozen = true;
859                        any_newly_frozen = true;
860                    }
861                }
862            }
863
864            if any_newly_frozen {
865                let current_sum: f32 = items.iter().map(|item| item.target_main).sum();
866                overflow = (current_sum + total_gaps) - inner_main;
867            } else {
868                for item in items.iter_mut() {
869                    if !item.frozen && item.style.flex_shrink > 0.0 {
870                        let scaled = item.style.flex_shrink * item.basis;
871                        let share = overflow * (scaled / sum_scaled_shrink);
872                        item.target_main -= share;
873                    }
874                }
875                break;
876            }
877        }
878    }
879}
880
881fn resolve_cross_axis_sizes(
882    items: &mut [FlexItem],
883    container_style: &Style,
884    inner_cross: f32,
885    is_row: bool,
886    available_space: Size<AvailableSpace>,
887) {
888    for item in items.iter_mut() {
889        let cross_dim = if is_row {
890            item.style.size.height
891        } else {
892            item.style.size.width
893        };
894        let item_align = effective_align_self(&item.style, container_style);
895
896        if !cross_dim.is_auto() {
897            let resolved = if is_row {
898                resolve_dimension(cross_dim, available_space.height)
899            } else {
900                resolve_dimension(cross_dim, available_space.width)
901            };
902            if let Some(val) = resolved {
903                item.target_cross = BoxConstraints::clamp_dimension(
904                    val,
905                    Some(item.min_cross),
906                    if item.max_cross.is_finite() {
907                        Some(item.max_cross)
908                    } else {
909                        None
910                    },
911                );
912                continue;
913            }
914        }
915
916        if item.style.aspect_ratio.is_none()
917            && (has_explicit_stretch_alignment(&item.style, container_style)
918                || item.target_cross <= 0.0)
919            && item_align == AlignSelf::Stretch
920            && inner_cross > 0.0
921        {
922            let margin_cross = if is_row {
923                item.margin.top + item.margin.bottom
924            } else {
925                item.margin.left + item.margin.right
926            };
927            let stretched = (inner_cross - margin_cross).max(0.0);
928            item.target_cross = BoxConstraints::clamp_dimension(
929                stretched,
930                Some(item.min_cross),
931                if item.max_cross.is_finite() {
932                    Some(item.max_cross)
933                } else {
934                    None
935                },
936            );
937        } else {
938            let hypo_cross = if is_row {
939                item.hypothetical.height
940            } else {
941                item.hypothetical.width
942            };
943            item.target_cross = BoxConstraints::clamp_dimension(
944                hypo_cross,
945                Some(item.min_cross),
946                if item.max_cross.is_finite() {
947                    Some(item.max_cross)
948                } else {
949                    None
950                },
951            );
952        }
953    }
954}
955
956fn calculate_main_axis_positions(
957    items: &[FlexItem],
958    container_style: &Style,
959    inner_main: f32,
960    gap_main: f32,
961    is_row: bool,
962    is_reverse: bool,
963) -> Vec<f32> {
964    let count = items.len();
965    let total_items_main: f32 = items.iter().map(|item| item.target_main).sum();
966    let total_gaps = (count.saturating_sub(1) as f32) * gap_main;
967    let remaining_main = (inner_main - total_items_main - total_gaps).max(0.0);
968
969    let justify = container_style
970        .justify_content
971        .unwrap_or(JustifyContent::Start);
972    let (main_offset, gap_extra) = match justify {
973        JustifyContent::Start | JustifyContent::Stretch => (0.0, 0.0),
974        JustifyContent::End => (remaining_main, 0.0),
975        JustifyContent::Center => (remaining_main / 2.0, 0.0),
976        JustifyContent::SpaceBetween => {
977            if count > 1 {
978                (0.0, remaining_main / (count - 1) as f32)
979            } else {
980                (0.0, 0.0)
981            }
982        }
983        JustifyContent::SpaceAround => {
984            if count > 0 {
985                let share = remaining_main / count as f32;
986                (share / 2.0, share)
987            } else {
988                (0.0, 0.0)
989            }
990        }
991        JustifyContent::SpaceEvenly => {
992            if count > 0 {
993                let share = remaining_main / (count + 1) as f32;
994                (share, share)
995            } else {
996                (0.0, 0.0)
997            }
998        }
999    };
1000
1001    let effective_gap = gap_main + gap_extra;
1002    let mut main_positions = Vec::with_capacity(count);
1003
1004    if !is_reverse {
1005        let mut cursor = main_offset;
1006        for item in items {
1007            let (m_start, m_end) = if is_row {
1008                (item.margin.left, item.margin.right)
1009            } else {
1010                (item.margin.top, item.margin.bottom)
1011            };
1012            let pos_main = cursor + m_start;
1013            main_positions.push(pos_main);
1014            cursor += m_start + item.target_main + m_end + effective_gap;
1015        }
1016    } else {
1017        let mut cursor = inner_main - main_offset;
1018        for item in items {
1019            let (m_start, m_end) = if is_row {
1020                (item.margin.left, item.margin.right)
1021            } else {
1022                (item.margin.top, item.margin.bottom)
1023            };
1024            let pos_main = cursor - m_end - item.target_main;
1025            main_positions.push(pos_main);
1026            cursor = pos_main - m_start - effective_gap;
1027        }
1028    }
1029
1030    main_positions
1031}
1032
1033#[allow(clippy::too_many_arguments)]
1034fn position_flex_items(
1035    items: &[FlexItem],
1036    container_style: &Style,
1037    inner_main: f32,
1038    inner_cross: f32,
1039    gap_main: f32,
1040    content_origin: Point<f32>,
1041    is_row: bool,
1042    is_reverse: bool,
1043) -> Vec<(LayoutNodeId, LayoutRect)> {
1044    let main_positions = calculate_main_axis_positions(
1045        items,
1046        container_style,
1047        inner_main,
1048        gap_main,
1049        is_row,
1050        is_reverse,
1051    );
1052
1053    let mut results = Vec::with_capacity(items.len());
1054
1055    for (idx, item) in items.iter().enumerate() {
1056        let pos_main = main_positions[idx];
1057
1058        let (c_start, c_end) = if is_row {
1059            (item.margin.top, item.margin.bottom)
1060        } else {
1061            (item.margin.left, item.margin.right)
1062        };
1063
1064        let align = effective_align_self(&item.style, container_style);
1065        let pos_cross = match align {
1066            AlignSelf::Start | AlignSelf::Stretch | AlignSelf::Baseline => c_start,
1067            AlignSelf::End => (inner_cross - c_end - item.target_cross).max(0.0),
1068            AlignSelf::Center => {
1069                c_start + (inner_cross - item.target_cross - c_start - c_end) / 2.0
1070            }
1071        };
1072
1073        let rect = if is_row {
1074            LayoutRect::new(
1075                content_origin.x + pos_main,
1076                content_origin.y + pos_cross,
1077                item.target_main,
1078                item.target_cross,
1079            )
1080        } else {
1081            LayoutRect::new(
1082                content_origin.x + pos_cross,
1083                content_origin.y + pos_main,
1084                item.target_cross,
1085                item.target_main,
1086            )
1087        };
1088
1089        results.push((item.id, rect));
1090    }
1091
1092    results
1093}
1094
1095fn effective_align_self(item_style: &Style, container_style: &Style) -> AlignSelf {
1096    item_style
1097        .align_self
1098        .or_else(|| container_style.align_items.map(to_align_self))
1099        .unwrap_or(AlignSelf::Stretch)
1100}
1101
1102fn has_explicit_stretch_alignment(item_style: &Style, container_style: &Style) -> bool {
1103    item_style.align_self == Some(AlignSelf::Stretch)
1104        || container_style.align_items == Some(AlignItems::Stretch)
1105}