Skip to main content

sui_layout/
lib.rs

1#![forbid(unsafe_code)]
2
3mod grid;
4
5pub use grid::{
6    GridItem, GridItemLayout, GridLayout, GridPlacement, GridStyle, GridTrack, GridTrackMax,
7    grid_layout,
8};
9
10use std::sync::Arc;
11
12use sui_core::{DpiInfo, ImageHandle, Point, Rect, Size};
13use sui_scene::ImageRegistry;
14use sui_text::{
15    FontRegistry, PersistentTextLayout, TextDocument, TextLayout, TextLayoutHandle,
16    TextLayoutRequest, TextMeasurement, TextStyle, TextSystem,
17};
18
19const FLEX_EPSILON: f32 = 0.001;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Axis {
23    Horizontal,
24    Vertical,
25}
26
27/// Minimum and preferred content extents reported by a widget along one axis.
28///
29/// The minimum is the smallest readable/unbreakable extent. The natural value
30/// is the extent the widget prefers when it is not asked to wrap or shrink.
31#[derive(Debug, Clone, Copy, Default, PartialEq)]
32pub struct IntrinsicSize {
33    pub minimum: f32,
34    pub natural: f32,
35}
36
37impl IntrinsicSize {
38    pub fn new(minimum: f32, natural: f32) -> Self {
39        let minimum = finite_non_negative(minimum);
40        Self {
41            minimum,
42            natural: finite_non_negative(natural).max(minimum),
43        }
44    }
45
46    pub fn fixed(extent: f32) -> Self {
47        Self::new(extent, extent)
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Alignment {
53    Start,
54    Center,
55    End,
56    Stretch,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum FlexWrap {
61    NoWrap,
62    Wrap,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum FlexJustify {
67    Start,
68    Center,
69    End,
70    SpaceBetween,
71    SpaceAround,
72    SpaceEvenly,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum FlexAlignContent {
77    Start,
78    Center,
79    End,
80    Stretch,
81    SpaceBetween,
82    SpaceAround,
83    SpaceEvenly,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub enum FlexBasis {
88    Auto,
89    Points(f32),
90    Fraction(f32),
91    GapAwareFraction(f32),
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct FlexStyle {
96    pub axis: Axis,
97    pub wrap: FlexWrap,
98    pub main_gap: f32,
99    pub cross_gap: f32,
100    pub justify: FlexJustify,
101    pub align_items: Alignment,
102    pub align_content: FlexAlignContent,
103}
104
105impl FlexStyle {
106    pub const fn new(axis: Axis) -> Self {
107        Self {
108            axis,
109            wrap: FlexWrap::NoWrap,
110            main_gap: 0.0,
111            cross_gap: 0.0,
112            justify: FlexJustify::Start,
113            align_items: Alignment::Start,
114            align_content: FlexAlignContent::Start,
115        }
116    }
117
118    pub const fn horizontal() -> Self {
119        Self::new(Axis::Horizontal)
120    }
121
122    pub const fn vertical() -> Self {
123        Self::new(Axis::Vertical)
124    }
125
126    pub fn wrap(mut self, wrap: FlexWrap) -> Self {
127        self.wrap = wrap;
128        self
129    }
130
131    pub fn gap(mut self, gap: f32) -> Self {
132        let gap = finite_non_negative(gap);
133        self.main_gap = gap;
134        self.cross_gap = gap;
135        self
136    }
137
138    pub fn main_gap(mut self, gap: f32) -> Self {
139        self.main_gap = finite_non_negative(gap);
140        self
141    }
142
143    pub fn cross_gap(mut self, gap: f32) -> Self {
144        self.cross_gap = finite_non_negative(gap);
145        self
146    }
147
148    pub fn justify(mut self, justify: FlexJustify) -> Self {
149        self.justify = justify;
150        self
151    }
152
153    pub fn align_items(mut self, alignment: Alignment) -> Self {
154        self.align_items = alignment;
155        self
156    }
157
158    pub fn align_content(mut self, alignment: FlexAlignContent) -> Self {
159        self.align_content = alignment;
160        self
161    }
162}
163
164impl Default for FlexStyle {
165    fn default() -> Self {
166        Self::horizontal()
167    }
168}
169
170#[derive(Debug, Clone, Copy, PartialEq)]
171pub struct FlexItem {
172    pub grow: f32,
173    pub shrink: f32,
174    pub basis: FlexBasis,
175    pub min_size: Size,
176    pub max_size: Size,
177    pub align_self: Option<Alignment>,
178}
179
180impl FlexItem {
181    pub const fn new() -> Self {
182        Self {
183            grow: 0.0,
184            shrink: 1.0,
185            basis: FlexBasis::Auto,
186            min_size: Size::ZERO,
187            max_size: Size::new(f32::INFINITY, f32::INFINITY),
188            align_self: None,
189        }
190    }
191
192    pub const fn fill() -> Self {
193        Self {
194            grow: 1.0,
195            shrink: 1.0,
196            basis: FlexBasis::Points(0.0),
197            min_size: Size::ZERO,
198            max_size: Size::new(f32::INFINITY, f32::INFINITY),
199            align_self: None,
200        }
201    }
202
203    pub fn flex(grow: f32) -> Self {
204        Self::fill().grow(grow)
205    }
206
207    pub fn fixed(basis: f32) -> Self {
208        Self::new().basis(basis).no_shrink()
209    }
210
211    pub fn grow(mut self, grow: f32) -> Self {
212        self.grow = finite_non_negative(grow);
213        self
214    }
215
216    pub fn shrink(mut self, shrink: f32) -> Self {
217        self.shrink = finite_non_negative(shrink);
218        self
219    }
220
221    pub fn no_shrink(mut self) -> Self {
222        self.shrink = 0.0;
223        self
224    }
225
226    pub fn basis(mut self, basis: f32) -> Self {
227        self.basis = FlexBasis::Points(finite_non_negative(basis));
228        self
229    }
230
231    pub fn basis_fraction(mut self, fraction: f32) -> Self {
232        self.basis = FlexBasis::Fraction(finite_non_negative(fraction));
233        self
234    }
235
236    pub fn basis_gap_aware_fraction(mut self, fraction: f32) -> Self {
237        self.basis = FlexBasis::GapAwareFraction(finite_non_negative(fraction));
238        self
239    }
240
241    pub fn auto_basis(mut self) -> Self {
242        self.basis = FlexBasis::Auto;
243        self
244    }
245
246    pub fn min_size(mut self, min_size: Size) -> Self {
247        self.min_size = Size::new(
248            finite_non_negative(min_size.width),
249            finite_non_negative(min_size.height),
250        );
251        self
252    }
253
254    pub fn min_width(mut self, min_width: f32) -> Self {
255        self.min_size.width = finite_non_negative(min_width);
256        self
257    }
258
259    pub fn min_height(mut self, min_height: f32) -> Self {
260        self.min_size.height = finite_non_negative(min_height);
261        self
262    }
263
264    pub fn max_size(mut self, max_size: Size) -> Self {
265        self.max_size = Size::new(
266            non_negative_or_infinity(max_size.width),
267            non_negative_or_infinity(max_size.height),
268        );
269        self
270    }
271
272    pub fn max_width(mut self, max_width: f32) -> Self {
273        self.max_size.width = non_negative_or_infinity(max_width);
274        self
275    }
276
277    pub fn max_height(mut self, max_height: f32) -> Self {
278        self.max_size.height = non_negative_or_infinity(max_height);
279        self
280    }
281
282    pub fn align_self(mut self, alignment: Alignment) -> Self {
283        self.align_self = Some(alignment);
284        self
285    }
286
287    pub fn inherit_alignment(mut self) -> Self {
288        self.align_self = None;
289        self
290    }
291}
292
293impl Default for FlexItem {
294    fn default() -> Self {
295        Self::new()
296    }
297}
298
299#[derive(Debug, Clone, PartialEq)]
300pub struct FlexLayout {
301    pub size: Size,
302    pub items: Vec<FlexItemLayout>,
303    pub lines: Vec<FlexLineLayout>,
304}
305
306impl FlexLayout {
307    pub fn empty(size: Size) -> Self {
308        Self {
309            size,
310            items: Vec::new(),
311            lines: Vec::new(),
312        }
313    }
314}
315
316#[derive(Debug, Clone, Copy, PartialEq)]
317pub struct FlexItemLayout {
318    pub rect: Rect,
319    pub measured_size: Size,
320    pub line: usize,
321}
322
323#[derive(Debug, Clone, Copy, PartialEq)]
324pub struct FlexLineLayout {
325    pub item_start: usize,
326    pub item_end: usize,
327    pub rect: Rect,
328}
329
330pub fn flex_layout<F>(
331    style: FlexStyle,
332    items: &[FlexItem],
333    constraints: Constraints,
334    mut measure_child: F,
335) -> FlexLayout
336where
337    F: FnMut(usize, Constraints) -> Size,
338{
339    let initial_measurements = items
340        .iter()
341        .enumerate()
342        .map(|(index, item)| {
343            let child_constraints = flex_child_constraints(style, *item, constraints);
344            let measured_size = clamp_item_size(*item, measure_child(index, child_constraints));
345            (child_constraints, measured_size)
346        })
347        .collect::<Vec<_>>();
348    let measured_sizes = initial_measurements
349        .iter()
350        .map(|(_, measured_size)| *measured_size)
351        .collect::<Vec<_>>();
352    let initial_layout = flex_layout_from_measured(style, items, constraints, &measured_sizes);
353
354    // Flex basis and grow/shrink resolution can assign a child a very different
355    // main-axis extent from the one used for its intrinsic measurement. Text is
356    // the important example: `FlexItem::flex(1.0)` has a zero-point basis, so an
357    // initial width of zero produces a one-glyph-per-line layout even though the
358    // item is then grown across the row. Measure again at the resolved allocation
359    // so width-dependent children can rebuild wrapping and report the resulting
360    // cross-axis size before the final line layout is computed.
361    let resolved_sizes = items
362        .iter()
363        .enumerate()
364        .map(|(index, item)| {
365            let resolved_main = initial_layout
366                .items
367                .get(index)
368                .map(|layout| axis_main(style.axis, layout.rect.size))
369                .unwrap_or(0.0);
370            let child_constraints =
371                resolved_flex_child_constraints(style, *item, constraints, resolved_main);
372            let (initial_constraints, initial_size) = initial_measurements[index];
373            if child_constraints == initial_constraints {
374                initial_size
375            } else {
376                clamp_item_size(*item, measure_child(index, child_constraints))
377            }
378        })
379        .collect::<Vec<_>>();
380
381    flex_layout_from_measured(style, items, constraints, &resolved_sizes)
382}
383
384pub fn arrange_flex(
385    style: FlexStyle,
386    items: &[FlexItem],
387    container_size: Size,
388    measured_sizes: &[Size],
389) -> FlexLayout {
390    flex_layout_from_measured(
391        style,
392        items,
393        Constraints::tight(Size::new(
394            finite_non_negative(container_size.width),
395            finite_non_negative(container_size.height),
396        )),
397        measured_sizes,
398    )
399}
400
401#[derive(Debug, Clone, Copy, PartialEq, Default)]
402pub struct Padding {
403    pub left: f32,
404    pub top: f32,
405    pub right: f32,
406    pub bottom: f32,
407}
408
409impl Padding {
410    pub const ZERO: Self = Self::all(0.0);
411
412    pub const fn all(value: f32) -> Self {
413        Self {
414            left: value,
415            top: value,
416            right: value,
417            bottom: value,
418        }
419    }
420
421    pub fn inset(self, size: Size) -> Size {
422        Size::new(
423            (size.width - (self.left + self.right)).max(0.0),
424            (size.height - (self.top + self.bottom)).max(0.0),
425        )
426    }
427
428    pub const fn offset(self) -> Point {
429        Point::new(self.left, self.top)
430    }
431}
432
433#[derive(Debug, Clone, Copy, PartialEq)]
434pub struct Constraints {
435    pub min: Size,
436    pub max: Size,
437}
438
439impl Constraints {
440    pub const UNBOUNDED: Self = Self {
441        min: Size::ZERO,
442        max: Size::new(f32::INFINITY, f32::INFINITY),
443    };
444
445    pub const fn new(min: Size, max: Size) -> Self {
446        Self { min, max }
447    }
448
449    pub const fn tight(size: Size) -> Self {
450        Self {
451            min: size,
452            max: size,
453        }
454    }
455
456    pub fn loosen(self) -> Self {
457        Self {
458            min: Size::ZERO,
459            max: self.max,
460        }
461    }
462
463    pub fn clamp(self, size: Size) -> Size {
464        Size::new(
465            size.width.clamp(self.min.width, self.max.width),
466            size.height.clamp(self.min.height, self.max.height),
467        )
468    }
469}
470
471#[derive(Debug, Clone)]
472pub struct LayoutContext {
473    dpi_info: DpiInfo,
474    text_system: Arc<TextSystem>,
475    font_registry: Arc<FontRegistry>,
476    image_registry: Arc<ImageRegistry>,
477}
478
479impl LayoutContext {
480    pub fn new(
481        dpi_info: DpiInfo,
482        text_system: Arc<TextSystem>,
483        font_registry: Arc<FontRegistry>,
484        image_registry: Arc<ImageRegistry>,
485    ) -> Self {
486        Self {
487            dpi_info,
488            text_system,
489            font_registry,
490            image_registry,
491        }
492    }
493
494    pub const fn dpi(&self) -> DpiInfo {
495        self.dpi_info
496    }
497
498    pub fn measure_text(
499        &self,
500        text: impl Into<String>,
501        style: TextStyle,
502    ) -> sui_core::Result<TextMeasurement> {
503        self.text_system
504            .measure_text(text, style, self.font_registry.as_ref())
505    }
506
507    pub fn measure_document(&self, document: TextDocument) -> sui_core::Result<TextMeasurement> {
508        self.text_system
509            .measure_document(document, self.font_registry.as_ref())
510    }
511
512    pub fn shape_text(
513        &self,
514        text: impl Into<String>,
515        box_size: Size,
516        style: TextStyle,
517    ) -> sui_core::Result<TextLayout> {
518        self.text_system
519            .shape_text(text, box_size, style, self.font_registry.as_ref())
520    }
521
522    pub fn shape_text_persistent(
523        &self,
524        handle: Option<TextLayoutHandle>,
525        text: impl Into<String>,
526        box_size: Size,
527        style: TextStyle,
528    ) -> sui_core::Result<PersistentTextLayout> {
529        self.text_system.shape_text_persistent(
530            handle,
531            text,
532            box_size,
533            style,
534            self.font_registry.as_ref(),
535        )
536    }
537
538    pub fn layout_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
539        self.text_system
540            .layout_document(request, self.font_registry.as_ref())
541    }
542
543    pub fn layout_document_persistent(
544        &self,
545        handle: Option<TextLayoutHandle>,
546        request: TextLayoutRequest,
547    ) -> sui_core::Result<PersistentTextLayout> {
548        self.text_system
549            .layout_document_persistent(handle, request, self.font_registry.as_ref())
550    }
551
552    pub fn image_size(&self, image: ImageHandle) -> Option<Size> {
553        self.image_registry
554            .dimensions(image)
555            .map(|(width, height)| Size::new(width as f32, height as f32))
556    }
557}
558
559impl Default for Constraints {
560    fn default() -> Self {
561        Self::UNBOUNDED
562    }
563}
564
565#[derive(Debug, Clone, Copy)]
566struct ResolvedFlexItem {
567    measured_size: Size,
568    base_size: Size,
569}
570
571#[derive(Debug, Clone, Copy)]
572struct FlexLine {
573    start: usize,
574    end: usize,
575    main: f32,
576    cross: f32,
577}
578
579fn flex_layout_from_measured(
580    style: FlexStyle,
581    items: &[FlexItem],
582    constraints: Constraints,
583    measured_sizes: &[Size],
584) -> FlexLayout {
585    if items.is_empty() {
586        return FlexLayout::empty(constraints.clamp(Size::ZERO));
587    }
588
589    let (_, initial_lines) = resolve_flex_lines(style, items, constraints, measured_sizes);
590    let natural_size = natural_flex_size(style, &initial_lines);
591    let size = constraints.clamp(natural_size);
592    let arrange_constraints = Constraints::tight(size);
593    let (resolved, lines) = resolve_flex_lines(style, items, arrange_constraints, measured_sizes);
594
595    arrange_resolved_flex(style, items, size, &resolved, &lines)
596}
597
598fn resolve_flex_lines(
599    style: FlexStyle,
600    items: &[FlexItem],
601    constraints: Constraints,
602    measured_sizes: &[Size],
603) -> (Vec<ResolvedFlexItem>, Vec<FlexLine>) {
604    let main_gap = finite_non_negative(style.main_gap);
605    let available_main = axis_main(style.axis, constraints.max);
606    let wrap_limit = if style.wrap == FlexWrap::Wrap && available_main.is_finite() {
607        available_main.max(0.0)
608    } else {
609        f32::INFINITY
610    };
611
612    let resolved = items
613        .iter()
614        .enumerate()
615        .map(|(index, item)| {
616            let measured = measured_sizes.get(index).copied().unwrap_or(Size::ZERO);
617            resolve_flex_item(style.axis, style.main_gap, *item, constraints, measured)
618        })
619        .collect::<Vec<_>>();
620
621    let mut lines = Vec::new();
622    let mut start = 0usize;
623    let mut main = 0.0f32;
624    let mut cross = 0.0f32;
625
626    for (index, item) in resolved.iter().enumerate() {
627        let item_main = axis_main(style.axis, item.base_size);
628        let item_cross = axis_cross(style.axis, item.base_size);
629        let spacing_before = if index == start { 0.0 } else { main_gap };
630
631        if style.wrap == FlexWrap::Wrap
632            && index > start
633            && main + spacing_before + item_main > wrap_limit + FLEX_EPSILON
634        {
635            lines.push(FlexLine {
636                start,
637                end: index,
638                main,
639                cross,
640            });
641            start = index;
642            main = item_main;
643            cross = item_cross;
644        } else {
645            main += spacing_before + item_main;
646            cross = cross.max(item_cross);
647        }
648    }
649
650    lines.push(FlexLine {
651        start,
652        end: resolved.len(),
653        main,
654        cross,
655    });
656
657    (resolved, lines)
658}
659
660fn resolve_flex_item(
661    axis: Axis,
662    main_gap: f32,
663    item: FlexItem,
664    constraints: Constraints,
665    measured_size: Size,
666) -> ResolvedFlexItem {
667    let measured_size = clamp_item_size(item, measured_size);
668    let min_main = item_min_main(axis, item);
669    let max_main = item_max_main(axis, item);
670    let min_cross = item_min_cross(axis, item);
671    let max_cross = item_max_cross(axis, item);
672
673    let base_main = basis_main_size(axis, main_gap, item.basis, constraints, measured_size)
674        .clamp(min_main, max_main);
675    let base_cross = axis_cross(axis, measured_size).clamp(min_cross, max_cross);
676
677    ResolvedFlexItem {
678        measured_size,
679        base_size: axis_size(axis, base_main, base_cross),
680    }
681}
682
683fn natural_flex_size(style: FlexStyle, lines: &[FlexLine]) -> Size {
684    let main = lines.iter().map(|line| line.main).fold(0.0f32, f32::max);
685    let cross_gap = finite_non_negative(style.cross_gap);
686    let cross = lines
687        .iter()
688        .enumerate()
689        .map(|(index, line)| line.cross + if index == 0 { 0.0 } else { cross_gap })
690        .sum();
691
692    axis_size(style.axis, main, cross)
693}
694
695fn arrange_resolved_flex(
696    style: FlexStyle,
697    items: &[FlexItem],
698    size: Size,
699    resolved: &[ResolvedFlexItem],
700    lines: &[FlexLine],
701) -> FlexLayout {
702    if lines.is_empty() {
703        return FlexLayout::empty(size);
704    }
705
706    let main_gap = finite_non_negative(style.main_gap);
707    let cross_gap = finite_non_negative(style.cross_gap);
708    let container_main = axis_main(style.axis, size);
709    let container_cross = axis_cross(style.axis, size);
710    let natural_cross = lines
711        .iter()
712        .enumerate()
713        .map(|(index, line)| line.cross + if index == 0 { 0.0 } else { cross_gap })
714        .sum::<f32>();
715    let extra_cross = (container_cross - natural_cross).max(0.0);
716    let line_count = lines.len();
717    let (cross_start, arranged_cross_gap, stretch_cross) =
718        cross_distribution(style.align_content, line_count, cross_gap, extra_cross);
719
720    let mut item_layouts = Vec::with_capacity(resolved.len());
721    let mut line_layouts = Vec::with_capacity(lines.len());
722    let mut cross_cursor = cross_start;
723
724    for (line_index, line) in lines.iter().enumerate() {
725        let count = line.end - line.start;
726        let line_cross = line.cross + stretch_cross;
727        let line_items = &resolved[line.start..line.end];
728        let target_mains = flex_line_main_sizes(
729            style.axis,
730            &items[line.start..line.end],
731            line_items,
732            container_main,
733            main_gap,
734        );
735        let used_main = target_mains.iter().sum::<f32>();
736        let gap_total = main_gap * count.saturating_sub(1) as f32;
737        let leftover_main = (container_main - used_main - gap_total).max(0.0);
738        let (main_start, arranged_main_gap) =
739            main_distribution(style.justify, count, main_gap, leftover_main);
740        let mut main_cursor = main_start;
741
742        for (offset, target_main) in target_mains.into_iter().enumerate() {
743            let index = line.start + offset;
744            let item = items[index];
745            let resolved_item = resolved[index];
746            let alignment = item.align_self.unwrap_or(style.align_items);
747            let item_cross = arranged_cross_size(
748                style.axis,
749                item,
750                alignment,
751                resolved_item.base_size,
752                line_cross,
753            );
754            let cross_offset = aligned_offset(alignment, line_cross - item_cross);
755            let rect = axis_rect(
756                style.axis,
757                main_cursor,
758                cross_cursor + cross_offset,
759                target_main,
760                item_cross,
761            );
762
763            item_layouts.push(FlexItemLayout {
764                rect,
765                measured_size: resolved_item.measured_size,
766                line: line_index,
767            });
768            main_cursor += target_main + arranged_main_gap;
769        }
770
771        line_layouts.push(FlexLineLayout {
772            item_start: line.start,
773            item_end: line.end,
774            rect: axis_rect(style.axis, 0.0, cross_cursor, container_main, line_cross),
775        });
776        cross_cursor += line_cross + arranged_cross_gap;
777    }
778
779    FlexLayout {
780        size,
781        items: item_layouts,
782        lines: line_layouts,
783    }
784}
785
786fn flex_line_main_sizes(
787    axis: Axis,
788    items: &[FlexItem],
789    line_items: &[ResolvedFlexItem],
790    container_main: f32,
791    main_gap: f32,
792) -> Vec<f32> {
793    let count = line_items.len();
794    let gap_total = finite_non_negative(main_gap) * count.saturating_sub(1) as f32;
795    let available_for_items = if container_main.is_finite() {
796        (container_main - gap_total).max(0.0)
797    } else {
798        line_items
799            .iter()
800            .map(|item| axis_main(axis, item.base_size))
801            .sum()
802    };
803    let base_sum = line_items
804        .iter()
805        .map(|item| axis_main(axis, item.base_size))
806        .sum::<f32>();
807    let free = available_for_items - base_sum;
808
809    if free > 0.0 {
810        if items
811            .iter()
812            .any(|item| finite_non_negative(item.grow) > 0.0)
813        {
814            return distribute_grow_space(axis, items, line_items, available_for_items);
815        }
816    } else if free < 0.0 {
817        let deficit = -free;
818        let total_shrink = items
819            .iter()
820            .zip(line_items.iter())
821            .map(|(item, resolved)| {
822                finite_non_negative(item.shrink) * axis_main(axis, resolved.base_size)
823            })
824            .sum::<f32>();
825        if total_shrink > 0.0 {
826            return items
827                .iter()
828                .zip(line_items.iter())
829                .map(|(item, resolved)| {
830                    let base = axis_main(axis, resolved.base_size);
831                    let weight = finite_non_negative(item.shrink) * base;
832                    let min = item_min_main(axis, *item);
833                    (base - (deficit * weight / total_shrink)).max(min)
834                })
835                .collect();
836        }
837    }
838
839    line_items
840        .iter()
841        .map(|item| axis_main(axis, item.base_size))
842        .collect()
843}
844
845fn distribute_grow_space(
846    axis: Axis,
847    items: &[FlexItem],
848    line_items: &[ResolvedFlexItem],
849    available_for_items: f32,
850) -> Vec<f32> {
851    let mut sizes = line_items
852        .iter()
853        .map(|item| axis_main(axis, item.base_size))
854        .collect::<Vec<_>>();
855    let mut frozen = vec![false; sizes.len()];
856
857    loop {
858        let remaining = available_for_items - sizes.iter().sum::<f32>();
859        if remaining <= FLEX_EPSILON {
860            break;
861        }
862
863        let total_grow = items
864            .iter()
865            .zip(frozen.iter())
866            .filter(|(_, frozen)| !**frozen)
867            .map(|(item, _)| finite_non_negative(item.grow))
868            .sum::<f32>();
869        if total_grow <= FLEX_EPSILON {
870            break;
871        }
872
873        let mut clamped = false;
874        for index in 0..sizes.len() {
875            if frozen[index] {
876                continue;
877            }
878
879            let grow = finite_non_negative(items[index].grow);
880            if grow <= 0.0 {
881                frozen[index] = true;
882                continue;
883            }
884
885            let proposed = sizes[index] + (remaining * grow / total_grow);
886            let max = item_max_main(axis, items[index]);
887            if proposed >= max - FLEX_EPSILON {
888                sizes[index] = max;
889                frozen[index] = true;
890                clamped = true;
891            } else {
892                sizes[index] = proposed;
893            }
894        }
895
896        if !clamped {
897            break;
898        }
899    }
900
901    sizes
902}
903
904fn flex_child_constraints(
905    style: FlexStyle,
906    item: FlexItem,
907    constraints: Constraints,
908) -> Constraints {
909    let min_main = item_min_main(style.axis, item);
910    let max_main = match item.basis {
911        FlexBasis::Auto => axis_main(style.axis, constraints.max),
912        FlexBasis::Points(points) => finite_non_negative(points),
913        FlexBasis::Fraction(fraction) => flex_fraction_constraint_main_size(
914            style.axis,
915            constraints,
916            finite_non_negative(fraction),
917        ),
918        FlexBasis::GapAwareFraction(fraction) => flex_gap_aware_fraction_constraint_main_size(
919            style.axis,
920            constraints,
921            style.main_gap,
922            finite_non_negative(fraction),
923        ),
924    }
925    .min(item_max_main(style.axis, item))
926    .max(min_main);
927    let max_cross = axis_cross(style.axis, constraints.max)
928        .min(item_max_cross(style.axis, item))
929        .max(0.0);
930    let alignment = item.align_self.unwrap_or(style.align_items);
931    let min_cross = if alignment == Alignment::Stretch && max_cross.is_finite() {
932        max_cross
933    } else {
934        item_min_cross(style.axis, item).min(max_cross)
935    };
936
937    axis_constraints(style.axis, min_main, max_main, min_cross, max_cross)
938}
939
940fn resolved_flex_child_constraints(
941    style: FlexStyle,
942    item: FlexItem,
943    constraints: Constraints,
944    resolved_main: f32,
945) -> Constraints {
946    let intrinsic = flex_child_constraints(style, item, constraints);
947    let min_cross = axis_cross(style.axis, intrinsic.min);
948    let max_cross = axis_cross(style.axis, intrinsic.max);
949    let resolved_main = finite_non_negative(resolved_main).clamp(
950        item_min_main(style.axis, item),
951        item_max_main(style.axis, item),
952    );
953
954    axis_constraints(
955        style.axis,
956        resolved_main,
957        resolved_main,
958        min_cross,
959        max_cross,
960    )
961}
962
963fn arranged_cross_size(
964    axis: Axis,
965    item: FlexItem,
966    alignment: Alignment,
967    base_size: Size,
968    line_cross: f32,
969) -> f32 {
970    let min = item_min_cross(axis, item);
971    let max = item_max_cross(axis, item);
972    if alignment == Alignment::Stretch {
973        line_cross.clamp(min, max)
974    } else {
975        axis_cross(axis, base_size).min(line_cross).clamp(min, max)
976    }
977}
978
979fn basis_main_size(
980    axis: Axis,
981    main_gap: f32,
982    basis: FlexBasis,
983    constraints: Constraints,
984    measured_size: Size,
985) -> f32 {
986    match basis {
987        FlexBasis::Auto => axis_main(axis, measured_size),
988        FlexBasis::Points(points) => finite_non_negative(points),
989        FlexBasis::Fraction(fraction) => {
990            let available = axis_main(axis, constraints.max);
991            if available.is_finite() {
992                available.max(0.0) * finite_non_negative(fraction)
993            } else {
994                axis_main(axis, measured_size)
995            }
996        }
997        FlexBasis::GapAwareFraction(fraction) => {
998            let available = axis_main(axis, constraints.max);
999            if available.is_finite() {
1000                gap_aware_fraction_basis(
1001                    available.max(0.0),
1002                    main_gap,
1003                    finite_non_negative(fraction),
1004                )
1005            } else {
1006                axis_main(axis, measured_size)
1007            }
1008        }
1009    }
1010}
1011
1012fn flex_fraction_constraint_main_size(axis: Axis, constraints: Constraints, fraction: f32) -> f32 {
1013    let available = axis_main(axis, constraints.max);
1014    if available.is_finite() {
1015        available.max(0.0) * fraction
1016    } else {
1017        available
1018    }
1019}
1020
1021fn flex_gap_aware_fraction_constraint_main_size(
1022    axis: Axis,
1023    constraints: Constraints,
1024    main_gap: f32,
1025    fraction: f32,
1026) -> f32 {
1027    let available = axis_main(axis, constraints.max);
1028    if available.is_finite() {
1029        gap_aware_fraction_basis(available.max(0.0), main_gap, fraction)
1030    } else {
1031        available
1032    }
1033}
1034
1035fn gap_aware_fraction_basis(available: f32, gap: f32, fraction: f32) -> f32 {
1036    let gap_share = (1.0 - fraction).max(0.0);
1037    (available * fraction - finite_non_negative(gap) * gap_share).max(0.0)
1038}
1039
1040fn cross_distribution(
1041    alignment: FlexAlignContent,
1042    count: usize,
1043    gap: f32,
1044    extra: f32,
1045) -> (f32, f32, f32) {
1046    if count == 0 || extra <= 0.0 {
1047        return (0.0, gap, 0.0);
1048    }
1049
1050    match alignment {
1051        FlexAlignContent::Start => (0.0, gap, 0.0),
1052        FlexAlignContent::Center => (extra * 0.5, gap, 0.0),
1053        FlexAlignContent::End => (extra, gap, 0.0),
1054        FlexAlignContent::Stretch => (0.0, gap, extra / count as f32),
1055        FlexAlignContent::SpaceBetween if count > 1 => {
1056            (0.0, gap + (extra / (count - 1) as f32), 0.0)
1057        }
1058        FlexAlignContent::SpaceAround => {
1059            let distributed = extra / count as f32;
1060            (distributed * 0.5, gap + distributed, 0.0)
1061        }
1062        FlexAlignContent::SpaceEvenly => {
1063            let distributed = extra / (count + 1) as f32;
1064            (distributed, gap + distributed, 0.0)
1065        }
1066        FlexAlignContent::SpaceBetween => (0.0, gap, 0.0),
1067    }
1068}
1069
1070fn main_distribution(justify: FlexJustify, count: usize, gap: f32, leftover: f32) -> (f32, f32) {
1071    if count == 0 || leftover <= 0.0 {
1072        return (0.0, gap);
1073    }
1074
1075    match justify {
1076        FlexJustify::Start => (0.0, gap),
1077        FlexJustify::Center => (leftover * 0.5, gap),
1078        FlexJustify::End => (leftover, gap),
1079        FlexJustify::SpaceBetween if count > 1 => (0.0, gap + (leftover / (count - 1) as f32)),
1080        FlexJustify::SpaceAround => {
1081            let distributed = leftover / count as f32;
1082            (distributed * 0.5, gap + distributed)
1083        }
1084        FlexJustify::SpaceEvenly => {
1085            let distributed = leftover / (count + 1) as f32;
1086            (distributed, gap + distributed)
1087        }
1088        FlexJustify::SpaceBetween => (0.0, gap),
1089    }
1090}
1091
1092fn clamp_item_size(item: FlexItem, size: Size) -> Size {
1093    Size::new(
1094        size.width.clamp(
1095            finite_non_negative(item.min_size.width),
1096            item_max_width(item),
1097        ),
1098        size.height.clamp(
1099            finite_non_negative(item.min_size.height),
1100            item_max_height(item),
1101        ),
1102    )
1103}
1104
1105fn axis_constraints(
1106    axis: Axis,
1107    min_main: f32,
1108    max_main: f32,
1109    min_cross: f32,
1110    max_cross: f32,
1111) -> Constraints {
1112    match axis {
1113        Axis::Horizontal => Constraints::new(
1114            Size::new(min_main, min_cross),
1115            Size::new(max_main, max_cross),
1116        ),
1117        Axis::Vertical => Constraints::new(
1118            Size::new(min_cross, min_main),
1119            Size::new(max_cross, max_main),
1120        ),
1121    }
1122}
1123
1124fn axis_main(axis: Axis, size: Size) -> f32 {
1125    match axis {
1126        Axis::Horizontal => size.width,
1127        Axis::Vertical => size.height,
1128    }
1129}
1130
1131fn axis_cross(axis: Axis, size: Size) -> f32 {
1132    match axis {
1133        Axis::Horizontal => size.height,
1134        Axis::Vertical => size.width,
1135    }
1136}
1137
1138fn axis_size(axis: Axis, main: f32, cross: f32) -> Size {
1139    match axis {
1140        Axis::Horizontal => Size::new(main, cross),
1141        Axis::Vertical => Size::new(cross, main),
1142    }
1143}
1144
1145fn axis_rect(axis: Axis, main: f32, cross: f32, main_size: f32, cross_size: f32) -> Rect {
1146    match axis {
1147        Axis::Horizontal => Rect::new(main, cross, main_size, cross_size),
1148        Axis::Vertical => Rect::new(cross, main, cross_size, main_size),
1149    }
1150}
1151
1152fn aligned_offset(alignment: Alignment, remaining: f32) -> f32 {
1153    let remaining = remaining.max(0.0);
1154    match alignment {
1155        Alignment::Start | Alignment::Stretch => 0.0,
1156        Alignment::Center => remaining * 0.5,
1157        Alignment::End => remaining,
1158    }
1159}
1160
1161fn item_min_main(axis: Axis, item: FlexItem) -> f32 {
1162    axis_main(axis, item.min_size).max(0.0)
1163}
1164
1165fn item_max_main(axis: Axis, item: FlexItem) -> f32 {
1166    axis_main(axis, Size::new(item_max_width(item), item_max_height(item)))
1167        .max(item_min_main(axis, item))
1168}
1169
1170fn item_min_cross(axis: Axis, item: FlexItem) -> f32 {
1171    axis_cross(axis, item.min_size).max(0.0)
1172}
1173
1174fn item_max_cross(axis: Axis, item: FlexItem) -> f32 {
1175    axis_cross(axis, Size::new(item_max_width(item), item_max_height(item)))
1176        .max(item_min_cross(axis, item))
1177}
1178
1179fn item_max_width(item: FlexItem) -> f32 {
1180    non_negative_or_infinity(item.max_size.width).max(finite_non_negative(item.min_size.width))
1181}
1182
1183fn item_max_height(item: FlexItem) -> f32 {
1184    non_negative_or_infinity(item.max_size.height).max(finite_non_negative(item.min_size.height))
1185}
1186
1187fn finite_non_negative(value: f32) -> f32 {
1188    if value.is_finite() {
1189        value.max(0.0)
1190    } else {
1191        0.0
1192    }
1193}
1194
1195fn non_negative_or_infinity(value: f32) -> f32 {
1196    if value.is_nan() || value < 0.0 {
1197        0.0
1198    } else {
1199        value
1200    }
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use std::sync::Arc;
1206
1207    use super::{
1208        Alignment, Constraints, FlexAlignContent, FlexItem, FlexJustify, FlexStyle, FlexWrap,
1209        LayoutContext, arrange_flex, flex_layout,
1210    };
1211    use sui_core::{Color, DpiInfo, ImageHandle, Rect, Size};
1212    use sui_scene::{ImageRegistry, RegisteredImage};
1213    use sui_text::{FontRegistry, TextStyle, TextSystem};
1214
1215    fn assert_rect_approx_eq(actual: Rect, expected: Rect) {
1216        assert!((actual.x() - expected.x()).abs() < 0.001);
1217        assert!((actual.y() - expected.y()).abs() < 0.001);
1218        assert!((actual.width() - expected.width()).abs() < 0.001);
1219        assert!((actual.height() - expected.height()).abs() < 0.001);
1220    }
1221
1222    #[test]
1223    fn layout_context_measures_text_and_images_without_runtime_widget_state() {
1224        let mut images = ImageRegistry::new();
1225        images.insert(
1226            ImageHandle::new(7),
1227            RegisteredImage::from_rgba8(4, 2, vec![255; 4 * 2 * 4]).unwrap(),
1228        );
1229
1230        let layout = LayoutContext::new(
1231            DpiInfo::new(
1232                2.0,
1233                Some(192.0),
1234                Size::new(320.0, 180.0),
1235                Size::new(640.0, 360.0),
1236            ),
1237            Arc::new(TextSystem::new()),
1238            Arc::new(FontRegistry::new()),
1239            Arc::new(images),
1240        );
1241
1242        let measurement = layout
1243            .measure_text("hello", TextStyle::new(Color::WHITE))
1244            .unwrap();
1245
1246        assert!(measurement.width > 0.0);
1247        assert_eq!(layout.dpi().effective_dpi(), 192.0);
1248        assert_eq!(
1249            layout.image_size(ImageHandle::new(7)),
1250            Some(Size::new(4.0, 2.0))
1251        );
1252    }
1253
1254    #[test]
1255    fn flex_layout_distributes_grow_space() {
1256        let items = [
1257            FlexItem::new(),
1258            FlexItem::new().grow(1.0),
1259            FlexItem::new().grow(2.0),
1260        ];
1261        let measured = [
1262            Size::new(20.0, 10.0),
1263            Size::new(10.0, 10.0),
1264            Size::new(10.0, 10.0),
1265        ];
1266        let layout = flex_layout(
1267            FlexStyle::horizontal(),
1268            &items,
1269            Constraints::tight(Size::new(100.0, 20.0)),
1270            |index, _| measured[index],
1271        );
1272
1273        assert_eq!(layout.size, Size::new(100.0, 20.0));
1274        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 10.0));
1275        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 30.0, 10.0));
1276        assert_rect_approx_eq(layout.items[2].rect, Rect::new(50.0, 0.0, 50.0, 10.0));
1277    }
1278
1279    #[test]
1280    fn flex_item_fill_creates_equal_columns() {
1281        let items = [FlexItem::fill(), FlexItem::fill()];
1282        let layout = flex_layout(
1283            FlexStyle::horizontal(),
1284            &items,
1285            Constraints::tight(Size::new(100.0, 12.0)),
1286            |_, _| Size::new(20.0, 10.0),
1287        );
1288
1289        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 50.0, 10.0));
1290        assert_rect_approx_eq(layout.items[1].rect, Rect::new(50.0, 0.0, 50.0, 10.0));
1291    }
1292
1293    #[test]
1294    fn flex_layout_remeasures_grown_children_at_their_resolved_main_size() {
1295        let items = [FlexItem::flex(1.0)];
1296        let mut seen = Vec::new();
1297        let layout = flex_layout(
1298            FlexStyle::horizontal(),
1299            &items,
1300            Constraints::new(Size::new(240.0, 0.0), Size::new(240.0, 200.0)),
1301            |_, constraints| {
1302                seen.push(constraints);
1303                if constraints.max.width <= 1.0 {
1304                    Size::new(constraints.max.width, 160.0)
1305                } else {
1306                    Size::new(constraints.max.width, 20.0)
1307                }
1308            },
1309        );
1310
1311        assert_eq!(seen.len(), 2);
1312        assert_eq!(seen[0].max.width, 0.0);
1313        assert_eq!(seen[1].min.width, 240.0);
1314        assert_eq!(seen[1].max.width, 240.0);
1315        assert_eq!(layout.size, Size::new(240.0, 20.0));
1316        assert_eq!(layout.items[0].measured_size, Size::new(240.0, 20.0));
1317        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 240.0, 20.0));
1318    }
1319
1320    #[test]
1321    fn flex_layout_supports_fraction_basis() {
1322        let items = [
1323            FlexItem::new().basis_fraction(0.25),
1324            FlexItem::new().basis_fraction(0.75),
1325        ];
1326        let layout = flex_layout(
1327            FlexStyle::horizontal(),
1328            &items,
1329            Constraints::tight(Size::new(200.0, 12.0)),
1330            |_, _| Size::new(10.0, 10.0),
1331        );
1332
1333        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 50.0, 10.0));
1334        assert_rect_approx_eq(layout.items[1].rect, Rect::new(50.0, 0.0, 150.0, 10.0));
1335    }
1336
1337    #[test]
1338    fn flex_layout_supports_gap_aware_fraction_basis() {
1339        let items = [
1340            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1341            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1342            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1343        ];
1344        let layout = flex_layout(
1345            FlexStyle::horizontal().gap(10.0),
1346            &items,
1347            Constraints::tight(Size::new(320.0, 12.0)),
1348            |_, _| Size::new(10.0, 10.0),
1349        );
1350
1351        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 100.0, 10.0));
1352        assert_rect_approx_eq(layout.items[1].rect, Rect::new(110.0, 0.0, 100.0, 10.0));
1353        assert_rect_approx_eq(layout.items[2].rect, Rect::new(220.0, 0.0, 100.0, 10.0));
1354    }
1355
1356    #[test]
1357    fn flex_layout_wraps_gap_aware_fraction_lines_after_full_rows() {
1358        let items = [
1359            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1360            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1361            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1362            FlexItem::new().basis_gap_aware_fraction(0.5),
1363            FlexItem::new().basis_gap_aware_fraction(0.5),
1364        ];
1365        let layout = flex_layout(
1366            FlexStyle::horizontal().wrap(FlexWrap::Wrap).gap(10.0),
1367            &items,
1368            Constraints::tight(Size::new(320.0, 100.0)),
1369            |_, _| Size::new(10.0, 10.0),
1370        );
1371
1372        assert_eq!(layout.lines.len(), 2);
1373        assert_eq!(layout.items[0].line, 0);
1374        assert_eq!(layout.items[2].line, 0);
1375        assert_eq!(layout.items[3].line, 1);
1376        assert_eq!(layout.items[4].line, 1);
1377        assert_rect_approx_eq(layout.items[3].rect, Rect::new(0.0, 20.0, 155.0, 10.0));
1378        assert_rect_approx_eq(layout.items[4].rect, Rect::new(165.0, 20.0, 155.0, 10.0));
1379    }
1380
1381    #[test]
1382    fn flex_layout_redistributes_grow_space_after_max_clamp() {
1383        let items = [FlexItem::fill().max_width(20.0), FlexItem::fill()];
1384        let layout = flex_layout(
1385            FlexStyle::horizontal(),
1386            &items,
1387            Constraints::tight(Size::new(100.0, 12.0)),
1388            |_, _| Size::new(0.0, 10.0),
1389        );
1390
1391        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 10.0));
1392        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 80.0, 10.0));
1393    }
1394
1395    #[test]
1396    fn flex_layout_shrinks_items_when_space_is_tight() {
1397        let items = [
1398            FlexItem::new().min_width(20.0),
1399            FlexItem::new().min_width(20.0),
1400        ];
1401        let layout = flex_layout(
1402            FlexStyle::horizontal(),
1403            &items,
1404            Constraints::tight(Size::new(100.0, 12.0)),
1405            |index, _| {
1406                if index == 0 {
1407                    Size::new(80.0, 10.0)
1408                } else {
1409                    Size::new(40.0, 10.0)
1410                }
1411            },
1412        );
1413
1414        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 66.666664, 10.0));
1415        assert_rect_approx_eq(
1416            layout.items[1].rect,
1417            Rect::new(66.666664, 0.0, 33.333332, 10.0),
1418        );
1419    }
1420
1421    #[test]
1422    fn flex_layout_wraps_lines_with_cross_gap() {
1423        let items = [FlexItem::new(), FlexItem::new(), FlexItem::new()];
1424        let measured = [
1425            Size::new(30.0, 10.0),
1426            Size::new(30.0, 10.0),
1427            Size::new(30.0, 10.0),
1428        ];
1429        let layout = flex_layout(
1430            FlexStyle::horizontal().wrap(FlexWrap::Wrap).gap(5.0),
1431            &items,
1432            Constraints::tight(Size::new(50.0, 40.0)),
1433            |index, _| measured[index],
1434        );
1435
1436        assert_eq!(layout.lines.len(), 3);
1437        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 30.0, 10.0));
1438        assert_rect_approx_eq(layout.items[1].rect, Rect::new(0.0, 15.0, 30.0, 10.0));
1439        assert_rect_approx_eq(layout.items[2].rect, Rect::new(0.0, 30.0, 30.0, 10.0));
1440    }
1441
1442    #[test]
1443    fn flex_layout_justifies_remaining_space_between_items() {
1444        let items = [FlexItem::new(), FlexItem::new(), FlexItem::new()];
1445        let layout = flex_layout(
1446            FlexStyle::horizontal().justify(FlexJustify::SpaceBetween),
1447            &items,
1448            Constraints::tight(Size::new(100.0, 10.0)),
1449            |_, _| Size::new(10.0, 10.0),
1450        );
1451
1452        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 10.0, 10.0));
1453        assert_rect_approx_eq(layout.items[1].rect, Rect::new(45.0, 0.0, 10.0, 10.0));
1454        assert_rect_approx_eq(layout.items[2].rect, Rect::new(90.0, 0.0, 10.0, 10.0));
1455    }
1456
1457    #[test]
1458    fn flex_layout_stretches_items_and_lines_on_cross_axis() {
1459        let items = [FlexItem::new(), FlexItem::new()];
1460        let layout = flex_layout(
1461            FlexStyle::horizontal()
1462                .align_items(Alignment::Stretch)
1463                .align_content(FlexAlignContent::Stretch),
1464            &items,
1465            Constraints::tight(Size::new(60.0, 20.0)),
1466            |_, _| Size::new(20.0, 8.0),
1467        );
1468
1469        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 20.0));
1470        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 20.0, 20.0));
1471    }
1472
1473    #[test]
1474    fn arrange_flex_uses_existing_measured_sizes() {
1475        let items = [FlexItem::new(), FlexItem::new().grow(1.0)];
1476        let layout = arrange_flex(
1477            FlexStyle::horizontal(),
1478            &items,
1479            Size::new(80.0, 12.0),
1480            &[Size::new(20.0, 8.0), Size::new(10.0, 8.0)],
1481        );
1482
1483        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 8.0));
1484        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 60.0, 8.0));
1485    }
1486}