waterui-layout 0.5.1

Layout components for WaterUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Horizontal stack layout.

use alloc::{vec, vec::Vec};
use nami::{Computed, Signal, SignalExt, collection::Collection};
use waterui_core::{
    AnyView, IntoSignalF32, View, env::with, id::Identifiable, layout::LayoutInvalidationCallback,
    view::TupleViews, views::ForEach,
};

use crate::{
    Layout, LazyContainer, PlacedSubview, Point, ProposalSize, Rect, Size, StretchAxis, SubView,
    SubviewPlacement,
    container::FixedContainer,
    stack::{
        Axis, VerticalAlignment,
        distribute::{
            ChildMeasurement, LineAnchor, container_line, cross_envelope, measure_stack,
            place_cross_extent, stack_spacing,
        },
        stack_stretch_axis,
    },
};

/// A view that arranges its children in a horizontal line.
///
/// Use an `HStack` to arrange views side-by-side. The stack sizes itself to fit
/// its contents, distributing available space among its children.
///
/// ```rust
/// # use waterui::prelude::*;
/// # fn greeting() -> impl View {
/// hstack((
///     text("Hello"),
///     text("World"),
/// ))
/// # }
/// ```
///
/// You can customize the spacing between children and their vertical alignment:
///
/// ```rust
/// # use waterui::prelude::*;
/// # fn spaced() -> impl View {
/// HStack::new(VerticalAlignment::Top, 20.0, (
///     text("First"),
///     text("Second"),
/// ))
/// # }
/// ```
///
/// Use [`spacer()`](crate::spacer()) to push content to the sides:
///
/// ```rust
/// # use waterui::prelude::*;
/// # fn toolbar() -> impl View {
/// hstack((
///     text("Leading"),
///     spacer(),
///     text("Trailing"),
/// ))
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct HStack<C> {
    layout: HStackLayout,
    contents: C,
}

/// Layout engine shared by the public [`HStack`] view.
#[derive(Debug, Clone)]
pub struct HStackLayout {
    /// The vertical alignment of children within the stack.
    pub alignment: VerticalAlignment,
    /// The spacing between children in the stack.
    pub spacing: Computed<f32>,
}

impl Default for HStackLayout {
    fn default() -> Self {
        Self {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(10.0),
        }
    }
}

/// The tallest child above and below the alignment guide.
///
/// Every child that reports a height counts, the ones that fill the cross axis
/// included. Filling means "at least what I measure, and more if you have it",
/// not "nothing": leaving a filler out of this makes a row of nothing-but-
/// fillers report zero height, and its parent then hands it zero height to
/// fill. A child that answers an unbounded height is answering "as much as you
/// have" rather than naming a size, so it sets no floor here — the fill pass in
/// [`Layout::place`] is what gives it the row's height.
/// The vertical envelope of the row's children lined up on `alignment`.
fn hstack_intrinsic_cross_metrics(
    measurements: &[ChildMeasurement],
    alignment: VerticalAlignment,
) -> (f32, f32) {
    cross_envelope(measurements.iter().map(|measurement| {
        (
            measurement.size().height,
            measurement.vertical_guide(alignment),
        )
    }))
}

impl Layout for HStackLayout {
    /// An `HStack` claims nothing of its own — a row of labels is content-sized,
    /// like `SwiftUI`'s, and a parent placing an undersized row centers it per
    /// its alignment. What it does claim is whatever its children claim: filling
    /// comes from children that ask for it (`Spacer`, greedy frames, `Color`),
    /// and the ask has to survive the trip up through every container between
    /// that child and whoever owns the space.
    fn stretch_axis(&self, children: &[StretchAxis]) -> StretchAxis {
        stack_stretch_axis(Axis::Horizontal, children)
    }

    fn size_that_fits(&self, proposal: ProposalSize, children: &[&dyn SubView]) -> Size {
        if children.is_empty() {
            return Size::zero();
        }

        let spacing = self.spacing.get();
        let measurements = measure_stack(Axis::Horizontal, proposal, spacing, children);
        let width = measurements.iter().map(|m| m.size().width).sum::<f32>()
            + stack_spacing(spacing, children.len());
        let (above, below) = hstack_intrinsic_cross_metrics(&measurements, self.alignment);
        let height = if measurements.iter().any(|m| m.size().height.is_infinite()) {
            f32::INFINITY
        } else {
            above + below
        };
        Size::new(width, height)
    }

    fn place(
        &self,
        bounds: Rect,
        _proposal: ProposalSize,
        children: &[&dyn SubView],
    ) -> Vec<SubviewPlacement> {
        if children.is_empty() {
            return vec![];
        }

        let spacing = self.spacing.get();
        // Placement is a fresh negotiation against the bounds the row was
        // placed in: every child is allocated from the row's resolved width
        // and proposed the row's resolved height, so what a child lays out
        // under is the extent it actually has, never the offer the row was
        // measured with.
        let placement = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let measurements = measure_stack(Axis::Horizontal, placement, spacing, children);

        let (above, below) = hstack_intrinsic_cross_metrics(&measurements, self.alignment);
        let guide_line = bounds.y()
            + container_line(
                bounds.height(),
                LineAnchor::vertical(self.alignment),
                above,
                below,
            );

        // Place children
        let mut placements = Vec::with_capacity(children.len());
        let mut current_x = bounds.x();

        for (i, measurement) in measurements.iter().enumerate() {
            if i > 0 {
                current_x += spacing;
            }

            let child_height = place_cross_extent(
                measurement.size().height,
                bounds.height(),
                measurement.stretches_cross_axis(),
            );

            let child_width = measurement.size().width;

            let mut adjusted_dimensions = measurement.dimensions.clone();
            adjusted_dimensions.size = Size::new(child_width, child_height);

            // A child that fills the cross axis spans the bounds; every other
            // child sits with its guide on the row's line, wherever that
            // guide lies.
            let y = if measurement.stretches_cross_axis() {
                bounds.y()
            } else {
                guide_line - adjusted_dimensions.vertical(self.alignment)
            };

            let rect = Rect::new(
                Point::new(current_x, y),
                Size::new(child_width, child_height),
            );
            placements.push(SubviewPlacement::new(rect, measurement.proposal));

            current_x += child_width;
        }

        placements
    }

    fn explicit_vertical(
        &self,
        alignment: VerticalAlignment,
        _bounds: Rect,
        children: &[PlacedSubview<'_>],
    ) -> Option<f32> {
        if alignment == VerticalAlignment::LastBaseline {
            return children
                .iter()
                .filter_map(|child| child.explicit_vertical(alignment))
                .max_by(f32::total_cmp);
        }

        if alignment == VerticalAlignment::FirstBaseline || alignment == self.alignment {
            return children
                .iter()
                .filter_map(|child| child.explicit_vertical(alignment))
                .min_by(f32::total_cmp);
        }

        None
    }

    fn watch_invalidation(
        &self,
        invalidate: LayoutInvalidationCallback,
    ) -> Vec<nami::watcher::BoxWatcherGuard> {
        vec![self.spacing.watch(move |_| invalidate())]
    }
}

impl<C: TupleViews> HStack<(C,)> {
    /// Creates a horizontal stack with the provided alignment, spacing, and
    /// children.
    pub fn new(alignment: VerticalAlignment, spacing: f32, contents: C) -> Self {
        Self {
            layout: HStackLayout {
                alignment,
                spacing: Computed::constant(spacing),
            },
            contents: (contents,),
        }
    }
}

impl<C> HStack<C> {
    /// Sets the vertical alignment for children in the stack — a
    /// [`VerticalAlignment`] or one of the tokens [`Top`], [`Center`],
    /// [`Bottom`], [`FirstBaseline`], [`LastBaseline`].
    ///
    /// [`Top`]: crate::Top
    /// [`Center`]: crate::Center
    /// [`Bottom`]: crate::Bottom
    /// [`FirstBaseline`]: crate::FirstBaseline
    /// [`LastBaseline`]: crate::LastBaseline
    #[must_use]
    pub fn alignment(mut self, alignment: impl Into<VerticalAlignment>) -> Self {
        self.layout.alignment = alignment.into();
        self
    }

    crate::alignment::vertical_alignment_methods!();

    /// Sets the spacing between children in the stack.
    ///
    /// Accepts any numeric literal or signal of f32. Signal changes invalidate
    /// only this stack's native layout.
    #[must_use]
    pub fn spacing(mut self, spacing: impl IntoSignalF32 + 'static) -> Self {
        self.layout.spacing = spacing.into_signal_f32().computed();
        self
    }
}

crate::stack::impl_stack_for_each!(HStack, HStackLayout);

impl<V> FromIterator<V> for HStack<(Vec<AnyView>,)>
where
    V: View,
{
    fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
        let contents = iter.into_iter().map(AnyView::new).collect();
        Self::new(VerticalAlignment::default(), 10.0, contents)
    }
}

/// Convenience constructor that centres children and uses the default spacing.
pub fn hstack<C: TupleViews>(contents: C) -> HStack<(C,)> {
    HStack::new(VerticalAlignment::Center, 10.0, contents)
}

impl<C, F, V> View for HStack<ForEach<C, F, V>>
where
    C: Collection + Clone,
    C::Item: Identifiable,
    F: 'static + Fn(C::Item) -> V,
    V: View,
{
    fn body(self, _env: &waterui_core::Environment) -> impl View {
        // Inject the horizontal axis into the container
        with(
            LazyContainer::new(self.layout, self.contents),
            Axis::Horizontal,
        )
    }

    /// Resolves to `LazyContainer`, which cannot enumerate children without
    /// materializing them and answers its layout's axis over an empty child
    /// set — matching `LazyContainer::stretch_axis`.
    fn stretch_axis(&self) -> StretchAxis {
        self.layout.stretch_axis(&[])
    }
}

impl<C: TupleViews + 'static> View for HStack<(C,)> {
    fn body(self, _env: &waterui_core::Environment) -> impl View {
        // Inject the horizontal axis into the container
        with(
            FixedContainer::new(self.layout, self.contents.0),
            Axis::Horizontal,
        )
    }

    /// Resolves to `FixedContainer` over the same layout and children;
    /// reports what that container would — matching `FixedContainer`'s
    /// `View::stretch_axis`.
    fn stretch_axis(&self) -> StretchAxis {
        self.layout.stretch_axis(&self.contents.0.stretch_axes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ViewDimensions;
    use crate::tests::CompressibleView;

    struct MockSubView {
        size: Size,
        stretch_axis: StretchAxis,
    }

    impl SubView for MockSubView {
        fn measure(&self, _proposal: ProposalSize) -> ViewDimensions {
            ViewDimensions::new(self.size)
        }
        fn stretch_axis(&self) -> StretchAxis {
            self.stretch_axis
        }
        fn priority(&self) -> i32 {
            0
        }
    }

    struct ResponsiveSubView {
        intrinsic: Size,
        wrapped_height: f32,
        wrap_at_or_below: f32,
        stretch_axis: StretchAxis,
    }

    impl SubView for ResponsiveSubView {
        fn measure(&self, proposal: ProposalSize) -> ViewDimensions {
            ViewDimensions::new(match proposal.width {
                Some(width) if width <= self.wrap_at_or_below => {
                    Size::new(width, self.wrapped_height)
                }
                Some(width) => Size::new(width, self.intrinsic.height),
                None => self.intrinsic,
            })
        }

        fn stretch_axis(&self) -> StretchAxis {
            self.stretch_axis
        }

        fn priority(&self) -> i32 {
            0
        }
    }

    #[test]
    fn test_hstack_size_two_children() {
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(10.0),
        };

        let mut child1 = MockSubView {
            size: Size::new(50.0, 30.0),
            stretch_axis: StretchAxis::None,
        };
        let mut child2 = MockSubView {
            size: Size::new(60.0, 40.0),
            stretch_axis: StretchAxis::None,
        };

        let children: Vec<&dyn SubView> = vec![&mut child1, &mut child2];

        let size = layout.size_that_fits(ProposalSize::UNSPECIFIED, &children);

        assert!((size.width - 120.0).abs() < f32::EPSILON); // 50 + 10 + 60
        assert!((size.height - 40.0).abs() < f32::EPSILON); // max height
    }

    #[test]
    fn test_hstack_with_spacer() {
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(0.0),
        };

        let mut child1 = MockSubView {
            size: Size::new(30.0, 40.0),
            stretch_axis: StretchAxis::None,
        };
        let mut spacer = MockSubView {
            size: Size::zero(),
            stretch_axis: StretchAxis::Both, // Spacer stretches in both directions
        };
        let mut child2 = MockSubView {
            size: Size::new(30.0, 40.0),
            stretch_axis: StretchAxis::None,
        };

        let children: Vec<&dyn SubView> = vec![&mut child1, &mut spacer, &mut child2];

        // With specified width, spacer should expand
        let size = layout.size_that_fits(ProposalSize::new(Some(200.0), None), &children);

        assert!((size.width - 200.0).abs() < f32::EPSILON);

        // Place should distribute remaining space to spacer
        let bounds = Rect::new(Point::zero(), Size::new(200.0, 40.0));

        let mut child1 = MockSubView {
            size: Size::new(30.0, 40.0),
            stretch_axis: StretchAxis::None,
        };
        let mut spacer = MockSubView {
            size: Size::zero(),
            stretch_axis: StretchAxis::Both,
        };
        let mut child2 = MockSubView {
            size: Size::new(30.0, 40.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child1, &mut spacer, &mut child2];

        let placements = layout.place(bounds, ProposalSize::new(Some(200.0), None), &children);

        assert!((placements[0].frame.width() - 30.0).abs() < f32::EPSILON);
        assert!((placements[1].frame.width() - 140.0).abs() < f32::EPSILON); // 200 - 30 - 30
        assert!((placements[2].frame.width() - 30.0).abs() < f32::EPSILON);
        assert!((placements[2].frame.x() - 170.0).abs() < f32::EPSILON); // 30 + 140
    }

    /// A child that fills the cross axis still contributes the height it
    /// measures. Filling means "at least this, and more if you have it": a row
    /// that reported less than its tallest child would be handed less, and the
    /// child would fill a box too small for it.
    #[test]
    fn a_cross_filling_child_still_sets_the_row_height() {
        // Vertical stretch component in HStack: stretches HEIGHT but has fixed WIDTH
        // This is like a Slider/TextField rotated for use in HStack context
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(10.0),
        };

        let mut label = MockSubView {
            size: Size::new(50.0, 20.0),
            stretch_axis: StretchAxis::None,
        };
        // A vertically-stretching component: fixed width, wants to fill height
        let mut vertical_stretch = MockSubView {
            size: Size::new(40.0, 100.0), // reports minimum width, tall height
            stretch_axis: StretchAxis::Vertical, // stretches height only
        };
        let mut button = MockSubView {
            size: Size::new(80.0, 44.0),
            stretch_axis: StretchAxis::None,
        };

        let children: Vec<&dyn SubView> = vec![&mut label, &mut vertical_stretch, &mut button];

        let size = layout.size_that_fits(ProposalSize::UNSPECIFIED, &children);

        // Width: all children contribute (vertical_stretch doesn't stretch horizontally)
        // = 50 + 10 + 40 + 10 + 80 = 190
        assert!((size.width - 190.0).abs() < f32::EPSILON);
        // Height: max of every child = max(20, 100, 44) = 100
        assert!(
            (size.height - 100.0).abs() < f32::EPSILON,
            "the stretching child's own height has to reach the row, got {}",
            size.height
        );
    }

    #[test]
    fn test_hstack_compresses_equal_children_evenly_bounded_proposal() {
        // Seven equal 40pt columns with 8pt spacing (a calendar's day row) in
        // a 272pt bound: the 56pt deficit must be shared equally — every
        // column shrinks to 32 at a uniform 40pt pitch — never taken
        // order-dependently from the leading children.
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(8.0),
        };

        let mut columns: Vec<CompressibleView> = (0..7)
            .map(|_| CompressibleView {
                ideal: Size::new(40.0, 40.0),
                floor: 0.0,
            })
            .collect();
        let children: Vec<&dyn SubView> = columns
            .iter_mut()
            .map(|child| child as &dyn SubView)
            .collect();

        let bounds = Rect::new(Point::zero(), Size::new(272.0, 40.0));
        let proposal = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let placements = layout.place(bounds, proposal, &children);

        for placement in &placements {
            assert!(
                (placement.frame.width() - 32.0).abs() < 0.001,
                "expected even 32pt columns, got {}",
                placement.frame.width()
            );
        }
        for pair in placements.windows(2) {
            assert!(
                ((pair[1].frame.x() - pair[0].frame.x()) - 40.0).abs() < 0.001,
                "expected uniform 40pt pitch, got {}",
                pair[1].frame.x() - pair[0].frame.x()
            );
        }
    }

    #[test]
    fn test_hstack_compression_keeps_small_children_intrinsic_bounded_proposal() {
        // A 50pt label next to a 200pt text in 140pt of space: the text alone
        // absorbs the deficit (clamped to 90) while the label keeps its
        // intrinsic width.
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(10.0),
        };

        let mut label = MockSubView {
            size: Size::new(50.0, 20.0),
            stretch_axis: StretchAxis::None,
        };
        let mut long_text = ResponsiveSubView {
            intrinsic: Size::new(200.0, 20.0),
            wrapped_height: 40.0,
            wrap_at_or_below: 60.0,
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut label, &mut long_text];

        let bounds = Rect::new(Point::zero(), Size::new(150.0, 40.0));
        let proposal = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let placements = layout.place(bounds, proposal, &children);

        assert!((placements[0].frame.width() - 50.0).abs() < 0.001);
        assert!((placements[1].frame.width() - 90.0).abs() < 0.001);
    }

    #[test]
    fn test_hstack_compression_never_goes_below_a_reported_minimum_bounded_proposal() {
        // Two children that will not go below 20pt, in 10pt of space: the row
        // overflows rather than squeezing them past what they said they need.
        // The floor is each child's own answer, not a constant the stack picked.
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(0.0),
        };

        let mut first = CompressibleView {
            ideal: Size::new(60.0, 20.0),
            floor: 20.0,
        };
        let mut second = CompressibleView {
            ideal: Size::new(60.0, 20.0),
            floor: 20.0,
        };
        let children: Vec<&dyn SubView> = vec![&mut first, &mut second];

        let bounds = Rect::new(Point::zero(), Size::new(10.0, 20.0));
        let proposal = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let placements = layout.place(bounds, proposal, &children);

        assert!((placements[0].frame.width() - 20.0).abs() < 0.001);
        assert!((placements[1].frame.width() - 20.0).abs() < 0.001);
    }

    #[test]
    fn test_hstack_measures_stretch_child_with_allocated_width_for_height() {
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(0.0),
        };

        let mut fixed = MockSubView {
            size: Size::new(4.0, 10.0),
            stretch_axis: StretchAxis::None,
        };

        // Simulate a content-bearing stretch child whose height increases when width is constrained.
        let mut stretch = ResponsiveSubView {
            intrinsic: Size::new(100.0, 20.0),
            wrapped_height: 40.0,
            wrap_at_or_below: 60.0,
            stretch_axis: StretchAxis::Horizontal,
        };

        let children: Vec<&dyn SubView> = vec![&mut fixed, &mut stretch];

        let size = layout.size_that_fits(ProposalSize::new(Some(40.0), None), &children);

        assert!((size.width - 40.0).abs() < f32::EPSILON);
        assert!((size.height - 40.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_hstack_place_uses_stretch_child_wrapped_height_bounded_proposal() {
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(0.0),
        };

        let bounds = Rect::new(Point::zero(), Size::new(40.0, 40.0));

        let mut fixed = MockSubView {
            size: Size::new(4.0, 10.0),
            stretch_axis: StretchAxis::None,
        };

        let mut stretch = ResponsiveSubView {
            intrinsic: Size::new(100.0, 20.0),
            wrapped_height: 40.0,
            wrap_at_or_below: 60.0,
            stretch_axis: StretchAxis::Horizontal,
        };

        let children: Vec<&dyn SubView> = vec![&mut fixed, &mut stretch];

        let proposal = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let placements = layout.place(bounds, proposal, &children);

        assert!((placements[0].frame.width() - 4.0).abs() < f32::EPSILON);
        assert!((placements[1].frame.width() - 36.0).abs() < f32::EPSILON);
        assert!((placements[1].frame.height() - 40.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_hstack_min_size_query_correctly_sums_children() {
        // When ProposalSize::ZERO is used (min size query), ALL children's widths
        // should be summed to ensure window minimum width calculation is correct.
        // Previous bug: if spacer (stretch) existed, it would return 0 width for min size query.
        let layout = HStackLayout {
            alignment: VerticalAlignment::Center,
            spacing: Computed::constant(10.0),
        };

        let mut label = MockSubView {
            size: Size::new(50.0, 20.0),
            stretch_axis: StretchAxis::None,
        };
        let mut spacer = MockSubView {
            size: Size::zero(),
            stretch_axis: StretchAxis::Both,
        };
        let mut button = MockSubView {
            size: Size::new(80.0, 44.0),
            stretch_axis: StretchAxis::None,
        };

        let children: Vec<&dyn SubView> = vec![&mut label, &mut spacer, &mut button];

        // With ZERO proposal (min size query)
        let min_size = layout.size_that_fits(ProposalSize::ZERO, &children);

        // Width: 50 + 10 + 0 + 10 + 80 = 150
        assert!(
            (min_size.width - 150.0).abs() < f32::EPSILON,
            "Min size query should return sum of child min widths (150.0), got {}",
            min_size.width
        );

        // Verify regular behavior (Unspecified) still works
        let intrinsic_size = layout.size_that_fits(ProposalSize::UNSPECIFIED, &children);
        // Should also be 150 because spacer has 0 intrinsic width
        assert!((intrinsic_size.width - 150.0).abs() < f32::EPSILON);
    }
}