cranpose-ui 0.9.10

Composable widgets, text, layouts and input for Cranpose apps
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
use cranpose_ui_layout::{
    Axis, Constraints, MeasurePolicy, MeasureResult, MeasureScope, ParentData, Placement,
    bias_offset, round_to_px,
};
use smallvec::SmallVec;

use crate::layout::core::{
    Alignment, Arrangement, HorizontalAlignment, LinearArrangement, Measurable, VerticalAlignment,
};

/// MeasurePolicy for Box layout - overlays children according to alignment.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxMeasurePolicy {
    pub content_alignment: Alignment,
    pub propagate_min_constraints: bool,
    /// Direction used to resolve start and end alignment.
    pub layout_direction: crate::LayoutDirection,
}

impl BoxMeasurePolicy {
    pub fn new(content_alignment: Alignment, propagate_min_constraints: bool) -> Self {
        Self {
            content_alignment,
            propagate_min_constraints,
            layout_direction: crate::LayoutDirection::Ltr,
        }
    }
}

impl MeasurePolicy for BoxMeasurePolicy {
    fn measure(
        &self,
        scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
    ) -> MeasureResult {
        let mut placements = Vec::new();
        let measurement = self.measure_into(scope, measurables, constraints, &mut placements);
        MeasureResult::new(measurement, placements)
    }

    /// A box holds while every child holds under the constraints it hands
    /// on and the largest child, which sizes the box, still fits.
    fn measure_hold(
        &self,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        size: crate::modifier::Size,
    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
        if measurables.is_empty() {
            return empty_layout_hold(constraints, size);
        }
        let mut width = cranpose_ui_layout::BoundRange::ANY;
        let mut height = cranpose_ui_layout::BoundRange::ANY;
        let mut held = cranpose_ui_layout::ConstraintsHold::sized(size.width, size.height);
        let mut largest = crate::modifier::Size::default();
        for measurable in measurables {
            let (child, hold) = measurable.measured_hold()?;
            if self.propagate_min_constraints {
                held = held.intersect(hold)?;
            } else {
                width = width.intersect(hold.width.max)?;
                height = height.intersect(hold.height.max)?;
            }
            largest.width = largest.width.max(child.width);
            largest.height = largest.height.max(child.height);
        }
        // Bounds that cut or stretched the box size it from themselves.
        if size != largest {
            return None;
        }
        held.width.max = held.width.max.intersect(width)?;
        held.height.max = held.height.max.intersect(height)?;
        Some(held)
    }

    fn measure_into(
        &self,
        scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        placements: &mut Vec<Placement>,
    ) -> cranpose_ui_layout::Measurement {
        placements.clear();
        let child_constraints = if self.propagate_min_constraints {
            constraints
        } else {
            Constraints {
                min_width: 0.0,
                max_width: constraints.max_width,
                min_height: 0.0,
                max_height: constraints.max_height,
            }
        };

        let mut max_width = 0.0_f32;
        let mut max_height = 0.0_f32;
        let mut placeables: SmallVec<[(cranpose_ui_layout::Placeable, Alignment); 8]> =
            SmallVec::new();

        for measurable in measurables {
            let placeable = measurable.measure(child_constraints);
            max_width = max_width.max(placeable.width());
            max_height = max_height.max(placeable.height());
            let alignment = measurable
                .parent_data()
                .box_alignment
                .unwrap_or(self.content_alignment);
            placeables.push((placeable, alignment));
        }

        let width = max_width.clamp(constraints.min_width, constraints.max_width);
        let height = max_height.clamp(constraints.min_height, constraints.max_height);

        placements.reserve(placeables.len());
        for (placeable, alignment) in placeables {
            let child_width = placeable.width();
            let child_height = placeable.height();

            let x = alignment
                .horizontal
                .align(width, child_width, scope.density());
            let x = self.layout_direction.place_x(x, width, child_width);
            let y = alignment
                .vertical
                .align(height, child_height, scope.density());

            placeable.place(x, y);
            placements.push(Placement::new(placeable.node_id(), x, y, 0));
        }

        crate::modifier::Size { width, height }.into()
    }

    fn min_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        measurables
            .iter()
            .map(|m| m.min_intrinsic_width(height))
            .fold(0.0, f32::max)
    }

    fn max_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        measurables
            .iter()
            .map(|m| m.max_intrinsic_width(height))
            .fold(0.0, f32::max)
    }

    fn min_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        measurables
            .iter()
            .map(|m| m.min_intrinsic_height(width))
            .fold(0.0, f32::max)
    }

    fn max_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        measurables
            .iter()
            .map(|m| m.max_intrinsic_height(width))
            .fold(0.0, f32::max)
    }
}

/// Unified Flex layout policy that powers both Row and Column.
///
/// This policy implements Jetpack Compose's flex layout semantics:
/// - Measures children with proper loose constraints (min = 0 on both axes)
/// - Supports weighted distribution of remaining space
/// - Handles bounded/unbounded main axis correctly
/// - Implements correct intrinsics for both axes
///
/// ## Overflow Behavior
///
/// Like Jetpack Compose, this policy **allows children to overflow** their container bounds:
/// - Children can be positioned outside the parent's measured size
/// - Overflowing content is rendered (unless clipped by a modifier)
/// - When content overflows, distribution arrangements switch to `Start` to avoid negative spacing
/// - `SpacedBy` keeps its fixed inter-child spacing even when content overflows
///
/// Example: A Row with 300px of content in a 200px container will:
/// 1. Measure children at their natural sizes
/// 2. Detect overflow (300px > 200px)
/// 3. Switch to Start arrangement (pack children at the start)
/// 4. Position last children beyond the 200px boundary
///
/// To prevent overflow:
/// - Use weights for flexible sizing: `.weight(1.0, true)`
/// - Use `fillMaxWidth()`/`fillMaxHeight()` modifiers
/// - Design UI to fit within available space
/// - Add a clip modifier to hide overflowing content
///
/// ## Weighted Children
///
/// When the main axis is bounded and children have weights:
/// 1. Fixed children (no weight) are measured first
/// 2. Remaining space is distributed proportionally to weights
/// 3. Each weighted child gets: `remaining * (weight / total_weight)`
/// 4. If `fill=true`, child gets tight constraints; if `fill=false`, loose constraints
///
/// When the main axis is unbounded, weights are ignored (all children wrap content).
#[derive(Clone, Debug, PartialEq)]
pub struct FlexMeasurePolicy {
    /// Main axis direction (Horizontal for Row, Vertical for Column)
    pub axis: Axis,
    /// Arrangement along the main axis
    pub main_axis_arrangement: LinearArrangement,
    /// Alignment along the cross axis (used as default for children without explicit alignment)
    pub cross_axis_alignment: CrossAxisAlignment,
    /// The device pixel grid children are spaced and placed on, the
    /// composition's density.
    pub density: f32,
    /// Direction used to resolve horizontal order and start/end alignment.
    pub layout_direction: crate::LayoutDirection,
}

/// Compose's weight distribution in whole device pixels: each weighted
/// child's share of the remaining space rounded half up, and the pixels
/// that rounding gained or lost handed back one per child from the first.
pub(crate) struct WeightShares {
    density: f32,
    unit_px: f32,
    remainder_px: f32,
}

impl WeightShares {
    pub(crate) fn new(
        remaining: f32,
        weights: impl Iterator<Item = f32> + Clone,
        density: f32,
    ) -> Self {
        let density = if density > 0.0 && density.is_finite() {
            density
        } else {
            1.0
        };
        let total_weight: f32 = weights.clone().sum();
        let remaining_px = (remaining * density).round();
        let unit_px = if total_weight > 0.0 {
            remaining_px / total_weight
        } else {
            0.0
        };
        let rounded_px: f32 = weights.map(|weight| (unit_px * weight + 0.5).floor()).sum();
        Self {
            density,
            unit_px,
            remainder_px: remaining_px - rounded_px,
        }
    }

    /// The main-axis size of the next weighted child, which weighs `weight`.
    pub(crate) fn next_share(&mut self, weight: f32) -> f32 {
        let step = if self.remainder_px > 0.0 {
            1.0
        } else if self.remainder_px < 0.0 {
            -1.0
        } else {
            0.0
        };
        self.remainder_px -= step;
        ((self.unit_px * weight + 0.5).floor() + step).max(0.0) / self.density
    }
}

/// Cross-axis alignment for flex layouts.
/// This is axis-agnostic and gets interpreted based on the flex axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CrossAxisAlignment {
    /// Align to the start of the cross axis (Top for Row, Start for Column)
    Start,
    /// Align to the center of the cross axis
    Center,
    /// Align to the end of the cross axis (Bottom for Row, End for Column)
    End,
}

impl CrossAxisAlignment {
    /// Where a child sits in `available` space: see [`bias_offset`].
    fn align(&self, available: f32, child: f32, density: f32) -> f32 {
        let bias = match self {
            CrossAxisAlignment::Start => -1.0,
            CrossAxisAlignment::Center => 0.0,
            CrossAxisAlignment::End => 1.0,
        };
        bias_offset(bias, available, child, density)
    }
}

impl From<HorizontalAlignment> for CrossAxisAlignment {
    fn from(alignment: HorizontalAlignment) -> Self {
        match alignment {
            HorizontalAlignment::Start => CrossAxisAlignment::Start,
            HorizontalAlignment::CenterHorizontally => CrossAxisAlignment::Center,
            HorizontalAlignment::End => CrossAxisAlignment::End,
        }
    }
}

impl From<VerticalAlignment> for CrossAxisAlignment {
    fn from(alignment: VerticalAlignment) -> Self {
        match alignment {
            VerticalAlignment::Top => CrossAxisAlignment::Start,
            VerticalAlignment::CenterVertically => CrossAxisAlignment::Center,
            VerticalAlignment::Bottom => CrossAxisAlignment::End,
        }
    }
}

impl FlexMeasurePolicy {
    /// A flex layout along `axis` on the device pixel grid of `density`.
    pub fn new(
        axis: Axis,
        main_axis_arrangement: LinearArrangement,
        cross_axis_alignment: CrossAxisAlignment,
        density: f32,
    ) -> Self {
        Self {
            axis,
            main_axis_arrangement,
            cross_axis_alignment,
            density,
            layout_direction: crate::LayoutDirection::Ltr,
        }
    }

    /// Creates a FlexMeasurePolicy for Row (horizontal main axis).
    pub fn row(
        horizontal_arrangement: LinearArrangement,
        vertical_alignment: VerticalAlignment,
        density: f32,
    ) -> Self {
        Self::new(
            Axis::Horizontal,
            horizontal_arrangement,
            vertical_alignment.into(),
            density,
        )
    }

    /// Creates a FlexMeasurePolicy for Column (vertical main axis).
    pub fn column(
        vertical_arrangement: LinearArrangement,
        horizontal_alignment: HorizontalAlignment,
        density: f32,
    ) -> Self {
        Self::new(
            Axis::Vertical,
            vertical_arrangement,
            horizontal_alignment.into(),
            density,
        )
    }

    fn get_axis_constraints(&self, constraints: Constraints) -> (f32, f32, f32, f32) {
        match self.axis {
            Axis::Horizontal => (
                constraints.min_width,
                constraints.max_width,
                constraints.min_height,
                constraints.max_height,
            ),
            Axis::Vertical => (
                constraints.min_height,
                constraints.max_height,
                constraints.min_width,
                constraints.max_width,
            ),
        }
    }

    fn make_constraints(
        &self,
        min_main: f32,
        max_main: f32,
        min_cross: f32,
        max_cross: f32,
    ) -> Constraints {
        match self.axis {
            Axis::Horizontal => Constraints {
                min_width: min_main,
                max_width: max_main,
                min_height: min_cross,
                max_height: max_cross,
            },
            Axis::Vertical => Constraints {
                min_width: min_cross,
                max_width: max_cross,
                min_height: min_main,
                max_height: max_main,
            },
        }
    }

    fn get_main_axis_size(&self, width: f32, height: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => width,
            Axis::Vertical => height,
        }
    }

    fn get_cross_axis_size(&self, width: f32, height: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => height,
            Axis::Vertical => width,
        }
    }

    /// Measures the unweighted children in order and returns Compose's
    /// `fixedSpace` with the largest cross size. Each child is offered only
    /// the main-axis space the ones before it leave, as
    /// `RowColumnMeasurementHelper` offers it, and the spacing after a child
    /// never runs past the main axis.
    fn measure_fixed_children(
        &self,
        measurables: &[Box<dyn Measurable>],
        fixed_children: &[usize],
        (max_main, max_cross): (f32, f32),
        spacing: f32,
        placeables: &mut [Option<cranpose_ui_layout::Placeable>],
    ) -> (f32, f32) {
        let main_axis_bounded = max_main.is_finite();
        let mut fixed_space = 0.0_f32;
        let mut max_cross_size = 0.0_f32;
        for &idx in fixed_children {
            let available_main = if main_axis_bounded {
                (max_main - fixed_space).max(0.0)
            } else {
                max_main
            };
            let placeable = measurables[idx].measure(self.make_constraints(
                0.0,
                available_main,
                0.0,
                max_cross,
            ));
            let main_size = self.get_main_axis_size(placeable.width(), placeable.height());
            let spacing_after = if main_axis_bounded {
                spacing.min(available_main - main_size).max(0.0)
            } else {
                spacing
            };
            fixed_space += main_size + spacing_after;
            max_cross_size =
                max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
            placeables[idx] = Some(placeable);
        }
        (fixed_space, max_cross_size)
    }

    /// Compose's intrinsic size along the main axis: the sizes `main_size`
    /// gives of the unweighted children, the space in which each weighted
    /// child gets its own size, and the spacing.
    fn intrinsic_main_size(
        &self,
        measurables: &[Box<dyn Measurable>],
        main_size: impl Fn(&dyn Measurable) -> f32,
    ) -> f32 {
        if measurables.is_empty() {
            return 0.0;
        }
        let mut fixed_space = 0.0_f32;
        let mut weight_unit = 0.0_f32;
        let mut total_weight = 0.0_f32;
        for measurable in measurables {
            let size = main_size(measurable.as_ref());
            match child_weight(measurable.as_ref()) {
                Some(weight) => {
                    total_weight += weight;
                    weight_unit = weight_unit.max(round_to_px(size / weight, self.density));
                }
                None => fixed_space += size,
            }
        }
        round_to_px(weight_unit * total_weight, self.density)
            + fixed_space
            + self.get_spacing() * (measurables.len() - 1) as f32
    }

    /// Compose's intrinsic size across the main axis, in `main_available`
    /// main-axis space: each unweighted child asks for the main-axis size
    /// `main_size` gives it, up to what the children before it leave, and
    /// the weighted children share the rest. `cross_size` gives a child's
    /// cross size in the main-axis space it gets.
    fn intrinsic_cross_size(
        &self,
        measurables: &[Box<dyn Measurable>],
        main_available: f32,
        main_size: impl Fn(&dyn Measurable, f32) -> f32,
        cross_size: impl Fn(&dyn Measurable, f32) -> f32,
    ) -> f32 {
        if measurables.is_empty() {
            return 0.0;
        }
        let mut fixed_space =
            (self.get_spacing() * (measurables.len() - 1) as f32).min(main_available);
        let mut cross = 0.0_f32;
        let mut total_weight = 0.0_f32;
        for measurable in measurables {
            let measurable = measurable.as_ref();
            if let Some(weight) = child_weight(measurable) {
                total_weight += weight;
                continue;
            }
            let space =
                main_size(measurable, f32::INFINITY).min((main_available - fixed_space).max(0.0));
            fixed_space += space;
            cross = cross.max(cross_size(measurable, space));
        }
        if total_weight == 0.0 {
            return cross;
        }
        let weight_unit = if main_available.is_finite() {
            round_to_px(
                (main_available - fixed_space).max(0.0) / total_weight,
                self.density,
            )
        } else {
            f32::INFINITY
        };
        for measurable in measurables {
            let measurable = measurable.as_ref();
            if let Some(weight) = child_weight(measurable) {
                cross = cross.max(cross_size(
                    measurable,
                    round_to_px(weight_unit * weight, self.density),
                ));
            }
        }
        cross
    }

    fn get_spacing(&self) -> f32 {
        self.main_axis_arrangement.spacing(self.density)
    }

    fn measure_weighted_children(
        &self,
        measurables: &[Box<dyn Measurable>],
        weighted_children: &[(usize, ParentData)],
        (max_main, max_cross): (f32, f32),
        (fixed_space, spacing): (f32, f32),
        placeables: &mut [Option<cranpose_ui_layout::Placeable>],
    ) -> f32 {
        let remaining_main =
            (max_main - fixed_space - spacing * weighted_children.len().saturating_sub(1) as f32)
                .max(0.0);
        let mut shares = WeightShares::new(
            remaining_main,
            weighted_children.iter().map(|(_, data)| data.weight),
            self.density,
        );
        let mut max_cross_size = 0.0_f32;
        for &(idx, data) in weighted_children {
            let constraints = if max_main.is_finite() {
                let allocated = shares.next_share(data.weight);
                let minimum = if data.fill { allocated } else { 0.0 };
                self.make_constraints(minimum, allocated, 0.0, max_cross)
            } else {
                self.make_constraints(0.0, max_main, 0.0, max_cross)
            };
            let placeable = measurables[idx].measure(constraints);
            max_cross_size =
                max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
            placeables[idx] = Some(placeable);
        }
        max_cross_size
    }

    fn measured_extents(
        &self,
        placeables: &[cranpose_ui_layout::Placeable],
        parent_data: &[cranpose_ui_layout::ParentData],
    ) -> (f32, f32, f32) {
        let mut main = 0.0;
        let mut before = 0.0_f32;
        let mut after = 0.0_f32;
        for (placeable, data) in placeables.iter().zip(parent_data) {
            main += self.get_main_axis_size(placeable.width(), placeable.height());
            if self.axis == Axis::Horizontal
                && data.row_baseline
                && let Some(baseline) = placeable.alignment_lines().first_baseline()
            {
                before = before.max(baseline);
                after = after.max(placeable.height() - baseline);
            }
        }
        (main, before, after)
    }

    fn cross_axis_position(
        &self,
        placeable: &cranpose_ui_layout::Placeable,
        parent_data: ParentData,
        container_cross: f32,
        before_baseline: f32,
    ) -> f32 {
        if self.axis == Axis::Horizontal && parent_data.row_baseline {
            return placeable
                .alignment_lines()
                .first_baseline()
                .map_or(0.0, |baseline| before_baseline - baseline);
        }
        let alignment = match self.axis {
            Axis::Horizontal => parent_data
                .row_alignment
                .map_or(self.cross_axis_alignment, Into::into),
            Axis::Vertical => parent_data
                .column_alignment
                .map_or(self.cross_axis_alignment, Into::into),
        };
        let child_cross = self.get_cross_axis_size(placeable.width(), placeable.height());
        alignment.align(container_cross, child_cross, self.density)
    }
}

/// The parent main-axis max range over which a held child keeps its size
/// after `fixed_space` taken by the children before it, with `spacing`
/// still fitting after it.
fn child_main_range(
    child_max: cranpose_ui_layout::BoundRange,
    max_main: f32,
    fixed_space: f32,
    child_main: f32,
    spacing: f32,
) -> Option<cranpose_ui_layout::BoundRange> {
    use cranpose_ui_layout::BoundRange;
    if !max_main.is_finite() {
        return child_max
            .contains(f32::INFINITY)
            .then_some(BoundRange::exactly(f32::INFINITY));
    }
    if (max_main - fixed_space).max(0.0) - child_main < spacing {
        return None;
    }
    child_max
        .outset(fixed_space)
        .intersect(BoundRange::from(fixed_space + child_main + spacing))
}

/// The weight of a child that shares the main axis by weight.
fn child_weight(measurable: &dyn Measurable) -> Option<f32> {
    measurable
        .flex_parent_data()
        .map(|data| data.weight)
        .filter(|weight| *weight > 0.0)
}

impl MeasurePolicy for FlexMeasurePolicy {
    fn measure(
        &self,
        scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
    ) -> MeasureResult {
        let mut placements = Vec::new();
        let measurement = self.measure_into(scope, measurables, constraints, &mut placements);
        MeasureResult::new(measurement, placements)
    }

    /// A row or column of unweighted children holds while each child holds
    /// under the main-axis space the ones before it leave, the spacing
    /// after each keeps its full width, and the bounds still fit the sum.
    fn measure_hold(
        &self,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        size: crate::modifier::Size,
    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
        use cranpose_ui_layout::{AxisHold, BoundRange, ConstraintsHold};
        if measurables.is_empty() {
            return empty_layout_hold(constraints, size);
        }
        if measurables
            .iter()
            .any(|measurable| measurable.parent_data().has_weight())
        {
            return None;
        }
        let (_, max_main, _, _) = self.get_axis_constraints(constraints);
        let spacing = self.get_spacing();
        let mut main = BoundRange::ANY;
        let mut cross = BoundRange::ANY;
        let mut fixed_space = 0.0_f32;
        let mut total_main = 0.0_f32;
        let mut cross_size = 0.0_f32;
        for measurable in measurables {
            let (child, hold) = measurable.measured_hold()?;
            let (main_hold, cross_hold) = match self.axis {
                Axis::Horizontal => (hold.width, hold.height),
                Axis::Vertical => (hold.height, hold.width),
            };
            let child_main = self.get_main_axis_size(child.width, child.height);
            main = main.intersect(child_main_range(
                main_hold.max,
                max_main,
                fixed_space,
                child_main,
                spacing,
            )?)?;
            cross = cross.intersect(cross_hold.max)?;
            fixed_space += child_main + spacing;
            total_main += child_main;
            cross_size = cross_size.max(self.get_cross_axis_size(child.width, child.height));
        }
        total_main += spacing * (measurables.len() - 1) as f32;
        let size_main = self.get_main_axis_size(size.width, size.height);
        let size_cross = self.get_cross_axis_size(size.width, size.height);
        // Bounds that cut or stretched the layout size it from themselves.
        if size_main != total_main || size_cross != cross_size {
            return None;
        }
        let main = AxisHold {
            min: BoundRange::up_to(size_main),
            max: main.intersect(BoundRange::from(size_main))?,
        };
        let cross = AxisHold {
            min: BoundRange::up_to(size_cross),
            max: cross.intersect(BoundRange::from(size_cross))?,
        };
        Some(match self.axis {
            Axis::Horizontal => ConstraintsHold {
                width: main,
                height: cross,
            },
            Axis::Vertical => ConstraintsHold {
                width: cross,
                height: main,
            },
        })
    }

    fn measure_into(
        &self,
        _scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        placements: &mut Vec<Placement>,
    ) -> cranpose_ui_layout::Measurement {
        placements.clear();
        if measurables.is_empty() {
            let (width, height) = constraints.constrain(0.0, 0.0);
            return crate::modifier::Size { width, height }.into();
        }

        let (min_main, max_main, min_cross, max_cross) = self.get_axis_constraints(constraints);
        let spacing = self.get_spacing();

        let mut fixed_children: SmallVec<[usize; 8]> = SmallVec::new();
        let parent_data: SmallVec<[ParentData; 8]> = measurables
            .iter()
            .map(|child| child.parent_data())
            .collect();
        let mut weighted_children: SmallVec<[(usize, ParentData); 8]> = SmallVec::new();

        for (idx, data) in parent_data.iter().copied().enumerate() {
            if data.has_weight() {
                weighted_children.push((idx, data));
            } else {
                fixed_children.push(idx);
            }
        }

        let child_constraints = self.make_constraints(0.0, max_main, 0.0, max_cross);

        let mut placeables: SmallVec<[Option<cranpose_ui_layout::Placeable>; 8]> = SmallVec::new();
        placeables.resize_with(measurables.len(), || None);
        let (fixed_space, mut max_cross_size) = self.measure_fixed_children(
            measurables,
            &fixed_children,
            (max_main, max_cross),
            spacing,
            &mut placeables,
        );

        let num_children = measurables.len();
        let total_spacing = if num_children > 1 {
            spacing * (num_children - 1) as f32
        } else {
            0.0
        };

        max_cross_size = max_cross_size.max(self.measure_weighted_children(
            measurables,
            &weighted_children,
            (max_main, max_cross),
            (fixed_space, spacing),
            &mut placeables,
        ));

        let placeables: SmallVec<[cranpose_ui_layout::Placeable; 8]> = placeables
            .into_iter()
            .enumerate()
            .map(|(idx, placeable)| {
                placeable.unwrap_or_else(|| measurables[idx].measure(child_constraints))
            })
            .collect();

        let (total_main, before_baseline, after_baseline) =
            self.measured_extents(&placeables, &parent_data);
        let total_main = total_main + total_spacing;
        max_cross_size = max_cross_size.max(before_baseline + after_baseline);

        let container_main = total_main.clamp(min_main, max_main);
        let container_cross = max_cross_size.clamp(min_cross, max_cross);

        let child_main_sizes: SmallVec<[f32; 8]> = placeables
            .iter()
            .map(|p| self.get_main_axis_size(p.width(), p.height()))
            .collect();

        let mut main_positions: SmallVec<[f32; 8]> =
            SmallVec::with_capacity(child_main_sizes.len());
        main_positions.resize(child_main_sizes.len(), 0.0);

        let arrangement = if total_main > container_main && !self.main_axis_arrangement.is_spaced()
        {
            LinearArrangement::Start
        } else {
            self.main_axis_arrangement
        };
        arrangement.arrange(
            self.density,
            container_main,
            &child_main_sizes,
            &mut main_positions,
        );

        placements.reserve(placeables.len());
        for (idx, (placeable, main_pos)) in placeables.into_iter().zip(main_positions).enumerate() {
            let cross_pos = self.cross_axis_position(
                &placeable,
                parent_data[idx],
                container_cross,
                before_baseline,
            );

            let (x, y) = match self.axis {
                Axis::Horizontal => (main_pos, cross_pos),
                Axis::Vertical => (cross_pos, main_pos),
            };
            let width = match self.axis {
                Axis::Horizontal => container_main,
                Axis::Vertical => container_cross,
            };
            let x = self.layout_direction.place_x(x, width, placeable.width());

            placeable.place(x, y);
            placements.push(Placement::new(placeable.node_id(), x, y, 0));
        }

        let (width, height) = match self.axis {
            Axis::Horizontal => (container_main, container_cross),
            Axis::Vertical => (container_cross, container_main),
        };

        crate::modifier::Size { width, height }.into()
    }

    fn min_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => {
                self.intrinsic_main_size(measurables, |m| m.min_intrinsic_width(height))
            }
            Axis::Vertical => self.intrinsic_cross_size(
                measurables,
                height,
                |m, width| m.max_intrinsic_height(width),
                |m, main| m.min_intrinsic_width(main),
            ),
        }
    }

    fn max_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => {
                self.intrinsic_main_size(measurables, |m| m.max_intrinsic_width(height))
            }
            Axis::Vertical => self.intrinsic_cross_size(
                measurables,
                height,
                |m, width| m.max_intrinsic_height(width),
                |m, main| m.max_intrinsic_width(main),
            ),
        }
    }

    fn min_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => self.intrinsic_cross_size(
                measurables,
                width,
                |m, height| m.max_intrinsic_width(height),
                |m, main| m.min_intrinsic_height(main),
            ),
            Axis::Vertical => {
                self.intrinsic_main_size(measurables, |m| m.min_intrinsic_height(width))
            }
        }
    }

    fn max_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        match self.axis {
            Axis::Horizontal => self.intrinsic_cross_size(
                measurables,
                width,
                |m, height| m.max_intrinsic_width(height),
                |m, main| m.max_intrinsic_height(main),
            ),
            Axis::Vertical => {
                self.intrinsic_main_size(measurables, |m| m.max_intrinsic_height(width))
            }
        }
    }
}

/// MeasurePolicy for FlowRow: children flow horizontally and wrap onto the
/// next line when the available width runs out (Jetpack Compose `FlowRow`).
///
/// - Children are measured with loose constraints (min = 0) capped at the
///   incoming max width/height, then packed left-to-right.
/// - A child that no longer fits on the current line starts a new line; a
///   child wider than the whole line gets a line of its own (and may
///   overflow, like Compose).
/// - `main_axis_spacing` separates children on the same line and
///   `cross_axis_spacing` separates lines; children are top-aligned within
///   their line.
/// - With an unbounded max width everything stays on one line.
#[derive(Clone, Debug, PartialEq)]
pub struct FlowRowMeasurePolicy {
    /// Horizontal gap between adjacent children on the same line, in dp.
    pub main_axis_spacing: f32,
    /// Vertical gap between consecutive lines, in dp.
    pub cross_axis_spacing: f32,
    /// Direction used to place items within each wrapped row.
    pub layout_direction: crate::LayoutDirection,
}

impl FlowRowMeasurePolicy {
    pub fn new(main_axis_spacing: f32, cross_axis_spacing: f32) -> Self {
        Self {
            main_axis_spacing: main_axis_spacing.max(0.0),
            cross_axis_spacing: cross_axis_spacing.max(0.0),
            layout_direction: crate::LayoutDirection::Ltr,
        }
    }

    fn wrapped_intrinsic_height(
        &self,
        measurables: &[Box<dyn Measurable>],
        available_width: f32,
        use_min_height: bool,
    ) -> f32 {
        let mut cursor_x = 0.0_f32;
        let mut line_top = 0.0_f32;
        let mut line_height = 0.0_f32;

        for measurable in measurables {
            let child_width = measurable.max_intrinsic_width(f32::INFINITY);
            let child_height = if use_min_height {
                measurable.min_intrinsic_height(child_width)
            } else {
                measurable.max_intrinsic_height(child_width)
            };

            if cursor_x > 0.0 && cursor_x + self.main_axis_spacing + child_width > available_width {
                line_top += line_height + self.cross_axis_spacing;
                cursor_x = 0.0;
                line_height = 0.0;
            }
            cursor_x += if cursor_x > 0.0 {
                self.main_axis_spacing + child_width
            } else {
                child_width
            };
            line_height = line_height.max(child_height);
        }

        line_top + line_height
    }
}

impl MeasurePolicy for FlowRowMeasurePolicy {
    fn measure(
        &self,
        scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
    ) -> MeasureResult {
        let mut placements = Vec::new();
        let measurement = self.measure_into(scope, measurables, constraints, &mut placements);
        MeasureResult::new(measurement, placements)
    }

    fn measure_into(
        &self,
        _scope: &dyn MeasureScope,
        measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        placements: &mut Vec<Placement>,
    ) -> cranpose_ui_layout::Measurement {
        placements.clear();
        if measurables.is_empty() {
            let (width, height) = constraints.constrain(0.0, 0.0);
            return crate::modifier::Size { width, height }.into();
        }

        let child_constraints = Constraints {
            min_width: 0.0,
            max_width: constraints.max_width,
            min_height: 0.0,
            max_height: constraints.max_height,
        };

        let placeables: SmallVec<[cranpose_ui_layout::Placeable; 8]> = measurables
            .iter()
            .map(|measurable| measurable.measure(child_constraints))
            .collect();

        let mut cursor_x = 0.0_f32;
        let mut line_top = 0.0_f32;
        let mut line_height = 0.0_f32;
        let mut max_line_width = 0.0_f32;

        placements.reserve(placeables.len());
        for placeable in &placeables {
            let child_width = placeable.width();
            let child_height = placeable.height();

            if cursor_x > 0.0
                && cursor_x + self.main_axis_spacing + child_width > constraints.max_width
            {
                max_line_width = max_line_width.max(cursor_x);
                line_top += line_height + self.cross_axis_spacing;
                cursor_x = 0.0;
                line_height = 0.0;
            }

            let x = if cursor_x > 0.0 {
                cursor_x + self.main_axis_spacing
            } else {
                0.0
            };
            if !self.layout_direction.is_rtl() {
                placeable.place(x, line_top);
            }
            placements.push(Placement::new(placeable.node_id(), x, line_top, 0));

            cursor_x = x + child_width;
            line_height = line_height.max(child_height);
        }
        max_line_width = max_line_width.max(cursor_x);

        let width = max_line_width.clamp(constraints.min_width, constraints.max_width);
        if self.layout_direction.is_rtl() {
            for (placement, placeable) in placements.iter_mut().zip(&placeables) {
                placement.x = self
                    .layout_direction
                    .place_x(placement.x, width, placeable.width());
                placeable.place(placement.x, placement.y);
            }
        }
        let height = (line_top + line_height).clamp(constraints.min_height, constraints.max_height);
        crate::modifier::Size { width, height }.into()
    }

    fn min_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        measurables
            .iter()
            .map(|m| m.min_intrinsic_width(height))
            .fold(0.0, f32::max)
    }

    fn max_intrinsic_width(&self, measurables: &[Box<dyn Measurable>], height: f32) -> f32 {
        let total_spacing = if measurables.len() > 1 {
            self.main_axis_spacing * (measurables.len() - 1) as f32
        } else {
            0.0
        };
        measurables
            .iter()
            .map(|m| m.max_intrinsic_width(height))
            .sum::<f32>()
            + total_spacing
    }

    fn min_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        self.wrapped_intrinsic_height(measurables, width, true)
    }

    fn max_intrinsic_height(&self, measurables: &[Box<dyn Measurable>], width: f32) -> f32 {
        self.wrapped_intrinsic_height(measurables, width, false)
    }
}

/// MeasurePolicy for leaf nodes with fixed intrinsic size (like Spacer).
/// This policy respects the provided constraints but has a preferred intrinsic size.
#[derive(Clone, Debug, PartialEq)]
pub struct LeafMeasurePolicy {
    pub intrinsic_size: crate::modifier::Size,
}

impl LeafMeasurePolicy {
    pub fn new(intrinsic_size: crate::modifier::Size) -> Self {
        Self { intrinsic_size }
    }
}

impl MeasurePolicy for LeafMeasurePolicy {
    fn measure(
        &self,
        scope: &dyn MeasureScope,
        _measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
    ) -> MeasureResult {
        let mut placements = Vec::new();
        let measurement = self.measure_into(scope, &[], constraints, &mut placements);
        MeasureResult::new(measurement, placements)
    }

    fn measure_into(
        &self,
        _scope: &dyn MeasureScope,
        _measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        placements: &mut Vec<Placement>,
    ) -> cranpose_ui_layout::Measurement {
        placements.clear();
        let (width, height) =
            constraints.constrain(self.intrinsic_size.width, self.intrinsic_size.height);

        crate::modifier::Size { width, height }.into()
    }

    fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
        self.intrinsic_size.width
    }

    fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
        self.intrinsic_size.width
    }

    fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
        self.intrinsic_size.height
    }

    fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
        self.intrinsic_size.height
    }
}

/// EmptyMeasurePolicy that delegates all measurement to modifier nodes.
///
/// This is used when a Layout has no child layout logic - all measurement
/// is handled by modifier nodes (e.g., TextModifierNode for Text widgets).
/// Matches Jetpack Compose's EmptyMeasurePolicy pattern used in BasicText.
#[derive(Clone, Debug, PartialEq)]
pub struct EmptyMeasurePolicy;

impl EmptyMeasurePolicy {
    pub fn new() -> Self {
        Self
    }
}

impl Default for EmptyMeasurePolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl MeasurePolicy for EmptyMeasurePolicy {
    fn measure(
        &self,
        scope: &dyn MeasureScope,
        _measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
    ) -> MeasureResult {
        let mut placements = Vec::new();
        let measurement = self.measure_into(scope, &[], constraints, &mut placements);
        MeasureResult::new(measurement, placements)
    }

    fn measure_into(
        &self,
        _scope: &dyn MeasureScope,
        _measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        placements: &mut Vec<Placement>,
    ) -> cranpose_ui_layout::Measurement {
        placements.clear();
        let (width, height) = constraints.constrain(0.0, 0.0);

        crate::modifier::Size { width, height }.into()
    }

    fn measure_hold(
        &self,
        _measurables: &[Box<dyn Measurable>],
        constraints: Constraints,
        size: crate::modifier::Size,
    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
        empty_layout_hold(constraints, size)
    }

    fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
        0.0
    }

    fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
        0.0
    }

    fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
        0.0
    }

    fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
        0.0
    }
}

#[cfg(test)]
#[path = "tests/policies_tests.rs"]
mod tests;

/// What a layout with nothing in it holds for: it takes its min
/// constraints, so any constraints with the same mins and a max that allows
/// them size it the same.
fn empty_layout_hold(
    constraints: Constraints,
    size: crate::modifier::Size,
) -> Option<cranpose_ui_layout::ConstraintsHold> {
    (size.width == constraints.min_width && size.height == constraints.min_height)
        .then(|| cranpose_ui_layout::ConstraintsHold::at_min(size.width, size.height))
}