Skip to main content

cranpose_ui/layout/policies/
flex_measure_policy.rs

1use std::cell::RefCell;
2
3use cranpose_ui_graphics::whole;
4use cranpose_ui_layout::{
5    Axis, Constraints, MeasurePolicy, MeasureResult, MeasureScope, ParentData, Placement,
6    bias_offset, round_to_px,
7};
8
9use super::empty_measure_policy::empty_layout_hold;
10use crate::{
11    layout::core::{
12        Arrangement, HorizontalAlignment, LinearArrangement, Measurable, Measurables,
13        VerticalAlignment,
14    },
15    thread_state,
16};
17
18/// Unified Flex layout policy that powers both Row and Column.
19///
20/// This policy implements Jetpack Compose's flex layout semantics:
21/// - Measures children with proper loose constraints (min = 0 on both axes)
22/// - Supports weighted distribution of remaining space
23/// - Handles bounded/unbounded main axis correctly
24/// - Implements correct intrinsics for both axes
25///
26/// ## Overflow Behavior
27///
28/// Like Jetpack Compose, this policy **allows children to overflow** their container bounds:
29/// - Children can be positioned outside the parent's measured size
30/// - Overflowing content is rendered (unless clipped by a modifier)
31/// - When content overflows, distribution arrangements switch to `Start` to avoid negative spacing
32/// - `SpacedBy` keeps its fixed inter-child spacing even when content overflows
33///
34/// Example: A Row with 300px of content in a 200px container will:
35/// 1. Measure children at their natural sizes
36/// 2. Detect overflow (300px > 200px)
37/// 3. Switch to Start arrangement (pack children at the start)
38/// 4. Position last children beyond the 200px boundary
39///
40/// To prevent overflow:
41/// - Use weights for flexible sizing: `.weight(1.0, true)`
42/// - Use `fillMaxWidth()`/`fillMaxHeight()` modifiers
43/// - Design UI to fit within available space
44/// - Add a clip modifier to hide overflowing content
45///
46/// ## Weighted Children
47///
48/// When the main axis is bounded and children have weights:
49/// 1. Fixed children (no weight) are measured first
50/// 2. Remaining space is distributed proportionally to weights
51/// 3. Each weighted child gets: `remaining * (weight / total_weight)`
52/// 4. If `fill=true`, child gets tight constraints; if `fill=false`, loose constraints
53///
54/// When the main axis is unbounded, weights are ignored (all children wrap content).
55#[derive(Clone, Debug, PartialEq)]
56pub struct FlexMeasurePolicy {
57    /// Main axis direction (Horizontal for Row, Vertical for Column)
58    pub axis: Axis,
59    /// Arrangement along the main axis
60    pub main_axis_arrangement: LinearArrangement,
61    /// Alignment along the cross axis (used as default for children without explicit alignment)
62    pub cross_axis_alignment: CrossAxisAlignment,
63    /// The device pixel grid children are spaced and placed on, the
64    /// composition's density.
65    pub density: f32,
66    /// Direction used to resolve horizontal order and start/end alignment.
67    pub layout_direction: crate::LayoutDirection,
68}
69
70/// Compose's weight distribution in whole device pixels: each weighted
71/// child's share of the remaining space rounded half up, and the pixels
72/// that rounding gained or lost handed back one per child from the first.
73pub(crate) struct WeightShares {
74    density: f32,
75    unit_px: f32,
76    remainder_px: f32,
77}
78
79impl WeightShares {
80    pub(crate) fn new(
81        remaining: f32,
82        weights: impl Iterator<Item = f32> + Clone,
83        density: f32,
84    ) -> Self {
85        let density = if density > 0.0 && density.is_finite() {
86            density
87        } else {
88            1.0
89        };
90        let total_weight: f32 = weights.clone().sum();
91        let remaining_px = whole::round(remaining * density);
92        let unit_px = if total_weight > 0.0 {
93            remaining_px / total_weight
94        } else {
95            0.0
96        };
97        let rounded_px: f32 = weights
98            .map(|weight| whole::floor(unit_px * weight + 0.5))
99            .sum();
100        Self {
101            density,
102            unit_px,
103            remainder_px: remaining_px - rounded_px,
104        }
105    }
106
107    /// The main-axis size of the next weighted child, which weighs `weight`.
108    pub(crate) fn next_share(&mut self, weight: f32) -> f32 {
109        let step = if self.remainder_px > 0.0 {
110            1.0
111        } else if self.remainder_px < 0.0 {
112            -1.0
113        } else {
114            0.0
115        };
116        self.remainder_px -= step;
117        (whole::floor(self.unit_px * weight + 0.5) + step).max(0.0) / self.density
118    }
119}
120
121/// Cross-axis alignment for flex layouts.
122/// This is axis-agnostic and gets interpreted based on the flex axis.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub enum CrossAxisAlignment {
125    /// Align to the start of the cross axis (Top for Row, Start for Column)
126    Start,
127    /// Align to the center of the cross axis
128    Center,
129    /// Align to the end of the cross axis (Bottom for Row, End for Column)
130    End,
131}
132
133impl CrossAxisAlignment {
134    /// Where a child sits in `available` space: see [`bias_offset`].
135    fn align(&self, available: f32, child: f32, density: f32) -> f32 {
136        let bias = match self {
137            Self::Start => -1.0,
138            Self::Center => 0.0,
139            Self::End => 1.0,
140        };
141        bias_offset(bias, available, child, density)
142    }
143}
144
145impl From<HorizontalAlignment> for CrossAxisAlignment {
146    fn from(alignment: HorizontalAlignment) -> Self {
147        match alignment {
148            HorizontalAlignment::Start => Self::Start,
149            HorizontalAlignment::CenterHorizontally => Self::Center,
150            HorizontalAlignment::End => Self::End,
151        }
152    }
153}
154
155impl From<VerticalAlignment> for CrossAxisAlignment {
156    fn from(alignment: VerticalAlignment) -> Self {
157        match alignment {
158            VerticalAlignment::Top => Self::Start,
159            VerticalAlignment::CenterVertically => Self::Center,
160            VerticalAlignment::Bottom => Self::End,
161        }
162    }
163}
164
165impl FlexMeasurePolicy {
166    /// A flex layout along `axis` on the device pixel grid of `density`.
167    pub fn new(
168        axis: Axis,
169        main_axis_arrangement: LinearArrangement,
170        cross_axis_alignment: CrossAxisAlignment,
171        density: f32,
172    ) -> Self {
173        Self {
174            axis,
175            main_axis_arrangement,
176            cross_axis_alignment,
177            density,
178            layout_direction: crate::LayoutDirection::Ltr,
179        }
180    }
181
182    /// Creates a FlexMeasurePolicy for Row (horizontal main axis).
183    pub fn row(
184        horizontal_arrangement: LinearArrangement,
185        vertical_alignment: VerticalAlignment,
186        density: f32,
187    ) -> Self {
188        Self::new(
189            Axis::Horizontal,
190            horizontal_arrangement,
191            vertical_alignment.into(),
192            density,
193        )
194    }
195
196    /// Creates a FlexMeasurePolicy for Column (vertical main axis).
197    pub fn column(
198        vertical_arrangement: LinearArrangement,
199        horizontal_alignment: HorizontalAlignment,
200        density: f32,
201    ) -> Self {
202        Self::new(
203            Axis::Vertical,
204            vertical_arrangement,
205            horizontal_alignment.into(),
206            density,
207        )
208    }
209
210    fn get_axis_constraints(&self, constraints: Constraints) -> (f32, f32, f32, f32) {
211        match self.axis {
212            Axis::Horizontal => (
213                constraints.min_width,
214                constraints.max_width,
215                constraints.min_height,
216                constraints.max_height,
217            ),
218            Axis::Vertical => (
219                constraints.min_height,
220                constraints.max_height,
221                constraints.min_width,
222                constraints.max_width,
223            ),
224        }
225    }
226
227    fn make_constraints(
228        &self,
229        min_main: f32,
230        max_main: f32,
231        min_cross: f32,
232        max_cross: f32,
233    ) -> Constraints {
234        match self.axis {
235            Axis::Horizontal => Constraints {
236                min_width: min_main,
237                max_width: max_main,
238                min_height: min_cross,
239                max_height: max_cross,
240            },
241            Axis::Vertical => Constraints {
242                min_width: min_cross,
243                max_width: max_cross,
244                min_height: min_main,
245                max_height: max_main,
246            },
247        }
248    }
249
250    fn get_main_axis_size(&self, width: f32, height: f32) -> f32 {
251        match self.axis {
252            Axis::Horizontal => width,
253            Axis::Vertical => height,
254        }
255    }
256
257    fn get_cross_axis_size(&self, width: f32, height: f32) -> f32 {
258        match self.axis {
259            Axis::Horizontal => height,
260            Axis::Vertical => width,
261        }
262    }
263
264    /// Measures the unweighted children in order and returns Compose's
265    /// `fixedSpace` with the largest cross size. Each child is offered only
266    /// the main-axis space the ones before it leave, as
267    /// `RowColumnMeasurementHelper` offers it, and the spacing after a child
268    /// never runs past the main axis.
269    fn measure_fixed_children(
270        &self,
271        measurables: Measurables<'_>,
272        children: &mut [FlexChild],
273        (max_main, max_cross): (f32, f32),
274        spacing: f32,
275    ) -> (f32, f32) {
276        let main_axis_bounded = max_main.is_finite();
277        let mut fixed_space = 0.0_f32;
278        let mut max_cross_size = 0.0_f32;
279        for (child, measurable) in children.iter_mut().zip(measurables) {
280            if child.data.has_weight() {
281                continue;
282            }
283            let available_main = if main_axis_bounded {
284                (max_main - fixed_space).max(0.0)
285            } else {
286                max_main
287            };
288            let placeable =
289                measurable.measure(self.make_constraints(0.0, available_main, 0.0, max_cross));
290            let main_size = self.get_main_axis_size(placeable.width(), placeable.height());
291            let spacing_after = if main_axis_bounded {
292                spacing.min(available_main - main_size).max(0.0)
293            } else {
294                spacing
295            };
296            fixed_space += main_size + spacing_after;
297            max_cross_size =
298                max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
299            child.placeable = Some(placeable);
300        }
301        (fixed_space, max_cross_size)
302    }
303
304    /// Compose's intrinsic size along the main axis: the sizes `main_size`
305    /// gives of the unweighted children, the space in which each weighted
306    /// child gets its own size, and the spacing.
307    fn intrinsic_main_size(
308        &self,
309        measurables: Measurables<'_>,
310        main_size: impl Fn(&dyn Measurable) -> f32,
311    ) -> f32 {
312        if measurables.is_empty() {
313            return 0.0;
314        }
315        let mut fixed_space = 0.0_f32;
316        let mut weight_unit = 0.0_f32;
317        let mut total_weight = 0.0_f32;
318        for measurable in measurables {
319            let size = main_size(measurable);
320            match child_weight(measurable) {
321                Some(weight) => {
322                    total_weight += weight;
323                    weight_unit = weight_unit.max(round_to_px(size / weight, self.density));
324                }
325                None => fixed_space += size,
326            }
327        }
328        round_to_px(weight_unit * total_weight, self.density)
329            + fixed_space
330            + self.get_spacing() * (measurables.len() - 1) as f32
331    }
332
333    /// Compose's intrinsic size across the main axis, in `main_available`
334    /// main-axis space: each unweighted child asks for the main-axis size
335    /// `main_size` gives it, up to what the children before it leave, and
336    /// the weighted children share the rest. `cross_size` gives a child's
337    /// cross size in the main-axis space it gets.
338    fn intrinsic_cross_size(
339        &self,
340        measurables: Measurables<'_>,
341        main_available: f32,
342        main_size: impl Fn(&dyn Measurable, f32) -> f32,
343        cross_size: impl Fn(&dyn Measurable, f32) -> f32,
344    ) -> f32 {
345        if measurables.is_empty() {
346            return 0.0;
347        }
348        let mut fixed_space =
349            (self.get_spacing() * (measurables.len() - 1) as f32).min(main_available);
350        let mut cross = 0.0_f32;
351        let mut total_weight = 0.0_f32;
352        for measurable in measurables {
353            if let Some(weight) = child_weight(measurable) {
354                total_weight += weight;
355                continue;
356            }
357            let space =
358                main_size(measurable, f32::INFINITY).min((main_available - fixed_space).max(0.0));
359            fixed_space += space;
360            cross = cross.max(cross_size(measurable, space));
361        }
362        if total_weight == 0.0 {
363            return cross;
364        }
365        let weight_unit = if main_available.is_finite() {
366            round_to_px(
367                (main_available - fixed_space).max(0.0) / total_weight,
368                self.density,
369            )
370        } else {
371            f32::INFINITY
372        };
373        for measurable in measurables {
374            if let Some(weight) = child_weight(measurable) {
375                cross = cross.max(cross_size(
376                    measurable,
377                    round_to_px(weight_unit * weight, self.density),
378                ));
379            }
380        }
381        cross
382    }
383
384    fn get_spacing(&self) -> f32 {
385        self.main_axis_arrangement.spacing(self.density)
386    }
387
388    fn measure_weighted_children(
389        &self,
390        measurables: Measurables<'_>,
391        children: &mut [FlexChild],
392        (max_main, max_cross): (f32, f32),
393        (fixed_space, spacing): (f32, f32),
394    ) -> f32 {
395        let weights = children
396            .iter()
397            .filter(|child| child.data.has_weight())
398            .map(|child| child.data.weight);
399        let weighted = weights.clone().count();
400        if weighted == 0 {
401            return 0.0;
402        }
403        let remaining_main = (max_main - fixed_space - spacing * (weighted - 1) as f32).max(0.0);
404        let mut shares = WeightShares::new(remaining_main, weights, self.density);
405        let mut max_cross_size = 0.0_f32;
406        for (child, measurable) in children.iter_mut().zip(measurables) {
407            let data = &child.data;
408            if !data.has_weight() {
409                continue;
410            }
411            let constraints = if max_main.is_finite() {
412                let allocated = shares.next_share(data.weight);
413                let minimum = if data.fill { allocated } else { 0.0 };
414                self.make_constraints(minimum, allocated, 0.0, max_cross)
415            } else {
416                self.make_constraints(0.0, max_main, 0.0, max_cross)
417            };
418            let placeable = measurable.measure(constraints);
419            max_cross_size =
420                max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
421            child.placeable = Some(placeable);
422        }
423        max_cross_size
424    }
425
426    fn measured_extents(&self, children: &[FlexChild]) -> (f32, f32, f32) {
427        let mut main = 0.0;
428        let mut before = 0.0_f32;
429        let mut after = 0.0_f32;
430        for (placeable, data) in measured(children) {
431            main += self.get_main_axis_size(placeable.width(), placeable.height());
432            if self.axis == Axis::Horizontal
433                && data.row_baseline
434                && let Some(baseline) = placeable.alignment_lines().first_baseline()
435            {
436                before = before.max(baseline);
437                after = after.max(placeable.height() - baseline);
438            }
439        }
440        (main, before, after)
441    }
442
443    fn cross_axis_position(
444        &self,
445        placeable: &cranpose_ui_layout::Placeable,
446        parent_data: &ParentData,
447        container_cross: f32,
448        before_baseline: f32,
449    ) -> f32 {
450        if self.axis == Axis::Horizontal && parent_data.row_baseline {
451            return placeable
452                .alignment_lines()
453                .first_baseline()
454                .map_or(0.0, |baseline| before_baseline - baseline);
455        }
456        let alignment = match self.axis {
457            Axis::Horizontal => parent_data
458                .row_alignment
459                .map_or(self.cross_axis_alignment, Into::into),
460            Axis::Vertical => parent_data
461                .column_alignment
462                .map_or(self.cross_axis_alignment, Into::into),
463        };
464        let child_cross = self.get_cross_axis_size(placeable.width(), placeable.height());
465        alignment.align(container_cross, child_cross, self.density)
466    }
467}
468
469/// The parent main-axis max range over which a held child keeps its size
470/// after `fixed_space` taken by the children before it, with `spacing`
471/// still fitting after it.
472fn child_main_range(
473    child_max: cranpose_ui_layout::BoundRange,
474    max_main: f32,
475    fixed_space: f32,
476    child_main: f32,
477    spacing: f32,
478) -> Option<cranpose_ui_layout::BoundRange> {
479    use cranpose_ui_layout::BoundRange;
480    if !max_main.is_finite() {
481        return child_max
482            .contains(f32::INFINITY)
483            .then_some(BoundRange::exactly(f32::INFINITY));
484    }
485    if (max_main - fixed_space).max(0.0) - child_main < spacing {
486        return None;
487    }
488    child_max
489        .outset(fixed_space)
490        .intersect(BoundRange::from(fixed_space + child_main + spacing))
491}
492
493/// The weight of a child that shares the main axis by weight.
494fn child_weight(measurable: &dyn Measurable) -> Option<f32> {
495    measurable
496        .flex_parent_data()
497        .map(|data| data.weight)
498        .filter(|weight| *weight > 0.0)
499}
500
501/// A child of a row or column while the row measures it: its parent data
502/// and, once measured, its placeable.
503struct FlexChild {
504    data: ParentData,
505    placeable: Option<cranpose_ui_layout::Placeable>,
506}
507
508// The lists a row or column measures with: its children, then their sizes
509// and positions along its main axis.
510#[derive(Default)]
511struct FlexLists {
512    children: Vec<FlexChild>,
513    main_sizes: Vec<f32>,
514    main_positions: Vec<f32>,
515}
516
517impl FlexLists {
518    // The heap bytes the lists hold.
519    fn bytes(&self) -> usize {
520        self.children.capacity() * size_of::<FlexChild>()
521            + (self.main_sizes.capacity() + self.main_positions.capacity()) * size_of::<f32>()
522    }
523}
524
525// The lists of a thread's rows and columns, kept between measures: one for
526// each row or column that measures at once, as deep as they nest, so each
527// nesting level takes back lists of its own size. Lists on the stack took
528// 548 bytes on the ESP32 at every nesting level a measure passes through,
529// eight children inline.
530pub(crate) struct SpareFlexLists(RefCell<Spares>);
531
532struct Spares {
533    // The last set given back is on top, for the next measure to take.
534    sets: Vec<FlexLists>,
535    // The heap bytes of the sets.
536    bytes: usize,
537}
538
539impl Spares {
540    // At most this many sets: the gauntlet nests columns 48 deep, the
541    // allocation test 65 rows and columns.
542    const SETS: usize = 128;
543    // At most this many bytes in the sets below the top one.
544    const IDLE_BYTES: usize = 64 * 1024;
545
546    // Keeps `lists` whole on top, so a row or column that measures again
547    // takes back lists of its own size, and drops the largest of the other
548    // sets while there are too many or they hold too many bytes.
549    fn keep(&mut self, lists: FlexLists) {
550        let top = lists.bytes();
551        self.bytes += top;
552        self.sets.push(lists);
553        while self.sets.len() > Self::SETS || self.bytes - top > Self::IDLE_BYTES {
554            let idle = &self.sets[..self.sets.len() - 1];
555            let Some(largest) = (0..idle.len()).max_by_key(|&at| idle[at].bytes()) else {
556                break;
557            };
558            self.bytes -= self.sets.remove(largest).bytes();
559        }
560    }
561
562    fn take(&mut self) -> Option<FlexLists> {
563        let lists = self.sets.pop()?;
564        self.bytes -= lists.bytes();
565        Some(lists)
566    }
567}
568
569impl SpareFlexLists {
570    pub(crate) const fn new() -> Self {
571        Self(RefCell::new(Spares {
572            sets: Vec::new(),
573            bytes: 0,
574        }))
575    }
576
577    fn take() -> FlexLists {
578        thread_state::with(|state| state.spare_flex_lists.0.borrow_mut().take()).unwrap_or_default()
579    }
580
581    fn give(mut lists: FlexLists) {
582        lists.children.clear();
583        lists.main_sizes.clear();
584        lists.main_positions.clear();
585        thread_state::with(|state| state.spare_flex_lists.0.borrow_mut().keep(lists));
586    }
587}
588
589/// The measured children with their parent data: every child, once both
590/// measuring passes ran, since each child is fixed or weighted.
591fn measured(
592    children: &[FlexChild],
593) -> impl Iterator<Item = (&cranpose_ui_layout::Placeable, &ParentData)> {
594    children
595        .iter()
596        .filter_map(|child| Some((child.placeable.as_ref()?, &child.data)))
597}
598
599impl MeasurePolicy for FlexMeasurePolicy {
600    fn measure(
601        &self,
602        scope: &dyn MeasureScope,
603        measurables: Measurables<'_>,
604        constraints: Constraints,
605    ) -> MeasureResult {
606        let mut placements = Vec::new();
607        let measurement = self.measure_into(scope, measurables, constraints, &mut placements);
608        MeasureResult::new(measurement, placements)
609    }
610
611    /// A row or column of unweighted children holds while each child holds
612    /// under the main-axis space the ones before it leave, the spacing
613    /// after each keeps its full width, and the bounds still fit the sum.
614    fn measure_hold(
615        &self,
616        measurables: Measurables<'_>,
617        constraints: Constraints,
618        size: crate::modifier::Size,
619    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
620        use cranpose_ui_layout::{AxisHold, BoundRange, ConstraintsHold};
621        if measurables.is_empty() {
622            return empty_layout_hold(constraints, size);
623        }
624        if measurables
625            .iter()
626            .any(|measurable| measurable.parent_data().has_weight())
627        {
628            return None;
629        }
630        let (_, max_main, _, _) = self.get_axis_constraints(constraints);
631        let spacing = self.get_spacing();
632        let mut main = BoundRange::ANY;
633        let mut cross = BoundRange::ANY;
634        let mut fixed_space = 0.0_f32;
635        let mut total_main = 0.0_f32;
636        let mut cross_size = 0.0_f32;
637        for measurable in measurables {
638            let (child, hold) = measurable.measured_hold()?;
639            let (main_hold, cross_hold) = match self.axis {
640                Axis::Horizontal => (hold.width, hold.height),
641                Axis::Vertical => (hold.height, hold.width),
642            };
643            let child_main = self.get_main_axis_size(child.width, child.height);
644            main = main.intersect(child_main_range(
645                main_hold.max,
646                max_main,
647                fixed_space,
648                child_main,
649                spacing,
650            )?)?;
651            cross = cross.intersect(cross_hold.max)?;
652            fixed_space += child_main + spacing;
653            total_main += child_main;
654            cross_size = cross_size.max(self.get_cross_axis_size(child.width, child.height));
655        }
656        total_main += spacing * (measurables.len() - 1) as f32;
657        let size_main = self.get_main_axis_size(size.width, size.height);
658        let size_cross = self.get_cross_axis_size(size.width, size.height);
659        // Bounds that cut or stretched the layout size it from themselves.
660        if size_main != total_main || size_cross != cross_size {
661            return None;
662        }
663        let main = AxisHold {
664            min: BoundRange::up_to(size_main),
665            max: main.intersect(BoundRange::from(size_main))?,
666        };
667        let cross = AxisHold {
668            min: BoundRange::up_to(size_cross),
669            max: cross.intersect(BoundRange::from(size_cross))?,
670        };
671        Some(match self.axis {
672            Axis::Horizontal => ConstraintsHold {
673                width: main,
674                height: cross,
675            },
676            Axis::Vertical => ConstraintsHold {
677                width: cross,
678                height: main,
679            },
680        })
681    }
682
683    fn measure_into(
684        &self,
685        _scope: &dyn MeasureScope,
686        measurables: Measurables<'_>,
687        constraints: Constraints,
688        placements: &mut Vec<Placement>,
689    ) -> cranpose_ui_layout::Measurement {
690        placements.clear();
691        if measurables.is_empty() {
692            let (width, height) = constraints.constrain(0.0, 0.0);
693            return crate::modifier::Size { width, height }.into();
694        }
695
696        let (min_main, max_main, min_cross, max_cross) = self.get_axis_constraints(constraints);
697        let spacing = self.get_spacing();
698
699        let mut lists = SpareFlexLists::take();
700        let FlexLists {
701            children,
702            main_sizes,
703            main_positions,
704        } = &mut lists;
705        children.extend(measurables.iter().map(|child| FlexChild {
706            data: child.parent_data(),
707            placeable: None,
708        }));
709        let (fixed_space, mut max_cross_size) =
710            self.measure_fixed_children(measurables, children, (max_main, max_cross), spacing);
711
712        let num_children = measurables.len();
713        let total_spacing = if num_children > 1 {
714            spacing * (num_children - 1) as f32
715        } else {
716            0.0
717        };
718
719        max_cross_size = max_cross_size.max(self.measure_weighted_children(
720            measurables,
721            children,
722            (max_main, max_cross),
723            (fixed_space, spacing),
724        ));
725
726        let (total_main, before_baseline, after_baseline) = self.measured_extents(children);
727        let total_main = total_main + total_spacing;
728        max_cross_size = max_cross_size.max(before_baseline + after_baseline);
729
730        let container_main = total_main.clamp(min_main, max_main);
731        let container_cross = max_cross_size.clamp(min_cross, max_cross);
732
733        main_sizes.extend(
734            measured(children).map(|(p, _)| self.get_main_axis_size(p.width(), p.height())),
735        );
736        main_positions.resize(main_sizes.len(), 0.0);
737
738        let arrangement = if total_main > container_main && !self.main_axis_arrangement.is_spaced()
739        {
740            LinearArrangement::Start
741        } else {
742            self.main_axis_arrangement
743        };
744        arrangement.arrange(self.density, container_main, main_sizes, main_positions);
745
746        placements.reserve(children.len());
747        for ((placeable, data), &main_pos) in measured(children).zip(main_positions.iter()) {
748            let cross_pos =
749                self.cross_axis_position(placeable, data, container_cross, before_baseline);
750
751            let (x, y) = match self.axis {
752                Axis::Horizontal => (main_pos, cross_pos),
753                Axis::Vertical => (cross_pos, main_pos),
754            };
755            let width = match self.axis {
756                Axis::Horizontal => container_main,
757                Axis::Vertical => container_cross,
758            };
759            let x = self.layout_direction.place_x(x, width, placeable.width());
760
761            placements.push(Placement::new(placeable.node_id(), x, y, 0.0));
762        }
763        SpareFlexLists::give(lists);
764
765        let (width, height) = match self.axis {
766            Axis::Horizontal => (container_main, container_cross),
767            Axis::Vertical => (container_cross, container_main),
768        };
769
770        crate::modifier::Size { width, height }.into()
771    }
772
773    fn min_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
774        match self.axis {
775            Axis::Horizontal => {
776                self.intrinsic_main_size(measurables, |m| m.min_intrinsic_width(height))
777            }
778            Axis::Vertical => self.intrinsic_cross_size(
779                measurables,
780                height,
781                |m, width| m.max_intrinsic_height(width),
782                |m, main| m.min_intrinsic_width(main),
783            ),
784        }
785    }
786
787    fn max_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
788        match self.axis {
789            Axis::Horizontal => {
790                self.intrinsic_main_size(measurables, |m| m.max_intrinsic_width(height))
791            }
792            Axis::Vertical => self.intrinsic_cross_size(
793                measurables,
794                height,
795                |m, width| m.max_intrinsic_height(width),
796                |m, main| m.max_intrinsic_width(main),
797            ),
798        }
799    }
800
801    fn min_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
802        match self.axis {
803            Axis::Horizontal => self.intrinsic_cross_size(
804                measurables,
805                width,
806                |m, height| m.max_intrinsic_width(height),
807                |m, main| m.min_intrinsic_height(main),
808            ),
809            Axis::Vertical => {
810                self.intrinsic_main_size(measurables, |m| m.min_intrinsic_height(width))
811            }
812        }
813    }
814
815    fn max_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
816        match self.axis {
817            Axis::Horizontal => self.intrinsic_cross_size(
818                measurables,
819                width,
820                |m, height| m.max_intrinsic_width(height),
821                |m, main| m.max_intrinsic_height(main),
822            ),
823            Axis::Vertical => {
824                self.intrinsic_main_size(measurables, |m| m.max_intrinsic_height(width))
825            }
826        }
827    }
828}