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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! Absolute positioning layout for `WaterUI`.
//!
//! This module provides an `Absolute` container that fills available space
//! and allows children to be positioned at specific coordinates within.
//!
//! # Example
//!
//! ```rust
//! use waterui::prelude::*;
//!
//! # fn overlay_stage(badge: impl View, panel: impl View) -> impl View {
//! absolute((
//!     Color::grey(), // Fills container
//!     text("Center").position_in(UnitPoint::CENTER),
//!     badge.position_in_offset(
//!         UnitPoint::TOP_TRAILING,
//!         UnitPoint::TOP_TRAILING,
//!         -8.0, 8.0
//!     ),
//!     panel.pin(PinConstraints::all(16.0)),
//! ))
//! # }
//! ```

use alloc::collections::BTreeSet;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;

use nami::{Computed, Signal, SignalExt, watcher::BoxWatcherGuard};
use waterui_core::{IntoSignalF32, View, layout::LayoutInvalidationCallback, view::TupleViews};

use crate::{
    Layout, Point, ProposalSize, Rect, Size, StretchAxis, SubView, SubviewPlacement, UnitPoint,
    container::FixedContainer,
};

// ============================================================================
// AbsoluteLayout - Fills parent, gives all children full bounds
// ============================================================================

/// Layout that fills parent and gives each child full bounds.
///
/// Children are responsible for their own positioning (via `PositionedLayout`).
#[derive(Debug, Clone, Default)]
pub struct AbsoluteLayout;

impl Layout for AbsoluteLayout {
    fn stretch_axis(&self, _children: &[StretchAxis]) -> StretchAxis {
        StretchAxis::Both
    }

    fn size_that_fits(&self, proposal: ProposalSize, _children: &[&dyn SubView]) -> Size {
        // Absolute fills offered space. In unconstrained contexts we use 0
        // to avoid propagating infinite dimensions to native backends.
        Size::new(
            proposal.width.unwrap_or(0.0),
            proposal.height.unwrap_or(0.0),
        )
    }

    fn place(
        &self,
        bounds: Rect,
        _proposal: ProposalSize,
        children: &[&dyn SubView],
    ) -> Vec<SubviewPlacement> {
        // Give every child the full bounds - they position themselves - and
        // offer each the resolved finite bounds as its proposal.
        let child_proposal = ProposalSize::new(bounds.width(), bounds.height());
        children
            .iter()
            .map(|_| SubviewPlacement::new(bounds, child_proposal))
            .collect()
    }
}

// ============================================================================
// PositionTarget - Where to position the child
// ============================================================================

/// Target position for absolute positioning.
#[derive(Debug, Clone)]
pub enum PositionTarget {
    /// Absolute position in points (relative to parent origin)
    Absolute {
        /// X coordinate in points
        x: Computed<f32>,
        /// Y coordinate in points
        y: Computed<f32>,
    },
    /// Fractional position (0.0-1.0 of parent) plus offset
    Fractional {
        /// Fractional position in parent
        unit: UnitPoint,
        /// Additional X offset in points
        offset_x: Computed<f32>,
        /// Additional Y offset in points
        offset_y: Computed<f32>,
    },
    /// Edge-based pinning with optional explicit size.
    Pinned(PinConstraints),
}

/// Edge-based constraints for absolute positioning.
///
/// This supports common pinning patterns:
/// - `leading + trailing` computes width from parent bounds
/// - `top + bottom` computes height from parent bounds
/// - explicit `width` / `height` override computed dimensions
#[derive(Debug, Clone, Default)]
pub struct PinConstraints {
    leading: Option<Computed<f32>>,
    trailing: Option<Computed<f32>>,
    top: Option<Computed<f32>>,
    bottom: Option<Computed<f32>>,
    width: Option<Computed<f32>>,
    height: Option<Computed<f32>>,
}

impl PinConstraints {
    /// Creates empty pin constraints.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            leading: None,
            trailing: None,
            top: None,
            bottom: None,
            width: None,
            height: None,
        }
    }

    /// Pins all four edges by the same inset.
    #[must_use]
    pub fn all(inset: impl IntoSignalF32) -> Self {
        let inset = inset.into_signal_f32().computed();
        Self {
            leading: Some(inset.clone()),
            trailing: Some(inset.clone()),
            top: Some(inset.clone()),
            bottom: Some(inset),
            width: None,
            height: None,
        }
    }

    /// Pins leading edge.
    #[must_use]
    pub fn leading(mut self, value: impl IntoSignalF32) -> Self {
        self.leading = Some(value.into_signal_f32().computed());
        self
    }

    /// Pins trailing edge.
    #[must_use]
    pub fn trailing(mut self, value: impl IntoSignalF32) -> Self {
        self.trailing = Some(value.into_signal_f32().computed());
        self
    }

    /// Pins top edge.
    #[must_use]
    pub fn top(mut self, value: impl IntoSignalF32) -> Self {
        self.top = Some(value.into_signal_f32().computed());
        self
    }

    /// Pins bottom edge.
    #[must_use]
    pub fn bottom(mut self, value: impl IntoSignalF32) -> Self {
        self.bottom = Some(value.into_signal_f32().computed());
        self
    }

    /// Sets explicit width.
    #[must_use]
    pub fn width(mut self, value: impl IntoSignalF32) -> Self {
        self.width = Some(value.into_signal_f32().computed());
        self
    }

    /// Sets explicit height.
    #[must_use]
    pub fn height(mut self, value: impl IntoSignalF32) -> Self {
        self.height = Some(value.into_signal_f32().computed());
        self
    }
}

// ============================================================================
// PositionedLayout - Positions a single child within received bounds
// ============================================================================

/// Layout that positions a single child within received bounds.
pub struct PositionedLayout {
    /// Anchor point on the child (0.0-1.0)
    pub anchor: UnitPoint,
    /// Target position in parent
    pub target: PositionTarget,
}

impl fmt::Debug for PositionedLayout {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PositionedLayout")
            .field("anchor", &self.anchor)
            .finish_non_exhaustive()
    }
}

impl Layout for PositionedLayout {
    fn stretch_axis(&self, _children: &[StretchAxis]) -> StretchAxis {
        StretchAxis::Both
    }

    fn size_that_fits(&self, proposal: ProposalSize, _children: &[&dyn SubView]) -> Size {
        Size::new(
            proposal.width.unwrap_or(0.0),
            proposal.height.unwrap_or(0.0),
        )
    }

    #[allow(clippy::too_many_lines)]
    fn place(
        &self,
        bounds: Rect,
        _proposal: ProposalSize,
        children: &[&dyn SubView],
    ) -> Vec<SubviewPlacement> {
        let child_proposal = ProposalSize::new(
            bounds
                .width()
                .is_finite()
                .then_some(bounds.width().max(0.0)),
            bounds
                .height()
                .is_finite()
                .then_some(bounds.height().max(0.0)),
        );

        children
            .iter()
            .map(|child| {
                let intrinsic = child.measure(child_proposal).size;

                match &self.target {
                    PositionTarget::Absolute { x, y } => {
                        let child_size = sanitize_size(intrinsic, bounds);
                        let target_x = bounds.x() + x.get();
                        let target_y = bounds.y() + y.get();

                        let x = target_x - child_size.width * self.anchor.x;
                        let y = target_y - child_size.height * self.anchor.y;

                        SubviewPlacement::new(
                            Rect::new(
                                Point::new(
                                    if x.is_finite() { x } else { bounds.x() },
                                    if y.is_finite() { y } else { bounds.y() },
                                ),
                                child_size,
                            ),
                            child_proposal,
                        )
                    }
                    PositionTarget::Fractional {
                        unit,
                        offset_x,
                        offset_y,
                    } => {
                        let child_size = sanitize_size(intrinsic, bounds);
                        let target_x = bounds.x() + bounds.width() * unit.x + offset_x.get();
                        let target_y = bounds.y() + bounds.height() * unit.y + offset_y.get();

                        let x = target_x - child_size.width * self.anchor.x;
                        let y = target_y - child_size.height * self.anchor.y;

                        SubviewPlacement::new(
                            Rect::new(
                                Point::new(
                                    if x.is_finite() { x } else { bounds.x() },
                                    if y.is_finite() { y } else { bounds.y() },
                                ),
                                child_size,
                            ),
                            child_proposal,
                        )
                    }
                    PositionTarget::Pinned(pinned) => {
                        let leading = pinned.leading.as_ref().map(waterui_core::Signal::get);
                        let trailing = pinned.trailing.as_ref().map(waterui_core::Signal::get);
                        let top = pinned.top.as_ref().map(waterui_core::Signal::get);
                        let bottom = pinned.bottom.as_ref().map(waterui_core::Signal::get);
                        let explicit_width = pinned.width.as_ref().map(waterui_core::Signal::get);
                        let explicit_height = pinned.height.as_ref().map(waterui_core::Signal::get);

                        let mut width = explicit_width.unwrap_or_else(|| {
                            if let (Some(leading), Some(trailing)) = (leading, trailing) {
                                bounds.width() - leading - trailing
                            } else {
                                intrinsic.width
                            }
                        });
                        let mut height = explicit_height.unwrap_or_else(|| {
                            if let (Some(top), Some(bottom)) = (top, bottom) {
                                bounds.height() - top - bottom
                            } else {
                                intrinsic.height
                            }
                        });

                        if !width.is_finite() {
                            width = bounds.width();
                        }
                        if !height.is_finite() {
                            height = bounds.height();
                        }
                        width = width.max(0.0);
                        height = height.max(0.0);

                        // The exact resolved pin box is the child's proposal;
                        // the measurement below may still adjust the final size.
                        let pinned_proposal = ProposalSize::new(Some(width), Some(height));
                        let measured = child.measure(pinned_proposal).size;
                        if explicit_width.is_none() && !(leading.is_some() && trailing.is_some()) {
                            width = sanitize_axis(measured.width, width);
                        }
                        if explicit_height.is_none() && !(top.is_some() && bottom.is_some()) {
                            height = sanitize_axis(measured.height, height);
                        }

                        let x = leading.map_or_else(
                            || {
                                trailing.map_or_else(
                                    || bounds.x(),
                                    |trailing| bounds.max_x() - trailing - width,
                                )
                            },
                            |leading| bounds.x() + leading,
                        );

                        let y = top.map_or_else(
                            || {
                                bottom.map_or_else(
                                    || bounds.y(),
                                    |bottom| bounds.max_y() - bottom - height,
                                )
                            },
                            |top| bounds.y() + top,
                        );

                        SubviewPlacement::new(
                            Rect::new(
                                Point::new(
                                    if x.is_finite() { x } else { bounds.x() },
                                    if y.is_finite() { y } else { bounds.y() },
                                ),
                                Size::new(width, height),
                            ),
                            pinned_proposal,
                        )
                    }
                }
            })
            .collect()
    }

    fn watch_invalidation(&self, invalidate: LayoutInvalidationCallback) -> Vec<BoxWatcherGuard> {
        let signals: Vec<&Computed<f32>> = match &self.target {
            PositionTarget::Absolute { x, y } => vec![x, y],
            PositionTarget::Fractional {
                offset_x, offset_y, ..
            } => vec![offset_x, offset_y],
            PositionTarget::Pinned(pinned) => [
                pinned.leading.as_ref(),
                pinned.trailing.as_ref(),
                pinned.top.as_ref(),
                pinned.bottom.as_ref(),
                pinned.width.as_ref(),
                pinned.height.as_ref(),
            ]
            .into_iter()
            .flatten()
            .collect(),
        };
        let mut identities = BTreeSet::new();
        let mut guards = Vec::new();
        for signal in signals {
            if signal
                .identity()
                .is_some_and(|identity| !identities.insert(identity))
            {
                continue;
            }
            let invalidate = invalidate.clone();
            guards.push(signal.watch(move |_| invalidate()));
        }
        guards
    }
}

const fn sanitize_size(intrinsic: Size, bounds: Rect) -> Size {
    let width = if intrinsic.width.is_finite() {
        intrinsic.width.max(0.0)
    } else {
        bounds.width().max(0.0)
    };
    let height = if intrinsic.height.is_finite() {
        intrinsic.height.max(0.0)
    } else {
        bounds.height().max(0.0)
    };
    Size::new(width, height)
}

const fn sanitize_axis(measured: f32, fallback: f32) -> f32 {
    if measured.is_finite() {
        measured.max(0.0)
    } else {
        fallback.max(0.0)
    }
}

// ============================================================================
// PositionedChild<V> - View wrapper with position info
// ============================================================================

/// A view with positioning information, for use in `Absolute` container.
pub struct PositionedChild<V> {
    layout: PositionedLayout,
    content: V,
}

impl<V> fmt::Debug for PositionedChild<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PositionedChild")
            .field("layout", &self.layout)
            .finish_non_exhaustive()
    }
}

impl<V: View> View for PositionedChild<V> {
    fn body(self, _env: &waterui_core::Environment) -> impl View {
        FixedContainer::new(self.layout, (self.content,))
    }

    fn stretch_axis(&self) -> StretchAxis {
        StretchAxis::Both
    }
}

// ============================================================================
// PositionExt - Extension trait for positioning views
// ============================================================================

/// Extension trait for absolute positioning of views.
///
/// Use these methods inside an `Absolute` container.
pub trait PositionExt: View + Sized {
    /// Position view's center at absolute (x, y) coordinates.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn placed() -> impl View {
    /// text("Hello").position(100.0, 50.0) // center at (100, 50)
    /// # }
    /// ```
    fn position(self, x: impl IntoSignalF32, y: impl IntoSignalF32) -> PositionedChild<Self> {
        self.position_anchor(UnitPoint::CENTER, x, y)
    }

    /// Position view's anchor point at absolute coordinates.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn placed() -> impl View {
    /// text("Hello").position_anchor(UnitPoint::TOP_LEADING, 10.0, 10.0)
    /// # }
    /// ```
    fn position_anchor(
        self,
        anchor: UnitPoint,
        x: impl IntoSignalF32,
        y: impl IntoSignalF32,
    ) -> PositionedChild<Self> {
        PositionedChild {
            layout: PositionedLayout {
                anchor,
                target: PositionTarget::Absolute {
                    x: x.into_signal_f32().computed(),
                    y: y.into_signal_f32().computed(),
                },
            },
            content: self,
        }
    }

    /// Position view's center at fractional location in parent.
    ///
    /// The anchor point on the view matches the target position.
    /// e.g., `UnitPoint::CENTER` means view's center at parent's center.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn placed() -> impl View {
    /// text("Centered").position_in(UnitPoint::CENTER)
    /// # }
    /// ```
    fn position_in(self, position: UnitPoint) -> PositionedChild<Self> {
        self.position_in_anchor(position, position)
    }

    /// Position view's anchor at fractional location in parent.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn placed(view: impl View) -> impl View {
    /// // Place view's top-left at parent's center
    /// view.position_in_anchor(UnitPoint::TOP_LEADING, UnitPoint::CENTER)
    /// # }
    /// ```
    fn position_in_anchor(self, anchor: UnitPoint, position: UnitPoint) -> PositionedChild<Self> {
        PositionedChild {
            layout: PositionedLayout {
                anchor,
                target: PositionTarget::Fractional {
                    unit: position,
                    offset_x: 0.0_f32.into_signal_f32().computed(),
                    offset_y: 0.0_f32.into_signal_f32().computed(),
                },
            },
            content: self,
        }
    }

    /// Position with fractional location plus offset.
    ///
    /// Great for "16pt from bottom-right corner" patterns.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn placed(fab: impl View) -> impl View {
    /// // FAB at bottom-right with 16pt inset
    /// fab.position_in_offset(
    ///     UnitPoint::BOTTOM_TRAILING,
    ///     UnitPoint::BOTTOM_TRAILING,
    ///     -16.0, -16.0
    /// )
    /// # }
    /// ```
    fn position_in_offset(
        self,
        anchor: UnitPoint,
        position: UnitPoint,
        offset_x: impl IntoSignalF32,
        offset_y: impl IntoSignalF32,
    ) -> PositionedChild<Self> {
        PositionedChild {
            layout: PositionedLayout {
                anchor,
                target: PositionTarget::Fractional {
                    unit: position,
                    offset_x: offset_x.into_signal_f32().computed(),
                    offset_y: offset_y.into_signal_f32().computed(),
                },
            },
            content: self,
        }
    }

    /// Position using edge pins and optional explicit size.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use waterui::prelude::*;
    /// # fn pinned(background: impl View, badge: impl View) {
    /// // Fill parent with 12pt inset
    /// background.pin(PinConstraints::all(12.0));
    ///
    /// // Bottom trailing fixed-size badge
    /// badge.pin(
    ///     PinConstraints::new()
    ///         .trailing(12.0)
    ///         .bottom(12.0)
    ///         .width(28.0)
    ///         .height(28.0)
    /// );
    /// # }
    /// ```
    fn pin(self, constraints: PinConstraints) -> PositionedChild<Self> {
        PositionedChild {
            layout: PositionedLayout {
                anchor: UnitPoint::TOP_LEADING,
                target: PositionTarget::Pinned(constraints),
            },
            content: self,
        }
    }
}

impl<V: View + Sized> PositionExt for V {}

// ============================================================================
// Absolute<C> - Container for positioned children
// ============================================================================

/// Container for absolutely positioned children.
///
/// Fills available space and positions each child within.
/// Children can use `PositionExt` methods like `.position()`, `.position_in()`,
/// and `.pin()`.
///
/// # Example
///
/// ```rust
/// # use waterui::prelude::*;
/// # fn stage(fab: impl View) -> impl View {
/// absolute((
///     Color::grey(), // Fills automatically (StretchAxis::Both)
///     text("Centered").position_in(UnitPoint::CENTER),
///     fab.position_in_offset(UnitPoint::BOTTOM_TRAILING, UnitPoint::BOTTOM_TRAILING, -16.0, -16.0),
/// ))
/// # }
/// ```
pub struct Absolute<C> {
    contents: C,
}

impl<C> fmt::Debug for Absolute<C> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Absolute").finish_non_exhaustive()
    }
}

impl<C: TupleViews> Absolute<C> {
    /// Creates a new `Absolute` container with the given contents.
    #[must_use]
    pub const fn new(contents: C) -> Self {
        Self { contents }
    }
}

impl<C: TupleViews + 'static> View for Absolute<C> {
    fn body(self, _env: &waterui_core::Environment) -> impl View {
        FixedContainer::new(AbsoluteLayout, self.contents)
    }

    fn stretch_axis(&self) -> StretchAxis {
        StretchAxis::Both
    }
}

/// Creates an `Absolute` container for positioning children.
///
/// The container fills available space and allows children to be
/// positioned at specific coordinates using `PositionExt` methods.
///
/// # Example
///
/// ```rust
/// # use waterui::prelude::*;
/// # fn stage(background: impl View, icon: impl View) -> impl View {
/// absolute((
///     background,
///     text("Hello").position(50.0, 100.0),
///     icon.position_in(UnitPoint::CENTER),
/// ))
/// # }
/// ```
#[must_use]
pub const fn absolute<C: TupleViews>(contents: C) -> Absolute<C> {
    Absolute::new(contents)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::StretchAxis;
    use crate::ViewDimensions;
    use alloc::vec;
    use core::cell::Cell;
    use waterui_core::MainThreadBound;

    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 ProposalAwareView {
        intrinsic: Size,
        constrained: Size,
        last_width: MainThreadBound<Cell<Option<f32>>>,
        last_height: MainThreadBound<Cell<Option<f32>>>,
    }

    impl ProposalAwareView {
        fn new(intrinsic: Size, constrained: Size) -> Self {
            Self {
                intrinsic,
                constrained,
                last_width: MainThreadBound::new(Cell::new(None)),
                last_height: MainThreadBound::new(Cell::new(None)),
            }
        }
    }

    impl SubView for ProposalAwareView {
        fn measure(&self, proposal: ProposalSize) -> ViewDimensions {
            self.last_width.set(proposal.width);
            self.last_height.set(proposal.height);
            ViewDimensions::new(if proposal.width.is_some() || proposal.height.is_some() {
                self.constrained
            } else {
                self.intrinsic
            })
        }
        fn stretch_axis(&self) -> StretchAxis {
            StretchAxis::Both
        }
        fn priority(&self) -> i32 {
            0
        }
    }

    #[test]
    fn test_absolute_layout_uses_finite_size_for_unspecified_proposal() {
        let layout = AbsoluteLayout;
        let size = layout.size_that_fits(ProposalSize::UNSPECIFIED, &[]);

        assert!(size.width.is_finite());
        assert!(size.height.is_finite());
        assert_eq!(size.width, 0.0);
        assert_eq!(size.height, 0.0);
    }

    #[test]
    fn test_absolute_layout_respects_parent_constraints() {
        let layout = AbsoluteLayout;
        let size = layout.size_that_fits(ProposalSize::new(Some(200.0), Some(300.0)), &[]);
        assert_eq!(size.width, 200.0);
        assert_eq!(size.height, 300.0);
    }

    #[test]
    fn test_absolute_layout_gives_full_bounds_to_each_child_bounded_proposal() {
        let layout = AbsoluteLayout;
        let mut child1 = MockSubView {
            size: Size::new(50.0, 50.0),
            stretch_axis: StretchAxis::None,
        };
        let mut child2 = MockSubView {
            size: Size::new(30.0, 30.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child1, &mut child2];
        let bounds = Rect::new(Point::new(10.0, 20.0), Size::new(200.0, 300.0));
        let proposal = ProposalSize::new(Some(bounds.width()), Some(bounds.height()));
        let placements = layout.place(bounds, proposal, &children);

        assert_eq!(placements.len(), 2);
        assert_eq!(placements[0].frame, bounds);
        assert_eq!(placements[1].frame, bounds);
    }

    #[test]
    fn test_positioned_layout_uses_finite_size_for_unspecified_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::CENTER,
            target: PositionTarget::Absolute {
                x: 10.0_f32.into_signal_f32().computed(),
                y: 20.0_f32.into_signal_f32().computed(),
            },
        };
        let size = layout.size_that_fits(ProposalSize::UNSPECIFIED, &[]);

        assert!(size.width.is_finite());
        assert!(size.height.is_finite());
        assert_eq!(size.width, 0.0);
        assert_eq!(size.height, 0.0);
    }

    #[test]
    fn test_positioned_layout_measures_child_with_parent_bounds_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::CENTER,
            target: PositionTarget::Fractional {
                unit: UnitPoint::CENTER,
                offset_x: 0.0_f32.into_signal_f32().computed(),
                offset_y: 0.0_f32.into_signal_f32().computed(),
            },
        };

        let child = ProposalAwareView::new(Size::new(10.0, 10.0), Size::new(200.0, 100.0));
        let children: Vec<&dyn SubView> = vec![&child];
        let bounds = Rect::new(Point::new(0.0, 0.0), Size::new(200.0, 100.0));

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

        assert_eq!(child.last_width.get(), Some(200.0));
        assert_eq!(child.last_height.get(), Some(100.0));
        assert_eq!(placements[0].frame.x(), 0.0);
        assert_eq!(placements[0].frame.y(), 0.0);
        assert_eq!(placements[0].frame.width(), 200.0);
        assert_eq!(placements[0].frame.height(), 100.0);
    }

    #[test]
    fn test_positioned_layout_absolute_anchor_math_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::BOTTOM_TRAILING,
            target: PositionTarget::Absolute {
                x: 50.0_f32.into_signal_f32().computed(),
                y: 40.0_f32.into_signal_f32().computed(),
            },
        };

        let mut child = MockSubView {
            size: Size::new(20.0, 10.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child];
        let bounds = Rect::new(Point::new(10.0, 20.0), Size::new(200.0, 100.0));

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

        // Target at (bounds.x + 50, bounds.y + 40) = (60, 60),
        // bottom-trailing anchor offsets by (20, 10).
        assert_eq!(placements[0].frame.x(), 40.0);
        assert_eq!(placements[0].frame.y(), 50.0);
        assert_eq!(placements[0].frame.width(), 20.0);
        assert_eq!(placements[0].frame.height(), 10.0);
    }

    #[test]
    fn test_positioned_layout_fractional_with_offset_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::BOTTOM_TRAILING,
            target: PositionTarget::Fractional {
                unit: UnitPoint::BOTTOM_TRAILING,
                offset_x: (-16.0).into_signal_f32().computed(),
                offset_y: (-16.0).into_signal_f32().computed(),
            },
        };

        let mut child = MockSubView {
            size: Size::new(50.0, 50.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child];
        let bounds = Rect::new(Point::new(0.0, 0.0), Size::new(200.0, 200.0));

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

        // Target = bottom-right (200, 200) + offset (-16, -16) = (184, 184)
        // Child's bottom-right at target, so origin = (184 - 50, 184 - 50) = (134, 134)
        assert!((placements[0].frame.x() - 134.0).abs() < f32::EPSILON);
        assert!((placements[0].frame.y() - 134.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_pin_constraints_fill_with_insets_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::TOP_LEADING,
            target: PositionTarget::Pinned(PinConstraints::all(12.0)),
        };

        let mut child = MockSubView {
            size: Size::new(20.0, 20.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child];
        let bounds = Rect::new(Point::new(0.0, 0.0), Size::new(200.0, 100.0));

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

        assert_eq!(placements[0].frame.x(), 12.0);
        assert_eq!(placements[0].frame.y(), 12.0);
        assert_eq!(placements[0].frame.width(), 176.0);
        assert_eq!(placements[0].frame.height(), 76.0);
    }

    #[test]
    fn test_pin_constraints_bottom_trailing_fixed_size_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::TOP_LEADING,
            target: PositionTarget::Pinned(
                PinConstraints::new()
                    .trailing(16.0)
                    .bottom(10.0)
                    .width(40.0)
                    .height(20.0),
            ),
        };

        let mut child = MockSubView {
            size: Size::new(8.0, 8.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child];
        let bounds = Rect::new(Point::new(5.0, 10.0), Size::new(200.0, 100.0));

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

        assert_eq!(placements[0].frame.x(), 149.0);
        assert_eq!(placements[0].frame.y(), 80.0);
        assert_eq!(placements[0].frame.width(), 40.0);
        assert_eq!(placements[0].frame.height(), 20.0);
    }

    #[test]
    fn test_pin_constraints_clamp_negative_size_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::TOP_LEADING,
            target: PositionTarget::Pinned(
                PinConstraints::new()
                    .leading(80.0)
                    .trailing(80.0)
                    .top(40.0)
                    .bottom(40.0),
            ),
        };

        let mut child = MockSubView {
            size: Size::new(30.0, 30.0),
            stretch_axis: StretchAxis::None,
        };
        let children: Vec<&dyn SubView> = vec![&mut child];
        let bounds = Rect::new(Point::new(0.0, 0.0), Size::new(100.0, 60.0));

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

        assert_eq!(placements[0].frame.x(), 80.0);
        assert_eq!(placements[0].frame.y(), 40.0);
        assert_eq!(placements[0].frame.width(), 0.0);
        assert_eq!(placements[0].frame.height(), 0.0);
    }

    #[test]
    fn test_pin_constraints_remeasure_after_width_resolution_bounded_proposal() {
        let layout = PositionedLayout {
            anchor: UnitPoint::TOP_LEADING,
            target: PositionTarget::Pinned(PinConstraints::new().leading(10.0).trailing(10.0)),
        };

        let child = ProposalAwareView::new(Size::new(120.0, 20.0), Size::new(100.0, 40.0));
        let children: Vec<&dyn SubView> = vec![&child];
        let bounds = Rect::new(Point::zero(), Size::new(120.0, 200.0));

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

        assert_eq!(placements[0].frame.x(), 10.0);
        assert_eq!(placements[0].frame.width(), 100.0);
        assert_eq!(placements[0].frame.height(), 40.0);
        assert_eq!(child.last_width.get(), Some(100.0));
    }
}